Search in sources :

Example 41 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project MantaroBot by Mantaro.

the class ImageCmd method call.

@Override
protected void call(GuildMessageReceivedEvent event, String content) {
    String random;
    String id = "";
    if (images.size() == 1) {
        if (type != null) {
            Pair<String, String> result = weebapi.getRandomImageByType(type, false, null);
            images = Collections.singletonList(result.getKey());
            id = result.getValue();
        }
        // Guaranteed random selection :^).
        random = images.get(0);
    } else {
        random = random(images);
    }
    String extension = random.substring(random.lastIndexOf("."));
    MessageBuilder builder = new MessageBuilder();
    builder.append(EmoteReference.TALKING);
    if (!noMentions) {
        List<User> users = event.getMessage().getMentionedUsers();
        String names = "";
        if (users != null)
            names = users.stream().map(user -> event.getGuild().getMember(user).getEffectiveName()).collect(Collectors.joining(", "));
        if (!names.isEmpty())
            builder.append("**").append(names).append("**, ");
    }
    builder.append(toSend);
    event.getChannel().sendFile(CACHE.getInput(random), imageName + "-" + id + "." + extension, builder.build()).queue();
}
Also used : NoArgsCommand(net.kodehawa.mantarobot.core.modules.commands.NoArgsCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Collectors(java.util.stream.Collectors) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) List(java.util.List) URLCache(net.kodehawa.mantarobot.utils.cache.URLCache) User(net.dv8tion.jda.core.entities.User) Pair(org.apache.commons.lang3.tuple.Pair) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Collections(java.util.Collections) User(net.dv8tion.jda.core.entities.User) MessageBuilder(net.dv8tion.jda.core.MessageBuilder)

Example 42 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project incubator-systemml by apache.

the class PlanSelectionFuseCostBased method rGetPlanCosts.

private static double rGetPlanCosts(CPlanMemoTable memo, Hop current, HashSet<Pair<Long, Long>> visited, HashSet<Long> partition, ArrayList<Long> M, boolean[] plan, HashMap<Long, Double> computeCosts, CostVector costsCurrent, TemplateType currentType) {
    // memoization per hop id and cost vector to account for redundant
    // computation without double counting materialized results or compute
    // costs of complex operation DAGs within a single fused operator
    Pair<Long, Long> tag = Pair.of(current.getHopID(), (costsCurrent == null) ? 0 : costsCurrent.ID);
    if (visited.contains(tag))
        return 0;
    visited.add(tag);
    // open template if necessary, including memoization
    // under awareness of current plan choice
    MemoTableEntry best = null;
    boolean opened = false;
    if (memo.contains(current.getHopID())) {
        if (currentType == null) {
            best = memo.get(current.getHopID()).stream().filter(p -> p.isValid()).filter(p -> hasNoRefToMaterialization(p, M, plan)).min(new BasicPlanComparator()).orElse(null);
            opened = true;
        } else {
            best = memo.get(current.getHopID()).stream().filter(p -> p.type == currentType || p.type == TemplateType.CELL).filter(p -> hasNoRefToMaterialization(p, M, plan)).min(Comparator.comparing(p -> 7 - ((p.type == currentType) ? 4 : 0) - p.countPlanRefs())).orElse(null);
        }
    }
    // create new cost vector if opened, initialized with write costs
    CostVector costVect = !opened ? costsCurrent : new CostVector(Math.max(current.getDim1(), 1) * Math.max(current.getDim2(), 1));
    // add compute costs of current operator to costs vector
    if (partition.contains(current.getHopID()))
        costVect.computeCosts += computeCosts.get(current.getHopID());
    // process children recursively
    double costs = 0;
    for (int i = 0; i < current.getInput().size(); i++) {
        Hop c = current.getInput().get(i);
        if (best != null && best.isPlanRef(i))
            costs += rGetPlanCosts(memo, c, visited, partition, M, plan, computeCosts, costVect, best.type);
        else if (best != null && isImplicitlyFused(current, i, best.type))
            costVect.addInputSize(c.getInput().get(0).getHopID(), Math.max(c.getDim1(), 1) * Math.max(c.getDim2(), 1));
        else {
            // include children and I/O costs
            costs += rGetPlanCosts(memo, c, visited, partition, M, plan, computeCosts, null, null);
            if (costVect != null && c.getDataType().isMatrix())
                costVect.addInputSize(c.getHopID(), Math.max(c.getDim1(), 1) * Math.max(c.getDim2(), 1));
        }
    }
    // add costs for opened fused operator
    if (partition.contains(current.getHopID())) {
        if (opened) {
            if (LOG.isTraceEnabled())
                LOG.trace("Cost vector for fused operator (hop " + current.getHopID() + "): " + costVect);
            // time for output write
            costs += costVect.outSize * 8 / WRITE_BANDWIDTH;
            costs += Math.max(costVect.computeCosts * costVect.getMaxInputSize() / COMPUTE_BANDWIDTH, costVect.getSumInputSizes() * 8 / READ_BANDWIDTH);
        } else // add costs for non-partition read in the middle of fused operator
        if (hasNonPartitionConsumer(current, partition)) {
            costs += rGetPlanCosts(memo, current, visited, partition, M, plan, computeCosts, null, null);
        }
    }
    // sanity check non-negative costs
    if (costs < 0 || Double.isNaN(costs) || Double.isInfinite(costs))
        throw new RuntimeException("Wrong cost estimate: " + costs);
    return costs;
}
Also used : TemplateRow(org.apache.sysml.hops.codegen.template.TemplateRow) Arrays(java.util.Arrays) IndexingOp(org.apache.sysml.hops.IndexingOp) HashMap(java.util.HashMap) AggUnaryOp(org.apache.sysml.hops.AggUnaryOp) TemplateOuterProduct(org.apache.sysml.hops.codegen.template.TemplateOuterProduct) ParameterizedBuiltinOp(org.apache.sysml.hops.ParameterizedBuiltinOp) AggOp(org.apache.sysml.hops.Hop.AggOp) ArrayList(java.util.ArrayList) LiteralOp(org.apache.sysml.hops.LiteralOp) HashSet(java.util.HashSet) MemoTableEntry(org.apache.sysml.hops.codegen.template.CPlanMemoTable.MemoTableEntry) Pair(org.apache.commons.lang3.tuple.Pair) ReorgOp(org.apache.sysml.hops.ReorgOp) IDSequence(org.apache.sysml.runtime.controlprogram.parfor.util.IDSequence) CollectionUtils(org.apache.commons.collections.CollectionUtils) InfrastructureAnalyzer(org.apache.sysml.runtime.controlprogram.parfor.stat.InfrastructureAnalyzer) AggBinaryOp(org.apache.sysml.hops.AggBinaryOp) Statistics(org.apache.sysml.utils.Statistics) TernaryOp(org.apache.sysml.hops.TernaryOp) Iterator(java.util.Iterator) Collection(java.util.Collection) TemplateType(org.apache.sysml.hops.codegen.template.TemplateBase.TemplateType) BinaryOp(org.apache.sysml.hops.BinaryOp) TemplateUtils(org.apache.sysml.hops.codegen.template.TemplateUtils) Collectors(java.util.stream.Collectors) Direction(org.apache.sysml.hops.Hop.Direction) Hop(org.apache.sysml.hops.Hop) List(java.util.List) Entry(java.util.Map.Entry) DMLScript(org.apache.sysml.api.DMLScript) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) UtilFunctions(org.apache.sysml.runtime.util.UtilFunctions) Comparator(java.util.Comparator) Collections(java.util.Collections) HopRewriteUtils(org.apache.sysml.hops.rewrite.HopRewriteUtils) UnaryOp(org.apache.sysml.hops.UnaryOp) CPlanMemoTable(org.apache.sysml.hops.codegen.template.CPlanMemoTable) MemoTableEntry(org.apache.sysml.hops.codegen.template.CPlanMemoTable.MemoTableEntry) Hop(org.apache.sysml.hops.Hop)

