com.google.common.base.Preconditions Java Examples

The following examples show how to use com.google.common.base.Preconditions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FilterConfig.java    From syncer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public SyncFilter toFilter(SpelExpressionParser parser) {
  switch (getType()) {
    case SWITCH:
      return new Switch(parser, getSwitcher());
    case STATEMENT:
      return new Statement(parser, getStatement());
    case FOREACH:
      return new ForeachFilter(parser, getForeach());
    case IF:
      return new If(parser, getIf());
    case DROP:
      return new Drop();
    case CREATE:
      try {
        return getCreate().toAction(parser);
      } catch (NoSuchFieldException e) {
        throw new InvalidConfigException("Unknown field of `SyncData` to copy", e);
      }
    case METHOD:
      Preconditions.checkState(filterMeta != null, "Not set filterMeta for method");
      return JavaMethod.build(consumerId, filterMeta, getMethod());
    default:
      throw new InvalidConfigException("Unknown filter type");
  }
}
 
Example #2
Source File: BaseTestMiniDFS.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Start a MiniDFS cluster backed SabotNode cluster
 * @param testClass
 * @param isImpersonationEnabled Enable impersonation in the cluster?
 * @throws Exception
 */
protected static void startMiniDfsCluster(final String testClass, Configuration configuration) throws Exception {
  Preconditions.checkArgument(!Strings.isNullOrEmpty(testClass), "Expected a non-null and non-empty test class name");
  dfsConf = Preconditions.checkNotNull(configuration);

  // Set the MiniDfs base dir to be the temp directory of the test, so that all files created within the MiniDfs
  // are properly cleanup when test exits.
  miniDfsStoragePath = Files.createTempDirectory(testClass).toString();
  dfsConf.set("hdfs.minidfs.basedir", miniDfsStoragePath);
  // HDFS-8880 and HDFS-8953 introduce metrics logging that requires log4j, but log4j is explicitly
  // excluded in build. So disable logging to avoid NoClassDefFoundError for Log4JLogger.
  dfsConf.set("dfs.namenode.metrics.logger.period.seconds", "0");
  dfsConf.set("dfs.datanode.metrics.logger.period.seconds", "0");

  // Start the MiniDfs cluster
  dfsCluster = new MiniDFSCluster.Builder(dfsConf)
      .numDataNodes(3)
      .format(true)
      .build();

  fs = dfsCluster.getFileSystem();
}
 
Example #3
Source File: XmlElement.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Merges two children when this children's type allow multiple elements declaration with the
 * same key value. In that case, we only merge the lower priority child if there is not already
 * an element with the same key value that is equal to the lower priority child. Two children
 * are equals if they have the same attributes and children declared irrespective of the
 * declaration order.
 *
 * @param lowerPriorityChild the lower priority element's child.
 * @param mergingReport the merging report to log errors and actions.
 */
private void mergeChildrenWithMultipleDeclarations(
        XmlElement lowerPriorityChild,
        MergingReport.Builder mergingReport) {

    Preconditions.checkArgument(lowerPriorityChild.getType().areMultipleDeclarationAllowed());
    if (lowerPriorityChild.getType().areMultipleDeclarationAllowed()) {
        for (XmlElement sameTypeChild : getAllNodesByType(lowerPriorityChild.getType())) {
            if (sameTypeChild.getId().equals(lowerPriorityChild.getId()) &&
                    sameTypeChild.isEquals(lowerPriorityChild)) {
                return;
            }
        }
    }
    // if we end up here, we never found a child of this element with the same key and strictly
    // equals to the lowerPriorityChild so we should merge it in.
    addElement(lowerPriorityChild, mergingReport);
}
 
Example #4
Source File: ReliableTaildirEventReader.java    From uavstack with Apache License 2.0 6 votes vote down vote up
/**
 * Create a ReliableTaildirEventReader to watch the given directory. map<serverid.appid.logid, logpath>
 */
