Search in sources :

Example 61 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project pulsar by apache.

the class AuthenticationSasl method authenticationStage.

@Override
public void authenticationStage(String requestUrl, AuthenticationDataProvider authData, Map<String, String> previousResHeaders, CompletableFuture<Map<String, String>> authFuture) {
    // a new request for sasl auth
    Builder builder = newRequestBuilder(client.target(requestUrl), authData, previousResHeaders);
    builder.async().get(new InvocationCallback<Response>() {

        @Override
        public void completed(Response response) {
            if (response.getStatus() == HTTP_UNAUTHORIZED) {
                // sasl auth on going
                authenticationStage(requestUrl, authData, getHeaders(response), authFuture);
                return;
            }
            if (response.getStatus() != HttpURLConnection.HTTP_OK) {
                log.warn("HTTP get request failed: {}", response.getStatusInfo());
                authFuture.completeExceptionally(new PulsarClientException("Sasl Auth request failed: " + response.getStatus()));
                return;
            } else {
                if (response.getHeaderString(SASL_AUTH_ROLE_TOKEN) != null) {
                    saslRoleToken = response.getHeaderString(SASL_AUTH_ROLE_TOKEN);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Complete auth with saslRoleToken: {}", saslRoleToken);
                }
                authFuture.complete(getHeaders(response));
                return;
            }
        }

        @Override
        public void failed(Throwable throwable) {
            log.warn("Failed to perform http request", throwable);
            authFuture.completeExceptionally(new PulsarClientException(throwable));
            return;
        }
    });
}
Also used : Response(javax.ws.rs.core.Response) ClientBuilder(javax.ws.rs.client.ClientBuilder) Builder(javax.ws.rs.client.Invocation.Builder) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException)

Example 62 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project pulsar by apache.

the class ConfigurationDataUtilsTest method testSocks5.

@Test
public void testSocks5() throws PulsarClientException {
    ClientConfigurationData clientConfig = new ClientConfigurationData();
    clientConfig.setServiceUrl("pulsar://unknown:6650");
    clientConfig.setSocks5ProxyAddress(new InetSocketAddress("localhost", 11080));
    clientConfig.setSocks5ProxyUsername("test");
    clientConfig.setSocks5ProxyPassword("test123");
    PulsarClientImpl pulsarClient = new PulsarClientImpl(clientConfig);
    assertEquals(pulsarClient.getConfiguration().getSocks5ProxyAddress(), new InetSocketAddress("localhost", 11080));
    assertEquals(pulsarClient.getConfiguration().getSocks5ProxyUsername(), "test");
    assertEquals(pulsarClient.getConfiguration().getSocks5ProxyPassword(), "test123");
    ClientConfigurationData clientConfig2 = new ClientConfigurationData();
    System.setProperty("socks5Proxy.address", "http://localhost:11080");
    System.setProperty("socks5Proxy.username", "pulsar");
    System.setProperty("socks5Proxy.password", "pulsar123");
    assertEquals(clientConfig2.getSocks5ProxyAddress(), new InetSocketAddress("localhost", 11080));
    assertEquals(clientConfig2.getSocks5ProxyUsername(), "pulsar");
    assertEquals(clientConfig2.getSocks5ProxyPassword(), "pulsar123");
    // invalid address, no scheme
    System.setProperty("socks5Proxy.address", "localhost:11080");
    try {
        clientConfig2.getSocks5ProxyAddress();
        fail("No exception thrown.");
    } catch (Exception ex) {
        assertTrue(ex.getMessage().contains("Invalid config [socks5Proxy.address]"));
    }
    System.clearProperty("socks5Proxy.address");
}
Also used : InetSocketAddress(java.net.InetSocketAddress) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) IOException(java.io.IOException) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) Test(org.testng.annotations.Test)

Example 63 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project pulsar by apache.

the class TopicPoliciesTest method testTopicMaxMessageSize.

