Java Code Examples for com.google.common.base.VerifyException

The following examples show how to use com.google.common.base.VerifyException. These examples are extracted from open source projects. 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 Project: nomulus   Source File: DnsUpdateWriterTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testPublishDomainFails_whenDnsUpdateReturnsError() throws Exception {
  DomainBase domain =
      persistActiveDomain("example.tld")
          .asBuilder()
          .setNameservers(ImmutableSet.of(persistActiveHost("ns1.example.tld").createVKey()))
          .build();
  persistResource(domain);
  when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL));
  VerifyException thrown =
      assertThrows(
          VerifyException.class,
          () -> {
            writer.publishDomain("example.tld");
            writer.commit();
          });
  assertThat(thrown).hasMessageThat().contains("SERVFAIL");
}
 
Example 2
Source Project: presto   Source File: ReflectionWindowFunctionSupplier.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected T newWindowFunction(List<Integer> inputs, boolean ignoreNulls, List<LambdaProvider> lambdaProviders)
{
    try {
        switch (constructorType) {
            case NO_INPUTS:
                return constructor.newInstance();
            case INPUTS:
                return constructor.newInstance(inputs);
            case INPUTS_IGNORE_NULLS:
                return constructor.newInstance(inputs, ignoreNulls);
            default:
                throw new VerifyException("Unhandled constructor type: " + constructorType);
        }
    }
    catch (ReflectiveOperationException e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source Project: presto   Source File: FilterStatsCalculator.java    License: Apache License 2.0 6 votes vote down vote up
private Type getType(Expression expression)
{
    if (expression instanceof SymbolReference) {
        Symbol symbol = Symbol.from(expression);
        return requireNonNull(types.get(symbol), () -> format("No type for symbol %s", symbol));
    }

    ExpressionAnalyzer expressionAnalyzer = ExpressionAnalyzer.createWithoutSubqueries(
            metadata,
            new AllowAllAccessControl(),
            session,
            types,
            ImmutableMap.of(),
            // At this stage, there should be no subqueries in the plan.
            node -> new VerifyException("Unexpected subquery"),
            WarningCollector.NOOP,
            false);
    return expressionAnalyzer.analyze(expression, Scope.create());
}
 
Example 4
Source Project: presto   Source File: RowExpressionCompiler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BytecodeNode visitLambda(LambdaDefinitionExpression lambda, Context context)
{
    checkState(compiledLambdaMap.containsKey(lambda), "lambda expressions map does not contain this lambda definition");
    if (!context.lambdaInterface.get().isAnnotationPresent(FunctionalInterface.class)) {
        // lambdaInterface is checked to be annotated with FunctionalInterface when generating ScalarFunctionImplementation
        throw new VerifyException("lambda should be generated as class annotated with FunctionalInterface");
    }

    BytecodeGeneratorContext generatorContext = new BytecodeGeneratorContext(
            RowExpressionCompiler.this,
            context.getScope(),
            callSiteBinder,
            cachedInstanceBinder,
            metadata);

    return generateLambda(
            generatorContext,
            ImmutableList.of(),
            compiledLambdaMap.get(lambda),
            context.getLambdaInterface().get());
}
 
Example 5
Source Project: presto   Source File: TestDynamicFiltersChecker.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "Dynamic filters \\[DF\\] present in join were not fully consumed by it's probe side.")
public void testUnconsumedDynamicFilterInJoin()
{
    PlanNode root = builder.join(
            INNER,
            builder.filter(expression("ORDERS_OK > 0"), ordersTableScanNode),
            lineitemTableScanNode,
            ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
            ImmutableList.of(ordersOrderKeySymbol),
            ImmutableList.of(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            ImmutableMap.of(new DynamicFilterId("DF"), lineitemOrderKeySymbol));
    validatePlan(root);
}
 
Example 6
Source Project: presto   Source File: TestDynamicFiltersChecker.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "Dynamic filters \\[DF\\] present in join were consumed by it's build side.")
public void testDynamicFilterConsumedOnBuildSide()
{
    PlanNode root = builder.join(
            INNER,
            builder.filter(
                    createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, ordersOrderKeySymbol.toSymbolReference()),
                    ordersTableScanNode),
            builder.filter(
                    createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, ordersOrderKeySymbol.toSymbolReference()),
                    lineitemTableScanNode),
            ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
            ImmutableList.of(ordersOrderKeySymbol),
            ImmutableList.of(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            ImmutableMap.of(new DynamicFilterId("DF"), lineitemOrderKeySymbol));
    validatePlan(root);
}
 
