io.vavr.Tuple2 Java Examples

The following examples show how to use io.vavr.Tuple2. 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: PaymentController.java    From spring-boot-ddd with GNU General Public License v3.0 6 votes vote down vote up
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Callable<CompletionStage<ResponseEntity<?>>> process(@Valid @RequestBody PerformPaymentRequest request) {

    LOG.debug("Request {}", request);

    return () -> {
        LOG.debug("Callable...");

        PerformPayment performPayment = PerformPayment.commandOf(
                new CustomerId(request.getCustomerId()),
                PaymentIntent.valueOf(request.getPaymentIntent()),
                PaymentMethod.valueOf(request.getPaymentMethod()),
                request.getTransaction());

        CompletionStage<Either<CommandFailure, Tuple2<PaymentId, PaymentStatus>>> promise = paymentProcessManager.process(performPayment);
        return promise.thenApply(acceptOrReject -> acceptOrReject.fold(
                reject -> ResponseEntity.badRequest().body(reject),
                accept -> ResponseEntity.accepted().body(new PerformPaymentResponse(accept._1.id, accept._2.name()))
        ));
    };


}
 
Example #2
Source File: PregelComputation.java    From kafka-graphs with Apache License 2.0 6 votes vote down vote up
@Override
public void process(final K readOnlyKey, final Tuple2<Integer, Map<K, List<Message>>> value) {
    try {
        int superstep = value._1 - 1;
        for (Map.Entry<K, List<Message>> entry : value._2.entrySet()) {
            // List of messages may be empty in case of sending to self
            Tuple3<Integer, K, List<Message>> tuple = new Tuple3<>(superstep + 1, readOnlyKey, entry.getValue());
            ProducerRecord<K, Tuple3<Integer, K, List<Message>>> producerRecord =
                new ProducerRecord<>(workSetTopic, entry.getKey(), tuple);
            Callback cb = callback(superstep, readOnlyKey, entry.getKey(), entry.getValue());
            producer.send(producerRecord, cb);
        }
        producer.flush();
        // Deactivate this vertex
        deactivateVertex(superstep, readOnlyKey);
    } catch (Exception e) {
        throw toRuntimeException(e);
    }
}
 
Example #3
Source File: StatisticsServiceImpl.java    From retro-game with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<Tuple2<Date, PointsAndRankPairDto>> getDistinctChanges(long bodyId, long userId, StatisticsKindDto kind,
                                                                   StatisticsPeriodDto period) {
  List<? extends Statistics> statistics;
  switch (kind) {
    case OVERALL:
    default:
      statistics = fetch(overallStatisticsRepository, period, userId);
      break;
    case BUILDINGS:
      statistics = fetch(buildingsStatisticsRepository, period, userId);
      break;
    case TECHNOLOGIES:
      statistics = fetch(technologiesStatisticsRepository, period, userId);
      break;
    case FLEET:
      statistics = fetch(fleetStatisticsRepository, period, userId);
      break;
    case DEFENSE:
      statistics = fetch(defenseStatisticsRepository, period, userId);
      break;
  }
  return statistics.stream()
      .map(s -> Tuple.of(s.getAt(), new PointsAndRankPairDto(s.getPoints(), s.getRank())))
      .collect(Collectors.toList());
}
 
