Java Code Examples for io.vlingo.common.Tuple2#from()

The following examples show how to use io.vlingo.common.Tuple2#from() . 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: Product.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
static Tuple2<ProductId, Product> defineWith(
        final Stage stage,
        final Tenant tenant,
        final ProductOwner productOwner,
        final String name,
        final String description,
        final boolean hasDiscussion) {

    assert (tenant != null && tenant.id != null);
    assert (productOwner != null && productOwner.id != null);
    assert (name != null);
    assert (description != null);

    Address address = stage.addressFactory().unique();
    final ProductId productId = ProductId.fromExisting(address.idString());
    final Definition definition = Definition.has(ProductEntity.class, Definition.parameters(tenant, productId), productId.id);
    final Product product = stage.actorFor(Product.class, definition);
    product.define(productOwner, name, description, hasDiscussion);
    return Tuple2.from(productId, product);
}
 
Example 2
Source File: ProxyGenerator.java    From vlingo-actors with Mozilla Public License 2.0 6 votes vote down vote up
private Tuple2<List<InvalidProtocolException.Failure>, String> methodDefinitions(final Class<?> protocolInterface, final Method[] methods) {
  final StringBuilder builder = new StringBuilder();
  final List<InvalidProtocolException.Failure> failures = new ArrayList<>();

  int count = 0;

  for (final Method method : methods) {
    if (!Modifier.isStatic(method.getModifiers())) {
        final Tuple2<InvalidProtocolException.Failure, String> result = methodDefinition(protocolInterface, method, ++count);
        if (result._1 == null) {
            builder.append(result._2);
        } else {
            failures.add(result._1);
        }
    }
  }

  if (failures.isEmpty()) {
      return Tuple2.from(null, builder.toString());
  } else {
      return Tuple2.from(failures, null);
  }
}
 
Example 3
Source File: ArgumentLock.java    From vlingo-actors with Mozilla Public License 2.0 6 votes vote down vote up
public static Lock acquire(Object param) {
  Object intern = null;
  synchronized (locks) {
    Tuple2<WeakReference<Object>, Lock> pair = locks.get(param);
    if (pair != null) {
      intern = pair._1.get();
    }
    if (intern == null) {
      intern = param;
      pair = Tuple2.from(new WeakReference<>(intern), new ReentrantLock());
      locks.put(intern, pair);
    }
  }

  return new ArgumentLock(intern, locks.get(intern)._2);
}
 
Example 4
Source File: Action.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
private Tuple2<String, List<MethodParameter>> parse(final String to) {
  final String bad = "Invalid to declaration: " + to;

  final int openParen = to.indexOf("(");
  final int closeParen = to.lastIndexOf(")");

  if (openParen < 0 || closeParen < 0) {
    throw new IllegalStateException(bad);
  }

  final String methodName = to.substring(0, openParen);
  final String[] rawParameters = to.substring(openParen + 1, closeParen).split(",");
  final List<MethodParameter> parameters = new ArrayList<>(rawParameters.length);

  for (String rawParameter : rawParameters) {
    rawParameter = rawParameter.trim();
    if (!rawParameter.isEmpty()) {
      if (rawParameter.startsWith("body:")) {
        final String[] body = typeAndName(rawParameter.substring(5));
        parameters.add(new MethodParameter(body[0], body[1], load(qualifiedType(body[0]))));
      } else {
        final String[] other = typeAndName(rawParameter);
        parameters.add(new MethodParameter(other[0], other[1]));
      }
    }
  }

  return Tuple2.from(methodName, parameters);
}
 
Example 5
Source File: AllSseFeedActor.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
private Tuple2<List<SseEvent>, Integer> readSubStream(final int startId, final int endId, final int retry) {
  final List<SseEvent> substream = new ArrayList<>();
  int type = 0;
  int id = startId;
  for ( ; id <= endId; ++id) {
    substream.add(builder.clear().event("mimeType-" + ('A' + type)).id(id).data("data-" + id).retry(retry).toEvent());
    type = type > 26 ? 0 : type + 1;
  }

  return Tuple2.from(substream, id + 1);
}
 
Example 6
Source File: Forum.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
static Tuple2<ForumId, Forum> startWith(
        final Stage stage,
        final Tenant tenant,
        final ForumDescription description) {
  final Forum forum = stage.actorFor(Forum.class, Definition.has(ForumEntity.class, Definition.parameters(tenant, description.forumId)));
  forum.startWith(description.creator, description.moderator, description.topic, description.description, description.exclusiveOwner);
  return Tuple2.from(description.forumId, forum);
}
 