Example 7
Source Project: presto   Source File: TestDynamicFiltersChecker.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "All consumed dynamic filters could not be matched with a join.")
public void testUnmatchedDynamicFilter()
{
    PlanNode root = builder.output(
            ImmutableList.of(),
            ImmutableList.of(),
            builder.join(
                    INNER,
                    ordersTableScanNode,
                    builder.filter(
                            combineConjuncts(
                                    metadata,
                                    expression("LINEITEM_OK > 0"),
                                    createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, lineitemOrderKeySymbol.toSymbolReference())),
                            lineitemTableScanNode),
                    ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
                    ImmutableList.of(ordersOrderKeySymbol),
                    ImmutableList.of(),
                    Optional.empty(),
                    Optional.empty(),
                    Optional.empty(),
                    ImmutableMap.of()));
    validatePlan(root);
}
 
Example 8
Source Project: presto   Source File: TestDynamicFiltersChecker.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "Dynamic filters \\[Descriptor\\{id=DF, input=\"ORDERS_OK\"\\}\\] present in filter predicate whose source is not a table scan.")
public void testDynamicFilterNotAboveTableScan()
{
    PlanNode root = builder.output(
            ImmutableList.of(),
            ImmutableList.of(),
            builder.join(
                    INNER,
                    builder.filter(
                            combineConjuncts(
                                    metadata,
                                    expression("LINEITEM_OK > 0"),
                                    createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, ordersOrderKeySymbol.toSymbolReference())),
                            builder.values(lineitemOrderKeySymbol)),
                    ordersTableScanNode,
                    ImmutableList.of(new JoinNode.EquiJoinClause(lineitemOrderKeySymbol, ordersOrderKeySymbol)),
                    ImmutableList.of(),
                    ImmutableList.of(),
                    Optional.empty(),
                    Optional.empty(),
                    Optional.empty(),
                    ImmutableMap.of(new DynamicFilterId("DF"), ordersOrderKeySymbol)));
    validatePlan(root);
}
 
Example 9
Source Project: presto   Source File: HivePartitionManager.java    License: Apache License 2.0 6 votes vote down vote up
public HivePartitionResult getPartitions(ConnectorTableHandle tableHandle, List<List<String>> partitionValuesList)
{
    HiveTableHandle hiveTableHandle = (HiveTableHandle) tableHandle;
    SchemaTableName tableName = hiveTableHandle.getSchemaTableName();
    List<HiveColumnHandle> partitionColumns = hiveTableHandle.getPartitionColumns();
    Optional<HiveBucketHandle> bucketHandle = hiveTableHandle.getBucketHandle();

    List<String> partitionColumnNames = partitionColumns.stream()
            .map(HiveColumnHandle::getName)
            .collect(toImmutableList());

    List<Type> partitionColumnTypes = partitionColumns.stream()
            .map(HiveColumnHandle::getType)
            .collect(toImmutableList());

    List<HivePartition> partitionList = partitionValuesList.stream()
            .map(partitionValues -> toPartitionName(partitionColumnNames, partitionValues))
            .map(partitionName -> parseValuesAndFilterPartition(tableName, partitionName, partitionColumns, partitionColumnTypes, TupleDomain.all(), value -> true))
            .map(partition -> partition.orElseThrow(() -> new VerifyException("partition must exist")))
            .collect(toImmutableList());

    return new HivePartitionResult(partitionColumns, partitionList, TupleDomain.all(), TupleDomain.all(), TupleDomain.all(), bucketHandle, Optional.empty());
}
 