Example 43 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project cas by apereo.

the class AbstractOAuth20Tests method internalVerifyClientOK.

protected Pair<String, String> internalVerifyClientOK(final RegisteredService service, final boolean refreshToken, final boolean json) throws Exception {
    final Principal principal = createPrincipal();
    final OAuthCode code = addCode(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(HttpMethod.GET.name(), CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase());
    final String auth = CLIENT_ID + ':' + CLIENT_SECRET;
    final String value = EncodingUtils.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
    mockRequest.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + value);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuth20Constants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
    assertNull(this.ticketRegistry.getTicket(code.getId()));
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();
    final String accessTokenId;
    String refreshTokenId = null;
    if (json) {
        assertEquals(MediaType.APPLICATION_JSON_VALUE, mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuth20Constants.ACCESS_TOKEN + "\":\"AT-"));
        final Map results = MAPPER.readValue(body, Map.class);
        if (refreshToken) {
            assertTrue(body.contains('"' + OAuth20Constants.REFRESH_TOKEN + "\":\"RT-"));
            refreshTokenId = results.get(OAuth20Constants.REFRESH_TOKEN).toString();
        }
        assertTrue(body.contains('"' + OAuth20Constants.EXPIRES_IN + "\":"));
        accessTokenId = results.get(OAuth20Constants.ACCESS_TOKEN).toString();
    } else {
        assertEquals(MediaType.TEXT_PLAIN_VALUE, mockResponse.getContentType());
        assertTrue(body.contains(OAuth20Constants.ACCESS_TOKEN + "=AT-"));
        if (refreshToken) {
            assertTrue(body.contains(OAuth20Constants.REFRESH_TOKEN + "=RT-"));
            refreshTokenId = Arrays.stream(body.split("&")).filter(f -> f.startsWith(OAuth20Constants.REFRESH_TOKEN)).map(f -> StringUtils.remove(f, OAuth20Constants.REFRESH_TOKEN + "=")).findFirst().get();
        }
        assertTrue(body.contains(OAuth20Constants.EXPIRES_IN + '='));
        accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + '=', "&");
    }
    final AccessToken accessToken = this.ticketRegistry.getTicket(accessTokenId, AccessToken.class);
    assertEquals(principal, accessToken.getAuthentication().getPrincipal());
    final int timeLeft = getTimeLeft(body, refreshToken, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
    return Pair.of(accessTokenId, refreshTokenId);
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Arrays(java.util.Arrays) ReturnAllAttributeReleasePolicy(org.apereo.cas.services.ReturnAllAttributeReleasePolicy) ZonedDateTime(java.time.ZonedDateTime) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) BasicIdentifiableCredential(org.apereo.cas.authentication.BasicIdentifiableCredential) CasCoreConfiguration(org.apereo.cas.config.CasCoreConfiguration) CasWebApplicationServiceFactoryConfiguration(org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration) Pair(org.apache.commons.lang3.tuple.Pair) OAuthCodeFactory(org.apereo.cas.ticket.code.OAuthCodeFactory) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) Map(java.util.Map) CasCoreWebConfiguration(org.apereo.cas.config.CasCoreWebConfiguration) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) SecurityInterceptor(org.pac4j.springframework.web.SecurityInterceptor) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) CasCoreAuthenticationPolicyConfiguration(org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration) StandardCharsets(java.nio.charset.StandardCharsets) OAuth20AccessTokenEndpointController(org.apereo.cas.support.oauth.web.endpoints.OAuth20AccessTokenEndpointController) CasCookieConfiguration(org.apereo.cas.web.config.CasCookieConfiguration) Slf4j(lombok.extern.slf4j.Slf4j) CasCoreComponentSerializationConfiguration(org.apereo.cas.config.CasCoreComponentSerializationConfiguration) CasCoreTicketCatalogConfiguration(org.apereo.cas.config.CasCoreTicketCatalogConfiguration) Principal(org.apereo.cas.authentication.principal.Principal) EncodingUtils(org.apereo.cas.util.EncodingUtils) MockTicketGrantingTicket(org.apereo.cas.mock.MockTicketGrantingTicket) ComponentSerializationPlan(org.apereo.cas.ComponentSerializationPlan) RefreshTokenFactory(org.apereo.cas.ticket.refreshtoken.RefreshTokenFactory) CasCoreAuthenticationConfiguration(org.apereo.cas.config.CasCoreAuthenticationConfiguration) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) RunWith(org.junit.runner.RunWith) WebApplicationServiceFactory(org.apereo.cas.authentication.principal.WebApplicationServiceFactory) EnableTransactionManagement(org.springframework.transaction.annotation.EnableTransactionManagement) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) CasOAuthAuthenticationServiceSelectionStrategyConfiguration(org.apereo.cas.config.CasOAuthAuthenticationServiceSelectionStrategyConfiguration) ArrayList(java.util.ArrayList) RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) RefreshAutoConfiguration(org.springframework.cloud.autoconfigure.RefreshAutoConfiguration) Authentication(org.apereo.cas.authentication.Authentication) ServicesManager(org.apereo.cas.services.ServicesManager) CasCoreUtilSerializationConfiguration(org.apereo.cas.config.CasCoreUtilSerializationConfiguration) CasCoreAuthenticationHandlersConfiguration(org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration) CasCoreServicesConfiguration(org.apereo.cas.config.CasCoreServicesConfiguration) EnvironmentConversionServiceInitializer(org.apereo.cas.config.support.EnvironmentConversionServiceInitializer) CasCoreServicesAuthenticationConfiguration(org.apereo.cas.config.CasCoreServicesAuthenticationConfiguration) CasCoreAuthenticationPrincipalConfiguration(org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration) HttpMethod(org.springframework.http.HttpMethod) AuthenticationHandlerExecutionResult(org.apereo.cas.authentication.AuthenticationHandlerExecutionResult) RegisteredService(org.apereo.cas.services.RegisteredService) CasOAuthThrottleConfiguration(org.apereo.cas.config.CasOAuthThrottleConfiguration) ContextConfiguration(org.springframework.test.context.ContextConfiguration) CasCoreUtilConfiguration(org.apereo.cas.config.CasCoreUtilConfiguration) Assert(org.junit.Assert) DirtiesContext(org.springframework.test.annotation.DirtiesContext) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AopAutoConfiguration(org.springframework.boot.autoconfigure.aop.AopAutoConfiguration) HttpStatus(org.apache.http.HttpStatus) TestConfiguration(org.springframework.boot.test.context.TestConfiguration) AbstractRegisteredService(org.apereo.cas.services.AbstractRegisteredService) SchedulingUtils(org.apereo.cas.util.SchedulingUtils) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) RegisteredServiceTestUtils(org.apereo.cas.services.RegisteredServiceTestUtils) CasCoreAuthenticationServiceSelectionStrategyConfiguration(org.apereo.cas.config.CasCoreAuthenticationServiceSelectionStrategyConfiguration) SpringRunner(org.springframework.test.context.junit4.SpringRunner) CredentialMetaData(org.apereo.cas.authentication.CredentialMetaData) CasCoreTicketIdGeneratorsConfiguration(org.apereo.cas.config.CasCoreTicketIdGeneratorsConfiguration) MediaType(org.springframework.http.MediaType) Collection(java.util.Collection) CasCoreLogoutConfiguration(org.apereo.cas.logout.config.CasCoreLogoutConfiguration) CasDefaultServiceTicketIdGeneratorsConfiguration(org.apereo.cas.config.CasDefaultServiceTicketIdGeneratorsConfiguration) List(java.util.List) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) ComponentSerializationPlanConfigurator(org.apereo.cas.ComponentSerializationPlanConfigurator) PostConstruct(javax.annotation.PostConstruct) CasCoreTicketsConfiguration(org.apereo.cas.config.CasCoreTicketsConfiguration) CasOAuthConfiguration(org.apereo.cas.config.CasOAuthConfiguration) CasPersonDirectoryConfiguration(org.apereo.cas.config.CasPersonDirectoryConfiguration) CasCoreAuthenticationSupportConfiguration(org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration) MockServiceTicket(org.apereo.cas.mock.MockServiceTicket) EnableAspectJAutoProxy(org.springframework.context.annotation.EnableAspectJAutoProxy) HttpConstants(org.pac4j.core.context.HttpConstants) HashMap(java.util.HashMap) Qualifier(org.springframework.beans.factory.annotation.Qualifier) CasCoreAuthenticationMetadataConfiguration(org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) CasOAuthComponentSerializationConfiguration(org.apereo.cas.config.CasOAuthComponentSerializationConfiguration) CasCoreHttpConfiguration(org.apereo.cas.config.CasCoreHttpConfiguration) OAuth20GrantTypes(org.apereo.cas.support.oauth.OAuth20GrantTypes) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ApplicationContext(org.springframework.context.ApplicationContext) Service(org.apereo.cas.authentication.principal.Service) Bean(org.springframework.context.annotation.Bean) CoreAuthenticationTestUtils(org.apereo.cas.authentication.CoreAuthenticationTestUtils) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) Map(java.util.Map) HashMap(java.util.HashMap) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 44 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project hive by apache.