Example #4
Source File: StatisticsServiceImpl.java    From retro-game with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ, readOnly = true)
public List<Tuple2<Date, StatisticsDistributionDto>> getDistributionChanges(long bodyId, long userId,
                                                                            StatisticsPeriodDto period) {
  Iterator<BuildingsStatistics> buildingsIt = fetch(buildingsStatisticsRepository, period, userId).iterator();
  Iterator<TechnologiesStatistics> technologiesIt = fetch(technologiesStatisticsRepository, period, userId).iterator();
  Iterator<FleetStatistics> fleetIt = fetch(fleetStatisticsRepository, period, userId).iterator();
  Iterator<DefenseStatistics> defenseIt = fetch(defenseStatisticsRepository, period, userId).iterator();

  List<Tuple2<Date, StatisticsDistributionDto>> distribution = new ArrayList<>();
  while (buildingsIt.hasNext() && technologiesIt.hasNext() && fleetIt.hasNext() && defenseIt.hasNext()) {
    BuildingsStatistics b = buildingsIt.next();
    TechnologiesStatistics t = technologiesIt.next();
    FleetStatistics f = fleetIt.next();
    DefenseStatistics d = defenseIt.next();

    assert t.getAt().equals(b.getAt());
    assert f.getAt().equals(b.getAt());
    assert d.getAt().equals(b.getAt());

    distribution.add(Tuple.of(b.getAt(), new StatisticsDistributionDto(b.getPoints(), t.getPoints(), f.getPoints(),
        d.getPoints())));
  }

  return distribution;
}
 
Example #5
Source File: ShipyardServiceImpl.java    From retro-game with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(readOnly = true)
public Map<UnitKind, Tuple2<Integer, Integer>> getCurrentAndFutureCounts(Body body) {
  EnumMap<UnitKind, Integer> inQueue = body.getShipyardQueue().stream()
      .collect(Collectors.toMap(
          ShipyardQueueEntry::getKind,
          ShipyardQueueEntry::getCount,
          (a, b) -> a + b,
          () -> new EnumMap<>(UnitKind.class)
      ));
  return Arrays.stream(UnitKind.values())
      .filter(kind -> body.getUnitsCount(kind) != 0 || inQueue.getOrDefault(kind, 0) != 0)
      .collect(Collectors.toMap(
          Function.identity(),
          kind -> {
            int n = body.getUnitsCount(kind);
            return Tuple.of(n, n + inQueue.getOrDefault(kind, 0));
          },
          (a, b) -> {
            throw new IllegalStateException();
          },
          () -> new EnumMap<>(UnitKind.class)
      ));
}
 
Example #6
Source File: PregelComputation.java    From kafka-graphs with Apache License 2.0 6 votes vote down vote up
@Override
public KeyValue<K, Tuple2<Integer, Map<K, List<Message>>>> transform(
    final K readOnlyKey, final Tuple3<Integer, K, List<Message>> value
) {
    Map<K, Map<K, List<Message>>> messages = localworkSetStore.get(value._1);
    if (messages == null) {
        messages = new HashMap<>();
    }
    Map<K, List<Message>> messagesForSuperstep = messages.computeIfAbsent(readOnlyKey, k -> new HashMap<>());
    if (value._3 != null) {
        messagesForSuperstep.put(value._2, value._3);
    }
    localworkSetStore.put(value._1, messages);
    positions.merge(new TopicPartition(context.topic(), context.partition()), context.offset() + 1, Math::max);

    Set<K> forwarded = forwardedVertices.get(value._1);
    if (forwarded != null) {
        forwarded.remove(readOnlyKey);
    }

    return null;
}
 
Example #7
Source File: ReflectionUtils.java    From test-data-supplier with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Tuple2<Class<?>, String> getFactoryAnnotationMetaData(final ITestNGMethod testMethod) {
    var constructor = testMethod.getConstructorOrMethod().getConstructor();
    var method = testMethod.getConstructorOrMethod().getMethod();

    var factoryAnnotation = nonNull(method)
            ? ofNullable(method.getDeclaredAnnotation(Factory.class))
            : ofNullable(constructor.getDeclaredAnnotation(Factory.class));

    var dataProviderClass = factoryAnnotation
            .map(fa -> (Class) fa.dataProviderClass())
            .filter(cl -> cl != Object.class)
            .orElseGet(() -> testMethod.getConstructorOrMethod().getDeclaringClass());

    var dataProviderMethod = factoryAnnotation.map(Factory::dataProvider).orElse("");

    return Tuple.of(dataProviderClass, dataProviderMethod);
}
 