Example 10
Source Project: cloud-opensource-java   Source File: ClassDumperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIsUnusedClassSymbolReference_classSymbolReferenceNotFound()
    throws IOException, URISyntaxException {
  ClassDumper classDumper =
      ClassDumper.create(
          ImmutableList.of(
              classPathEntryOfResource("testdata/conscrypt-openjdk-uber-1.4.2.jar")));

  try {
    classDumper.isUnusedClassSymbolReference(
        "org.conscrypt.Conscrypt", new ClassSymbol("dummy.NoSuchClass"));

    Assert.fail("It should throw VerifyException when it cannot find a class symbol reference");
  } catch (VerifyException ex) {
    // pass
    Truth.assertThat(ex)
        .hasMessageThat()
        .isEqualTo(
            "When checking a class reference from org.conscrypt.Conscrypt to dummy.NoSuchClass,"
                + " the reference to the target class is no longer found in the source class's"
                + " constant pool.");
  }
}
 
Example 11
private void checkOverrideMethods() {
  annotatedElement.getEnclosedElements().stream()
      .filter(element -> element instanceof ExecutableElement)
      .map(element -> (ExecutableElement) element)
      .forEach(
          method -> {
            if (keyNameFields.contains(
                method.getSimpleName().toString().replace(SETTER_PREFIX, "")))
              throw new VerifyException(
                  getMethodNameVerifyErrorMessage(method.getSimpleName().toString()));
            else if (keyNameFields.contains(
                method.getSimpleName().toString().replace(GETTER_PREFIX, "")))
              throw new VerifyException(
                  getMethodNameVerifyErrorMessage(method.getSimpleName().toString()));
            else if (keyNameFields.contains(
                method.getSimpleName().toString().replace(HAS_PREFIX, "")))
              throw new VerifyException(
                  getMethodNameVerifyErrorMessage(method.getSimpleName().toString()));
            else if (keyNameFields.contains(
                method.getSimpleName().toString().replace(REMOVE_PREFIX, "")))
              throw new VerifyException(
                  getMethodNameVerifyErrorMessage(method.getSimpleName().toString()));
          });
}
 
Example 12
Source Project: PreferenceRoom   Source File: PreferenceRoomProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void processInjector(PreferenceComponentAnnotatedClass annotatedClass)
    throws VerifyException {
  try {
    annotatedClass.annotatedElement.getEnclosedElements().stream()
        .filter(element -> element instanceof ExecutableElement)
        .map(element -> (ExecutableElement) element)
        .filter(method -> method.getParameters().size() == 1)
        .forEach(
            method -> {
              MethodSpec methodSpec = MethodSpec.overriding(method).build();
              ParameterSpec parameterSpec = methodSpec.parameters.get(0);
              TypeElement injectedElement =
                  processingEnv.getElementUtils().getTypeElement(parameterSpec.type.toString());
              generateProcessInjector(annotatedClass, injectedElement);
            });
  } catch (VerifyException e) {
    showErrorLog(e.getMessage(), annotatedClass.annotatedElement);
    e.printStackTrace();
  }
}
 
Example 13
Source Project: nomulus   Source File: RequestModule.java    License: Apache License 2.0 6 votes vote down vote up
@Provides
@JsonPayload
@SuppressWarnings("unchecked")
static Map<String, Object> provideJsonPayload(
    @Header("Content-Type") MediaType contentType,
    @Payload String payload) {
  if (!JSON_UTF_8.is(contentType.withCharset(UTF_8))) {
    throw new UnsupportedMediaTypeException(
        String.format("Expected %s Content-Type", JSON_UTF_8.withoutParameters()));
  }
  try {
    return (Map<String, Object>) JSONValue.parseWithException(payload);
  } catch (ParseException e) {
    throw new BadRequestException(
        "Malformed JSON", new VerifyException("Malformed JSON:\n" + payload, e));
  }
}
 
Example 14
Source Project: nomulus   Source File: PgpHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Search for public key on keyring based on a substring (like an email address).
 *
 * @throws VerifyException if the key couldn't be found.
 * @see #lookupKeyPair
 */
