Java Code Examples for java.math.BigInteger

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.

Source file: ViewTools.java

  34 
vote

public void stopTimer(String timerName){
  if (AppProperties.enableTemplateTimers) {
    BigInteger startTime=this.timers.get(timerName);
    if (startTime == null) {
      logger.warn("Timer '" + timerName + "' has not been started");
      return;
    }
    this.timers.remove(timerName);
    long elapsedTime=System.currentTimeMillis() - startTime.longValue();
    this.log(timerName + " elapsed time = " + elapsedTime+ "ms");
  }
}
 

Example 2

From project AlgorithmsNYC, under directory /SlidingPuzzle/src/com/oti/solutions/sam/.

Source file: SASolver.java

  33 
vote

/** 
 * shrink a Board object in a BigInt each 4 bits representing one call of the board.
 */
private BigInteger createState(Board board){
  BigInteger res=BigInteger.valueOf(0);
  for (int i=0; i < 4; i++) {
    int fourth=0;
    for (int j=0; j < 4; j++) {
      Piece cell=board.pieceAt(j,i);
      fourth=fourth << 4;
      fourth|=cell.getPieceNumber();
    }
    res=res.shiftLeft(16);
    res=res.add(BigInteger.valueOf(fourth));
  }
  return res;
}
 

Example 3

From project androidquery, under directory /src/com/androidquery/util/.

Source file: AQUtility.java

  33 
vote

private static String getMD5Hex(String str){
  byte[] data=getMD5(str.getBytes());
  BigInteger bi=new BigInteger(data).abs();
  String result=bi.toString(36);
  return result;
}
 

Example 4

From project android_8, under directory /src/com/google/gson/.

Source file: JsonPrimitive.java

  33 
vote

/** 
 * convenience method to get this element as an Object.
 * @return get this element as an Object that can be converted to a suitable value.
 */
@Override Object getAsObject(){
  if (value instanceof BigInteger) {
    BigInteger big=(BigInteger)value;
    if (big.compareTo(INTEGER_MAX) < 0) {
      return big.intValue();
    }
 else     if (big.compareTo(LONG_MAX) < 0) {
      return big.longValue();
    }
  }
  return value;
}
 

Example 5

From project astyanax, under directory /src/main/java/com/netflix/astyanax/util/.

Source file: TokenGenerator.java

  33 
vote

public static String tokenMinusOne(String payload){
  BigInteger bigInt=new BigInteger(payload);
  if (bigInt.equals(MINIMUM))   bigInt=MAXIMUM;
  bigInt=bigInt.subtract(new BigInteger("1"));
  return bigInt.toString();
}
 

Example 6

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/ui/.

Source file: CurrencyAmountView.java

  33 
vote

private boolean isValidAmount(){
  final String amount=textView.getText().toString().trim();
  try {
    if (amount.length() > 0) {
      final BigInteger nanoCoins=Utils.toNanoCoins(amount);
      if (nanoCoins.signum() >= 0)       return true;
    }
  }
 catch (  final Exception x) {
  }
  return false;
}
 

Example 7

From project candlepin, under directory /src/main/java/org/candlepin/service/impl/.

Source file: DefaultProductServiceAdapter.java

  33 
vote

private ProductCertificate createForProduct(Product product) throws GeneralSecurityException, IOException {
  KeyPair keyPair=pki.generateNewKeyPair();
  Set<X509ExtensionWrapper> extensions=this.extensionUtil.productExtensions(product);
  BigInteger serial=BigInteger.valueOf(product.getId().hashCode()).abs();
  Calendar future=Calendar.getInstance();
  future.add(Calendar.YEAR,10);
  X509Certificate x509Cert=this.pki.createX509Certificate("CN=" + product.getId(),extensions,null,new Date(),future.getTime(),keyPair,serial,null);
  ProductCertificate cert=new ProductCertificate();
  cert.setKeyAsBytes(pki.getPemEncoded(keyPair.getPrivate()));
  cert.setCertAsBytes(this.pki.getPemEncoded(x509Cert));
  cert.setProduct(product);
  return cert;
}
 

Example 8

From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/bpmn20/model/activity/.

Source file: Activity.java

  32 
vote

/** 
 * Gets the value of the startQuantity property.
 * @return possible object is {@link BigInteger }
 */
public BigInteger getStartQuantity(){
  if (startQuantity == null) {
    return new BigInteger("1");
  }
 else {
    return startQuantity;
  }
}
 

Example 9

