Example usage for java.util Collections nCopies

List of usage examples for java.util Collections nCopies

Introduction

In this page you can find the example usage for java.util Collections nCopies.

Prototype

public static <T> List<T> nCopies(int n, T o) 

Source Link

Document

Returns an immutable list consisting of n copies of the specified object.

Usage

From source file:org.apache.hadoop.hive.serde2.teradata.TeradataBinaryDataOutputStream.java

/**
 * Write DECIMAL(P, S).//  w  ww  .ja v a  2s  .co m
 * The representation of decimal in Teradata binary format is:
 * the byte number to read is decided solely by the precision(P),
 * HiveDecimal is constructed through the byte array and scale.
 * the rest of byte will use 0x00 to pad (positive) and use 0xFF to pad (negative).
 * the null DECIMAL will use 0x00 to pad.
 *
 * @param writable the writable
 * @param byteNum the byte num
 * @throws IOException the io exception
 */
public void writeDecimal(HiveDecimalWritable writable, int byteNum, int scale) throws IOException {
    if (writable == null) {
        byte[] pad = new byte[byteNum];
        write(pad);
        return;
    }
    // since the HiveDecimal will auto adjust the scale to save resource
    // we need to adjust it back otherwise the output bytes will be wrong
    int hiveScale = writable.getHiveDecimal().scale();
    BigInteger bigInteger = writable.getHiveDecimal().unscaledValue();
    if (hiveScale < scale) {
        BigInteger multiplicand = new BigInteger("1" + join("", Collections.nCopies(scale - hiveScale, "0")));
        bigInteger = bigInteger.multiply(multiplicand);
    }
    byte[] content = bigInteger.toByteArray();
    int signBit = content[0] >> 7 & 1;
    ArrayUtils.reverse(content);
    write(content);
    if (byteNum > content.length) {
        byte[] pad;
        if (signBit == 0) {
            pad = new byte[byteNum - content.length];
        } else {
            pad = new byte[byteNum - content.length];
            Arrays.fill(pad, (byte) 255);
        }
        write(pad);
    }
}

From source file:org.pentaho.di.trans.dataservice.optimization.paramgen.TableInputParameterGeneration.java

protected String convertAtomicCondition(Condition condition, RowMeta paramsMeta, List<Object> params)
        throws PushDownOptimizationException {
    String value = condition.getRightExactString();
    String function = condition.getFunctionDesc();
    String placeholder = "?";

    switch (condition.getFunction()) {
    case Condition.FUNC_REGEXP:
    case Condition.FUNC_CONTAINS:
    case Condition.FUNC_STARTS_WITH:
    case Condition.FUNC_ENDS_WITH:
    case Condition.FUNC_TRUE:
        throw new PushDownOptimizationException(
                condition.getFunctionDesc() + " is not supported for push down.");
    case Condition.FUNC_NOT_NULL:
    case Condition.FUNC_NULL:
        placeholder = "";
        break;/*from w  w  w  .j a v  a 2 s.c o m*/
    case Condition.FUNC_IN_LIST:
        Object[] inList = getInListArray(condition);
        ValueMetaInterface inListValueMeta = getResolvedValueMeta(condition);
        for (int i = 0; i < inList.length; i++) {
            paramsMeta.addValueMeta(inListValueMeta);
            params.add(inList[i]);
        }
        placeholder = String.format("(%s)",
                StringUtils.join(Collections.nCopies(inList.length, "?").iterator(), ","));
        function = " IN ";
        break;
    default:
        if (value == null) {
            throw new PushDownOptimizationException("Condition value can not be null: " + condition);
        }
        paramsMeta.addValueMeta(getResolvedValueMeta(condition));
        params.add(getResolvedValue(condition));
        break;
    }

    return String.format("%s %s %s", getQuotedFieldName(condition), function, placeholder);
}

From source file:org.pentaho.di.core.database.ConnectionPoolUtilIntegrationIT.java