Example #8
Source File: EmpireSummaryDto.java    From retro-game with GNU Affero General Public License v3.0 6 votes vote down vote up
public EmpireSummaryDto(T diameter, T usedFields, T maxFields, T temperature, Tuple2<ResourcesDto, T> resources,
                        T availableEnergy, T totalEnergy, Tuple2<ResourcesDto, T> productionHourly,
                        Tuple2<ResourcesDto, T> productionDaily, Tuple2<ResourcesDto, T> productionWeekly,
                        Tuple2<ResourcesDto, T> production30days, Tuple2<ResourcesDto, T> capacity,
                        Map<BuildingKindDto, Tuple2<T, T>> buildings, Map<UnitKindDto, Tuple2<T, T>> units) {
  this.diameter = diameter;
  this.usedFields = usedFields;
  this.maxFields = maxFields;
  this.temperature = temperature;
  this.resources = resources;
  this.availableEnergy = availableEnergy;
  this.totalEnergy = totalEnergy;
  this.productionHourly = productionHourly;
  this.productionDaily = productionDaily;
  this.productionWeekly = productionWeekly;
  this.production30days = production30days;
  this.capacity = capacity;
  this.buildings = buildings;
  this.units = units;
}
 
Example #9
Source File: PaymentProcessManagerImpl.java    From spring-boot-ddd with GNU General Public License v3.0 6 votes vote down vote up
@HystrixCommand(fallbackMethod = "fallback")
@Override
public CompletionStage<Either<CommandFailure, Tuple2<PaymentId, PaymentStatus>>> process(PerformPayment performPayment) {

    LOG.debug("Payment process {}", performPayment);

    Payment payment = new Payment(applicationContext);
    CompletionStage<Either<CommandFailure, PaymentRequested>> performPaymentPromise = payment.handle(performPayment);
    return performPaymentPromise.thenCompose(paymentRequested -> paymentRequested.fold(
            rejectPayment -> completed(rejectPayment),
            acceptPayment -> authorize(payment, acceptPayment).thenCompose(paymentAuthorized -> paymentAuthorized.fold(
                    rejectAuthorization -> completed(rejectAuthorization),
                    acceptAuthorization -> {
                        if (acceptPayment.getPaymentIntent().isAuthorize()) {
                            return completed(acceptAuthorization, PaymentStatus.AUTHORIZED);
                        } else {
                            return confirm(payment, acceptPayment, acceptAuthorization);
                        }
                    }
            ))
    ));
}
 
Example #10
Source File: AnyFieldProtocol.java    From ts-reaktive with MIT License 6 votes vote down vote up
public static <T> WriteProtocol<JSONEvent, Tuple2<String,T>> write(WriteProtocol<JSONEvent, T> innerProtocol) {
    return new WriteProtocol<JSONEvent, Tuple2<String,T>>() {
        @Override
        public Class<? extends JSONEvent> getEventType() {
            return JSONEvent.class;
        }
        
        @Override
        public Writer<JSONEvent, Tuple2<String,T>> writer() {
            return innerProtocol.writer()
                .compose((Tuple2<String, T> t) -> t._2)
                .mapWithInput((t, events) -> Vector.<JSONEvent>of(new JSONEvent.FieldName(t._1)).appendAll(events));
        }
        
        @Override
        public String toString() {
            return "(any): " + innerProtocol;
        }
    };
}
 
Example #11
Source File: AriCommandResponseKafkaProcessor.java    From ari-proxy with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Tuple2<AriMessageEnvelope, CallContextAndCommandId> envelopeAriResponse(
		AriResponse ariResponse, CallContextAndCommandId callContextAndResourceId, String kafkaCommandsTopic) {
	final AriMessageEnvelope envelope = new AriMessageEnvelope(
			AriMessageType.RESPONSE,
			kafkaCommandsTopic,
			ariResponse,
			callContextAndResourceId.getCallContext(),
			callContextAndResourceId.getCommandId()
	);

	return Tuple.of(envelope, callContextAndResourceId);
}
 