private ReliableTaildirEventReader(Map<String, CollectTask> tasks, Table<String, String, String> headerTable,
        boolean skipToEnd, boolean addByteOffset) throws IOException {
    Map<String, LogPatternInfo> filePaths = getFilePaths(tasks);

    // Sanity checks
    Preconditions.checkNotNull(filePaths);
    // get operation system info
    if (log.isDebugEnable()) {
        log.debug(this, "Initializing {" + ReliableTaildirEventReader.class.getSimpleName() + "} with directory={"
                + filePaths + "}");
    }

    // tailFile
    this.tailFileTable = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.DAYS)
            .<String, LogPatternInfo> build();
    this.headerTable = headerTable;
    this.addByteOffset = addByteOffset;
    this.os = JVMToolHelper.isWindows() ? OS_WINDOWS : null;

    updatelog(filePaths);
    updateTailFiles(skipToEnd);

    log.info(this, "tailFileTable: " + tailFileTable.toString());
    log.info(this, "headerTable: " + headerTable.toString());
}
 
Example #5
Source File: DefaultMonitor.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
@Override
public synchronized boolean startup(InstrumentInfo instrumentInfo) {
    if (status == Status.started) {
        return true;
    }
    if (status != Status.notStart) {
        return false;
    }
    Preconditions.checkNotNull(instrumentInfo, "instrumentation not allowed null");
    this.instrumentInfo = instrumentInfo;
    this.inst = instrumentInfo.getInstrumentation();
    this.lock = instrumentInfo.getLock();
    this.classFileBuffer = instrumentInfo.getClassFileBuffer();

    this.classPathLookup = createClassPathLookup();
    if (classPathLookup == null) {
        status = Status.error;
        return false;
    }
    status = Status.started;
    logger.info("qmonitor started");
    return true;
}
 
Example #6
Source File: DefinitelyDerefedParamsDriver.java    From NullAway with MIT License 6 votes vote down vote up
/**
 * Write model jar file with nullability model at DEFAULT_ASTUBX_LOCATION
 *
 * @param outPath Path of output model jar file.
 */
private void writeModelJAR(String outPath) throws IOException {
  Preconditions.checkArgument(
      outPath.endsWith(ASTUBX_JAR_SUFFIX), "invalid model file path! " + outPath);
  ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outPath));
  if (!nonnullParams.isEmpty()) {
    ZipEntry entry = new ZipEntry(DEFAULT_ASTUBX_LOCATION);
    // Set the modification/creation time to 0 to ensure that this jars always have the same
    // checksum
    entry.setTime(0);
    entry.setCreationTime(FileTime.fromMillis(0));
    zos.putNextEntry(entry);
    writeModel(new DataOutputStream(zos));
    zos.closeEntry();
  }
  zos.close();
  LOG(VERBOSE, "Info", "wrote model to: " + outPath);
}
 
Example #7
Source File: RegistrySecurity.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a string down to an ID, adding a realm if needed
 * @param idPair id:data tuple
 * @param realm realm to add
 * @return the ID.
 * @throws IllegalArgumentException if the idPair is invalid
 */
public Id parse(String idPair, String realm) {
  int firstColon = idPair.indexOf(':');
  int lastColon = idPair.lastIndexOf(':');
  if (firstColon == -1 || lastColon == -1 || firstColon != lastColon) {
    throw new IllegalArgumentException(
        "ACL '" + idPair + "' not of expected form scheme:id");
  }
  String scheme = idPair.substring(0, firstColon);
  String id = idPair.substring(firstColon + 1);
  if (id.endsWith("@")) {
    Preconditions.checkArgument(
        StringUtils.isNotEmpty(realm),
        "@ suffixed account but no realm %s", id);
    id = id + realm;
  }
  return new Id(scheme, id);
}
 
Example #8
Source File: JdbcWriter.java    From iteratorx with Apache License 2.0 6 votes vote down vote up
public int[] executeBatch(final String sql, final Object[]... records) {
	Preconditions.checkArgument(records.length <= this.batchSize,
			"records size is larger than max batch size, invoke executeBatch(final String sql, final Iterable<Object[]> records) instead of this one");

	try {
		conn = dataSource.getConnection();
		ps = conn.prepareStatement(sql);
		for (final Object[] record : records) {
			for (int i = 0; i < record.length; i++) {
				ps.setObject(i + 1, record[i]);
			}
			ps.addBatch();
		}
		ps.setQueryTimeout(queryTimeout);

		return ps.executeBatch();

	} catch (final SQLException e) {
		throw new RuntimeException(e);

	} finally {
		IOUtils.close(rs, ps, conn);
	}
}
 
Example #9
Source File: StorageContainerLocationProtocolClientSideTranslatorPB.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Queries a list of Node Statuses.
 */