@Test(dataProvider = "persistentAndPartition")
public void testTopicMaxMessageSize(TopicDomain topicDomain, boolean isPartitioned) throws Exception {
    final String topic = TopicName.get(topicDomain.value(), NamespaceName.get(myNamespace), "test-" + UUID.randomUUID()).toString();
    if (isPartitioned) {
        admin.topics().createPartitionedTopic(topic, 3);
    }
    // init cache
    Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).create();
    assertNull(admin.topicPolicies().getMaxMessageSize(topic));
    // set msg size
    admin.topicPolicies().setMaxMessageSize(topic, 10);
    Awaitility.await().until(() -> pulsar.getTopicPoliciesService().getTopicPolicies(TopicName.get(topic)) != null);
    if (isPartitioned) {
        for (int i = 0; i < 3; i++) {
            String partitionName = TopicName.get(topic).getPartition(i).toString();
            Awaitility.await().untilAsserted(() -> {
                AbstractTopic partition = (AbstractTopic) pulsar.getBrokerService().getTopicIfExists(partitionName).get().get();
                assertEquals(partition.getHierarchyTopicPolicies().getTopicMaxMessageSize().get(), Integer.valueOf(10));
            });
        }
    } else {
        Awaitility.await().untilAsserted(() -> {
            AbstractTopic abstractTopic = (AbstractTopic) pulsar.getBrokerService().getTopicIfExists(topic).get().get();
            assertEquals(abstractTopic.getHierarchyTopicPolicies().getTopicMaxMessageSize().get(), Integer.valueOf(10));
        });
    }
    assertEquals(admin.topicPolicies().getMaxMessageSize(topic).intValue(), 10);
    try {
        producer.send(new byte[1024]);
    } catch (PulsarClientException e) {
        assertTrue(e instanceof PulsarClientException.NotAllowedException);
    }
    admin.topicPolicies().removeMaxMessageSize(topic);
    assertNull(admin.topicPolicies().getMaxMessageSize(topic));
    try {
        admin.topicPolicies().setMaxMessageSize(topic, Integer.MAX_VALUE);
        fail("should fail");
    } catch (PulsarAdminException e) {
        assertEquals(e.getStatusCode(), 412);
    }
    try {
        admin.topicPolicies().setMaxMessageSize(topic, -1);
        fail("should fail");
    } catch (PulsarAdminException e) {
        assertEquals(e.getStatusCode(), 412);
    }
    // make sure policy value take effect.
    if (isPartitioned) {
        for (int i = 0; i < 3; i++) {
            String partitionName = TopicName.get(topic).getPartition(i).toString();
            Awaitility.await().untilAsserted(() -> {
                AbstractTopic partition = (AbstractTopic) pulsar.getBrokerService().getTopicIfExists(partitionName).get().get();
                assertNull(partition.getHierarchyTopicPolicies().getTopicMaxMessageSize().getTopicValue());
            });
        }
    } else {
        Awaitility.await().untilAsserted(() -> {
            AbstractTopic abstractTopic = (AbstractTopic) pulsar.getBrokerService().getTopicIfExists(topic).get().get();
            assertNull(abstractTopic.getHierarchyTopicPolicies().getTopicMaxMessageSize().getTopicValue());
        });
    }
    Awaitility.await().untilAsserted(() -> {
        try {
            MessageId messageId = producer.send(new byte[1024]);
            assertNotNull(messageId);
        } catch (PulsarClientException e) {
            fail("failed to send message");
        }
    });
    producer.close();
}
Also used : PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) AbstractTopic(org.apache.pulsar.broker.service.AbstractTopic) MessageId(org.apache.pulsar.client.api.MessageId) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 64 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project pulsar by apache.

the class TopicPoliciesTest method testNonPersistentMaxConsumerOnSub.