private void testGetConnectionFromPool(final int threadCount) throws Exception {
    ArgumentCaptor<String> captorLogMessage = ArgumentCaptor.forClass(String.class);

    final DatabaseMeta dbMeta = mock(DatabaseMeta.class, RETURNS_MOCKS);
    when(dbMeta.getDriverClass()).thenReturn(driver.getClass().getCanonicalName());
    when(dbMeta.getConnectionPoolingProperties()).thenReturn(new Properties());
    when(dbMeta.environmentSubstitute(anyString())).thenAnswer(new Answer<Object>() {
        @Override/*ww w  .j a  v  a 2  s  .  com*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getArguments()[0];
        }
    });
    when(dbMeta.getName()).thenReturn("CP1");
    when(dbMeta.getPassword()).thenReturn(PASSWORD);

    Callable<Connection> task = new Callable<Connection>() {
        @Override
        public Connection call() throws Exception {
            return ConnectionPoolUtil.getConnection(logChannelInterface, dbMeta, "", INITIAL_POOL_SIZE,
                    threadCount);
        }
    };
    List<Callable<Connection>> tasks = Collections.nCopies(threadCount, task);
    ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
    List<Future<Connection>> futures = executorService.invokeAll(tasks);

    assertNotNull(futures);
    assertEquals(threadCount, futures.size());

    //pool should be creates only once for KettleClientEnvironment
    verify(logChannelInterface, atMost(2)).logBasic(captorLogMessage.capture());
    List<String> capturedLogEntry = captorLogMessage.getAllValues();
    if (capturedLogEntry != null && !capturedLogEntry.isEmpty()) {
        assertEquals(BaseMessages.getString(PKG, "Database.CreatingConnectionPool", dbMeta.getName()),
                capturedLogEntry.get(0));
        assertEquals(BaseMessages.getString(PKG, "Database.CreatedConnectionPool", dbMeta.getName()),
                capturedLogEntry.get(1));
    }
}

From source file:de.christianseipl.utilities.maputils.MapMath.java

/**
 * Erzeugt eine spezielle Map, zu deren Schlssel der jeweilige Wert {@code
 * _repetitions} wiederholt in der Collection abgelegt wird.
 * //w  w w  .j  ava2  s.co m
 * @param <K>
 * @param <V>
 * @param _map
 * @param _repetitions Anzahl an Wiederholungen, mu grer als Null sein.
 * @return
 */
public static <K, V> Map<K, Collection<V>> expandToMultiMap(Map<K, V> _map, int _repetitions) {
    if (_repetitions < 0)
        throw new IllegalArgumentException();
    Map<K, Collection<V>> result = new HashMap<K, Collection<V>>();
    for (Entry<K, V> entry : _map.entrySet()) {
        result.put(entry.getKey(), Collections.nCopies(_repetitions, entry.getValue()));
    }
    return result;
}

From source file:org.wildfly.security.tool.FileSystemRealmCommand.java

@Override
public void execute(String[] args) throws Exception {
    setStatus(GENERAL_CONFIGURATION_ERROR);
    cmdLine = parser.parse(options, args, false);
    setEnableDebug(cmdLine.hasOption(DEBUG_PARAM));
    if (cmdLine.hasOption(HELP_PARAM)) {
        help();//from   www .  j  ava2  s.  c o m
        setStatus(ElytronTool.ElytronToolExitStatus_OK);
        return;
    }
    if (cmdLine.hasOption(SILENT_PARAM)) {
        silentMode = true;
    }
    if (cmdLine.hasOption(SUMMARY_PARAM)) {
        summaryMode = true;
        summaryString = new StringBuilder();
        summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-")));
        summaryString.append(System.getProperty("line.separator"));
        summaryString.append("Summary for execution of Elytron-Tool command FileSystemRealm");
        summaryString.append(System.getProperty("line.separator"));
        summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-")));
        summaryString.append(System.getProperty("line.separator"));
    }
    printDuplicatesWarning(cmdLine);

    String bulkConvert = cmdLine.getOptionValue("b");
    String usersFileOption = cmdLine.getOptionValue("u");
    String rolesFileOption = cmdLine.getOptionValue("r");
    String outputLocationOption = cmdLine.getOptionValue("o");

    if (bulkConvert == null) {
        if (summaryMode) {
            summaryString.append("Options were specified via CLI, converting single users-roles combination");
            summaryString.append(System.getProperty("line.separator"));
        }

        if (usersFileOption == null) {
            errorHandler(ElytronToolMessages.msg.missingUsersFile());
        } else if (rolesFileOption == null) {
            errorHandler(ElytronToolMessages.msg.missingRolesFile());
        } else if (outputLocationOption == null) {
            errorHandler(ElytronToolMessages.msg.missingOutputLocation());
        }

        Descriptor descriptor = new Descriptor();
        descriptor.setUsersFile(usersFileOption);
        descriptor.setRolesFile(rolesFileOption);
        descriptor.setOutputLocation(outputLocationOption);
        descriptor.setFileSystemRealmName(cmdLine.getOptionValue("f"));
        descriptor.setSecurityDomainName(cmdLine.getOptionValue("s"));
        descriptors.add(descriptor);

        findMissingRequiredValuesAndSetValues(0, descriptor);
    } else if (usersFileOption != null || rolesFileOption != null || outputLocationOption != null) {
        throw ElytronToolMessages.msg.mutuallyExclusiveOptionsSpecified();
    } else {
        if (summaryMode) {
            summaryString.append(String.format(
                    "Options were specified via descriptor file: %s, converting multiple users-roles combinations",
                    bulkConvert));
            summaryString.append(System.getProperty("line.separator"));
        }
        parseDescriptorFile(bulkConvert);
    }

    createFileSystemRealm();
    createWildFlyScript();

    if (summaryMode) {
        summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-")));
        summaryString.append(System.getProperty("line.separator"));
        summaryString.append("End of summary");
        summaryString.append(System.getProperty("line.separator"));
        summaryString.append(String.join("", Collections.nCopies(SUMMARY_WIDTH, "-")));
        System.out.println(summaryString);
    }

    if (warningOccurred) {
        setStatus(GENERAL_CONFIGURATION_WARNING);
    } else {
        setStatus(ElytronTool.ElytronToolExitStatus_OK);
    }
}

From source file:org.broadinstitute.gatk.utils.Dirichlet.java

/**
 * Create a symmetric distribution Dir(a/K, a/K, a/K . . .) where K is the number of states and
 * a is the concentration.//from  w  ww . java2 s  .  c  o m
 */
public static Dirichlet symmetricDirichlet(final int numStates, final double concentration) {
    Utils.validateArg(numStates > 0, "Must have at leat one state");
    Utils.validateArg(concentration > 0, "concentration must be positive");
    return new Dirichlet(
            Collections.nCopies(numStates, concentration / numStates).stream().mapToDouble(x -> x).toArray());
}

From source file:com.networknt.client.ClientTest.java

private void callApiAsyncMultiThread(final int threadCount) throws InterruptedException, ExecutionException {
    Callable<String> task = new Callable<String>() {
        @Override//from   w ww.j a v  a 2  s.  c  o m
        public String call() throws Exception {
            return callApiAsync();
        }
    };
    List<Callable<String>> tasks = Collections.nCopies(threadCount, task);
    ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
    List<Future<String>> futures = executorService.invokeAll(tasks);
    List<String> resultList = new ArrayList<String>(futures.size());
    for (Future<String> future : futures) {
        resultList.add(future.get());
    }
    System.out.println("resultList = " + resultList);
}

From source file:org.ballerinalang.langserver.command.CommandUtil.java

/**
 * Get the object constructor snippet generated from public object fields.
 *
 * @param fields     List of Fields/*w  ww  . j av  a2 s  . c  om*/
 * @param baseOffset Offset of snippet
 * @return {@link String}   Constructor snippet as String
 */
public static String getObjectConstructorSnippet(List<BLangSimpleVariable> fields, int baseOffset) {
    StringJoiner funcFields = new StringJoiner(", ");
    StringJoiner funcBody = new StringJoiner(CommonUtil.LINE_SEPARATOR);
    String offsetStr = String.join("", Collections.nCopies(baseOffset, " "));
    fields.stream().filter(bField -> ((bField.symbol.flags & Flags.PUBLIC) != Flags.PUBLIC)).forEach(var -> {
        funcFields.add(generateTypeDefinition(null, null, var) + " " + var.name.value);
        funcBody.add(offsetStr + "    self." + var.name.value + " = " + var.name.value + ";");
    });

    return offsetStr + "public function __init(" + funcFields.toString() + ") {" + CommonUtil.LINE_SEPARATOR
            + funcBody.toString() + CommonUtil.LINE_SEPARATOR + offsetStr + "}" + CommonUtil.LINE_SEPARATOR;
}

From source file:org.apache.metron.profiler.integration.ProfilerIntegrationTest.java

public void setup(String pathToConfig) throws Exception {
    columnBuilder = new ValueOnlyColumnBuilder(columnFamily);

    // create input messages for the profiler to consume
    input = Stream.of(message1, message2, message3).map(Bytes::toBytes).map(m -> Collections.nCopies(5, m))
            .flatMap(l -> l.stream()).collect(Collectors.toList());

    // storm topology properties
    final Properties topologyProperties = new Properties() {
        {//  w w w. jav  a  2  s . c o m
            setProperty("kafka.start", "UNCOMMITTED_EARLIEST");
            setProperty("profiler.workers", "1");
            setProperty("profiler.executors", "0");
            setProperty("profiler.input.topic", inputTopic);
            setProperty("profiler.output.topic", outputTopic);
            setProperty("profiler.period.duration", "20");
            setProperty("profiler.period.duration.units", "SECONDS");
            setProperty("profiler.ttl", "30");
            setProperty("profiler.ttl.units", "MINUTES");
            setProperty("profiler.hbase.salt.divisor", "10");
            setProperty("profiler.hbase.table", tableName);
            setProperty("profiler.hbase.column.family", columnFamily);
            setProperty("profiler.hbase.batch", "10");
            setProperty("profiler.hbase.flush.interval.seconds", "1");
            setProperty("profiler.profile.ttl", "20");
            setProperty("hbase.provider.impl", "" + MockTableProvider.class.getName());
        }
    };

    // create the mock table
    profilerTable = (MockHTable) MockHTable.Provider.addToCache(tableName, columnFamily);

    zkComponent = getZKServerComponent(topologyProperties);

    // create the input topic
    kafkaComponent = getKafkaComponent(topologyProperties,
            Arrays.asList(new KafkaComponent.Topic(inputTopic, 1), new KafkaComponent.Topic(outputTopic, 1)));

    // upload profiler configuration to zookeeper
    ConfigUploadComponent configUploadComponent = new ConfigUploadComponent()
            .withTopologyProperties(topologyProperties).withGlobalConfiguration(pathToConfig)
            .withProfilerConfiguration(pathToConfig);

    // load flux definition for the profiler topology
    fluxComponent = new FluxTopologyComponent.Builder().withTopologyLocation(new File(FLUX_PATH))
            .withTopologyName("profiler").withTopologyProperties(topologyProperties).build();

    // start all components
    runner = new ComponentRunner.Builder().withComponent("zk", zkComponent)
            .withComponent("kafka", kafkaComponent).withComponent("config", configUploadComponent)
            .withComponent("storm", fluxComponent).withMillisecondsBetweenAttempts(15000).withNumRetries(10)
            .withCustomShutdownOrder(new String[] { "storm", "config", "kafka", "zk" }).build();
    runner.start();
}

From source file:org.dhatim.javabean.context.StandaloneBeanContext.java

/**
 * Sync's the BeanRepositories bean map with the bean map from the
 * {@link BeanIdStore}. All missing keys that are in the BeanIdList's map
 * are added to the BeanRepositories map.
 *///  www  .ja v a  2 s  . com
private void updateBeanMap() {

    Map<String, BeanId> beanIdMap = beanIdStore.getBeanIdMap();

    int largestBeanIdIndex = -1;
    for (Entry<String, BeanId> beanIdEntry : beanIdMap.entrySet()) {
        String beanIdName = beanIdEntry.getKey();
        BeanId beanId = beanIdEntry.getValue();
        if (!beanMap.containsKey(beanIdName)) {
            beanMap.put(beanIdName, null);
        }
        if (largestBeanIdIndex < beanId.getIndex()) {
            largestBeanIdIndex = beanId.getIndex();
        }
    }
    if (largestBeanIdIndex >= 0) {
        int newEntries = (largestBeanIdIndex - entries.size()) + 1;
        entries.addAll(Collections.nCopies(newEntries, (ContextEntry) null));

        for (Entry<String, Object> beanMapEntry : beanMap.entrySet()) {

            BeanId beanId = beanIdMap.get(beanMapEntry.getKey());

            int index = beanId.getIndex();
            if (entries.get(index) == null) {

                entries.set(index, new ContextEntry(beanId, beanMapEntry));
            }
        }
    }
}