@Override
public List<HddsProtos.Node> queryNode(HddsProtos.NodeState
    nodeStatuses, HddsProtos.QueryScope queryScope, String poolName)
    throws IOException {
  // TODO : We support only cluster wide query right now. So ignoring checking
  // queryScope and poolName
  Preconditions.checkNotNull(nodeStatuses);
  NodeQueryRequestProto request = NodeQueryRequestProto.newBuilder()
      .setState(nodeStatuses)
      .setTraceID(TracingUtil.exportCurrentSpan())
      .setScope(queryScope).setPoolName(poolName).build();
  NodeQueryResponseProto response = submitRequest(Type.QueryNode,
      builder -> builder.setNodeQueryRequest(request)).getNodeQueryResponse();
  return response.getDatanodesList();

}
 
Example #10
Source File: MemoryInstance.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
private SetMultimap<String, String> getOperationProvisions(Operation operation)
    throws InterruptedException {

  ExecuteOperationMetadata metadata = expectExecuteOperationMetadata(operation);
  Preconditions.checkState(metadata != null, "metadata not found");

  Action action =
      getUnchecked(
          expect(
              metadata.getActionDigest(),
              Action.parser(),
              newDirectExecutorService(),
              RequestMetadata.getDefaultInstance()));
  Preconditions.checkState(action != null, "action not found");

  Command command =
      getUnchecked(
          expect(
              action.getCommandDigest(),
              Command.parser(),
              newDirectExecutorService(),
              RequestMetadata.getDefaultInstance()));
  Preconditions.checkState(command != null, "command not found");

  return createProvisions(command.getPlatform());
}
 
Example #11
Source File: MysqlPipeFactory.java    From SpinalTap with Apache License 2.0 6 votes vote down vote up
private Pipe create(
    final MysqlConfiguration sourceConfig,
    final String partitionName,
    final StateRepositoryFactory repositoryFactory,
    final long leaderEpoch)
    throws Exception {
  final Source source = createSource(sourceConfig, repositoryFactory, partitionName, leaderEpoch);
  final DestinationConfiguration destinationConfig = sourceConfig.getDestinationConfiguration();

  Preconditions.checkState(
      !(sourceConfig.getHostRole().equals(MysqlConfiguration.HostRole.MIGRATION)
          && destinationConfig.getPoolSize() > 0),
      String.format(
          "Destination pool size is not 0 for MIGRATION source %s", sourceConfig.getName()));

  final Destination destination = createDestination(sourceConfig, destinationConfig);
  return new Pipe(source, destination, new PipeMetrics(source.getName(), metricRegistry));
}
 
Example #12
Source File: ResourceConsumptions.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
/**
 * Find all {@link ResourceConsumption} instances at a specific consumption level.
 */
public static Map<String, ResourceConsumption> groupBy(CompositeResourceConsumption parent,
                                                       ResourceConsumption.ConsumptionLevel level) {
    Preconditions.checkArgument(parent.getConsumptionLevel().ordinal() <= level.ordinal());

    if (parent.getConsumptionLevel() == level) {
        return Collections.singletonMap(parent.getConsumerName(), parent);
    }

    // If this is the Application level, the next one needs to be the InstanceType level, which is the last one
    if (parent.getConsumptionLevel() == ResourceConsumption.ConsumptionLevel.Application) {
        Preconditions.checkArgument(level == ResourceConsumption.ConsumptionLevel.InstanceType);
        return parent.getContributors();
    }

    Map<String, ResourceConsumption> result = new HashMap<>();
    for (ResourceConsumption nested : parent.getContributors().values()) {
        result.putAll(groupBy((CompositeResourceConsumption) nested, level));
    }
    return result;
}
 
Example #13
Source File: DefaultDriverExecutor.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private DeferredEvent poll() {
   synchronized(lock) {
      Preconditions.checkState(running == Thread.currentThread(), "Attempt to poll() from non-dispatch thread");
      if(stopped) {
         DeferredEvent event = events.poll();
         if(event == null) {
            return null;
         }

         if(canExecute(event)) {
            return event;
         }
         else if(event.event instanceof PlatformMessage) {
            return new CancelledMessageEvent((PlatformMessage) event.event);
         }
         else {
            // dropping it
            return null;
         }
      }
      else if(canExecute(events.peek())) {
         return events.poll();
      }
      return null;
   }
}
 
Example #14
Source File: ZookeeperNameResolver.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * 根据负载策略选择一台服务器
 *
 * @Author yuanzhonglin
 * @since 2019/4/17
 */