Example #12
Source File: PatronFactory.java    From library with MIT License 5 votes vote down vote up
public Patron create(PatronType patronType, PatronId patronId, Set<Tuple2<BookId, LibraryBranchId>> patronHolds, Map<LibraryBranchId, Set<BookId>> overdueCheckouts) {
    return new Patron(new PatronInformation(patronId, patronType),
            allCurrentPolicies(),
            new OverdueCheckouts(overdueCheckouts),
            new PatronHolds(
                    patronHolds
                            .stream()
                            .map(tuple -> new Hold(tuple._1, tuple._2))
                            .collect(toSet())));
}
 
Example #13
Source File: RemoteTestsUtilsImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
private Option<Tuple2<String, String>> loadDetailsFromProfile() {
	return Option.ofOptional(profileAccess.getProfile())
		.map(profile -> Tuple.of(
			profile.getBrowserstack().getUsername(),
			profile.getBrowserstack().getAccessToken()))
		.filter(tuple -> StringUtils.isNotBlank(tuple._1) && StringUtils.isNotBlank(tuple._2));
}
 
Example #14
Source File: ReflectionUtils.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static Tuple2<Class<?>, String> getTestAnnotationMetaData(final ITestNGMethod testMethod) {
    var declaringClass = testMethod.getConstructorOrMethod().getDeclaringClass();
    var parentClass = findParentDataSupplierClass(testMethod.getConstructorOrMethod().getMethod(), declaringClass);
    var testAnnotation = ofNullable(testMethod.getConstructorOrMethod()
            .getMethod()
            .getDeclaredAnnotation(Test.class))
            .orElseGet(() -> declaringClass.getDeclaredAnnotation(Test.class));
    var dataSupplierClass = ofNullable(testAnnotation)
            .map(Test::dataProviderClass)
            .filter(dp -> dp != Object.class)
            .orElse((Class) parentClass);

    return Tuple.of(dataSupplierClass, testAnnotation.dataProvider());
}
 
Example #15
Source File: JavaBeanUtil.java    From javabeanutil-benchmark with MIT License 5 votes vote down vote up
private static List<Function> createFunctions(Class<?> javaBeanClass, String path) {
    List<Function> functions = new ArrayList<>();
    Stream.of(FIELD_SEPARATOR.split(path))
            .reduce(javaBeanClass, (nestedJavaBeanClass, fieldName) -> {
                Tuple2<? extends Class, Function> getFunction = createFunction(fieldName, nestedJavaBeanClass);
                functions.add(getFunction._2);
                return getFunction._1;
            }, (previousClass, nextClass) -> nextClass);
    return functions;
}
 
Example #16
Source File: Regex.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Returns a Regex for a regular expression with 2 capture groups.
 */
public static Regex<Tuple2<String,String>> compile2(String regex, int flags) {
    return new Regex<Tuple2<String,String>>(regex, flags) {
        @Override
        protected Tuple2<String, String> extract(Matcher m) {
            return Tuple.of(m.group(1), m.group(2));
        }
    };
}
 
Example #17
Source File: PatronsDatabaseRepository.java    From library with MIT License 5 votes vote down vote up
Set<Tuple2<BookId, LibraryBranchId>> mapPatronHolds(PatronDatabaseEntity patronDatabaseEntity) {
    return patronDatabaseEntity
            .booksOnHold
            .stream()
            .map(entity -> Tuple.of((new BookId(entity.bookId)), new LibraryBranchId(entity.libraryBranchId)))
            .collect(toSet());
}
 
Example #18
Source File: TestNGMethod.java    From test-data-supplier with Apache License 2.0 5 votes vote down vote up
public Tuple2<Method, Object[]> getDataSupplierMetaData() {
    return Tuple.of(dataSupplierMethod, stream(dataSupplierMethod.getParameterTypes())
        .map(t -> Match((Class) t).of(
            Case($(ITestContext.class), () -> context),
            Case($(Method.class), () -> testMethod.getConstructorOrMethod().getMethod()),
            Case($(ITestNGMethod.class), () -> testMethod),
            Case($(), () -> null)))
        .toArray());
}
 
Example #19
Source File: RemoteThreadWebDriverMapImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Load the browserstack details from configuration
 */