public static PGPPublicKey lookupPublicKey(
    PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) {
  try {
    Iterator<PGPPublicKeyRing> results =
        keyring.getKeyRings(checkNotNull(query, "query"), true, true);
    verify(results.hasNext(), "No public key found matching substring: %s", query);
    while (results.hasNext()) {
      Optional<PGPPublicKey> result = lookupPublicSubkey(results.next(), want);
      if (result.isPresent()) {
        return result.get();
      }
    }
    throw new VerifyException(String.format(
        "No public key (%s) found matching substring: %s", want, query));
  } catch (PGPException e) {
    throw new VerifyException(String.format("Public key lookup failed for query: %s", query), e);
  }
}
 
Example 15
Source Project: nomulus   Source File: PgpHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Same as {@link #lookupPublicKey} but also retrieves the associated private key.
 *
 * @throws VerifyException if either keys couldn't be found.
 * @see #lookupPublicKey
 */
public static PGPKeyPair lookupKeyPair(
    PGPPublicKeyRingCollection publics,
    PGPSecretKeyRingCollection privates,
    String query,
    KeyRequirement want) {
  PGPPublicKey publicKey = lookupPublicKey(publics, query, want);
  PGPPrivateKey privateKey;
  try {
    PGPSecretKey secret = verifyNotNull(privates.getSecretKey(publicKey.getKeyID()),
        "Keyring missing private key associated with public key id: %x (query '%s')",
        publicKey.getKeyID(), query);
    // We do not support putting a password on the private key so we're just going to
    // put char[0] here.
    privateKey = secret.extractPrivateKey(
        new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
            .build(new char[0]));
  } catch (PGPException e) {
    throw new VerifyException(String.format("Could not load PGP private key for: %s", query), e);
  }
  return new PGPKeyPair(publicKey, privateKey);
}
 
Example 16
Source Project: nomulus   Source File: DnsUpdateWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testPublishHostFails_whenDnsUpdateReturnsError() throws Exception {
  HostResource host =
      persistActiveSubordinateHost("ns1.example.tld", persistActiveDomain("example.tld"))
          .asBuilder()
          .setInetAddresses(ImmutableSet.of(InetAddresses.forString("10.0.0.1")))
          .build();
  persistResource(host);
  when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL));
  VerifyException thrown =
      assertThrows(
          VerifyException.class,
          () -> {
            writer.publishHost("ns1.example.tld");
            writer.commit();
          });
  assertThat(thrown).hasMessageThat().contains("SERVFAIL");
}
 
Example 17
Source Project: yangtools   Source File: ArgumentContextUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
final @NonNull String stringFromStringContext(final ArgumentContext context, final StatementSourceReference ref) {
    // Get first child, which we fully expect to exist and be a lexer token
    final ParseTree firstChild = context.getChild(0);
    verify(firstChild instanceof TerminalNode, "Unexpected shape of %s", context);
    final TerminalNode firstNode = (TerminalNode) firstChild;
    final int firstType = firstNode.getSymbol().getType();
    switch (firstType) {
        case YangStatementParser.IDENTIFIER:
            // Simple case, there is a simple string, which cannot contain anything that we would need to process.
            return firstNode.getText();
        case YangStatementParser.STRING:
            // Complex case, defer to a separate method
            return concatStrings(context, ref);
        default:
            throw new VerifyException("Unexpected first symbol in " + context);
    }
}
 
Example 18
Source Project: yangtools   Source File: JaxenTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Test(expected = UnresolvableException.class)
public void testYangFunctionContext() throws UnresolvableException, FunctionCallException {
    final YangFunctionContext yangFun = YangFunctionContext.getInstance();
    assertNotNull(yangFun);
    final Function function = yangFun.getFunction("urn:opendaylight.test2", null, "current");
    assertNotNull(function);

    try {
        final Context context = mock(Context.class);
        final ArrayList<Object> list = new ArrayList<>();
        function.call(context, list);
        fail();
    } catch (VerifyException e) {
        // Expected
    }

    yangFun.getFunction("urn:opendaylight.test2", "test2", "root");
}
 