private void loadBalancer(String method) {
  Preconditions.checkNotNull(providersForLoadBalance, "providersForLoadBalance");

  Object argument = this.listener.getArgument();

  LB_STRATEGY lb = LoadBalanceUtil.getLoadBalanceStrategy(loadBlanceStrategyMap, method);

  // loadBlanceStrategy已经计算好了,直接拿过来使用
  serviceProviderMap = LoadBalancerFactory.getServiceProviderByLbStrategy(
          lb, providersForLoadBalance, serviceName, argument);
}
 
Example #15
Source File: NumwantProvider.java    From joal with Apache License 2.0 5 votes vote down vote up
public NumwantProvider(final Integer numwant, final Integer numwantOnStop) {
    Preconditions.checkNotNull(numwant, "numwant must not be null.");
    Preconditions.checkArgument(numwant > 0, "numwant must be at least 1.");
    Preconditions.checkNotNull(numwantOnStop, "numwantOnStop must not be null.");
    Preconditions.checkArgument(numwantOnStop >= 0, "numwantOnStop must be at least 0.");
    this.numwant = numwant;
    this.numwantOnStop = numwantOnStop;
}
 
Example #16
Source File: ElasticsearchStoragePlugin.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public ElasticMapping getMapping(NamespaceKey datasetPath){
  if(datasetPath.size() != 3){
    return null;
  }

  final ElasticConnection connection = this.connectionPool.getRandomConnection();
  try {
    final String schema = datasetPath.getPathComponents().get(1);
    final String type = datasetPath.getPathComponents().get(2);
    ClusterMetadata clusterMetadata = connection.execute(new ElasticActions.GetClusterMetadata().setIndex(datasetPath.getPathComponents().get(1)));
    List<ElasticIndex> indices = clusterMetadata.getIndices();
    if(indices.isEmpty()){
      return null;
    }

    final ElasticIndex firstIndex = indices.get(0);
    if(firstIndex.getName().equals(schema)){
      // not an alias.
      ElasticIndex index = firstIndex.filterToType(type);
      if(index == null){
        // no type for this path.
        return null;
      }
      Preconditions.checkArgument(indices.size() == 1, "More than one Index returned for alias %s.", schema);
      return index.getMappings().get(0);
    } else {

      ElasticMappingSet ems = new ElasticMappingSet(indices).filterToType(type);
      if(ems.isEmpty()){
        return null;
      }
      return ems.getMergedMapping();
    }
  } catch (Exception ex){
    logger.info("Failure while attempting to retrieve dataset {}", datasetPath, ex);
    return null;
  }
}
 
Example #17
Source File: TransactionStatus.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public TransactionStatus<DATA> complete(DATA current) {
    Preconditions.checkState(state == State.ResultReady, "Not in ResultReady state: %s", state);
    try {
        return new TransactionStatus<>(
                State.Completed,
                null,
                resultEvaluator.apply(current),
                null
        );
    } catch (Exception e) {
        return failed(e);
    }
}
 
Example #18
Source File: GoogleJobStore.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends DataModel> void create(UUID jobId, String key, T model) throws IOException {
  Preconditions.checkNotNull(jobId);
  Transaction transaction = datastore.newTransaction();
  Key fullKey = getDataKey(jobId, key);
  Entity shouldNotExist = transaction.get(fullKey);
  if (shouldNotExist != null) {
    transaction.rollback();
    throw new IOException(
        "Record already exists for key: " + fullKey.getName() + ". Record: " + shouldNotExist);
  }

  String serialized = objectMapper.writeValueAsString(model);
  Entity entity =
      Entity.newBuilder(fullKey)
          .set(CREATED_FIELD, Timestamp.now())
          .set(model.getClass().getName(), serialized)
          .build();

  try {
    transaction.put(entity);
  } catch (DatastoreException e) {
    throw new IOException(
        "Could not create initial record for jobID: " + jobId + ". Record: " + entity, e);
  }
  transaction.commit();
}
 