Example 7
Source File: FileProcessorTest.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
private Tuple2<File,String> generateFile() throws Exception {
  final String prefix = "data" + random.nextLong();
  final String suffix = ".dat";

  final File file = File.createTempFile(prefix, suffix);

  return Tuple2.from(file, file.getAbsolutePath());
}
 
Example 8
Source File: FiltersTest.java    From vlingo-http with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public Tuple2<Request, Boolean> filter(final Request request) {
  return Tuple2.from(request, ++count < 5);
}
 
Example 9
Source File: FiltersTest.java    From vlingo-http with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public Tuple2<Response, Boolean> filter(final Response response) {
  return Tuple2.from(response, ++count < 5);
}
 
Example 10
Source File: ProxyGenerator.java    From vlingo-actors with Mozilla Public License 2.0 4 votes vote down vote up
private Tuple2<InvalidProtocolException.Failure, String> methodDefinition(final Class<?> protocolInterface, final Method method, final int count) {
  final StringBuilder builder = new StringBuilder();

  final String genericTemplate = GenericParser.genericTemplateOf(method);
  final String parameterTemplate = GenericParser.parametersTemplateOf(method);
  final String signatureReturnType = GenericParser.returnTypeOf(method);
  final boolean isACompletes = signatureReturnType.startsWith("io.vlingo.common.Completes");
  final boolean isAFuture = signatureReturnType.startsWith("java.util.concurrent.Future") || signatureReturnType.startsWith("java.util.concurrent.CompletableFuture");
  final boolean hasResult = isACompletes || isAFuture;

  final String methodSignature = MessageFormat.format("  public {0}{1} {2}{3}", genericTemplate, signatureReturnType, method.getName(), parameterTemplate);
  final String throwsExceptions = throwsExceptions(method);
  final String ifNotStopped = "    if (!actor.isStopped()) {";
  final String bindSelfStatement = MessageFormat.format("      ActorProxyBase<{0}> self = this;", protocolInterface.getSimpleName());
  final String consumerStatement = MessageFormat.format("      final SerializableConsumer<{0}> consumer = (actor) -> actor.{1}{2};", protocolInterface.getSimpleName(), method.getName(), parameterNamesFor(method));
  final String completesStatement = isACompletes ? MessageFormat.format("      final {0} returnValue = Completes.using(actor.scheduler());\n", signatureReturnType) : "";
  final String futureStatement = isAFuture ? MessageFormat.format("      final {0} returnValue = new java.util.concurrent.CompletableFuture<>();\n", signatureReturnType) : "";
  final String representationName = MessageFormat.format("{0}Representation{1}", method.getName(), count);
  final String preallocatedMailbox =  MessageFormat.format("      if (mailbox.isPreallocated()) '{' mailbox.send(actor, {0}.class, {1}, {2}{3}); '}'", protocolInterface.getSimpleName(), "consumer", hasResult ? "Returns.value(returnValue), ":"null, ", representationName);
  final String mailboxSendStatement = MessageFormat.format("      else '{' mailbox.send(new LocalMessage<{0}>(actor, {0}.class, {1}, {2}{3})); '}'", protocolInterface.getSimpleName(), "consumer", hasResult ? "Returns.value(returnValue), ":"", representationName);
  final String completesReturnStatement = hasResult ? "      return returnValue;\n" : "";
  final String elseDead = MessageFormat.format("      actor.deadLetters().failedDelivery(new DeadLetter(actor, {0}));", representationName);
  final String returnValue = returnValue(method.getReturnType());
  final String returnStatement = returnValue.isEmpty() ? "" : MessageFormat.format("    return {0};\n", returnValue);

  if (!isACompletes
          && !returnValue.isEmpty()
          && !genericTemplate.contains(signatureReturnType)
          && !genericTemplate.contains(parameterTemplate)
          && !isSafeGenerable(protocolInterface)
          && !isAFuture) {
      return Tuple2.from(
              new InvalidProtocolException.Failure(
                      methodSignature,
                      "method return type should be either `void`, `Completes<T>`, `Future<T>` or `CompletableFuture<T>`. The found return type is `" + signatureReturnType + "`. Consider wrapping it in `Completes<T>`, like `Completes<" + validForCompletes(signatureReturnType) + ">`."
              ), null
      );
  }
  builder
    .append(methodSignature).append(throwsExceptions).append(" {\n")
    .append(ifNotStopped).append("\n")
    .append(bindSelfStatement).append("\n")
    .append(consumerStatement).append("\n")
    .append(completesStatement)
    .append(futureStatement)
    .append(preallocatedMailbox).append("\n")
    .append(mailboxSendStatement).append("\n")
    .append(completesReturnStatement)
    .append("    } else {\n")
    .append(elseDead).append("\n")
    .append("    }\n")
    .append(returnStatement)
    .append("  }\n");

  return Tuple2.from(null, builder.toString());
}