Example 19
Source Project: grpc-java   Source File: ServiceConfigUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static Set<Status.Code> getStatusCodesFromList(List<?> statuses) {
  EnumSet<Status.Code> codes = EnumSet.noneOf(Status.Code.class);
  for (Object status : statuses) {
    Status.Code code;
    if (status instanceof Double) {
      Double statusD = (Double) status;
      int codeValue = statusD.intValue();
      verify((double) codeValue == statusD, "Status code %s is not integral", status);
      code = Status.fromCodeValue(codeValue).getCode();
      verify(code.value() == statusD.intValue(), "Status code %s is not valid", status);
    } else if (status instanceof String) {
      try {
        code = Status.Code.valueOf((String) status);
      } catch (IllegalArgumentException iae) {
        throw new VerifyException("Status code " + status + " is not valid", iae);
      }
    } else {
      throw new VerifyException(
          "Can not convert status code " + status + " to Status.Code, because its type is "
              + status.getClass());
    }
    codes.add(code);
  }
  return Collections.unmodifiableSet(codes);
}
 
Example 20
Source Project: buck   Source File: VersionUniverseVersionSelector.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected Optional<Map.Entry<String, VersionUniverse>> getVersionUniverse(TargetNode<?> root) {
  Optional<String> universeName = getVersionUniverseName(root);
  if (!universeName.isPresent() && !universes.isEmpty()) {
    return Optional.of(Iterables.get(universes.entrySet(), 0));
  }
  if (!universeName.isPresent()) {
    return Optional.empty();
  }
  VersionUniverse universe = universes.get(universeName.get());
  if (universe == null) {
    throw new VerifyException(
        String.format(
            "%s: unknown version universe \"%s\"", root.getBuildTarget(), universeName.get()));
  }
  return Optional.of(new AbstractMap.SimpleEntry<>(universeName.get(), universe));
}
 
Example 21
Source Project: grpc-nebula-java   Source File: DetailErrorSample.java    License: Apache License 2.0 5 votes vote down vote up
static void verifyErrorReply(Throwable t) {
  Status status = Status.fromThrowable(t);
  Metadata trailers = Status.trailersFromThrowable(t);
  Verify.verify(status.getCode() == Status.Code.INTERNAL);
  Verify.verify(trailers.containsKey(DEBUG_INFO_TRAILER_KEY));
  Verify.verify(status.getDescription().equals(DEBUG_DESC));
  try {
    Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO));
  } catch (IllegalArgumentException e) {
    throw new VerifyException(e);
  }
}
 
Example 22
Source Project: grpc-nebula-java   Source File: DetailErrorSample.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
  ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new ClientCall.Listener<HelloReply>() {

    @Override
    public void onClose(Status status, Metadata trailers) {
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(trailers.containsKey(DEBUG_INFO_TRAILER_KEY));
      try {
        Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO));
      } catch (IllegalArgumentException e) {
        throw new VerifyException(e);
      }

      latch.countDown();
    }
  }, new Metadata());

  call.sendMessage(HelloRequest.newBuilder().build());
  call.halfClose();

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
 
Example 23
Source Project: presto   Source File: AggregationImplementation.java    License: Apache License 2.0 5 votes vote down vote up
private static List<ParameterType> parseParameterMetadataTypes(Method method)
{
    ImmutableList.Builder<ParameterType> builder = ImmutableList.builder();

    Annotation[][] annotations = method.getParameterAnnotations();
    String methodName = method.getDeclaringClass() + "." + method.getName();

    checkArgument(method.getParameterCount() > 0, "At least @AggregationState argument is required for each of aggregation functions.");

    int i = 0;
    if (annotations[0].length == 0) {
        // Backward compatibility - first argument without annotations is interpreted as State argument
        builder.add(STATE);
        i++;
    }

    for (; i < annotations.length; ++i) {
        Annotation baseTypeAnnotation = baseTypeAnnotation(annotations[i], methodName);
        if (isImplementationDependencyAnnotation(baseTypeAnnotation)) {
            // Implementation dependencies are bound in specializing phase.
            // For that reason there are omitted in parameter metadata, as they
            // are no longer visible while processing aggregations.
        }
        else if (baseTypeAnnotation instanceof AggregationState) {
            builder.add(STATE);
        }
        else if (baseTypeAnnotation instanceof SqlType) {
            boolean isParameterBlock = isParameterBlock(annotations[i]);
            boolean isParameterNullable = isParameterNullable(annotations[i]);
            builder.add(inputChannelParameterType(isParameterNullable, isParameterBlock, methodName));
        }
        else if (baseTypeAnnotation instanceof BlockIndex) {
            builder.add(BLOCK_INDEX);
        }
        else {
            throw new VerifyException("Unhandled annotation: " + baseTypeAnnotation);
        }
    }
    return builder.build();
}
 