Example #19
Source File: CubeBuildJob.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private List<NBuildSourceInfo> buildLayer(Collection<NBuildSourceInfo> buildSourceInfos, SegmentInfo seg,
                                          SpanningTree st) {
    int cuboidsNumInLayer = 0;

    // build current layer
    List<LayoutEntity> allIndexesInCurrentLayer = new ArrayList<>();
    for (NBuildSourceInfo info : buildSourceInfos) {
        Collection<LayoutEntity> toBuildCuboids = info.getToBuildCuboids();
        infos.recordParent2Children(info.getLayout(),
                toBuildCuboids.stream().map(LayoutEntity::getId).collect(Collectors.toList()));
        cuboidsNumInLayer += toBuildCuboids.size();
        Preconditions.checkState(!toBuildCuboids.isEmpty(), "To be built cuboids is empty.");
        Dataset<Row> parentDS = info.getParentDS();

        for (LayoutEntity index : toBuildCuboids) {
            Preconditions.checkNotNull(parentDS, "Parent dataset is null when building.");
            buildLayoutWithUpdate.submit(new BuildLayoutWithUpdate.JobEntity() {
                @Override
                public String getName() {
                    return "build-index-" + index.getId();
                }

                @Override
                public LayoutEntity build() throws IOException {
                    return buildIndex(seg, index, parentDS, st, info.getLayoutId());
                }
            }, config);
            allIndexesInCurrentLayer.add(index);
        }
    }

    infos.recordCuboidsNumPerLayer(seg.id(), cuboidsNumInLayer);
    buildLayoutWithUpdate.updateLayout(seg, config);

    // decided the next layer by current layer's all indexes.
    st.decideTheNextLayer(allIndexesInCurrentLayer, seg);
    return constructTheNextLayerBuildInfos(st, seg, allIndexesInCurrentLayer);
}
 
Example #20
Source File: MinMaxSelectorGenerator.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public MinMaxSelectorGenerator(double min, double max, double inc, Unit unit) {
 Preconditions.checkArgument(min <= max, "min value should not exceed max value.");
 Preconditions.checkArgument(inc > 0, "increment value should be greater than 0.");
 this.min = min;
 this.max = max;
 this.increment = inc;
 this.unit = unit;
}
 
Example #21
Source File: ByteSlice.java    From zetasketch with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new byte slice. The slice's position will be zero, its limit will be its capacity and
 * each of its elements will be initialized to zero. The backing array will be mutable and its
 * array offset will be zero.
 */
public static ByteSlice allocate(int capacity) {
  Preconditions.checkArgument(capacity >= 0);
  ByteSlice slice = new ByteSlice();
  slice.initForAllocate(capacity);
  return slice;
}
 
Example #22
Source File: TimeRangeStrategy.java    From das with Apache License 2.0 5 votes vote down vote up
private TimeRangeShardLocator createTimeRangeShardLocator(Map<String, String> settings, String propName) {
    Preconditions.checkArgument(settings.containsKey(propName),
            "Property " + propName + " is missing");

    String patternString = settings.get(propName);
    Optional<TIME_PATTERN> pattern = Stream.of(TIME_PATTERN.values())
            .filter(p -> p.name().equals(patternString.toUpperCase()))
            .findFirst();
    Preconditions.checkArgument(pattern.isPresent(),
            "Property " + propName + " is required within: " + TIME_PATTERN.values());
    return new TimeRangeShardLocator<>(pattern.get());
}
 
Example #23
Source File: BaseServiceImpl.java    From dynamic-data-source-demo with Apache License 2.0 5 votes vote down vote up
@Override
public PageInfo<T> selectPageAndCountByExample(Example example, int pageNum, int pageSize) {
    Preconditions.checkNotNull(example);
    return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(
            () -> mapper.selectByExample(example)
    );
}
 
Example #24
Source File: CountdownRunner.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public CountdownRunner(@Nonnull Match match, Logger parentLogger, @Nonnull Countdown countdown) {
  Preconditions.checkNotNull(match, "match");
  Preconditions.checkNotNull(countdown, "countdown");

  this.match = match;
  this.logger = ClassLogger.get(parentLogger, getClass());
  this.countdown = countdown;
}
 
Example #25
Source File: ThresholdTrigger.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public ThresholdTrigger(String attributeName, double threshold, double sensitivity, TriggerOn triggerOn, Predicate<Address> source) {
   Preconditions.checkNotNull(attributeName, "attribute name may not be null");
   Preconditions.checkNotNull(triggerOn, "triggerOn value may not be null");
   Preconditions.checkNotNull(source, "source value may not be null");
   
   this.attributeName = attributeName;
   this.threshold = threshold;
   this.sensitivity = sensitivity;
   this.triggerOn = triggerOn;
   this.sourcePredicate = source;
}
 