From project addis, under directory /application/src/main/java/org/drugis/addis/util/jaxb/.

Source file: JAXBConvertor.java

  32 
vote

private static References convertReferences(PubMedIdList pubMedIdList){
  References refs=new References();
  for (  PubMedId x : pubMedIdList) {
    refs.getPubMedId().add(new BigInteger(x.getId()));
  }
  return refs;
}
 

Example 10

From project agile, under directory /agile-api/src/main/java/org/headsupdev/agile/api/util/.

Source file: HashUtil.java

  32 
vote

public static String getMD5Hex(String in){
  MessageDigest messageDigest;
  try {
    messageDigest=java.security.MessageDigest.getInstance("MD5");
    messageDigest.update(in.getBytes(),0,in.length());
    return new BigInteger(1,messageDigest.digest()).toString(16);
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  return "";
}
 

Example 11

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/data/.

Source file: HashUtils.java

  32 
vote

/** 
 * Creates a SHA-1 digest of byte array and returns it as a hexadecimal number.
 * @param data The data to digest.
 * @return The hexadecimal result of the digest.
 */
public static String sha1Hex(final byte[] data){
  AjahUtils.requireParam(data,"data");
  try {
    final MessageDigest md=MessageDigest.getInstance("SHA-1");
    md.update(data,0,data.length);
    byte[] bytes=md.digest();
    return String.format("%0" + (bytes.length << 1) + "x",new BigInteger(1,bytes));
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new UnsupportedOperationException(e);
  }
}
 

Example 12

From project alphaportal_dev, under directory /sys-src/alphaportal/core/src/main/java/alpha/portal/dao/hibernate/.

Source file: PayloadDaoHibernate.java

  32 
vote

/** 
 * Internal function to load the highest sequenceNumber from the AlphaCard table.
 * @param sessionFactory the session factory
 * @param column the column
 * @return 0 if no record is found
 */
private Long getLastValue(final SessionFactory sessionFactory,final String column){
  Session session;
  boolean sessionOwn=false;
  try {
    session=sessionFactory.getCurrentSession();
  }
 catch (  final Exception e) {
    session=sessionFactory.openSession();
    sessionOwn=true;
  }
  final Query q=session.createSQLQuery("select max(" + column + ") from payload");
  final List<Object> list=q.list();
  BigInteger value=(BigInteger)list.get(0);
  if (value == null) {
    value=new BigInteger("0");
  }
  if (sessionOwn) {
    session.close();
  }
  return value.longValue();
}
 

Example 13

From project android-aac-enc, under directory /src/com/googlecode/mp4parser/boxes/.

Source file: AbstractSampleEncryptionBox.java

  32 
vote

@Override public boolean equals(Object o){
  if (this == o)   return true;
  if (o == null || getClass() != o.getClass())   return false;
  Entry entry=(Entry)o;
  if (!new BigInteger(iv).equals(new BigInteger(entry.iv)))   return false;
  if (pairs != null ? !pairs.equals(entry.pairs) : entry.pairs != null)   return false;
  return true;
}
 

Example 14

From project android-sdk, under directory /src/main/java/com/mobeelizer/mobile/android/.

Source file: MobeelizerInternalDatabase.java

  32 
vote

private String getMd5(final String password){
  MessageDigest m;
  try {
    m=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e.getMessage(),e);
  }
  m.update(password.getBytes(),0,password.length());
  String hash=new BigInteger(1,m.digest()).toString(16);
  return hash;
}
 

Example 15

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.

Source file: AStream.java

  31 
vote

static Object read3_parse(JSONObject jo,Twitter jtwitr) throws JSONException {
  if (jo.has("text")) {
    Status tweet=new Status(jo,null);
    return tweet;
  }
  String eventType=jo.optString("event");
  if (eventType != "") {
    TwitterEvent event=new TwitterEvent(jo,jtwitr);
    return event;
  }
  JSONObject del=jo.optJSONObject("delete");
  if (del != null) {
    JSONObject s=del.getJSONObject("status");
    BigInteger id=new BigInteger(s.getString("id_str"));
    long userId=s.getLong("user_id");
    Status deadTweet=new Status(null,null,id,null);
    return new Object[]{"delete",deadTweet,userId};
  }
  JSONObject limit=jo.optJSONObject("limit");
  if (limit != null) {
    int cnt=limit.optInt("track");
    if (cnt == 0) {
      System.out.println(jo);
    }
    return new Object[]{"limit",cnt};
  }
  System.out.println(jo);
  return jo;
}
 

