List of usage examples for java.math BigInteger ZERO
BigInteger ZERO
To view the source code for java.math BigInteger ZERO.
Click Source Link
From source file:Networking.Client.java
public void Calculateg_xy_mod() { this.node.setG_pow_modp(this.node.getG_pow_y().modPow(this.node.getX(), this.node.getP())); this.node.setX(BigInteger.ZERO); }
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
private void stepTwoA() throws Exception { byte[] send;/*from w w w. java2 s . c om*/ BigInteger n = this.pubKey.getModulus(); loggerInstance.log(getClass(), "Step 2a: Starting the search", Logger.LogLevel.INFO); // si = ceil(n/(3B)) BigInteger tmp[] = n.divideAndRemainder(BigInteger.valueOf(3).multiply(bigB)); if (BigInteger.ZERO.compareTo(tmp[1]) != 0) { this.si = tmp[0].add(BigInteger.ONE); } else { this.si = tmp[0]; } // correction will be done in do while this.si = this.si.subtract(BigInteger.ONE); IHttpRequestResponse response; byte[] request; do { // Check if user has cancelled the worker if (isCancelled()) { loggerInstance.log(getClass(), "Decryption Attack Executor Worker cancelled by user", Logger.LogLevel.INFO); return; } this.si = this.si.add(BigInteger.ONE); send = prepareMsg(this.c0, this.si); request = this.requestResponse.getRequest(); String[] components = Decoder.getComponents(this.parameter.getJoseValue()); components[1] = Decoder.base64UrlEncode(send); String newComponentsConcatenated = Decoder.concatComponents(components); request = JoseParameter.updateRequest(request, this.parameter, helpers, newComponentsConcatenated); response = callbacks.makeHttpRequest(this.httpService, request); updateAmountRequest(); } while (oracle.getResult(response.getResponse()) != BleichenbacherPkcs1Oracle.Result.VALID); loggerInstance.log(getClass(), "Matching response: " + helpers.bytesToString(response.getResponse()), Logger.LogLevel.DEBUG); }
From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POCast.java
@Override public Result getNextBigInteger() throws ExecException { PhysicalOperator in = inputs.get(0); Byte resultType = in.getResultType(); switch (resultType) { case DataType.BAG: case DataType.TUPLE: case DataType.MAP: case DataType.DATETIME: return error(); case DataType.BYTEARRAY: { DataByteArray dba;/*from ww w. j ava 2 s . com*/ Result res = in.getNextDataByteArray(); if (res.returnStatus == POStatus.STATUS_OK && res.result != null) { try { dba = (DataByteArray) res.result; } catch (ClassCastException e) { // res.result is not of type ByteArray. But it can be one of the types from which cast is still possible. if (realType == null) { // Find the type and cache it. realType = DataType.findType(res.result); } try { res.result = DataType.toBigInteger(res.result, realType); } catch (ClassCastException cce) { // Type has changed. Need to find type again and try casting it again. realType = DataType.findType(res.result); res.result = DataType.toBigInteger(res.result, realType); } return res; } try { if (null != caster) { res.result = caster.bytesToBigInteger(dba.get()); } else { int errCode = 1075; String msg = unknownByteArrayErrorMessage + "BigInteger."; throw new ExecException(msg, errCode, PigException.INPUT); } } catch (ExecException ee) { throw ee; } catch (IOException e) { log.error("Error while casting from ByteArray to BigInteger"); } } return res; } case DataType.BOOLEAN: { Result res = in.getNextBoolean(); if (res.returnStatus == POStatus.STATUS_OK && res.result != null) { if ((Boolean) res.result) { res.result = BigInteger.ONE; } else { res.result = BigInteger.ZERO; } } return res; } case DataType.INTEGER: { Result res = in.getNextInteger(); if (res.returnStatus == POStatus.STATUS_OK && res.result != null) { res.result = BigInteger.valueOf(((Integer) res.result).longValue()); } return res; } case DataType.DOUBLE: { Result res = in.getNextDouble(); if (res.returnStatus == POStatus.STATUS_OK && res.result != null) { res.result = BigInteger.valueOf(((Double) res.result).longValue()); } return res; } case DataType.LONG: { Result res = in.getNextLong(); if (res.returnStatus == POStatus.STATUS_OK && res.result != null) { res.result = BigInteger.valueOf(((Long) res.result).longValue()); } return res; } case DataType.FLOAT: { Result res = in.getNextFloat(); if (res.returnStatus == POStatus.STATUS_OK && res.result != null) { res.result = BigInteger.valueOf(((Float) res.result).longValue()); } return res; } case DataType.CHARARRAY: { Result res = in.getNextString(); if (res.returnStatus == POStatus.STATUS_OK && res.result != null) { res.result = new BigInteger((String) res.result); } return res; } case DataType.BIGINTEGER: { return in.getNextBigInteger(); } case DataType.BIGDECIMAL: { Result res = in.getNextBigDecimal(); if (res.returnStatus == POStatus.STATUS_OK && res.result != null) { res.result = ((BigDecimal) res.result).toBigInteger(); } return res; } } return error(); }
From source file:io.ecarf.core.cloud.task.processor.reason.phase2.DoReasonTask8.java
@Override public void run() throws IOException { GoogleCloudService cloud = (GoogleCloudService) this.getCloudService(); Stopwatch stopwatch1 = Stopwatch.createUnstarted(); Stopwatch stopwatch2 = Stopwatch.createUnstarted(); Set<String> termsSet; if (terms == null) { // too large, probably saved as a file log.info("Using json file for terms: " + termsFile); Validate.notNull(termsFile);// www. j a va 2 s . co m String localTermsFile = Utils.TEMP_FOLDER + termsFile; cloud.downloadObjectFromCloudStorage(termsFile, localTermsFile, bucket); // convert from JSON termsSet = io.cloudex.framework.utils.FileUtils.jsonFileToSet(localTermsFile); } else { termsSet = ObjectUtils.csvToSet(terms); } String localSchemaFile = Utils.TEMP_FOLDER + schemaFile; // download the file from the cloud storage cloud.downloadObjectFromCloudStorage(schemaFile, localSchemaFile, bucket); // uncompress if compressed if (GzipUtils.isCompressedFilename(schemaFile)) { localSchemaFile = GzipUtils.getUncompressedFilename(localSchemaFile); } Map<Long, Set<Triple>> allSchemaTriples = TripleUtils.getRelevantSchemaETriples(localSchemaFile, TermUtils.RDFS_TBOX); // get all the triples we care about schemaTerms = new HashMap<>(); for (String termStr : termsSet) { Long term = Long.parseLong(termStr); if (allSchemaTriples.containsKey(term)) { schemaTerms.put(term, allSchemaTriples.get(term)); } } String decoratedTable = table; int emptyRetries = 0; int totalInferredTriples = 0; int maxRetries = Config.getIntegerProperty(Constants.REASON_RETRY_KEY, 6); this.ddLimit = Config.getIntegerProperty(Constants.REASON_DATA_DIRECT_DOWNLOAD_LIMIT, 1_200_000); String instanceId = cloud.getInstanceId(); QueryGenerator<Long> generator = new QueryGenerator<Long>(schemaTerms, null); // timestamp loop do { Set<Long> productiveTerms = new HashSet<>(); int interimInferredTriples = 0; // First of all run all the queries asynchronously and remember the jobId and filename for each term List<QueryResult> queryResults = new ArrayList<QueryResult>(); generator.setDecoratedTable(decoratedTable); List<String> queries = generator.getQueries(); log.debug("Generated Queries: " + queries); String queryResultFilePrefix = instanceId + '_' + System.currentTimeMillis() + "_QueryResults_"; int fileCount = 0; for (String query : queries) { String jobId = cloud.startBigDataQuery(query, new BigDataTable(this.table)); queryResults .add(QueryResult.create().setFilename(queryResultFilePrefix + fileCount).setJobId(jobId)); fileCount++; } // invoke all the queries in parallel //this.invokeAll(queryTasks); long start = System.currentTimeMillis(); String inferredTriplesFile = Utils.TEMP_FOLDER + instanceId + '_' + start + Constants.DOT_INF; // save all the query results in files in parallel //this.invokeAll(saveTasks); for (QueryResult queryResult : queryResults) { try { // block and wait for each job to complete then save results to a file QueryStats stats = cloud.saveBigQueryResultsToFile(queryResult.getJobId(), queryResult.getFilename(), this.bucket, null, this.ddLimit); queryResult.setStats(stats); } catch (IOException ioe) { log.error("failed to save query results to file, jobId: " + queryResult.getJobId(), ioe); throw ioe; } } try (PrintWriter writer = new PrintWriter( new GZIPOutputStream(new FileOutputStream(inferredTriplesFile), Constants.GZIP_BUF_SIZE))) { // now loop through the queries //for(Entry<Term, Set<Triple>> entry: schemaTerms.entrySet()) { for (QueryResult queryResult : queryResults) { //Term term = entry.getKey(); QueryStats stats = queryResult.getStats(); BigInteger rows = stats.getTotalRows();//term.getRows(); this.totalBytes = this.totalBytes + stats.getTotalProcessedBytes();//term.getBytes(); // only process if triples are found matching this term if (!BigInteger.ZERO.equals(rows)) { stopwatch1.start(); int inferredTriplesCount = this.inferAndSaveTriplesToFile(queryResult, productiveTerms, writer); interimInferredTriples += inferredTriplesCount; this.totalRows = this.totalRows.add(rows); stopwatch1.stop(); } else { log.info("Skipping query as no data is found"); } } } totalInferredTriples += interimInferredTriples; if (interimInferredTriples > 0) { // stream smaller numbers of inferred triples // try uploading from cloud storage int streamingThreshold = Config.getIntegerProperty("ecarf.io.reasoning.streaming.threshold", 100000); log.info("Inserting " + interimInferredTriples + ", inferred triples into Big Data table for " + productiveTerms.size() + " productive terms. Filename: " + inferredTriplesFile); if (interimInferredTriples <= streamingThreshold) { // stream the data Set<Triple> inferredTriples = TripleUtils.loadCompressedCSVTriples(inferredTriplesFile, true); log.info("Total triples to stream into Big Data: " + inferredTriples.size()); cloud.streamObjectsIntoBigData(inferredTriples, TableUtils.getBigQueryEncodedTripleTable(table)); log.info("All inferred triples are streamed into Big Data table"); } else { // load the data through cloud storage // upload the file to cloud storage log.info("Uploading inferred triples file into cloud storage: " + inferredTriplesFile); StorageObject file = cloud.uploadFileToCloudStorage(inferredTriplesFile, bucket); log.info("File " + file + ", uploaded successfully. Now loading it into big data."); String jobId = cloud.loadCloudStorageFilesIntoBigData(Lists.newArrayList(file.getUri()), TableUtils.getBigQueryEncodedTripleTable(table), false); log.info( "All inferred triples are loaded into Big Data table through cloud storage, completed jobId: " + jobId); } // reset empty retries emptyRetries = 0; stopwatch2.reset(); } else { log.info("No new inferred triples"); // increment empty retries emptyRetries++; if (!stopwatch2.isRunning()) { stopwatch2.start(); } } log.info("Total inferred triples so far = " + totalInferredTriples + ", current retry count: " + emptyRetries); if (emptyRetries < maxRetries) { ApiUtils.block(Config.getIntegerProperty(Constants.REASON_SLEEP_KEY, 20)); // FIXME move into the particular cloud implementation service long elapsed = System.currentTimeMillis() - start; decoratedTable = "[" + table + "@-" + elapsed + "-]"; log.info("Using table decorator: " + decoratedTable + ". Empty retries count: " + emptyRetries); } } while (emptyRetries < maxRetries); // end timestamp loop //executor.shutdown(); log.info("Finished reasoning, total inferred triples = " + totalInferredTriples); //log.info("Number of avoided duplicate terms = " + this.duplicates); log.info("Total rows retrieved from big data = " + this.totalRows); log.info("Total processed GBytes = " + ((double) this.totalBytes / FileUtils.ONE_GB)); log.info("Total process reasoning time (serialization in inf file) = " + stopwatch1); log.info("Total time spent in empty inference cycles = " + stopwatch2); }
From source file:com.github.strawberry.guice.config.ConfigLoader.java
/** * Utility method to create a default non-null value for the given type * parameter. This gets called when {@link Redis#allowNull()} was set to * false for the given {@link Field}, and no value for the specified key(s) * (see {@link Redis#value()}) was present in the Redis database. * @param type The type to create the non-null value for. * @return A non-null instance of the type. Note: for primitives this will * obviously result in a boxed return value. *///from ww w . j a v a2 s. co m private static Object nonNullValueOf(Class<?> type) { Object value = null; if (type.equals(char[].class)) { value = new char[] {}; } else if (type.equals(Character[].class)) { value = new Character[] {}; } else if (type.equals(char.class) || type.equals(Character.class)) { value = '\0'; } else if (type.equals(String.class)) { value = ""; } else if (type.equals(byte[].class)) { value = new byte[] {}; } else if (type.equals(Byte[].class)) { value = new Byte[] {}; } else if (type.equals(byte.class) || type.equals(Byte.class)) { value = (byte) 0; } else if (type.equals(boolean.class) || type.equals(Boolean.class)) { value = false; } else if (type.equals(short.class) || type.equals(Short.class)) { value = (short) 0; } else if (type.equals(int.class) || type.equals(Integer.class)) { value = 0; } else if (type.equals(long.class) || type.equals(Long.class)) { value = 0L; } else if (type.equals(BigInteger.class)) { value = BigInteger.ZERO; } else if (type.equals(float.class) || type.equals(Float.class)) { value = 0.0f; } else if (type.equals(double.class) || type.equals(Double.class)) { value = 0.0; } else if (type.equals(BigDecimal.class)) { value = BigDecimal.ZERO; } else if (Map.class.isAssignableFrom(type)) { value = mapImplementationOf(type); } else if (Collection.class.isAssignableFrom(type)) { value = collectionImplementationOf(type); } return value; }
From source file:org.opendaylight.genius.alivenessmonitor.protocols.internal.AlivenessProtocolHandlerLLDP.java
private List<ActionInfo> getInterfaceActions( org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface interfaceState, long portNum) throws InterruptedException, ExecutionException { Class<? extends InterfaceType> intfType; if (interfaceState != null) { intfType = interfaceState.getType(); } else {//from www. j a v a 2 s . c om LOG.error("Could not retrieve port type for interface to construct actions"); return Collections.emptyList(); } List<ActionInfo> actionInfos = new ArrayList<>(); // Set the LLDP service Id which is 0 if (Tunnel.class.equals(intfType)) { actionInfos.add(new ActionSetFieldTunnelId(BigInteger.ZERO)); } actionInfos.add(new ActionOutput(new Uri(Long.toString(portNum)))); return actionInfos; }
From source file:org.seasar.mayaa.impl.util.ObjectUtil.java
/** * ??????????/*from ww w.j a v a2 s.co m*/ * ??????????????? * * @param expectedClass ???? * @param value ?? * @return ?? (expectedClass?) */ public static Object convert(Class expectedClass, Object value) { if (Object.class.equals(expectedClass) || (value != null && expectedClass.isAssignableFrom(value.getClass()))) { return value; } if (String.class.equals(expectedClass)) { return (value != null) ? value.toString() : null; } if (Boolean.class.equals(expectedClass) || Boolean.TYPE.equals(expectedClass)) { if (value instanceof Boolean) { return value; } return Boolean.valueOf(ObjectUtil.booleanValue(value, false)); } Converter converter = ConvertUtils.lookup(expectedClass); if (converter != null) { if (value != null) { return converter.convert(expectedClass, value); } if (expectedClass.isPrimitive() || Number.class.isAssignableFrom(expectedClass)) { if (BigInteger.class.isAssignableFrom(expectedClass)) { return BigInteger.ZERO; } else if (BigDecimal.class.isAssignableFrom(expectedClass)) { return BigDecimal.valueOf(0); } return converter.convert(expectedClass, value); } } return value; }
From source file:org.openhim.mediator.denormalization.ATNAAuditingActor.java
protected String generateForRegistryQueryResponse(ATNAAudit audit) throws JAXBException { AuditMessage res = new AuditMessage(); EventIdentificationType eid = new EventIdentificationType(); eid.setEventID(ATNAUtil.buildCodedValueType("DCM", "110112", "Query")); eid.setEventActionCode("E"); eid.setEventDateTime(ATNAUtil.newXMLGregorianCalendar()); eid.getEventTypeCode()//from w ww . java2s . co m .add(ATNAUtil.buildCodedValueType("IHE Transactions", "ITI-18", "Registry Stored Query")); eid.setEventOutcomeIndicator(audit.getOutcome() ? BigInteger.ZERO : new BigInteger("4")); res.setEventIdentification(eid); String xdsRegistryHost = config.getProperty("xds.registry.host"); res.getActiveParticipant().add(ATNAUtil.buildActiveParticipant(ATNAUtil.WSA_REPLYTO_ANON, ATNAUtil.getProcessID(), true, ATNAUtil.getHostIP(), (short) 2, "DCM", "110153", "Source")); res.getActiveParticipant().add(ATNAUtil.buildActiveParticipant(buildRegistryPath(), xdsRegistryHost, false, xdsRegistryHost, (short) 1, "DCM", "110152", "Destination")); res.getAuditSourceIdentification().add(ATNAUtil.buildAuditSource("openhim")); // Max of 1 patient is allowed Identifier id = audit.getParticipantIdentifiers().get(0); if (id != null) { res.getParticipantObjectIdentification().add(ATNAUtil.buildParticipantObjectIdentificationType( id.toCX(), (short) 1, (short) 1, "RFC-3881", "2", "PatientNumber", null)); } List<ATNAUtil.ParticipantObjectDetail> pod = new ArrayList<>(); pod.add(new ATNAUtil.ParticipantObjectDetail("QueryEncoding", "UTF-8".getBytes())); if (audit.getHomeCommunityId() != null) pod.add(new ATNAUtil.ParticipantObjectDetail("urn:ihe:iti:xca:2010:homeCommunityId", audit.getHomeCommunityId().getBytes())); res.getParticipantObjectIdentification() .add(ATNAUtil.buildParticipantObjectIdentificationType(audit.getUniqueId(), (short) 2, (short) 24, "IHE Transactions", "ITI-18", "Registry Stored Query", audit.getMessage(), pod)); return ATNAUtil.marshallATNAObject(res); }
From source file:org.openestate.io.wis_it.WisItUtils.java
public static String printNonNegativeInteger(BigInteger value) { if (value == null || value.compareTo(BigInteger.ZERO) == -1) throw new IllegalArgumentException("Can't print integer value!"); else//from ww w.java2 s . c o m return DatatypeConverter.printInteger(value); }
From source file:com.netxforge.oss2.config.SnmpEventInfo.java
/** * Creates an SNMP config definition representing the data in this class. * The defintion will either have one specific IP element or one Range element. * * @return a {@link org.opennms.netmgt.config.snmp.Definition} object. *//*from www . j av a 2s . com*/ public Definition createDef() { Definition definition = new Definition(); if (getCommunityString() != null) definition.setReadCommunity(getCommunityString()); if (getVersion() != null && ("v1".equals(getVersion()) || "v2c".equals(getVersion()))) { definition.setVersion(getVersion()); } if (getRetryCount() != 0) definition.setRetry(getRetryCount()); if (getTimeout() != 0) definition.setTimeout(getTimeout()); if (getPort() != 0) definition.setPort(getPort()); if (isSpecific()) { definition.addSpecific(getFirstIPAddress()); } else { if (BigInteger.ZERO .compareTo(InetAddressUtils.difference(getFirstIPAddress(), getLastIPAddress())) < 0) { log().error( "createDef: Can not create Definition when specified last is < first IP address: " + this); throw new IllegalArgumentException( "First: " + getFirstIPAddress() + " is greater than: " + getLastIPAddress()); } Range range = new Range(); range.setBegin(getFirstIPAddress()); range.setEnd(getLastIPAddress()); definition.addRange(range); } log().debug("createDef: created new Definition from: " + this); return definition; }