Example #26
Source File: InnerNodeImpl.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Get a ancestor to its excluded node count map.
 *
 * @param nodes a collection of leaf nodes to exclude
 * @param genToExclude  the ancestor generation to exclude
 * @param genToReturn  the ancestor generation to return the count map
 * @return the map.
 * example:
 *
 *                *  --- root
 *              /    \
 *             *      *   -- genToReturn =2
 *            / \    / \
 *          *   *   *   *  -- genToExclude = 1
 *         /\  /\  /\  /\
 *       *  * * * * * * *  -- nodes
 */
private Map<Node, Integer> getAncestorCountMap(Collection<Node> nodes,
    int genToExclude, int genToReturn) {
  Preconditions.checkState(genToExclude >= 0);
  Preconditions.checkState(genToReturn >= 0);

  if (nodes == null || nodes.size() == 0) {
    return Collections.emptyMap();
  }
  // with the recursive call, genToReturn can be smaller than genToExclude
  if (genToReturn < genToExclude) {
    genToExclude = genToReturn;
  }
  // ancestorToExclude to ancestorToReturn map
  HashMap<Node, Node> ancestorMap = new HashMap<>();
  for (Node node: nodes) {
    Node ancestorToExclude = node.getAncestor(genToExclude);
    Node ancestorToReturn = node.getAncestor(genToReturn);
    if (ancestorToExclude == null || ancestorToReturn == null) {
      LOG.warn("Ancestor not found, node: {}"
          + ", generation to exclude: {}"
          + ", generation to return: {}", node.getNetworkFullPath(),
              genToExclude, genToReturn);
      continue;
    }
    ancestorMap.put(ancestorToExclude, ancestorToReturn);
  }
  // ancestorToReturn to exclude node count map
  HashMap<Node, Integer> countMap = new HashMap<>();
  for (Map.Entry<Node, Node> entry : ancestorMap.entrySet()) {
    countMap.compute(entry.getValue(),
        (key, n) -> (n == null ? 0 : n) + entry.getKey().getNumOfLeaves());
  }

  return countMap;
}
 
Example #27
Source File: NativeSecp256k1.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it
 *
 * @param tweak some bytes to tweak with
 * @param seckey 32-byte seckey
 */
public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException {
    Preconditions.checkArgument(privkey.length == 32);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
        byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(privkey);
    byteBuff.put(tweak);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_privkey_tweak_mul(byteBuff, Secp256k1Context.getContext());
    } finally {
        r.unlock();
    }

    byte[] privArr = retByteArray[0];

    int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(privArr.length, privLen, "Got bad pubkey length.");

    assertEquals(retVal, 1, "Failed return value check.");

    return privArr;
}
 
Example #28
Source File: SnippetFormatter.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
public String createIndentationString(int indentationLevel) {
    Preconditions.checkArgument(
            indentationLevel >= 0,
            "Indentation level cannot be less than zero. Given: %s",
            indentationLevel);
    int spaces = indentationLevel * INDENTATION_SIZE;
    StringBuilder buf = new StringBuilder(spaces);
    for (int i = 0; i < spaces; i++) {
        buf.append(' ');
    }
    return buf.toString();
}
 
Example #29
Source File: GradleDslSimpleExpression.java    From ok-gradle with Apache License 2.0 5 votes vote down vote up
public void setConfigBlock(@NotNull PsiElement block) {
  // For now we only support setting the config block on literals for newly created dependencies.
  Preconditions.checkState(getPsiElement() == null, "Can't add configuration block to an existing DSL literal.");

  // TODO: Use me.scana.okgradle.internal.dsl.parser.dependencies.DependencyConfigurationDslElement to add a dependency configuration.

  myUnsavedConfigBlock = block;
  setModified();
}
 
Example #30
Source File: JdbcConnectionUtil.java    From dbeam with Apache License 2.0 5 votes vote down vote up
public static String getDriverClass(final String url) throws ClassNotFoundException {
  final String[] parts = url.split(":", 3);
  Preconditions.checkArgument(
      parts.length > 1 && "jdbc".equals(parts[0]) && driverMapping.get(parts[1]) != null,
      "Invalid jdbc connection URL: %s. Expect jdbc:postgresql or jdbc:mysql as prefix.",
      url);
  return Class.forName(driverMapping.get(parts[1])).getCanonicalName();
}