Example 24
Source Project: presto   Source File: SignatureBinder.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<BoundVariables> iterativeSolve(List<TypeConstraintSolver> constraints)
{
    BoundVariables.Builder boundVariablesBuilder = BoundVariables.builder();
    for (int i = 0; true; i++) {
        if (i == SOLVE_ITERATION_LIMIT) {
            throw new VerifyException(format("SignatureBinder.iterativeSolve does not converge after %d iterations.", SOLVE_ITERATION_LIMIT));
        }
        SolverReturnStatusMerger statusMerger = new SolverReturnStatusMerger();
        for (TypeConstraintSolver constraint : constraints) {
            statusMerger.add(constraint.update(boundVariablesBuilder));
            if (statusMerger.getCurrent() == SolverReturnStatus.UNSOLVABLE) {
                return Optional.empty();
            }
        }
        switch (statusMerger.getCurrent()) {
            case UNCHANGED_SATISFIED:
                break;
            case UNCHANGED_NOT_SATISFIED:
                return Optional.empty();
            case CHANGED:
                continue;
            case UNSOLVABLE:
                throw new VerifyException();
            default:
                throw new UnsupportedOperationException("unknown status");
        }
        break;
    }

    calculateVariableValuesForLongConstraints(boundVariablesBuilder);

    BoundVariables boundVariables = boundVariablesBuilder.build();
    if (!allTypeVariablesBound(boundVariables)) {
        return Optional.empty();
    }
    return Optional.of(boundVariables);
}
 
Example 25
Source Project: presto   Source File: TestQueryResultRows.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "data present without columns and types")
public void shouldThrowWhenDataIsPresentWithoutColumns()
{
    List<Page> pages = rowPagesBuilder(ImmutableList.of(IntegerType.INTEGER, BooleanType.BOOLEAN))
            .row(0, null)
            .build();

    queryResultRowsBuilder(getSession())
            .addPages(pages)
            .build();
}
 
Example 26
Source Project: presto   Source File: TestDynamicFiltersChecker.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "All consumed dynamic filters could not be matched with a join.")
public void testUnmatchedNestedDynamicFilter()
{
    PlanNode root = builder.output(
            ImmutableList.of(),
            ImmutableList.of(),
            builder.join(
                    INNER,
                    ordersTableScanNode,
                    builder.filter(
                            combineConjuncts(
                                    metadata,
                                    combineDisjuncts(
                                            metadata,
                                            expression("LINEITEM_OK IS NULL"),
                                            createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, lineitemOrderKeySymbol.toSymbolReference())),
                                    combineDisjuncts(
                                            metadata,
                                            expression("LINEITEM_OK IS NOT NULL"),
                                            createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, lineitemOrderKeySymbol.toSymbolReference()))),
                            lineitemTableScanNode),
                    ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
                    ImmutableList.of(ordersOrderKeySymbol),
                    ImmutableList.of(),
                    Optional.empty(),
                    Optional.empty(),
                    Optional.empty(),
                    ImmutableMap.of()));
    validatePlan(root);
}
 