Example 16

From project android_5, under directory /src/aarddict/.

Source file: Volume.java

  31 
vote

public void verify(VerifyProgressListener listener) throws IOException, NoSuchAlgorithmException {
  FileInputStream fis=new FileInputStream(origFile);
  fis.skip(44);
  byte[] buff=new byte[1 << 16];
  MessageDigest m=MessageDigest.getInstance("SHA-1");
  int readCount;
  long totalReadCount=0;
  double totalBytes=origFile.length() - 44;
  boolean proceed=true;
  while ((readCount=fis.read(buff)) != -1) {
    m.update(buff,0,readCount);
    totalReadCount+=readCount;
    proceed=listener.updateProgress(this,totalReadCount / totalBytes);
  }
  fis.close();
  if (proceed) {
    BigInteger b=new BigInteger(1,m.digest());
    String calculated=b.toString(16);
    Log.d(TAG,"calculated: " + calculated + " actual: "+ sha1sum);
    listener.verified(this,calculated.equals(this.sha1sum));
  }
}
 

Example 17

From project arastreju, under directory /arastreju.sge/src/main/java/org/arastreju/sge/model/nodes/.

Source file: SNValue.java

  31 
vote

/** 
 * {@inheritDoc}
 */
public BigInteger getIntegerValue(){
  if (value instanceof String) {
    return new BigInteger((String)value);
  }
  return (BigInteger)value;
}
 

Example 18

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-impl/src/main/java/org/jboss/arquillian/ajocado/utils/.

Source file: URLUtils.java

  31 
vote

/** 
 * Gets a MD5 digest of some resource obtains as input stream from connection to URL given by URL string.
 * @param url of the resource
 * @return MD5 message digest of resource
 * @throws IOException when connection to URL fails
 */
public static String resourceMd5Digest(String url) throws IOException {
  URLConnection connection=new URL(url).openConnection();
  InputStream in=connection.getInputStream();
  MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new IllegalStateException("MD5 hashing is unsupported",ex);
  }
  byte[] buffer=new byte[MD5_BUFFER_SIZE];
  int read=0;
  while ((read=in.read(buffer)) > 0) {
    digest.update(buffer,0,read);
  }
  byte[] md5sum=digest.digest();
  BigInteger bigInt=new BigInteger(1,md5sum);
  return bigInt.toString(HEX_RADIX);
}
 

Example 19

From project authme-2.0, under directory /src/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  31 
vote

private static String getMD5(String message) throws NoSuchAlgorithmException {
  MessageDigest md5=MessageDigest.getInstance("MD5");
  md5.reset();
  md5.update(message.getBytes());
  byte[] digest=md5.digest();
  return String.format("%0" + (digest.length << 1) + "x",new BigInteger(1,digest));
}
 

Example 20

From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  31 
vote

private static String getMD5(String message) throws NoSuchAlgorithmException {
  MessageDigest md5=MessageDigest.getInstance("MD5");
  md5.reset();
  md5.update(message.getBytes());
  byte[] digest=md5.digest();
  return String.format("%0" + (digest.length << 1) + "x",new BigInteger(1,digest));
}
 

Example 21

From project AuthMe-Reloaded-Charge-fix, under directory /src/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  31 
vote

private static String getMD5(String message) throws NoSuchAlgorithmException {
  MessageDigest md5=MessageDigest.getInstance("MD5");
  md5.reset();
  md5.update(message.getBytes());
  byte[] digest=md5.digest();
  return String.format("%0" + (digest.length << 1) + "x",new BigInteger(1,digest));
}
 

Example 22

From project avro, under directory /lang/java/avro/src/test/java/org/apache/avro/reflect/.

Source file: ByteBufferTest.java

  31 
vote

String getmd5(ByteBuffer buffer) throws NoSuchAlgorithmException {
  MessageDigest mdEnc=MessageDigest.getInstance("MD5");
  mdEnc.reset();
  mdEnc.update(buffer);
  return new BigInteger(1,mdEnc.digest()).toString(16);
}
 

Example 23

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: DeviceId.java

  31 
vote