private void loadBrowserStackSettings() {
	final Option<Tuple2<String, String>> credentials = REMOTE_TESTS_UTILS.getCredentials();
	if (credentials.isDefined()) {
		browserStackUsername = credentials.get()._1();
		browserStackAccessToken = credentials.get()._2();
	} else {
		/*
				Log an error because there were no details
			 */
		LOGGER.error("Could not load browserstack config");
	}
}
 
Example #20
Source File: ClutchPIDConfig.java    From mantis with Apache License 2.0 5 votes vote down vote up
@java.beans.ConstructorProperties( {"setPoint", "rope", "kp", "kd"})
public ClutchPIDConfig(double setPoint, Tuple2<Double, Double> rope, double kp, double kd) {
    this.setPoint = setPoint;
    this.rope = rope;
    this.kp = kp;
    this.kd = kd;
}
 
Example #21
Source File: MaterializerWorkersTheories.java    From ts-reaktive with MIT License 5 votes vote down vote up
private Gen<Tuple2<Instant,Instant>> startAndEndTimestamps(MaterializerWorkers w) {
    return integers().from(0).upTo(w.getIds().size())
        .zip(longs().from(-5).upTo(100), longs().from(1).upTo(1000), (idx, ofs, dur) -> {
            Instant start = atLeastEpoch(w.getTimestamp(w.getIds().apply(idx)).plusMillis(ofs));
            return Tuple.of(start, start.plusMillis(dur));
        });

}
 
Example #22
Source File: ConnectedComponentsTest.java    From kafka-graphs with Apache License 2.0 5 votes vote down vote up
@Test
public void testGridConnectedComponents() throws Exception {
    String suffix = "grid";
    StreamsBuilder builder = new StreamsBuilder();

    Properties producerConfig = ClientUtils.producerConfig(CLUSTER.bootstrapServers(), LongSerializer.class,
        LongSerializer.class, new Properties()
    );
    KGraph<Long, Tuple2<Long, Long>, Long> gridGraph = GraphGenerators.gridGraph(builder, producerConfig, 10, 10);
    KTable<Long, Long> initialVertices = gridGraph.vertices().mapValues((id, v) -> id);
    KGraph<Long, Long, Long> graph = new KGraph<>(initialVertices, gridGraph.edges(),
        GraphSerialized.with(Serdes.Long(), Serdes.Long(), Serdes.Long()));

    Properties props = ClientUtils.streamsConfig("prepare-" + suffix, "prepare-client-" + suffix,
        CLUSTER.bootstrapServers(), graph.keySerde().getClass(), graph.vertexValueSerde().getClass());
    CompletableFuture<Map<TopicPartition, Long>> state = GraphUtils.groupEdgesBySourceAndRepartition(builder, props, graph, "vertices-" + suffix, "edgesGroupedBySource-" + suffix, 2, (short) 1);
    Map<TopicPartition, Long> offsets = state.get();

    algorithm =
        new PregelGraphAlgorithm<>(null, "run-" + suffix, CLUSTER.bootstrapServers(),
            CLUSTER.zKConnectString(), "vertices-" + suffix, "edgesGroupedBySource-" + suffix, offsets, graph.serialized(),
            "solutionSet-" + suffix, "solutionSetStore-" + suffix, "workSet-" + suffix, 2, (short) 1,
            Collections.emptyMap(), Optional.empty(), new ConnectedComponents<>());
    props = ClientUtils.streamsConfig("run-" + suffix, "run-client-" + suffix, CLUSTER.bootstrapServers(),
        graph.keySerde().getClass(), KryoSerde.class);
    KafkaStreams streams = algorithm.configure(new StreamsBuilder(), props).streams();
    GraphAlgorithmState<KTable<Long, Long>> paths = algorithm.run();
    paths.result().get();

    Thread.sleep(2000);

    Map<Long, Long> map = StreamUtils.mapFromStore(paths.streams(), "solutionSetStore-" + suffix);
    log.debug("result: {}", map);

    for (long i = 0; i < 100; i++) {
        assertEquals(0L, map.get(i).longValue());
    }
}
 
