use of java.util.stream.IntStream in project kie-wb-common by kiegroup.
the class AbstractFormDefinitionGeneratorTest method verifyInvoiceForm.
protected void verifyInvoiceForm(FormMigrationSummary summary) {
Form originalForm = summary.getOriginalForm().get();
Assertions.assertThat(originalForm.getFormFields()).isNotEmpty().hasSize(3);
FormDefinition newForm = summary.getNewForm().get();
Assertions.assertThat(newForm.getFields()).isNotEmpty().hasSize(3);
Assertions.assertThat(newForm.getModel()).isNotNull().hasFieldOrPropertyWithValue("className", INVOICE_MODEL).isInstanceOf(DataObjectFormModel.class);
IntStream indexStream = IntStream.range(0, newForm.getFields().size());
LayoutTemplate formLayout = newForm.getLayoutTemplate();
assertNotNull(formLayout);
Assertions.assertThat(formLayout.getRows()).isNotEmpty().hasSize(newForm.getFields().size());
indexStream.forEach(index -> {
FieldDefinition fieldDefinition = newForm.getFields().get(index);
switch(index) {
case 0:
checkFieldDefinition(fieldDefinition, INVOICE_USER, "user (invoice)", "user", SubFormFieldDefinition.class, newForm, originalForm.getField(fieldDefinition.getName()));
break;
case 1:
checkFieldDefinition(fieldDefinition, INVOICE_LINES, "lines (invoice)", "lines", MultipleSubFormFieldDefinition.class, newForm, originalForm.getField(fieldDefinition.getName()));
break;
case 3:
checkFieldDefinition(fieldDefinition, INVOICE_LINES, "lines (invoice)", "lines", MultipleSubFormFieldDefinition.class, newForm, originalForm.getField(fieldDefinition.getName()));
break;
}
LayoutRow fieldRow = formLayout.getRows().get(index);
assertNotNull(fieldRow);
Assertions.assertThat(fieldRow.getLayoutColumns()).isNotEmpty().hasSize(1);
LayoutColumn fieldColumn = fieldRow.getLayoutColumns().get(0);
assertNotNull(fieldColumn);
assertEquals("12", fieldColumn.getSpan());
Assertions.assertThat(fieldColumn.getLayoutComponents()).isNotEmpty().hasSize(1);
checkLayoutFormField(fieldColumn.getLayoutComponents().get(0), fieldDefinition, newForm);
});
}
use of java.util.stream.IntStream in project cyclops by aol.
the class IdenticalToStream method measureThroughput.
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@Fork(1)
public List<Entry<Integer, List<String>>> measureThroughput() {
// Function to compute the score of a given word
IntUnaryOperator scoreOfALetter = letter -> letterScores[letter - 'a'];
// score of the same letters in a word
ToIntFunction<Entry<Integer, Long>> letterScore = entry -> letterScores[entry.getKey() - 'a'] * Integer.min(entry.getValue().intValue(), scrabbleAvailableLetters[entry.getKey() - 'a']);
// Histogram of the letters in a given word
Function<String, Map<Integer, Long>> histoOfLetters = word -> ReactiveSeq.fromCharSequence(word).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// number of blanks for a given letter
ToLongFunction<Entry<Integer, Long>> blank = entry -> Long.max(0L, entry.getValue() - scrabbleAvailableLetters[entry.getKey() - 'a']);
// number of blanks for a given word
Function<String, Long> nBlanks = word -> reactiveSeq(histoOfLetters.apply(word).entrySet()).mapToLong(blank).sum();
// can a word be written with 2 blanks?
Predicate<String> checkBlanks = word -> nBlanks.apply(word) <= 2;
// score taking blanks into account
Function<String, Integer> score2 = word -> reactiveSeq(histoOfLetters.apply(word).entrySet()).mapToInt(letterScore).sum();
// Placing the word on the board
// Building the streams of first and last letters
Function<String, IntStream> first3 = word -> word.chars().limit(3);
Function<String, IntStream> last3 = word -> word.chars().skip(Integer.max(0, word.length() - 4));
// Stream to be maxed
Function<String, IntStream> toBeMaxed = word -> ReactiveSeq.of(first3.apply(word), last3.apply(word)).flatMapToInt(Function.identity());
// Bonus for double letter
ToIntFunction<String> bonusForDoubleLetter = word -> toBeMaxed.apply(word).map(scoreOfALetter).max().orElse(0);
// score of the word put on the board
Function<String, Integer> score3 = word -> (score2.apply(word) + bonusForDoubleLetter.applyAsInt(word)) + (score2.apply(word) + bonusForDoubleLetter.applyAsInt(word)) + (word.length() == 7 ? 50 : 0);
Function<Function<String, Integer>, ReactiveSeq<Map<Integer, List<String>>>> buildHistoOnScore = score -> ReactiveSeq.of(reactiveSeq(shakespeareWords).filter(scrabbleWords::contains).filter(// filter out the words that needs more than 2 blanks
checkBlanks).collect(Collectors.groupingBy(score, () -> new TreeMap<Integer, List<String>>(Comparator.reverseOrder()), Collectors.toList())));
// best key / value pairs
List<Entry<Integer, List<String>>> finalList = buildHistoOnScore.apply(score3).map(e -> reactiveSeq(e.entrySet()).limit(3).collect(Collectors.toList())).findAny().get();
return finalList;
}
use of java.util.stream.IntStream in project data-prep by Talend.
the class PreparationService method extractActionsAfterStep.
/**
* Extract all actions after a provided step
*
* @param stepsIds The steps list
* @param afterStep The (excluded) step id where to start the extraction
* @return The actions after 'afterStep' to the end of the list
*/
private List<AppendStep> extractActionsAfterStep(final List<String> stepsIds, final String afterStep) {
final int stepIndex = stepsIds.indexOf(afterStep);
if (stepIndex == -1) {
return emptyList();
}
final List<PersistentStep> steps;
try (IntStream range = IntStream.range(stepIndex, stepsIds.size())) {
steps = range.mapToObj(index -> getStep(stepsIds.get(index))).collect(toList());
}
final List<List<Action>> stepActions = steps.stream().map(this::getActions).collect(toList());
try (IntStream filteredActions = IntStream.range(1, steps.size())) {
return filteredActions.mapToObj(index -> {
final List<Action> previous = stepActions.get(index - 1);
final List<Action> current = stepActions.get(index);
final PersistentStep step = steps.get(index);
final AppendStep appendStep = new AppendStep();
appendStep.setDiff(step.getDiff());
appendStep.setActions(current.subList(previous.size(), current.size()));
return appendStep;
}).collect(toList());
}
}
use of java.util.stream.IntStream in project accumulo by apache.
the class SimpleGarbageCollector method startStatsService.
private HostAndPort startStatsService() {
Iface rpcProxy = TraceUtil.wrapService(this);
final Processor<Iface> processor;
if (getContext().getThriftServerType() == ThriftServerType.SASL) {
Iface tcProxy = TCredentialsUpdatingWrapper.service(rpcProxy, getClass(), getConfiguration());
processor = new Processor<>(tcProxy);
} else {
processor = new Processor<>(rpcProxy);
}
IntStream port = getConfiguration().getPortStream(Property.GC_PORT);
HostAndPort[] addresses = TServerUtils.getHostAndPorts(getHostname(), port);
long maxMessageSize = getConfiguration().getAsBytes(Property.GENERAL_MAX_MESSAGE_SIZE);
try {
ServerAddress server = TServerUtils.startTServer(getConfiguration(), getContext().getThriftServerType(), processor, this.getClass().getSimpleName(), "GC Monitor Service", 2, ThreadPools.DEFAULT_TIMEOUT_MILLISECS, 1000, maxMessageSize, getContext().getServerSslParams(), getContext().getSaslParams(), 0, addresses);
log.debug("Starting garbage collector listening on " + server.address);
return server.address;
} catch (Exception ex) {
// ACCUMULO-3651 Level changed to error and FATAL added to message for slf4j compatibility
log.error("FATAL:", ex);
throw new RuntimeException(ex);
}
}
use of java.util.stream.IntStream in project accumulo by apache.
the class TServerUtils method startServer.
/**
* Start a server, at the given port, or higher, if that port is not available.
*
* @param context
* RPC configuration
* @param portHintProperty
* the port to attempt to open, can be zero, meaning "any available port"
* @param processor
* the service to be started
* @param serverName
* the name of the class that is providing the service
* @param threadName
* name this service's thread for better debugging
* @param portSearchProperty
* A boolean Property to control if port-search should be used, or null to disable
* @param minThreadProperty
* A Property to control the minimum number of threads in the pool
* @param timeBetweenThreadChecksProperty
* A Property to control the amount of time between checks to resize the thread pool
* @param maxMessageSizeProperty
* A Property to control the maximum Thrift message size accepted
* @return the server object created, and the port actually used
* @throws UnknownHostException
* when we don't know our own address
*/
public static ServerAddress startServer(ServerContext context, String hostname, Property portHintProperty, TProcessor processor, String serverName, String threadName, Property portSearchProperty, Property minThreadProperty, Property threadTimeOutProperty, Property timeBetweenThreadChecksProperty, Property maxMessageSizeProperty) throws UnknownHostException {
final AccumuloConfiguration config = context.getConfiguration();
final IntStream portHint = config.getPortStream(portHintProperty);
int minThreads = 2;
if (minThreadProperty != null) {
minThreads = config.getCount(minThreadProperty);
}
long threadTimeOut = ThreadPools.DEFAULT_TIMEOUT_MILLISECS;
if (threadTimeOutProperty != null) {
threadTimeOut = config.getTimeInMillis(threadTimeOutProperty);
}
long timeBetweenThreadChecks = 1000;
if (timeBetweenThreadChecksProperty != null) {
timeBetweenThreadChecks = config.getTimeInMillis(timeBetweenThreadChecksProperty);
}
long maxMessageSize = 10_000_000;
if (maxMessageSizeProperty != null) {
maxMessageSize = config.getAsBytes(maxMessageSizeProperty);
}
boolean portSearch = false;
if (portSearchProperty != null) {
portSearch = config.getBoolean(portSearchProperty);
}
final ThriftServerType serverType = context.getThriftServerType();
if (serverType == ThriftServerType.SASL) {
processor = updateSaslProcessor(serverType, processor);
}
// create the TimedProcessor outside the port search loop so we don't try to
// register the same
// metrics mbean more than once
TimedProcessor timedProcessor = new TimedProcessor(config, processor, serverName, threadName);
HostAndPort[] addresses = getHostAndPorts(hostname, portHint);
try {
return TServerUtils.startTServer(serverType, timedProcessor, serverName, threadName, minThreads, threadTimeOut, config, timeBetweenThreadChecks, maxMessageSize, context.getServerSslParams(), context.getSaslParams(), context.getClientTimeoutInMillis(), addresses);
} catch (TTransportException e) {
if (portSearch) {
// Build a list of reserved ports - as identified by properties of type PropertyType.PORT
Map<Integer, Property> reservedPorts = getReservedPorts(config, portHintProperty);
HostAndPort last = addresses[addresses.length - 1];
// Search sequentially over the next 1000 ports
for (int port = last.getPort() + 1; port < last.getPort() + 1001; port++) {
if (reservedPorts.containsKey(port)) {
log.debug("During port search, skipping reserved port {} - property {} ({})", port, reservedPorts.get(port).getKey(), reservedPorts.get(port).getDescription());
continue;
}
if (PortRange.VALID_RANGE.isBefore(port)) {
break;
}
try {
HostAndPort addr = HostAndPort.fromParts(hostname, port);
return TServerUtils.startTServer(serverType, timedProcessor, serverName, threadName, minThreads, threadTimeOut, config, timeBetweenThreadChecks, maxMessageSize, context.getServerSslParams(), context.getSaslParams(), context.getClientTimeoutInMillis(), addr);
} catch (TTransportException tte) {
log.info("Unable to use port {}, retrying. (Thread Name = {})", port, threadName);
}
}
log.error("Unable to start TServer", e);
throw new UnknownHostException("Unable to find a listen port");
} else {
log.error("Unable to start TServer", e);
throw new UnknownHostException("Unable to find a listen port");
}
}
}
Aggregations