public static String toSHA1(String input){
  try {
    int lenght=40;
    MessageDigest sha=MessageDigest.getInstance("SHA-1");
    byte[] messageDigest=sha.digest(input.getBytes());
    BigInteger number=new BigInteger(1,messageDigest);
    String out=number.toString(16);
    if (out.length() < lenght) {
      char[] charArray=new char[lenght];
      Arrays.fill(charArray,'0');
      out.getChars(0,out.length(),charArray,lenght - out.length());
      out=new String(charArray);
    }
    return out;
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return null;
}
 

Example 24

From project BetterShop_1, under directory /src/me/jascotty2/lib/io/.

Source file: CheckInput.java

  31 
vote

public static BigInteger GetBigInt(String str,long defaultNum){
  if (str == null) {
    return new BigInteger(String.valueOf(defaultNum));
  }
  try {
    return new BigInteger(str);
  }
 catch (  Exception e) {
    return new BigInteger(String.valueOf(defaultNum));
  }
}
 

Example 25

From project blueprint-namespaces, under directory /blueprint/blueprint-annotation-impl/src/main/java/org/apache/aries/blueprint/jaxb/.

Source file: Tblueprint.java

  31 
vote

/** 
 * Gets the value of the defaultTimeout property.
 * @return possible object is {@link BigInteger }
 */
public BigInteger getDefaultTimeout(){
  if (defaultTimeout == null) {
    return new BigInteger("300000");
  }
 else {
    return defaultTimeout;
  }
}
 

Example 26

From project bson4jackson, under directory /src/main/java/de/undercouch/bson4jackson/.

Source file: BsonParser.java

  31 
vote

@Override public BigInteger getBigIntegerValue() throws IOException, JsonParseException {
  Number n=getNumberValue();
  if (n == null) {
    return null;
  }
  if (n instanceof Byte || n instanceof Integer || n instanceof Long|| n instanceof Short) {
    return BigInteger.valueOf(n.longValue());
  }
 else   if (n instanceof Double || n instanceof Float) {
    return BigDecimal.valueOf(n.doubleValue()).toBigInteger();
  }
  return new BigInteger(n.toString());
}
 

Example 27

From project BSPAN---Bluetooth-Sensor-Processing-for-Android, under directory /AndroidSpineServer/src/com/t2/.

Source file: SharedPref.java

  31 
vote

private static String md5(String s){
  MessageDigest m=null;
  try {
    m=java.security.MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
  }
  if (m != null)   m.update(s.getBytes(),0,s.length());
  String hash=new BigInteger(1,m.digest()).toString();
  return hash;
}
 

Example 28

From project capedwarf-green, under directory /server-api/src/main/java/org/jboss/capedwarf/server/api/security/impl/.

Source file: BasicSecurityProvider.java

  31 
vote

public String hash(String... strings){
  if (strings == null || strings.length == 0)   throw new IllegalArgumentException("Null or empty strings: " + Arrays.toString(strings));
  try {
    MessageDigest m=MessageDigest.getInstance("MD5");
    StringBuilder builder=new StringBuilder();
    for (    String s : strings)     builder.append(s);
    builder.append(SALT);
    byte[] bytes=builder.toString().getBytes();
    m.update(bytes,0,bytes.length);
    BigInteger i=new BigInteger(1,m.digest());
    return String.format("%1$032X",i);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 29

From project Cassandra-Client-Tutorial, under directory /src/main/java/com/jeklsoft/cassandraclient/hector/.

Source file: HectorHeterogeneousSuperColumnExample.java

  31 
vote

private Reading getReadingFromSuperColumn(UUID sensorId,HSuperColumn row){
  DateTime timestamp=new DateTime(row.getName());
  BigDecimal temperature=null;
  Integer windSpeed=null;
  String windDirection=null;
  BigInteger humidity=null;
  Boolean badAirQualityDetected=null;
  List<HColumn<String,ByteBuffer>> columns=row.getColumns();
  for (  HColumn<String,ByteBuffer> column : columns) {
    if (temperatureNameColumnName.equals(column.getName())) {
      temperature=BigDecimalSerializer.get().fromByteBuffer(column.getValue());
    }
 else     if (windSpeedNameColumnName.equals(column.getName())) {
      windSpeed=IntegerSerializer.get().fromByteBuffer(column.getValue());
    }
 else     if (windDirectionNameColumnName.equals(column.getName())) {
      windDirection=StringSerializer.get().fromByteBuffer(column.getValue());
    }
 else     if (humidityNameColumnName.equals(column.getName())) {
      humidity=BigIntegerSerializer.get().fromByteBuffer(column.getValue());
    }
 else     if (badAirQualityDetectedNameColumnName.equals(column.getName())) {
      badAirQualityDetected=BooleanSerializer.get().fromByteBuffer(column.getValue());
    }
 else {
      throw new RuntimeException("Unknown column name " + column.getName());
    }
  }
  Validate.notNull(temperature,"Temperature not found in retrieved super column");
  Validate.notNull(windSpeed,"Wind speed not found in retrieved super column");
  Validate.notNull(windDirection,"Wind Direction not found in retrieved super column");
  Validate.notNull(humidity,"Humidity not found in retrieved super column");
  Validate.notNull(badAirQualityDetected,"Bad air quality detection not found in retrieved super column");
  Reading reading=new Reading(sensorId,timestamp,temperature,windSpeed,windDirection,humidity,badAirQualityDetected);
  return reading;
}
 

Example 30

From project anadix, under directory /anadix-tests/src/test/java/org/anadix/section508/rules/.

Source file: RulesetTest.java

  30 
vote

public RulesetTest(String source) throws IllegalStateException {
  KnowledgeBuilder kbuilder=KnowledgeBuilderFactory.newKnowledgeBuilder();
  kbuilder.add(ResourceFactory.newClassPathResource("commons.drl",Section508.class),ResourceType.DRL);
  kbuilder.add(ResourceFactory.newClassPathResource(source,Section508.class),ResourceType.DRL);
  kbuilder.add(ResourceFactory.newClassPathResource("query.drl",getClass()),ResourceType.DRL);
  if (kbuilder.hasErrors()) {
    throw new IllegalStateException(kbuilder.getErrors().toString());
  }
  kbase=KnowledgeBaseFactory.newKnowledgeBase();
  kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
  factory=new HTMLElementFactory(KnowledgeBaseFactory.newKnowledgeBase().newStatefulKnowledgeSession());
  html=factory.createHtmlTag(new BigInteger("1"),new Properties());
  body=factory.createBodyTag(new BigInteger("101"),html,new Properties());
  id=BigInteger.ONE;
}
 

Example 31

From project Android, under directory /app/src/main/java/com/github/mobile/util/.

Source file: GravatarUtils.java

  30 
vote

private static String digest(final String value){
  if (MD5 == null)   return null;
  byte[] bytes;
  try {
    bytes=value.getBytes(CHARSET);
  }
 catch (  UnsupportedEncodingException e) {
    return null;
  }
synchronized (MD5) {
    MD5.reset();
    bytes=MD5.digest(bytes);
  }
  String hashed=new BigInteger(1,bytes).toString(16);
  int padding=HASH_LENGTH - hashed.length();
  if (padding == 0)   return hashed;
  char[] zeros=new char[padding];
  Arrays.fill(zeros,'0');
  return new StringBuilder(HASH_LENGTH).append(zeros).append(hashed).toString();
}
 

Example 32

From project apg, under directory /src/org/thialfihar/android/apg/.

Source file: Primes.java

  30 
vote

public static BigInteger getBestPrime(int keySize){
  String primeString;
  if (keySize >= (8192 + 6144) / 2) {
    primeString=P8192;
  }
 else   if (keySize >= (6144 + 4096) / 2) {
    primeString=P6144;
  }
 else   if (keySize >= (4096 + 3072) / 2) {
    primeString=P4096;
  }
 else   if (keySize >= (3072 + 2048) / 2) {
    primeString=P3072;
  }
 else   if (keySize >= (2048 + 1536) / 2) {
    primeString=P2048;
  }
 else {
    primeString=P1536;
  }
  return new BigInteger(primeString.replaceAll(" ",""),16);
}
 

Example 33

From project caseconductor-platform, under directory /utest-common/src/main/java/com/utest/util/.

Source file: CrytographicTool.java

  30 
vote

/** 
 * Encrypts a text.
 * @param source the plain text to encrypt.
 * @return the encrypted text.
 * @throws Exception
 */
public static String encrypt(final String source,final CryptoAlgorithm algorithm,final String blowfishKey) throws Exception {
  String result="";
  if (CryptoAlgorithm.BLOWFISH.equals(algorithm)) {
    final byte[] keyBytes=new BigInteger(blowfishKey,16).toByteArray();
    final Key key=new SecretKeySpec(keyBytes,"Blowfish");
    final BASE64Encoder encoder=new BASE64Encoder();
    final Cipher cipher=Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE,key);
    final byte[] ciphertext=cipher.doFinal(source.getBytes("UTF8"));
    result=encoder.encode(ciphertext);
    return result;
  }
  if (CryptoAlgorithm.DES.equals(algorithm)) {
    result=DES.encrypt(source);
  }
  return result;
}
 

Example 34

From project aether-core, under directory /aether-util/src/main/java/org/eclipse/aether/util/version/.

Source file: GenericVersion.java

  29 
vote

public int compareTo(Item that){
  int rel;
  if (that == null) {
switch (kind) {
case KIND_BIGINT:
case KIND_STRING:
      rel=1;
    break;
case KIND_INT:
case KIND_QUALIFIER:
  rel=((Integer)value).intValue();
break;
default :
throw new IllegalStateException("unknown version item kind " + kind);
}
}
 else {
rel=kind - that.kind;
if (rel == 0) {
switch (kind) {
case KIND_BIGINT:
rel=((BigInteger)value).compareTo((BigInteger)that.value);
break;
case KIND_INT:
case KIND_QUALIFIER:
rel=((Integer)value).compareTo((Integer)that.value);
break;
case KIND_STRING:
rel=((String)value).compareToIgnoreCase((String)that.value);
break;
default :
throw new IllegalStateException("unknown version item kind " + kind);
}
}
}
return rel;
}
 

Example 35

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/base64/.

Source file: Base64.java

  29 
vote

/** 
 * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
 * @param bigInt a BigInteger
 * @return A byte array containing base64 character data
 * @throws NullPointerException if null is passed in
 * @since 1.4
 */
public static byte[] encodeInteger(BigInteger bigInt){
  if (bigInt == null) {
    throw new NullPointerException("encodeInteger called with null parameter");
  }
  return encodeBase64(toIntegerBytes(bigInt),false);
}
 

Example 36

From project android-share-menu, under directory /src/org/apache/commons/codec_1_4/binary/.

Source file: Base64.java

  29 
vote

/** 
 * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
 * @param bigInt a BigInteger
 * @return A byte array containing base64 character data
 * @throws NullPointerException if null is passed in
 * @since 1.4
 */
public static byte[] encodeInteger(BigInteger bigInt){
  if (bigInt == null) {
    throw new NullPointerException("encodeInteger called with null parameter");
  }
  return encodeBase64(toIntegerBytes(bigInt),false);
}
 

Example 37

From project apjp, under directory /APJP_LOCAL_JAVA/src/main/java/APJP/HTTPS/.

Source file: HTTPS.java

  29 
vote

private static KeyStore getDefaultKeyStore() throws HTTPSException {
  try {
    if (defaultKeyStore == null) {
      defaultKeyStore=KeyStore.getInstance(KeyStore.getDefaultType());
      try {
        defaultKeyStore.load(new FileInputStream("APJP_LOCAL.jks"),"APJP".toCharArray());
      }
 catch (      Exception e) {
        defaultKeyStore.load(null,"APJP".toCharArray());
        KeyPairGenerator keyPairGenerator=new RSAKeyPairGenerator();
        keyPairGenerator.initialize(1024);
        KeyPair keyPair=keyPairGenerator.generateKeyPair();
        X509Certificate x509CertificateAuthority=new X509Certificate();
        Name name=new Name();
        name.addRDN(new ObjectID("2.5.4.3"),"APJP");
        name.addRDN(new ObjectID("2.5.4.10"),"APJP");
        name.addRDN(new ObjectID("2.5.4.11"),"APJP");
        x509CertificateAuthority.setSubjectDN(name);
        x509CertificateAuthority.setIssuerDN(name);
        x509CertificateAuthority.setValidNotBefore(new Date(new Date().getTime() - 1 * (1000L * 60 * 60* 24* 365)));
        x509CertificateAuthority.setValidNotAfter(new Date(new Date().getTime() + 10 * (1000L * 60 * 60* 24* 365)));
        x509CertificateAuthority.setSerialNumber(BigInteger.valueOf(new Date().getTime()));
        x509CertificateAuthority.setPublicKey(keyPair.getPublic());
        x509CertificateAuthority.sign(new AlgorithmID(new ObjectID("1.2.840.113549.1.1.5")),keyPair.getPrivate());
        x509CertificateAuthority.writeTo(new FileOutputStream("APJP_LOCAL.pem"));
        X509Certificate[] x509CertificateArray=new X509Certificate[1];
        x509CertificateArray[0]=x509CertificateAuthority;
        defaultKeyStore.setCertificateEntry("APJP",x509CertificateAuthority);
        defaultKeyStore.setKeyEntry("APJP",keyPair.getPrivate(),"APJP".toCharArray(),x509CertificateArray);
        defaultKeyStore.store(new FileOutputStream("APJP_LOCAL.jks"),"APJP".toCharArray());
      }
    }
    return defaultKeyStore;
  }
 catch (  Exception e) {
    logger.log(2,"HTTPS/GET_DEFAULT_KEY_STORE: EXCEPTION",e);
    throw new HTTPSException("HTTPS/GET_DEFAULT_KEY_STORE",e);
  }
}
 

Example 38

From project Arecibo, under directory /util/src/main/java/com/ning/arecibo/util/timeline/samples/.

Source file: ScalarSample.java

  29 
vote

public static double getDoubleValue(final SampleOpcode opcode,final Object sampleValue){
switch (opcode) {
case NULL:
case DOUBLE_ZERO:
case INT_ZERO:
    return 0.0;
case BYTE:
case BYTE_FOR_DOUBLE:
  return (double)((Byte)sampleValue);
case SHORT:
case SHORT_FOR_DOUBLE:
return (double)((Short)sampleValue);
case INT:
return (double)((Integer)sampleValue);
case LONG:
return (double)((Long)sampleValue);
case FLOAT:
case FLOAT_FOR_DOUBLE:
return (double)((Float)sampleValue);
case HALF_FLOAT_FOR_DOUBLE:
return (double)HalfFloat.toFloat((short)((Short)sampleValue));
case DOUBLE:
return (double)((Double)sampleValue);
case BIGINT:
return ((BigInteger)sampleValue).doubleValue();
default :
throw new IllegalArgumentException(String.format("In getDoubleValue(), sample opcode is %s, sample value is %s",opcode.name(),String.valueOf(sampleValue)));
}
}
 

Example 39

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/utils/.

Source file: Base64.java

  29 
vote

/** 
 * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
 * @param bigInt a BigInteger
 * @return A byte array containing base64 character data
 * @throws NullPointerException if null is passed in
 * @since 1.4
 */
public static byte[] encodeInteger(BigInteger bigInt){
  if (bigInt == null) {
    throw new NullPointerException("encodeInteger called with null parameter");
  }
  return encodeBase64(toIntegerBytes(bigInt),false);
}
 

Example 40

From project beanvalidation-tck, under directory /tests/src/main/java/org/hibernate/beanvalidation/tck/tests/constraints/builtinconstraints/.

Source file: BuiltinConstraintsTest.java

  29 
vote

@Test @SpecAssertions({@SpecAssertion(section="6",id="a"),@SpecAssertion(section="6",id="g")}) public void testMinConstraint(){
  Validator validator=TestUtil.getValidatorUnderTest();
  MinDummyEntity dummy=new MinDummyEntity();
  Set<ConstraintViolation<MinDummyEntity>> constraintViolations=validator.validate(dummy);
  assertCorrectNumberOfViolations(constraintViolations,4);
  assertCorrectPropertyPaths(constraintViolations,"bytePrimitive","intPrimitive","longPrimitive","shortPrimitive");
  dummy.intPrimitive=101;
  dummy.longPrimitive=1001;
  dummy.bytePrimitive=111;
  dummy.shortPrimitive=142;
  dummy.intObject=Integer.valueOf("100");
  dummy.longObject=Long.valueOf("0");
  dummy.byteObject=Byte.parseByte("-1");
  dummy.shortObject=Short.parseShort("3");
  dummy.bigDecimal=BigDecimal.valueOf(100.9);
  dummy.bigInteger=BigInteger.valueOf(100);
  constraintViolations=validator.validate(dummy);
  assertCorrectNumberOfViolations(constraintViolations,6);
  assertCorrectPropertyPaths(constraintViolations,"byteObject","intObject","longObject","shortObject","bigDecimal","bigInteger");
  dummy.intObject=Integer.valueOf("101");
  dummy.longObject=Long.valueOf("12345");
  dummy.byteObject=Byte.parseByte("102");
  dummy.shortObject=Short.parseShort("111");
  dummy.bigDecimal=BigDecimal.valueOf(101.1);
  dummy.bigInteger=BigInteger.valueOf(101);
  constraintViolations=validator.validate(dummy);
  assertCorrectNumberOfViolations(constraintViolations,0);
}
 

Example 41

From project brix-cms, under directory /brix-rmiserver/src/main/java/org/brixcms/rmiserver/web/admin/.

Source file: Base64.java

  29 
vote

/** 
 * Encode to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature
 * @param bigInt a BigInteger
 * @return A byte array containing base64 character data
 * @throws NullPointerException if null is passed in
 */
public static byte[] encodeInteger(BigInteger bigInt){
  if (bigInt == null) {
    throw new NullPointerException("encodeInteger called with null parameter");
  }
  return encodeBase64(toIntegerBytes(bigInt),false);
}
 

Example 42

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: CertificateGenerator.java

  29 
vote

public X509Certificate generateCertificate(KeyPair pair,String dn){
  try {
    X509v3CertificateBuilder builder=new X509v3CertificateBuilder(new X500Name("CN=" + dn),BigInteger.valueOf(new SecureRandom().nextLong()),new Date(System.currentTimeMillis() - 10000),new Date(System.currentTimeMillis() + 24L * 3600 * 1000),new X500Name("CN=" + dn),SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
    builder.addExtension(X509Extension.basicConstraints,true,new BasicConstraints(false));
    builder.addExtension(X509Extension.keyUsage,true,new KeyUsage(KeyUsage.digitalSignature));
    builder.addExtension(X509Extension.extendedKeyUsage,true,new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    X509CertificateHolder holder=builder.build(createContentSigner(pair));
    Certificate certificate=holder.toASN1Structure();
    return convertToJavaCertificate(certificate);
  }
 catch (  CertificateEncodingException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
catch (  OperatorCreationException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
catch (  CertIOException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
catch (  IOException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
catch (  CertificateException e) {
    throw new RuntimeException("Cannot generate X509 certificate",e);
  }
}
 

Example 43

From project Carolina-Digital-Repository, under directory /fcrepo-clients/src/main/java/edu/unc/lib/dl/fedora/.

Source file: AccessClient.java

  29 
vote

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);
  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;
}
 

Example 44

From project cas, under directory /cas-server-support-x509/src/test/java/org/jasig/cas/adaptors/x509/authentication/handler/support/.

Source file: CRLDistributionPointRevocationCheckerTests.java

  29 
vote

/** 
 * Gets the unit test parameters.
 * @return  Test parameter data.
 */
@Parameters public static Collection<Object[]> getTestParameters(){
  final Collection<Object[]> params=new ArrayList<Object[]>();
  Cache cache;
  final ThresholdExpiredCRLRevocationPolicy defaultPolicy=new ThresholdExpiredCRLRevocationPolicy();
  final ThresholdExpiredCRLRevocationPolicy zeroThresholdPolicy=new ThresholdExpiredCRLRevocationPolicy();
  zeroThresholdPolicy.setThreshold(0);
  cache=new Cache("crlCache-1",100,false,false,20,10);
  cache.initialise();
  params.add(new Object[]{new CRLDistributionPointRevocationChecker(cache),defaultPolicy,new String[]{"user-valid-distcrl.crt"},"userCA-valid.crl",null});
  cache=new Cache("crlCache-2",100,false,false,20,10);
  cache.initialise();
  params.add(new Object[]{new CRLDistributionPointRevocationChecker(cache),defaultPolicy,new String[]{"user-revoked-distcrl.crt"},"userCA-valid.crl",new RevokedCertificateException(new Date(),new BigInteger("1"))});
  cache=new Cache("crlCache-3",100,false,false,20,10);
  cache.initialise();
  params.add(new Object[]{new CRLDistributionPointRevocationChecker(cache),zeroThresholdPolicy,new String[]{"user-valid-distcrl.crt"},"userCA-expired.crl",new ExpiredCRLException("test",new Date())});
  cache=new Cache("crlCache-4",100,false,false,20,10);
  cache.initialise();
  params.add(new Object[]{new CRLDistributionPointRevocationChecker(cache),new RevocationPolicy<X509CRL>(){
    public void apply(    X509CRL crl){
    }
  }
,new String[]{"user-valid-distcrl.crt"},"userCA-expired.crl",null});
  cache=new Cache("crlCache-5",100,false,false,20,10);
  cache.initialise();
  final CRLDistributionPointRevocationChecker checker5=new CRLDistributionPointRevocationChecker(cache);
  checker5.setUnavailableCRLPolicy(new AllowRevocationPolicy());
  params.add(new Object[]{checker5,defaultPolicy,new String[]{"user-valid.crt"},"userCA-expired.crl",null});
  cache=new Cache("crlCache-6",100,false,false,20,10);
  cache.initialise();
  params.add(new Object[]{new CRLDistributionPointRevocationChecker(cache),defaultPolicy,new String[]{"user-revoked-distcrl2.crt"},"userCA-valid.crl",new RevokedCertificateException(new Date(),new BigInteger("1"))});
  return params;
}