Example #23
Source File: PaymentProcessManagerImpl.java    From spring-boot-ddd with GNU General Public License v3.0 5 votes vote down vote up
private CompletionStage<Either<CommandFailure, Tuple2<PaymentId, PaymentStatus>>> confirm(Payment payment, PaymentRequested acceptPayment, PaymentAuthorized acceptAuthorization) {
    ConfirmPayment confirmPayment = ConfirmPayment.commandOf(
            acceptAuthorization.getPaymentId(),
            acceptAuthorization.getCustomerId()
    );
    CompletionStage<Either<CommandFailure, PaymentConfirmed>> confirmPaymentPromise = payment.handle(confirmPayment);
    return confirmPaymentPromise.thenApply(paymentConfirmed -> paymentConfirmed.fold(
            rejectConfirmation -> left(rejectConfirmation),
            acceptConfirmation -> right(Tuple.of(acceptPayment.getPaymentId(), PaymentStatus.CAPTURED))
    ));
}
 
Example #24
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
private Tuple2<String, Option<CNode>> configureMapping(CNode config) {
    Mapping mapping = unchecked(config::asMapping).apply();
    if (mapping.size() != 1) {
        throw new IllegalArgumentException("Single entry map expected to configure a " + target.getName());
    } else {
        Map.Entry<String, CNode> next = mapping.entrySet().iterator().next();
        return Tuple.of(next.getKey(), Option.some(next.getValue()));
    }
}
 
Example #25
Source File: EmpireBodyDto.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
public EmpireBodyDto(long id, String name, CoordinatesDto coordinates, BodyTypeDto type, int image, int diameter,
                     int usedFields, int maxFields, int temperature, Tuple2<ResourcesDto, Long> resources,
                     int availableEnergy, int totalEnergy, Tuple2<ResourcesDto, Long> productionHourly,
                     Tuple2<ResourcesDto, Long> productionDaily, Tuple2<ResourcesDto, Long> productionWeekly,
                     Tuple2<ResourcesDto, Long> production30days, Tuple2<ResourcesDto, Long> capacity,
                     Map<BuildingKindDto, Tuple2<Integer, Integer>> buildings,
                     Map<UnitKindDto, Tuple2<Integer, Integer>> units) {
  this.id = id;
  this.name = name;
  this.coordinates = coordinates;
  this.type = type;
  this.image = image;
  this.diameter = diameter;
  this.usedFields = usedFields;
  this.maxFields = maxFields;
  this.temperature = temperature;
  this.resources = resources;
  this.availableEnergy = availableEnergy;
  this.totalEnergy = totalEnergy;
  this.productionHourly = productionHourly;
  this.productionDaily = productionDaily;
  this.productionWeekly = productionWeekly;
  this.production30days = production30days;
  this.capacity = capacity;
  this.buildings = buildings;
  this.units = units;
}
 
Example #26
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
private Tuple2<String, Option<CNode>> preConfigure(CNode config) {
    switch (config.getType()) {
        case SCALAR:
            return configureScalar(config);
        case MAPPING:
            return configureMapping(config);
        default:
            return configureUnexpected(config);
    }
}
 
Example #27
Source File: TechnologyServiceImpl.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
private Map<Long, int[]> getEffectiveLevelTables(User user, Collection<Long> bodiesIds) {
  var irnLevel = user.getTechnologyLevel(TechnologyKind.INTERGALACTIC_RESEARCH_NETWORK);

  var bodies = user.getBodies();
  var labs = bodies.entrySet().stream()
      .map(entry -> Tuple.of(entry.getKey(), entry.getValue().getBuildingLevel(BuildingKind.RESEARCH_LAB)))
      .sorted(Comparator.comparingInt(Tuple2<Long, Integer>::_2).reversed())
      .collect(Collectors.toList());

  Map<Long, int[]> tables = new HashMap<>(bodiesIds.size());
  for (long bodyId : bodiesIds) {
    var currentBodyLabLevel = bodies.get(bodyId).getBuildingLevel(BuildingKind.RESEARCH_LAB);

    int[] table = new int[maxRequiredLabLevel + 1];
    Arrays.fill(table, 0, Math.min(maxRequiredLabLevel, currentBodyLabLevel) + 1, currentBodyLabLevel);
    labs.stream()
        .filter(tuple -> tuple._1 != bodyId)
        .limit(irnLevel)
        .mapToInt(Tuple2::_2)
        .forEach(level -> {
          for (int i = Math.min(maxRequiredLabLevel, level); i >= 0; i--) {
            if (table[i] != 0) {
              table[i] += level;
            }
          }
        });

    tables.put(bodyId, table);
  }
  return tables;
}
 