@Test(timeOut = 20000)
public void testNonPersistentMaxConsumerOnSub() throws Exception {
    int maxConsumerPerSubInBroker = 1;
    int maxConsumerPerSubInNs = 2;
    int maxConsumerPerSubInTopic = 3;
    conf.setMaxConsumersPerSubscription(maxConsumerPerSubInBroker);
    final String topic = "non-persistent://" + myNamespace + "/test-" + UUID.randomUUID();
    admin.topics().createPartitionedTopic(topic, 3);
    Producer producer = pulsarClient.newProducer().topic(topic).create();
    final String subName = "my-sub";
    ConsumerBuilder builder = pulsarClient.newConsumer().subscriptionType(SubscriptionType.Shared).subscriptionName(subName).topic(topic);
    Consumer consumer = builder.subscribe();
    try {
        builder.subscribe();
        fail("should fail");
    } catch (PulsarClientException e) {
        assertTrue(e.getMessage().contains("reached max consumers limit"));
    }
    // set namespace policy
    admin.namespaces().setMaxConsumersPerSubscription(myNamespace, maxConsumerPerSubInNs);
    Awaitility.await().untilAsserted(() -> {
        assertNotNull(admin.namespaces().getMaxConsumersPerSubscription(myNamespace));
        assertEquals(admin.namespaces().getMaxConsumersPerSubscription(myNamespace).intValue(), maxConsumerPerSubInNs);
    });
    Consumer consumer2 = builder.subscribe();
    try {
        builder.subscribe();
        fail("should fail");
    } catch (PulsarClientException e) {
        assertTrue(e.getMessage().contains("reached max consumers limit"));
    }
    // set topic policy
    admin.topicPolicies().setMaxConsumersPerSubscription(topic, maxConsumerPerSubInTopic);
    Awaitility.await().untilAsserted(() -> {
        assertNotNull(admin.topicPolicies().getMaxConsumersPerSubscription(topic));
        assertEquals(admin.topicPolicies().getMaxConsumersPerSubscription(topic).intValue(), maxConsumerPerSubInTopic);
    });
    Consumer consumer3 = builder.subscribe();
    try {
        builder.subscribe();
        fail("should fail");
    } catch (PulsarClientException e) {
        assertTrue(e.getMessage().contains("reached max consumers limit"));
    }
    consumer.close();
    consumer2.close();
    consumer3.close();
    producer.close();
}
Also used : Producer(org.apache.pulsar.client.api.Producer) Consumer(org.apache.pulsar.client.api.Consumer) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ConsumerBuilder(org.apache.pulsar.client.api.ConsumerBuilder) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 65 with PulsarClientException

use of org.apache.pulsar.client.api.PulsarClientException in project pulsar by apache.

the class TopicPoliciesTest method doTestMaxSubscriptionsFailFast.

private void doTestMaxSubscriptionsFailFast(SubscriptionMode subMode) throws Exception {
    final String topic = "persistent://" + myNamespace + "/test-" + UUID.randomUUID();
    // init cache
    pulsarClient.newProducer().topic(topic).create().close();
    int maxSubInNamespace = 2;
    List<Consumer> consumers = new ArrayList<>();
    ConsumerBuilder consumerBuilder = pulsarClient.newConsumer().subscriptionMode(subMode).subscriptionType(SubscriptionType.Shared).topic(topic);
    admin.namespaces().setMaxSubscriptionsPerTopic(myNamespace, maxSubInNamespace);
    Awaitility.await().untilAsserted(() -> assertNotNull(admin.namespaces().getMaxSubscriptionsPerTopic(myNamespace)));
    for (int i = 0; i < maxSubInNamespace; i++) {
        consumers.add(consumerBuilder.subscriptionName("sub" + i).subscribe());
    }
    long start = System.currentTimeMillis();
    try {
        consumerBuilder.subscriptionName("sub").subscribe();
        fail("should fail");
    } catch (PulsarClientException e) {
        assertTrue(e instanceof PulsarClientException.NotAllowedException);
    }
    // fail fast
    assertTrue(System.currentTimeMillis() - start < 3000);
    // clean
    for (Consumer consumer : consumers) {
        consumer.close();
    }
}
Also used : Consumer(org.apache.pulsar.client.api.Consumer) ArrayList(java.util.ArrayList) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ConsumerBuilder(org.apache.pulsar.client.api.ConsumerBuilder)

Aggregations

PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)240 Test (org.testng.annotations.Test)86 PulsarClient (org.apache.pulsar.client.api.PulsarClient)75 MessageId (org.apache.pulsar.client.api.MessageId)44 Consumer (org.apache.pulsar.client.api.Consumer)41 ArrayList (java.util.ArrayList)39 Message (org.apache.pulsar.client.api.Message)38 CompletableFuture (java.util.concurrent.CompletableFuture)36 Producer (org.apache.pulsar.client.api.Producer)35 IOException (java.io.IOException)32 Cleanup (lombok.Cleanup)27 Map (java.util.Map)25 PulsarAdminException (org.apache.pulsar.client.admin.PulsarAdminException)25 List (java.util.List)24 ExecutionException (java.util.concurrent.ExecutionException)23 ByteBuf (io.netty.buffer.ByteBuf)22 TopicName (org.apache.pulsar.common.naming.TopicName)22 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)18 MockedPulsarServiceBaseTest (org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)17 Schema (org.apache.pulsar.client.api.Schema)17