the class MetastoreSchemaTool method validateSequences.

boolean validateSequences(Connection conn) throws HiveMetaException {
    Map<String, Pair<String, String>> seqNameToTable = new ImmutableMap.Builder<String, Pair<String, String>>().put("MDatabase", Pair.of("DBS", "DB_ID")).put("MRole", Pair.of("ROLES", "ROLE_ID")).put("MGlobalPrivilege", Pair.of("GLOBAL_PRIVS", "USER_GRANT_ID")).put("MTable", Pair.of("TBLS", "TBL_ID")).put("MStorageDescriptor", Pair.of("SDS", "SD_ID")).put("MSerDeInfo", Pair.of("SERDES", "SERDE_ID")).put("MColumnDescriptor", Pair.of("CDS", "CD_ID")).put("MTablePrivilege", Pair.of("TBL_PRIVS", "TBL_GRANT_ID")).put("MTableColumnStatistics", Pair.of("TAB_COL_STATS", "CS_ID")).put("MPartition", Pair.of("PARTITIONS", "PART_ID")).put("MPartitionColumnStatistics", Pair.of("PART_COL_STATS", "CS_ID")).put("MFunction", Pair.of("FUNCS", "FUNC_ID")).put("MIndex", Pair.of("IDXS", "INDEX_ID")).put("MStringList", Pair.of("SKEWED_STRING_LIST", "STRING_LIST_ID")).build();
    System.out.println("Validating sequence number for SEQUENCE_TABLE");
    boolean isValid = true;
    try {
        Statement stmt = conn.createStatement();
        for (String seqName : seqNameToTable.keySet()) {
            String tableName = seqNameToTable.get(seqName).getLeft();
            String tableKey = seqNameToTable.get(seqName).getRight();
            String fullSequenceName = "org.apache.hadoop.hive.metastore.model." + seqName;
            String seqQuery = needsQuotedIdentifier ? ("select t.\"NEXT_VAL\" from \"SEQUENCE_TABLE\" t WHERE t.\"SEQUENCE_NAME\"=? order by t.\"SEQUENCE_NAME\" ") : ("select t.NEXT_VAL from SEQUENCE_TABLE t WHERE t.SEQUENCE_NAME=? order by t.SEQUENCE_NAME ");
            String maxIdQuery = needsQuotedIdentifier ? ("select max(\"" + tableKey + "\") from \"" + tableName + "\"") : ("select max(" + tableKey + ") from " + tableName);
            ResultSet res = stmt.executeQuery(maxIdQuery);
            if (res.next()) {
                long maxId = res.getLong(1);
                if (maxId > 0) {
                    PreparedStatement pStmt = conn.prepareStatement(seqQuery);
                    pStmt.setString(1, fullSequenceName);
                    ResultSet resSeq = pStmt.executeQuery();
                    if (!resSeq.next()) {
                        isValid = false;
                        logAndPrintToError("Missing SEQUENCE_NAME " + seqName + " from SEQUENCE_TABLE");
                    } else if (resSeq.getLong(1) < maxId) {
                        isValid = false;
                        logAndPrintToError("NEXT_VAL for " + seqName + " in SEQUENCE_TABLE < max(" + tableKey + ") in " + tableName);
                    }
                }
            }
        }
        System.out.println((isValid ? "Succeeded" : "Failed") + " in sequence number validation for SEQUENCE_TABLE.");
        return isValid;
    } catch (SQLException e) {
        throw new HiveMetaException("Failed to validate sequence number for SEQUENCE_TABLE", e);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) HiveMetaException(org.apache.hadoop.hive.metastore.HiveMetaException) PreparedStatement(java.sql.PreparedStatement) ImmutableMap(com.google.common.collect.ImmutableMap) Pair(org.apache.commons.lang3.tuple.Pair)

Example 45 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project pravega by pravega.

the class ControllerImplTest method setup.

@Before
public void setup() throws IOException {
    // Setup test server generating different success and failure responses.
    testServerImpl = new ControllerServiceImplBase() {

        @Override
        public void createStream(StreamConfig request, StreamObserver<CreateStreamStatus> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1") || request.getStreamInfo().getStream().equals("stream8")) {
                responseObserver.onNext(CreateStreamStatus.newBuilder().setStatus(CreateStreamStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream2")) {
                responseObserver.onNext(CreateStreamStatus.newBuilder().setStatus(CreateStreamStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream3")) {
                responseObserver.onNext(CreateStreamStatus.newBuilder().setStatus(CreateStreamStatus.Status.SCOPE_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream4")) {
                responseObserver.onNext(CreateStreamStatus.newBuilder().setStatus(CreateStreamStatus.Status.STREAM_EXISTS).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream5")) {
                responseObserver.onNext(CreateStreamStatus.newBuilder().setStatus(CreateStreamStatus.Status.INVALID_STREAM_NAME).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("streamparallel")) {
                // Simulating delay in sending response.
                Exceptions.handleInterrupted(() -> Thread.sleep(500));
                responseObserver.onNext(CreateStreamStatus.newBuilder().setStatus(CreateStreamStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("streamdelayed")) {
                // Simulating delay in sending response. This is used for the keepalive test,
                // where response time > 30 seconds is required to simulate a failure.
                Exceptions.handleInterrupted(() -> Thread.sleep(40000));
                responseObserver.onNext(CreateStreamStatus.newBuilder().setStatus(CreateStreamStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("streamretryfailure")) {
                responseObserver.onError(Status.UNKNOWN.withDescription("Transport error").asRuntimeException());
            } else if (request.getStreamInfo().getStream().equals("streamretrysuccess")) {
                if (retryAttempts.incrementAndGet() > 3) {
                    responseObserver.onNext(CreateStreamStatus.newBuilder().setStatus(CreateStreamStatus.Status.SUCCESS).build());
                    responseObserver.onCompleted();
                } else {
                    responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
                }
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void updateStream(StreamConfig request, StreamObserver<UpdateStreamStatus> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream2")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream3")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.SCOPE_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream4")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.STREAM_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream5")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.UNRECOGNIZED).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void truncateStream(Controller.StreamCut request, StreamObserver<UpdateStreamStatus> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream2")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream3")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.SCOPE_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream4")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.STREAM_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream5")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.UNRECOGNIZED).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void sealStream(StreamInfo request, StreamObserver<UpdateStreamStatus> responseObserver) {
            if (request.getStream().equals("stream1")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStream().equals("stream2")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getStream().equals("stream3")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.SCOPE_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStream().equals("stream4")) {
                responseObserver.onNext(UpdateStreamStatus.newBuilder().setStatus(UpdateStreamStatus.Status.STREAM_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void deleteStream(StreamInfo request, StreamObserver<DeleteStreamStatus> responseObserver) {
            if (request.getStream().equals("stream1")) {
                responseObserver.onNext(DeleteStreamStatus.newBuilder().setStatus(DeleteStreamStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStream().equals("stream2")) {
                responseObserver.onNext(DeleteStreamStatus.newBuilder().setStatus(DeleteStreamStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getStream().equals("stream3")) {
                responseObserver.onNext(DeleteStreamStatus.newBuilder().setStatus(DeleteStreamStatus.Status.STREAM_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStream().equals("stream4")) {
                responseObserver.onNext(DeleteStreamStatus.newBuilder().setStatus(DeleteStreamStatus.Status.STREAM_NOT_SEALED).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void getCurrentSegments(StreamInfo request, StreamObserver<SegmentRanges> responseObserver) {
            if (request.getStream().equals("stream1")) {
                responseObserver.onNext(SegmentRanges.newBuilder().addSegmentRanges(ModelHelper.createSegmentRange("scope1", "stream1", 6, 0.0, 0.4)).addSegmentRanges(ModelHelper.createSegmentRange("scope1", "stream1", 7, 0.4, 1.0)).build());
                responseObserver.onCompleted();
            } else if (request.getStream().equals("stream8")) {
                responseObserver.onNext(SegmentRanges.newBuilder().addSegmentRanges(ModelHelper.createSegmentRange("scope1", "stream8", 9, 0.0, 0.5)).addSegmentRanges(ModelHelper.createSegmentRange("scope1", "stream8", 10, 0.5, 1.0)).build());
                responseObserver.onCompleted();
            } else if (request.getStream().equals("streamparallel")) {
                Exceptions.handleInterrupted(() -> Thread.sleep(500));
                responseObserver.onNext(SegmentRanges.newBuilder().addSegmentRanges(ModelHelper.createSegmentRange("scope1", "streamparallel", 0, 0.0, 0.4)).addSegmentRanges(ModelHelper.createSegmentRange("scope1", "streamparallel", 1, 0.4, 1.0)).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void getSegments(GetSegmentsRequest request, StreamObserver<SegmentsAtTime> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                SegmentId segment1 = ModelHelper.createSegmentId("scope1", "stream1", 0);
                SegmentId segment2 = ModelHelper.createSegmentId("scope1", "stream1", 1);
                responseObserver.onNext(SegmentsAtTime.newBuilder().addSegments(SegmentLocation.newBuilder().setSegmentId(segment1).setOffset(10).build()).addSegments(SegmentLocation.newBuilder().setSegmentId(segment2).setOffset(20).build()).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream8")) {
                SegmentId segment1 = ModelHelper.createSegmentId("scope1", "stream8", 0);
                SegmentId segment2 = ModelHelper.createSegmentId("scope1", "stream8", 1);
                SegmentId segment3 = ModelHelper.createSegmentId("scope1", "stream8", 2);
                responseObserver.onNext(SegmentsAtTime.newBuilder().addSegments(SegmentLocation.newBuilder().setSegmentId(segment1).setOffset(10).build()).addSegments(SegmentLocation.newBuilder().setSegmentId(segment2).setOffset(20).build()).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void getSegmentsImmediatlyFollowing(SegmentId request, StreamObserver<SuccessorResponse> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                Map<SegmentId, Pair<Double, Double>> result = new HashMap<>();
                if (request.getSegmentNumber() == 0) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream1", 2), Pair.of(0.0, 0.25));
                    result.put(ModelHelper.createSegmentId("scope1", "stream1", 3), Pair.of(0.25, 0.5));
                } else if (request.getSegmentNumber() == 1) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream1", 4), Pair.of(0.5, 0.75));
                    result.put(ModelHelper.createSegmentId("scope1", "stream1", 5), Pair.of(0.75, 1.0));
                } else if (request.getSegmentNumber() == 2 || request.getSegmentNumber() == 3) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream1", 6), Pair.of(0.0, 0.5));
                } else if (request.getSegmentNumber() == 4 || request.getSegmentNumber() == 5) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream1", 7), Pair.of(0.5, 0.25));
                }
                val builder = SuccessorResponse.newBuilder();
                for (Entry<SegmentId, Pair<Double, Double>> entry : result.entrySet()) {
                    builder.addSegments(SuccessorResponse.SegmentEntry.newBuilder().setSegment(Controller.SegmentRange.newBuilder().setSegmentId(entry.getKey()).setMinKey(entry.getValue().getLeft()).setMaxKey(entry.getValue().getRight()).build()).addValue(10 * entry.getKey().getSegmentNumber()).build());
                }
                responseObserver.onNext(builder.build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream8")) {
                Map<SegmentId, Pair<Double, Double>> result = new HashMap<>();
                if (request.getSegmentNumber() == 0) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream8", 3), Pair.of(0.0, 0.2));
                    result.put(ModelHelper.createSegmentId("scope1", "stream8", 4), Pair.of(0.2, 0.33));
                } else if (request.getSegmentNumber() == 1) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream8", 5), Pair.of(0.33, 0.5));
                    result.put(ModelHelper.createSegmentId("scope1", "stream8", 6), Pair.of(0.5, 0.66));
                } else if (request.getSegmentNumber() == 2) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream8", 7), Pair.of(0.66, 0.8));
                    result.put(ModelHelper.createSegmentId("scope1", "stream8", 8), Pair.of(0.8, 1.0));
                } else if (request.getSegmentNumber() == 3 || request.getSegmentNumber() == 4 || request.getSegmentNumber() == 5) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream8", 9), Pair.of(0.0, 0.5));
                } else if (request.getSegmentNumber() == 6 || request.getSegmentNumber() == 7 || request.getSegmentNumber() == 8) {
                    result.put(ModelHelper.createSegmentId("scope1", "stream8", 10), Pair.of(0.5, 1.0));
                }
                val builder = SuccessorResponse.newBuilder();
                for (Entry<SegmentId, Pair<Double, Double>> entry : result.entrySet()) {
                    builder.addSegments(SuccessorResponse.SegmentEntry.newBuilder().setSegment(Controller.SegmentRange.newBuilder().setSegmentId(entry.getKey()).setMinKey(entry.getValue().getLeft()).setMaxKey(entry.getValue().getRight()).build()).addValue(10 * entry.getKey().getSegmentNumber()).build());
                }
                responseObserver.onNext(builder.build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void scale(ScaleRequest request, StreamObserver<ScaleResponse> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(ScaleResponse.newBuilder().setStatus(ScaleResponse.ScaleStreamStatus.STARTED).addSegments(ModelHelper.createSegmentRange("scope1", "stream1", 0, 0.0, 0.5)).addSegments(ModelHelper.createSegmentRange("scope1", "stream1", 1, 0.5, 1.0)).setEpoch(0).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void checkScale(ScaleStatusRequest request, StreamObserver<ScaleStatusResponse> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(ScaleStatusResponse.newBuilder().setStatus(ScaleStatusResponse.ScaleStatus.SUCCESS).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void getURI(SegmentId request, StreamObserver<NodeUri> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(NodeUri.newBuilder().setEndpoint("localhost").setPort(SERVICE_PORT).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void isSegmentValid(SegmentId request, StreamObserver<SegmentValidityResponse> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(SegmentValidityResponse.newBuilder().setResponse(true).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream2")) {
                responseObserver.onNext(SegmentValidityResponse.newBuilder().setResponse(false).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void createTransaction(CreateTxnRequest request, StreamObserver<Controller.CreateTxnResponse> responseObserver) {
            Controller.CreateTxnResponse.Builder builder = Controller.CreateTxnResponse.newBuilder();
            if (request.getStreamInfo().getStream().equals("stream1")) {
                builder.setTxnId(TxnId.newBuilder().setHighBits(11L).setLowBits(22L).build());
                builder.addActiveSegments(ModelHelper.createSegmentRange("scope1", "stream1", 0, 0.0, 0.5));
                builder.addActiveSegments(ModelHelper.createSegmentRange("scope1", "stream1", 1, 0.5, 1.0));
                responseObserver.onNext(builder.build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream2")) {
                builder.addActiveSegments(ModelHelper.createSegmentRange("scope1", "stream2", 0, 0.0, 1.0));
                builder.setTxnId(TxnId.newBuilder().setHighBits(33L).setLowBits(44L).build());
                responseObserver.onNext(builder.build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void commitTransaction(TxnRequest request, StreamObserver<Controller.TxnStatus> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(Controller.TxnStatus.newBuilder().setStatus(Controller.TxnStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream2")) {
                responseObserver.onNext(Controller.TxnStatus.newBuilder().setStatus(Controller.TxnStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream3")) {
                responseObserver.onNext(Controller.TxnStatus.newBuilder().setStatus(Controller.TxnStatus.Status.STREAM_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream4")) {
                responseObserver.onNext(Controller.TxnStatus.newBuilder().setStatus(Controller.TxnStatus.Status.TRANSACTION_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void abortTransaction(TxnRequest request, StreamObserver<Controller.TxnStatus> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(Controller.TxnStatus.newBuilder().setStatus(Controller.TxnStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream2")) {
                responseObserver.onNext(Controller.TxnStatus.newBuilder().setStatus(Controller.TxnStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream3")) {
                responseObserver.onNext(Controller.TxnStatus.newBuilder().setStatus(Controller.TxnStatus.Status.STREAM_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream4")) {
                responseObserver.onNext(Controller.TxnStatus.newBuilder().setStatus(Controller.TxnStatus.Status.TRANSACTION_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void pingTransaction(PingTxnRequest request, StreamObserver<PingTxnStatus> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(PingTxnStatus.newBuilder().setStatus(PingTxnStatus.Status.OK).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void checkTransactionState(TxnRequest request, StreamObserver<TxnState> responseObserver) {
            if (request.getStreamInfo().getStream().equals("stream1")) {
                responseObserver.onNext(TxnState.newBuilder().setState(TxnState.State.OPEN).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream2")) {
                responseObserver.onNext(TxnState.newBuilder().setState(TxnState.State.UNKNOWN).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream3")) {
                responseObserver.onNext(TxnState.newBuilder().setState(TxnState.State.COMMITTING).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream4")) {
                responseObserver.onNext(TxnState.newBuilder().setState(TxnState.State.COMMITTED).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream5")) {
                responseObserver.onNext(TxnState.newBuilder().setState(TxnState.State.ABORTING).build());
                responseObserver.onCompleted();
            } else if (request.getStreamInfo().getStream().equals("stream6")) {
                responseObserver.onNext(TxnState.newBuilder().setState(TxnState.State.ABORTED).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void createScope(ScopeInfo request, StreamObserver<CreateScopeStatus> responseObserver) {
            if (request.getScope().equals("scope1")) {
                responseObserver.onNext(CreateScopeStatus.newBuilder().setStatus(CreateScopeStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getScope().equals("scope2")) {
                responseObserver.onNext(CreateScopeStatus.newBuilder().setStatus(CreateScopeStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getScope().equals("scope3")) {
                responseObserver.onNext(CreateScopeStatus.newBuilder().setStatus(CreateScopeStatus.Status.INVALID_SCOPE_NAME).build());
                responseObserver.onCompleted();
            } else if (request.getScope().equals("scope4")) {
                responseObserver.onNext(CreateScopeStatus.newBuilder().setStatus(CreateScopeStatus.Status.SCOPE_EXISTS).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }

        @Override
        public void getDelegationToken(io.pravega.controller.stream.api.grpc.v1.Controller.StreamInfo request, io.grpc.stub.StreamObserver<io.pravega.controller.stream.api.grpc.v1.Controller.DelegationToken> responseObserver) {
            responseObserver.onNext(Controller.DelegationToken.newBuilder().setDelegationToken("token").build());
            responseObserver.onCompleted();
        }

        @Override
        public void deleteScope(ScopeInfo request, StreamObserver<DeleteScopeStatus> responseObserver) {
            if (request.getScope().equals("scope1")) {
                responseObserver.onNext(DeleteScopeStatus.newBuilder().setStatus(DeleteScopeStatus.Status.SUCCESS).build());
                responseObserver.onCompleted();
            } else if (request.getScope().equals("scope2")) {
                responseObserver.onNext(DeleteScopeStatus.newBuilder().setStatus(DeleteScopeStatus.Status.FAILURE).build());
                responseObserver.onCompleted();
            } else if (request.getScope().equals("scope3")) {
                responseObserver.onNext(DeleteScopeStatus.newBuilder().setStatus(DeleteScopeStatus.Status.SCOPE_NOT_EMPTY).build());
                responseObserver.onCompleted();
            } else if (request.getScope().equals("scope4")) {
                responseObserver.onNext(DeleteScopeStatus.newBuilder().setStatus(DeleteScopeStatus.Status.SCOPE_NOT_FOUND).build());
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.INTERNAL.withDescription("Server error").asRuntimeException());
            }
        }
    };
    serverPort = TestUtils.getAvailableListenPort();
    serverBuilder = NettyServerBuilder.forPort(serverPort).addService(testServerImpl);
    if (testSecure) {
        serverBuilder = serverBuilder.useTransportSecurity(new File("../config/cert.pem"), new File("../config/key.pem"));
        creds = new DefaultCredentials("1111_aaaa", "admin");
    }
    testGRPCServer = serverBuilder.build().start();
    executor = Executors.newSingleThreadScheduledExecutor();
    controllerClient = new ControllerImpl(ControllerImplConfig.builder().clientConfig(ClientConfig.builder().controllerURI(URI.create((testSecure ? "tls://" : "tcp://") + "localhost:" + serverPort)).credentials(new DefaultCredentials("1111_aaaa", "admin")).trustStore("../config/cert.pem").build()).retryAttempts(1).build(), executor);
}
Also used : ScaleStatusRequest(io.pravega.controller.stream.api.grpc.v1.Controller.ScaleStatusRequest) HashMap(java.util.HashMap) NettyServerBuilder(io.grpc.netty.NettyServerBuilder) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) PingTxnRequest(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnRequest) CreateTxnRequest(io.pravega.controller.stream.api.grpc.v1.Controller.CreateTxnRequest) TxnRequest(io.pravega.controller.stream.api.grpc.v1.Controller.TxnRequest) UpdateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateStreamStatus) CreateScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateScopeStatus) SuccessorResponse(io.pravega.controller.stream.api.grpc.v1.Controller.SuccessorResponse) ScaleRequest(io.pravega.controller.stream.api.grpc.v1.Controller.ScaleRequest) lombok.val(lombok.val) ScaleStatusResponse(io.pravega.controller.stream.api.grpc.v1.Controller.ScaleStatusResponse) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) NodeUri(io.pravega.controller.stream.api.grpc.v1.Controller.NodeUri) PingTxnRequest(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnRequest) TxnState(io.pravega.controller.stream.api.grpc.v1.Controller.TxnState) SegmentRanges(io.pravega.controller.stream.api.grpc.v1.Controller.SegmentRanges) GetSegmentsRequest(io.pravega.controller.stream.api.grpc.v1.Controller.GetSegmentsRequest) CreateTxnRequest(io.pravega.controller.stream.api.grpc.v1.Controller.CreateTxnRequest) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) SegmentsAtTime(io.pravega.controller.stream.api.grpc.v1.Controller.SegmentsAtTime) SegmentValidityResponse(io.pravega.controller.stream.api.grpc.v1.Controller.SegmentValidityResponse) PingTxnStatus(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus) Entry(java.util.Map.Entry) StreamInfo(io.pravega.controller.stream.api.grpc.v1.Controller.StreamInfo) Pair(org.apache.commons.lang3.tuple.Pair) ControllerServiceImplBase(io.pravega.controller.stream.api.grpc.v1.ControllerServiceGrpc.ControllerServiceImplBase) CreateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateStreamStatus) SegmentId(io.pravega.controller.stream.api.grpc.v1.Controller.SegmentId) StreamConfig(io.pravega.controller.stream.api.grpc.v1.Controller.StreamConfig) ScaleResponse(io.pravega.controller.stream.api.grpc.v1.Controller.ScaleResponse) ScopeInfo(io.pravega.controller.stream.api.grpc.v1.Controller.ScopeInfo) Controller(io.pravega.controller.stream.api.grpc.v1.Controller) DeleteScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteScopeStatus) DeleteStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteStreamStatus) StreamInfo(io.pravega.controller.stream.api.grpc.v1.Controller.StreamInfo) PingTxnStatus(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus) Before(org.junit.Before)

Aggregations

Pair (org.apache.commons.lang3.tuple.Pair)685 ArrayList (java.util.ArrayList)209 List (java.util.List)154 Test (org.junit.Test)150 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)142 HashMap (java.util.HashMap)123 Collectors (java.util.stream.Collectors)123 Map (java.util.Map)112 Message (com.microsoft.azure.sdk.iot.device.Message)71 IOException (java.io.IOException)70 MutablePair (org.apache.commons.lang3.tuple.MutablePair)64 java.util (java.util)55 IotHubTransportMessage (com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage)52 Set (java.util.Set)49 StringUtils (org.apache.commons.lang3.StringUtils)48 File (java.io.File)46 Optional (java.util.Optional)45 Arrays (java.util.Arrays)44 HashSet (java.util.HashSet)40 Test (org.junit.jupiter.api.Test)39