Example #28
Source File: BuildingsServiceImpl.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Map<BuildingKind, Tuple2<Integer, Integer>> getCurrentAndFutureLevels(Body body) {
  State state = new State(body, body.getBuildingQueue());
  return Arrays.stream(BuildingKind.values())
      .filter(kind -> body.getBuildingLevel(kind) != 0 || state.buildings.getOrDefault(kind, 0) != 0)
      .collect(Collectors.toMap(
          Function.identity(),
          kind -> Tuple.of(body.getBuildingLevel(kind), state.buildings.getOrDefault(kind, 0)),
          (a, b) -> {
            throw new IllegalStateException();
          },
          () -> new EnumMap<>(BuildingKind.class)
      ));
}
 
Example #29
Source File: StatisticsController.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
@GetMapping("/statistics/distinct-changes")
@PreAuthorize("hasPermission(#bodyId, 'ACCESS')")
@Activity(bodies = "#bodyId")
public String distinctChanges(@RequestParam(name = "body") long bodyId,
                              @RequestParam(name = "user") long userId,
                              @RequestParam @NotNull StatisticsKindDto kind,
                              @RequestParam @NonNull StatisticsPeriodDto period,
                              Model model) {
  List<Tuple2<Date, PointsAndRankPairDto>> changes = statisticsService.getDistinctChanges(bodyId, userId, kind,
      period);
  StringBuilder builder = new StringBuilder();
  boolean first = true;
  for (Tuple2<Date, PointsAndRankPairDto> change : changes) {
    if (!first)
      builder.append(';');
    else
      first = false;
    builder.append(change._1.toInstant().getEpochSecond());
    builder.append(',');
    builder.append(change._2.getPoints());
    builder.append(',');
    builder.append(change._2.getRank());
  }

  model.addAttribute("bodyId", bodyId);
  model.addAttribute("userId", userId);
  model.addAttribute("kind", kind);
  model.addAttribute("period", period);
  model.addAttribute("changes", builder.toString());

  return "statistics-distinct-changes";
}
 
Example #30
Source File: StatisticsController.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
@GetMapping("/statistics/distribution-changes")
@PreAuthorize("hasPermission(#bodyId, 'ACCESS')")
@Activity(bodies = "#bodyId")
public String distributionChanges(@RequestParam(name = "body") long bodyId,
                                  @RequestParam(name = "user") long userId,
                                  @RequestParam @NonNull StatisticsPeriodDto period,
                                  Model model) {
  List<Tuple2<Date, StatisticsDistributionDto>> changes = statisticsService.getDistributionChanges(bodyId, userId,
      period);
  StringBuilder builder = new StringBuilder();
  boolean first = true;
  for (Tuple2<Date, StatisticsDistributionDto> change : changes) {
    if (!first)
      builder.append(';');
    else
      first = false;

    builder.append(change._1.toInstant().getEpochSecond());
    builder.append(',');

    StatisticsDistributionDto d = change._2;
    builder.append(d.getBuildings());
    builder.append(',');
    builder.append(d.getTechnologies());
    builder.append(',');
    builder.append(d.getFleet());
    builder.append(',');
    builder.append(d.getDefense());
  }

  model.addAttribute("bodyId", bodyId);
  model.addAttribute("userId", userId);
  model.addAttribute("period", period);
  model.addAttribute("changes", builder.toString());

  return "statistics-distribution-changes";
}