List of usage examples for java.math BigInteger intValue
public int intValue()
From source file:org.opendaylight.netvirt.vpnmanager.VpnUtil.java
static String getVpnInterfaceName(OdlInterfaceRpcService odlInterfaceRpcService, BigInteger metadata) throws InterruptedException, ExecutionException { GetInterfaceFromIfIndexInputBuilder ifIndexInputBuilder = new GetInterfaceFromIfIndexInputBuilder(); BigInteger lportTag = MetaDataUtil.getLportFromMetadata(metadata); ifIndexInputBuilder.setIfIndex(lportTag.intValue()); GetInterfaceFromIfIndexInput input = ifIndexInputBuilder.build(); Future<RpcResult<GetInterfaceFromIfIndexOutput>> interfaceFromIfIndex = odlInterfaceRpcService .getInterfaceFromIfIndex(input); GetInterfaceFromIfIndexOutput interfaceFromIfIndexOutput; RpcResult<GetInterfaceFromIfIndexOutput> rpcResult = interfaceFromIfIndex.get(); if (rpcResult == null) { return null; }/*from w ww . ja va 2 s . c om*/ interfaceFromIfIndexOutput = rpcResult.getResult(); String interfaceName = interfaceFromIfIndexOutput.getInterfaceName(); return interfaceName; }
From source file:org.apache.tajo.querymaster.Repartitioner.java
public static void scheduleRangeShuffledFetches(TaskSchedulerContext schedulerContext, MasterPlan masterPlan, Stage stage, DataChannel channel, int maxNum) throws IOException { ExecutionBlock execBlock = stage.getBlock(); ScanNode scan = execBlock.getScanNodes()[0]; ExecutionBlock sampleChildBlock = masterPlan.getChild(stage.getId(), 0); SortNode sortNode = PlannerUtil.findTopNode(sampleChildBlock.getPlan(), NodeType.SORT); SortSpec[] sortSpecs = sortNode.getSortKeys(); Schema sortSchema = SchemaBuilder.builder().addAll(channel.getShuffleKeys()).build(); TupleRange[] ranges;//from w w w . j a v a 2 s. c om int determinedTaskNum; // calculate the number of maximum query ranges TableStats totalStat = computeChildBlocksStats(stage.getContext(), masterPlan, stage.getId()); // If there is an empty table in inner join, it should return zero rows. if (totalStat.getNumBytes() == 0 && totalStat.getColumnStats().size() == 0) { return; } TupleRange mergedRange = TupleUtil.columnStatToRange(sortSpecs, sortSchema, totalStat.getColumnStats(), false); if (sortNode.getSortPurpose() == SortPurpose.STORAGE_SPECIFIED) { String dataFormat = PlannerUtil.getDataFormat(masterPlan.getLogicalPlan()); CatalogService catalog = stage.getContext().getQueryMasterContext().getWorkerContext().getCatalog(); LogicalRootNode rootNode = masterPlan.getLogicalPlan().getRootBlock().getRoot(); TableDesc tableDesc = null; try { tableDesc = PlannerUtil.getTableDesc(catalog, rootNode.getChild()); } catch (UndefinedTableException e) { throw new IOException("Can't get table meta data from catalog: " + PlannerUtil.getStoreTableName(masterPlan.getLogicalPlan())); } Tablespace space = TablespaceManager.getAnyByScheme(dataFormat).get(); ranges = space.getInsertSortRanges(stage.getContext().getQueryContext(), tableDesc, sortNode.getInSchema(), sortSpecs, mergedRange); determinedTaskNum = ranges.length; } else { RangePartitionAlgorithm partitioner = new UniformRangePartition(mergedRange, sortSpecs); BigInteger card = partitioner.getTotalCardinality(); // if the number of the range cardinality is less than the desired number of tasks, // we set the the number of tasks to the number of range cardinality. if (card.compareTo(BigInteger.valueOf(maxNum)) < 0) { LOG.info(stage.getId() + ", The range cardinality (" + card + ") is less then the desired number of tasks (" + maxNum + ")"); determinedTaskNum = card.intValue(); } else { determinedTaskNum = maxNum; } LOG.info(stage.getId() + ", Try to divide " + mergedRange + " into " + determinedTaskNum + " sub ranges (total units: " + determinedTaskNum + ")"); ranges = partitioner.partition(determinedTaskNum); if (ranges == null) { throw new NullPointerException("ranges is null on " + stage.getId() + " stage."); } if (ranges.length == 0) { LOG.warn(stage.getId() + " no range infos."); } TupleUtil.setMaxRangeIfNull(sortSpecs, sortSchema, totalStat.getColumnStats(), ranges); if (LOG.isDebugEnabled()) { for (TupleRange eachRange : ranges) { LOG.debug(stage.getId() + " range: " + eachRange.getStart() + " ~ " + eachRange.getEnd()); } } } // TODO - We should remove dummy fragment. FileFragment dummyFragment = new FileFragment(scan.getTableName(), new Path("/dummy"), 0, 0, new String[] { UNKNOWN_HOST }); Stage.scheduleFragment(stage, dummyFragment); Map<Pair<PullHost, ExecutionBlockId>, FetchImpl> fetches = new HashMap<>(); List<ExecutionBlock> childBlocks = masterPlan.getChilds(stage.getId()); for (ExecutionBlock childBlock : childBlocks) { Stage childExecSM = stage.getContext().getStage(childBlock.getId()); for (Task qu : childExecSM.getTasks()) { for (IntermediateEntry p : qu.getIntermediateData()) { Pair<PullHost, ExecutionBlockId> key = new Pair<>(p.getPullHost(), childBlock.getId()); if (fetches.containsKey(key)) { fetches.get(key).addPart(p.getTaskId(), p.getAttemptId()); } else { FetchImpl fetch = new FetchImpl(scan.getTableName(), p.getPullHost(), RANGE_SHUFFLE, childBlock.getId(), 0); fetch.addPart(p.getTaskId(), p.getAttemptId()); fetches.put(key, fetch); } } } } SortedMap<TupleRange, Collection<FetchProto>> map; map = new TreeMap<>(); Set<FetchProto> fetchSet; RowStoreUtil.RowStoreEncoder encoder = RowStoreUtil.createEncoder(sortSchema); for (int i = 0; i < ranges.length; i++) { fetchSet = new HashSet<>(); RangeParam rangeParam = new RangeParam(ranges[i], i == (ranges.length - 1), encoder); for (FetchImpl fetch : fetches.values()) { FetchImpl copy = null; try { copy = fetch.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } copy.setRangeParams(rangeParam); fetchSet.add(copy.getProto()); } map.put(ranges[i], fetchSet); } scheduleFetchesByRoundRobin(stage, map, scan.getTableName(), determinedTaskNum); schedulerContext.setEstimatedTaskNum(determinedTaskNum); }
From source file:org.owasp.jbrofuzz.core.FuzzerBigInteger.java
/** * <p>Return the next element of the fuzzer during iteration.</p> * // w w w . ja v a 2s .c o m * <p>This method should be used to access fuzzing payloads, after * construction of the fuzzer object.</p> * * @return String The next fuzzer payload, during the iteration * process * * @author subere@uncon.org * @version 2.4 * @since 1.2 */ public String next() { final StringBuffer output = new StringBuffer(""); // Replacive Prototype if (maxValue.compareTo(BigInteger.valueOf(payloads.size())) == 0) { output.append(payloads.get(cValue.intValue())); cValue = cValue.add(BigInteger.ONE); } // Recursive Prototype else { BigInteger val = cValue; // Perform division on a stack final Stack<BigInteger> stack = new Stack<BigInteger>(); while (val.compareTo(BigInteger.valueOf(payloads.size())) >= 0) { stack.push(val.mod(BigInteger.valueOf(payloads.size()))); val = val.divide(BigInteger.valueOf(payloads.size())); } // Append the relevant empty positions with the first element // identified output.append(StringUtils.leftPad(payloads.get(val.intValue()), len - stack.size(), payloads.get(0))); while (!stack.isEmpty()) { output.append(payloads.get(stack.pop().intValue())); } cValue = cValue.add(BigInteger.ONE); } return output.toString(); }
From source file:org.openhie.openempi.dao.hibernate.PersonDaoHibernate.java
private int getFieldPresentNumberInHibernate(Session session, String tableName, String field) { //ValidationUtil.sanityCheckFieldName(field); String fieldLowerCase = field.toLowerCase(); StringBuilder sqlSelect = new StringBuilder("SELECT COUNT("); sqlSelect.append(COLUMN_NAME_PREFIX + fieldLowerCase); sqlSelect.append(") FROM public." + getTableFullName(tableName)); sqlSelect.append(" WHERE "); sqlSelect.append(COLUMN_NAME_PREFIX + fieldLowerCase); sqlSelect.append(" IS NOT NULL;"); java.math.BigInteger bigInt = (java.math.BigInteger) session.createSQLQuery(sqlSelect.toString()) .uniqueResult();/*from w w w . j a v a 2 s. c om*/ int numOfNotNull = bigInt.intValue(); // Another possible solution for the opposite (counting NULL columns): // SELECT SUM(CASE WHEN ColumnName IS NULL THEN 1 ELSE 0 END) FROM Table return numOfNotNull; }
From source file:org.apache.tajo.master.querymaster.Repartitioner.java
public static void scheduleRangeShuffledFetches(TaskSchedulerContext schedulerContext, MasterPlan masterPlan, Stage stage, DataChannel channel, int maxNum) throws IOException { ExecutionBlock execBlock = stage.getBlock(); ScanNode scan = execBlock.getScanNodes()[0]; Path tablePath;/*from www . ja v a 2s. c om*/ tablePath = ((FileStorageManager) StorageManager.getFileStorageManager(stage.getContext().getConf())) .getTablePath(scan.getTableName()); ExecutionBlock sampleChildBlock = masterPlan.getChild(stage.getId(), 0); SortNode sortNode = PlannerUtil.findTopNode(sampleChildBlock.getPlan(), NodeType.SORT); SortSpec[] sortSpecs = sortNode.getSortKeys(); Schema sortSchema = new Schema(channel.getShuffleKeys()); TupleRange[] ranges; int determinedTaskNum; // calculate the number of maximum query ranges TableStats totalStat = computeChildBlocksStats(stage.getContext(), masterPlan, stage.getId()); // If there is an empty table in inner join, it should return zero rows. if (totalStat.getNumBytes() == 0 && totalStat.getColumnStats().size() == 0) { return; } TupleRange mergedRange = TupleUtil.columnStatToRange(sortSpecs, sortSchema, totalStat.getColumnStats(), false); if (sortNode.getSortPurpose() == SortPurpose.STORAGE_SPECIFIED) { StoreType storeType = PlannerUtil.getStoreType(masterPlan.getLogicalPlan()); CatalogService catalog = stage.getContext().getQueryMasterContext().getWorkerContext().getCatalog(); LogicalRootNode rootNode = masterPlan.getLogicalPlan().getRootBlock().getRoot(); TableDesc tableDesc = PlannerUtil.getTableDesc(catalog, rootNode.getChild()); if (tableDesc == null) { throw new IOException("Can't get table meta data from catalog: " + PlannerUtil.getStoreTableName(masterPlan.getLogicalPlan())); } ranges = StorageManager.getStorageManager(stage.getContext().getConf(), storeType).getInsertSortRanges( stage.getContext().getQueryContext(), tableDesc, sortNode.getInSchema(), sortSpecs, mergedRange); determinedTaskNum = ranges.length; } else { RangePartitionAlgorithm partitioner = new UniformRangePartition(mergedRange, sortSpecs); BigInteger card = partitioner.getTotalCardinality(); // if the number of the range cardinality is less than the desired number of tasks, // we set the the number of tasks to the number of range cardinality. if (card.compareTo(BigInteger.valueOf(maxNum)) < 0) { LOG.info(stage.getId() + ", The range cardinality (" + card + ") is less then the desired number of tasks (" + maxNum + ")"); determinedTaskNum = card.intValue(); } else { determinedTaskNum = maxNum; } LOG.info(stage.getId() + ", Try to divide " + mergedRange + " into " + determinedTaskNum + " sub ranges (total units: " + determinedTaskNum + ")"); ranges = partitioner.partition(determinedTaskNum); if (ranges == null || ranges.length == 0) { LOG.warn(stage.getId() + " no range infos."); } TupleUtil.setMaxRangeIfNull(sortSpecs, sortSchema, totalStat.getColumnStats(), ranges); if (LOG.isDebugEnabled()) { if (ranges != null) { for (TupleRange eachRange : ranges) { LOG.debug(stage.getId() + " range: " + eachRange.getStart() + " ~ " + eachRange.getEnd()); } } } } FileFragment dummyFragment = new FileFragment(scan.getTableName(), tablePath, 0, 0, new String[] { UNKNOWN_HOST }); Stage.scheduleFragment(stage, dummyFragment); List<FetchImpl> fetches = new ArrayList<FetchImpl>(); List<ExecutionBlock> childBlocks = masterPlan.getChilds(stage.getId()); for (ExecutionBlock childBlock : childBlocks) { Stage childExecSM = stage.getContext().getStage(childBlock.getId()); for (Task qu : childExecSM.getTasks()) { for (IntermediateEntry p : qu.getIntermediateData()) { FetchImpl fetch = new FetchImpl(p.getPullHost(), RANGE_SHUFFLE, childBlock.getId(), 0); fetch.addPart(p.getTaskId(), p.getAttemptId()); fetches.add(fetch); } } } boolean ascendingFirstKey = sortSpecs[0].isAscending(); SortedMap<TupleRange, Collection<FetchImpl>> map; if (ascendingFirstKey) { map = new TreeMap<TupleRange, Collection<FetchImpl>>(); } else { map = new TreeMap<TupleRange, Collection<FetchImpl>>(new TupleRange.DescendingTupleRangeComparator()); } Set<FetchImpl> fetchSet; try { RowStoreUtil.RowStoreEncoder encoder = RowStoreUtil.createEncoder(sortSchema); for (int i = 0; i < ranges.length; i++) { fetchSet = new HashSet<FetchImpl>(); for (FetchImpl fetch : fetches) { String rangeParam = TupleUtil.rangeToQuery(ranges[i], ascendingFirstKey ? i == (ranges.length - 1) : i == 0, encoder); FetchImpl copy = null; try { copy = fetch.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } copy.setRangeParams(rangeParam); fetchSet.add(copy); } map.put(ranges[i], fetchSet); } } catch (UnsupportedEncodingException e) { LOG.error(e); } scheduleFetchesByRoundRobin(stage, map, scan.getTableName(), determinedTaskNum); schedulerContext.setEstimatedTaskNum(determinedTaskNum); }
From source file:com.linute.linute.API.MyGcmListenerService.java
/** * Create and show a simple notification containing the received GCM message. * * @param data GCM Bundle received.// w ww .ja va2 s .c om */ private void sendNotification(Bundle data, String action) { Intent intent = buildIntent(data, action); PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_ONE_SHOT); //Log.d(TAG, data.toString()); String message = data.getString("message"); //int type = gettNotificationType(data.getString("action")); //String name = data.getString("ownerFullName"); boolean isAnon = "1".equals(data.getString("privacy")); String profileImage = null; switch (action) { case "messager": try { JSONObject image = new JSONObject(data.getString("roomProfileImage")); profileImage = image.getString("original"); } catch (JSONException | NullPointerException e) { } break; default: profileImage = data.getString("ownerProfileImage"); profileImage = (isAnon ? Utils.getAnonImageUrl(String.valueOf(profileImage)) : Utils.getImageUrlOfUser(String.valueOf(profileImage))); } Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); ChatRoom chatRoom = (ChatRoom) intent.getParcelableExtra("chatRoom"); String title = chatRoom != null ? chatRoom.getRoomName() : "Tapt"; final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_untitled_4_01).setColor(Color.BLACK).setContentTitle(title) .setContentText(message).setAutoCancel(true).setSound(defaultSoundUri) .setContentIntent(pendingIntent).setStyle(new NotificationCompat.BigTextStyle().bigText(message)); if (profileImage != null) { File image = null; try { image = Glide.with(this).load(profileImage).downloadOnly(256, 256).get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } if (image != null) { /*ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo(); manager.getMemoryInfo(info);*/ notificationBuilder.setLargeIcon(getCircleBitmap(image)); } } BigInteger notificationId; Object ownerId = data.get("room"); Object eventId = data.get("event"); if (eventId != null) { notificationId = new BigInteger(String.valueOf(eventId), 16); } else if (ownerId != null) { notificationId = new BigInteger(String.valueOf(ownerId), 16); } else { notificationId = BigInteger.ZERO; } final int notifId = notificationId.intValue(); Notification notifications = notificationBuilder.build(); NotificationManagerCompat.from(this).notify(notificationId.intValue(), notifications); }
From source file:com.sourcesense.opencmis.server.TypeManager.java
/** * CMIS getTypesChildren./* w w w . j av a 2s .c om*/ */ public TypeDefinitionList getTypesChildren(CallContext context, String typeId, boolean includePropertyDefinitions, BigInteger maxItems, BigInteger skipCount) { TypeDefinitionListImpl result = new TypeDefinitionListImpl(); result.setList(new ArrayList<TypeDefinition>()); result.setHasMoreItems(false); result.setNumItems(BigInteger.valueOf(0)); int skip = (skipCount == null ? 0 : skipCount.intValue()); if (skip < 0) { skip = 0; } int max = (maxItems == null ? Integer.MAX_VALUE : maxItems.intValue()); if (max < 1) { return result; } if (typeId == null) { if (skip < 1) { result.getList().add(copyTypeDefintion(fTypes.get(FOLDER_TYPE_ID).getTypeDefinition())); max--; } if ((skip < 2) && (max > 0)) { result.getList().add(copyTypeDefintion(fTypes.get(DOCUMENT_TYPE_ID).getTypeDefinition())); max--; } result.setHasMoreItems((result.getList().size() + skip) < 2); result.setNumItems(BigInteger.valueOf(2)); } else { TypeDefinitionContainer tc = fTypes.get(typeId); if ((tc == null) || (tc.getChildren() == null)) { return result; } for (TypeDefinitionContainer child : tc.getChildren()) { if (skip > 0) { skip--; continue; } result.getList().add(copyTypeDefintion(child.getTypeDefinition())); max--; if (max == 0) { break; } } result.setHasMoreItems((result.getList().size() + skip) < tc.getChildren().size()); result.setNumItems(BigInteger.valueOf(tc.getChildren().size())); } if (!includePropertyDefinitions) { for (TypeDefinition type : result.getList()) { type.getPropertyDefinitions().clear(); } } return result; }
From source file:org.openhie.openempi.dao.hibernate.PersonDaoHibernate.java
public int getFieldNumberOfMissing(final String tableName, final String field) { if (field == null || field.length() == 0) { return 0; }/* w w w . ja v a 2s. co m*/ //ValidationUtil.sanityCheckFieldName(field); return (Integer) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { String fieldLowerCase = field.toLowerCase(); StringBuilder sqlSelect = new StringBuilder("SELECT SUM(CASE WHEN "); sqlSelect.append(COLUMN_NAME_PREFIX + fieldLowerCase); sqlSelect.append(" IS NULL THEN 1 ELSE 0 END) FROM "); sqlSelect.append(getTableFullName(tableName) + ";"); java.math.BigInteger bigInt = (java.math.BigInteger) session.createSQLQuery(sqlSelect.toString()) .uniqueResult(); int numOfMissing = bigInt.intValue(); return numOfMissing; } }); }
From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransactionTest.java
@Test public void testTransactionAtomicity() throws Exception { // This test runs multiple transactions in parallel, with KeyValueService.put calls throwing // a RuntimeException from time to time and hanging other times. which effectively kills the // thread. We ensure that every transaction either adds 5 rows to the table or adds 0 rows // by checking at the end that the number of rows is a multiple of 5. final String tableName = "table"; Random random = new Random(1); final UnstableKeyValueService unstableKvs = new UnstableKeyValueService(keyValueService, random); final TestTransactionManager unstableTransactionManager = new TestTransactionManagerImpl(unstableKvs, timestampService, lockClient, lockService, transactionService, conflictDetectionManager, sweepStrategyManager);// ww w.j a va 2 s. co m ScheduledExecutorService service = PTExecutors.newScheduledThreadPool(20); for (int i = 0; i < 30; i++) { final int threadNumber = i; service.schedule(new Callable<Void>() { @Override public Void call() throws Exception { if (threadNumber == 10) { unstableKvs.setRandomlyThrow(true); } if (threadNumber == 20) { unstableKvs.setRandomlyHang(true); } Transaction transaction = unstableTransactionManager.createNewTransaction(); BatchingVisitable<RowResult<byte[]>> results = transaction.getRange(tableName, RangeRequest.builder().build()); final MutableInt nextIndex = new MutableInt(0); results.batchAccept(1, AbortingVisitors.batching(new AbortingVisitor<RowResult<byte[]>, Exception>() { @Override public boolean visit(RowResult<byte[]> row) throws Exception { byte[] dataBytes = row.getColumns().get("data".getBytes()); BigInteger dataValue = new BigInteger(dataBytes); nextIndex.setValue(Math.max(nextIndex.toInteger(), dataValue.intValue() + 1)); return true; } })); // nextIndex now contains the least row number not already in the table. Add 5 more // rows to the table. for (int j = 0; j < 5; j++) { int rowNumber = nextIndex.toInteger() + j; Cell cell = Cell.create(("row" + rowNumber).getBytes(), "data".getBytes()); transaction.put(tableName, ImmutableMap.of(cell, BigInteger.valueOf(rowNumber).toByteArray())); Thread.yield(); } transaction.commit(); return null; } }, i * 20, TimeUnit.MILLISECONDS); } service.shutdown(); service.awaitTermination(1, TimeUnit.SECONDS); // Verify each table has a number of rows that's a multiple of 5 Transaction verifyTransaction = txManager.createNewTransaction(); BatchingVisitable<RowResult<byte[]>> results = verifyTransaction.getRange(tableName, RangeRequest.builder().build()); final MutableInt numRows = new MutableInt(0); results.batchAccept(1, AbortingVisitors.batching(new AbortingVisitor<RowResult<byte[]>, Exception>() { @Override public boolean visit(RowResult<byte[]> row) throws Exception { numRows.increment(); return true; } })); Assert.assertEquals(0, numRows.toInteger() % 5); }
From source file:de.undercouch.bson4jackson.BsonGenerator.java
@Override public void writeNumber(BigInteger v) throws IOException, JsonGenerationException { int bl = v.bitLength(); if (bl < 32) { writeNumber(v.intValue()); } else if (bl < 64) { writeNumber(v.longValue());//from ww w . j a v a2 s . c om } else { writeString(v.toString()); } }