Example 27
Source Project: presto   Source File: IcebergMetadata.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ConnectorOutputMetadata> finishInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments, Collection<ComputedStatistics> computedStatistics)
{
    IcebergWritableTableHandle table = (IcebergWritableTableHandle) insertHandle;
    org.apache.iceberg.Table icebergTable = transaction.table();

    List<CommitTaskData> commitTasks = fragments.stream()
            .map(slice -> commitTaskCodec.fromJson(slice.getBytes()))
            .collect(toImmutableList());

    Type[] partitionColumnTypes = icebergTable.spec().fields().stream()
            .map(field -> field.transform().getResultType(
                    icebergTable.schema().findType(field.sourceId())))
            .toArray(Type[]::new);

    AppendFiles appendFiles = transaction.newFastAppend();
    for (CommitTaskData task : commitTasks) {
        HdfsContext context = new HdfsContext(session, table.getSchemaName(), table.getTableName());
        Configuration configuration = hdfsEnvironment.getConfiguration(context, new Path(task.getPath()));

        DataFiles.Builder builder = DataFiles.builder(icebergTable.spec())
                .withInputFile(HadoopInputFile.fromLocation(task.getPath(), configuration))
                .withFormat(table.getFileFormat())
                .withMetrics(task.getMetrics().metrics());

        if (!icebergTable.spec().fields().isEmpty()) {
            String partitionDataJson = task.getPartitionDataJson()
                    .orElseThrow(() -> new VerifyException("No partition data for partitioned table"));
            builder.withPartition(PartitionData.fromJson(partitionDataJson, partitionColumnTypes));
        }

        appendFiles.appendFile(builder.build());
    }

    appendFiles.commit();
    transaction.commitTransaction();

    return Optional.of(new HiveWrittenPartitions(commitTasks.stream()
            .map(CommitTaskData::getPath)
            .collect(toImmutableList())));
}
 
Example 28
Source Project: presto   Source File: IcebergPageSink.java    License: Apache License 2.0 5 votes vote down vote up
private Metrics getMetrics(WriteContext writeContext)
{
    switch (fileFormat) {
        case PARQUET:
            return ParquetUtil.fileMetrics(HadoopInputFile.fromPath(writeContext.getPath(), jobConf), MetricsConfig.getDefault());
        case ORC:
            return writeContext.getWriter().getMetrics()
                    .orElseThrow(() -> new VerifyException("Iceberg ORC file writers should return Iceberg metrics"));
    }
    throw new PrestoException(NOT_SUPPORTED, "File format not supported for Iceberg: " + fileFormat);
}
 
Example 29
Source Project: presto   Source File: AbstractCostBasedPlanTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitJoin(JoinNode node, Integer indent)
{
    JoinNode.DistributionType distributionType = node.getDistributionType()
            .orElseThrow(() -> new VerifyException("Expected distribution type to be set"));
    if (node.isCrossJoin()) {
        checkState(node.getType() == INNER && distributionType == REPLICATED, "Expected CROSS JOIN to be INNER REPLICATED");
        output(indent, "cross join:");
    }
    else {
        output(indent, "join (%s, %s):", node.getType(), distributionType);
    }

    return visitPlan(node, indent + 1);
}
 
Example 30
Source Project: presto   Source File: HiveMetadata.java    License: Apache License 2.0 5 votes vote down vote up
private PartitionStatistics createPartitionStatistics(
        ConnectorSession session,
        Map<String, Type> columnTypes,
        ComputedStatistics computedStatistics)
{
    Map<ColumnStatisticMetadata, Block> computedColumnStatistics = computedStatistics.getColumnStatistics();

    Block rowCountBlock = Optional.ofNullable(computedStatistics.getTableStatistics().get(ROW_COUNT))
            .orElseThrow(() -> new VerifyException("rowCount not present"));
    verify(!rowCountBlock.isNull(0), "rowCount must never be null");
    long rowCount = BIGINT.getLong(rowCountBlock, 0);
    HiveBasicStatistics rowCountOnlyBasicStatistics = new HiveBasicStatistics(OptionalLong.empty(), OptionalLong.of(rowCount), OptionalLong.empty(), OptionalLong.empty());
    return createPartitionStatistics(session, rowCountOnlyBasicStatistics, columnTypes, computedColumnStatistics);
}