Java Code Examples for org.apache.pulsar.common.naming.NamespaceName#get()

The following examples show how to use org.apache.pulsar.common.naming.NamespaceName#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NonPersistentTopicsImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<List<String>> getListInBundleAsync(String namespace, String bundleRange) {
    NamespaceName ns = NamespaceName.get(namespace);
    final CompletableFuture<List<String>> future = new CompletableFuture<>();
    WebTarget path = namespacePath("non-persistent", ns, bundleRange);
    asyncGetRequest(path,
            new InvocationCallback<List<String>>() {
                @Override
                public void completed(List<String> response) {
                    future.complete(response);
                }
                @Override
                public void failed(Throwable throwable) {
                    future.completeExceptionally(getApiException(throwable.getCause()));
                }
            });
    return future;
}
 
Example 2
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Long> getCompactionThresholdAsync(String namespace) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "compactionThreshold");
    final CompletableFuture<Long> future = new CompletableFuture<>();
    asyncGetRequest(path,
            new InvocationCallback<Long>() {
                @Override
                public void completed(Long threshold) {
                    future.complete(threshold);
                }

                @Override
                public void failed(Throwable throwable) {
                    future.completeExceptionally(getApiException(throwable.getCause()));
                }
            });
    return future;
}
 
Example 3
Source File: NamespacesTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateNamespaceOwnershipWithBundles() throws Exception {
    try {
        URL localWebServiceUrl = new URL(pulsar.getSafeWebServiceAddress());
        String bundledNsLocal = "test-bundled-namespace-1";
        BundlesData bundleData = new BundlesData(Lists.newArrayList("0x00000000", "0xffffffff"));
        createBundledTestNamespaces(this.testTenant, this.testLocalCluster, bundledNsLocal, bundleData);
        final NamespaceName testNs = NamespaceName.get(this.testTenant, this.testLocalCluster, bundledNsLocal);
        mockWebUrl(localWebServiceUrl, testNs);

        OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());
        doReturn(CompletableFuture.completedFuture(null)).when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
        Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
        ownership.setAccessible(true);
        ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);
        namespaces.validateNamespaceOwnershipWithBundles(this.testTenant, this.testLocalCluster, bundledNsLocal,
                false, true, bundleData);
    } catch (RestException e) {
        fail("ValidateNamespaceOwnershipWithBundles failed");
    }
}
 
Example 4
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<DispatchRate> getSubscriptionDispatchRateAsync(String namespace) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "subscriptionDispatchRate");
    final CompletableFuture<DispatchRate> future = new CompletableFuture<>();
    asyncGetRequest(path,
            new InvocationCallback<DispatchRate>() {
                @Override
                public void completed(DispatchRate dispatchRate) {
                    future.complete(dispatchRate);
                }

                @Override
                public void failed(Throwable throwable) {
                    future.completeExceptionally(getApiException(throwable.getCause()));
                }
            });
    return future;
}
 
Example 5
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<PersistencePolicies> getPersistenceAsync(String namespace) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "persistence");
    final CompletableFuture<PersistencePolicies> future = new CompletableFuture<>();
    asyncGetRequest(path,
            new InvocationCallback<PersistencePolicies>() {
                @Override
                public void completed(PersistencePolicies persistencePolicies) {
                    future.complete(persistencePolicies);
                }

                @Override
                public void failed(Throwable throwable) {
                    future.completeExceptionally(getApiException(throwable.getCause()));
                }
            });
    return future;
}
 
Example 6
Source File: LoadBalancerTestingUtils.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static NamespaceBundle[] makeBundles(final NamespaceBundleFactory nsFactory, final String property,
        final String cluster, final String namespace, final int numBundles) {
    final NamespaceBundle[] result = new NamespaceBundle[numBundles];
    final NamespaceName namespaceName = NamespaceName.get(property, cluster, namespace);
    for (int i = 0; i < numBundles - 1; ++i) {
        final long lower = NamespaceBundles.FULL_UPPER_BOUND * i / numBundles;
        final long upper = NamespaceBundles.FULL_UPPER_BOUND * (i + 1) / numBundles;
        result[i] = nsFactory.getBundle(namespaceName, Range.range(lower, BoundType.CLOSED, upper, BoundType.OPEN));
    }
    result[numBundles - 1] = nsFactory.getBundle(namespaceName,
            Range.range(NamespaceBundles.FULL_UPPER_BOUND * (numBundles - 1) / numBundles, BoundType.CLOSED,
                    NamespaceBundles.FULL_UPPER_BOUND, BoundType.CLOSED));
    return result;
}
 
Example 7
Source File: AdminResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Deprecated
protected void validateNamespaceName(String property, String cluster, String namespace) {
    try {
        this.namespaceName = NamespaceName.get(property, cluster, namespace);
    } catch (IllegalArgumentException e) {
        log.warn("[{}] Failed to create namespace with invalid name {}", clientAppId(), namespace, e);
        throw new RestException(Status.PRECONDITION_FAILED, "Namespace name is not valid");
    }
}
 
Example 8
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> setMaxUnackedMessagesPerConsumerAsync(
        String namespace, int maxUnackedMessagesPerConsumer) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "maxUnackedMessagesPerConsumer");
    return asyncPostRequest(path, Entity.entity(maxUnackedMessagesPerConsumer, MediaType.APPLICATION_JSON));
}
 
Example 9
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> createNamespaceAsync(String namespace, Policies policies) {
    NamespaceName ns = NamespaceName.get(namespace);
    checkArgument(ns.isV2(), "Create namespace with policies is only supported on newer namespaces");
    WebTarget path = namespacePath(ns);
    // For V2 API we pass full Policy class instance
    return asyncPutRequest(path, Entity.entity(policies, MediaType.APPLICATION_JSON));
}
 
Example 10
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> grantPermissionOnNamespaceAsync(
        String namespace, String role, Set<AuthAction> actions) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "permissions", role);
    return asyncPostRequest(path, Entity.entity(actions, MediaType.APPLICATION_JSON));
}
 
Example 11
Source File: NamespacesTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplitBundles() throws Exception {
    URL localWebServiceUrl = new URL(pulsar.getSafeWebServiceAddress());
    String bundledNsLocal = "test-bundled-namespace-1";
    BundlesData bundleData = new BundlesData(Lists.newArrayList("0x00000000", "0xffffffff"));
    createBundledTestNamespaces(this.testTenant, this.testLocalCluster, bundledNsLocal, bundleData);
    final NamespaceName testNs = NamespaceName.get(this.testTenant, this.testLocalCluster, bundledNsLocal);

    OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());
    doReturn(CompletableFuture.completedFuture(null)).when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);
    ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);
    mockWebUrl(localWebServiceUrl, testNs);

    // split bundles
    try {
        namespaces.splitNamespaceBundle(testTenant, testLocalCluster, bundledNsLocal, "0x00000000_0xffffffff",
                false, true);
        // verify split bundles
        BundlesData bundlesData = namespaces.getBundlesData(testTenant, testLocalCluster, bundledNsLocal);
        assertNotNull(bundlesData);
        assertEquals(bundlesData.boundaries.size(), 3);
        assertEquals(bundlesData.boundaries.get(0), "0x00000000");
        assertEquals(bundlesData.boundaries.get(1), "0x7fffffff");
        assertEquals(bundlesData.boundaries.get(2), "0xffffffff");
    } catch (RestException re) {
        assertEquals(re.getResponse().getStatus(), Status.PRECONDITION_FAILED.getStatusCode());
    }
}
 
Example 12
Source File: NamespaceIsolationPoliciesTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testBrokerAssignment() throws Exception {
    NamespaceIsolationPolicies policies = this.getDefaultTestPolicies();
    NamespaceName ns = NamespaceName.get("pulsar/use/testns-1");
    SortedSet<BrokerStatus> primaryCandidates = new TreeSet<>();
    BrokerStatus primary = new BrokerStatus("prod1-broker1.messaging.use.example.com", true, 0);
    BrokerStatus secondary = new BrokerStatus("prod1-broker4.use.example.com", true, 0);
    BrokerStatus shared = new BrokerStatus("use.example.com", true, 0);
    SortedSet<BrokerStatus> secondaryCandidates = new TreeSet<>();
    SortedSet<BrokerStatus> sharedCandidates = new TreeSet<>();
    policies.assignBroker(ns, primary, primaryCandidates, secondaryCandidates, sharedCandidates);
    assertEquals(primaryCandidates.size(), 1);
    assertEquals(secondaryCandidates.size(), 0);
    assertEquals(sharedCandidates.size(), 0);
    assertEquals(primary, primaryCandidates.first());
    policies.assignBroker(ns, secondary, primaryCandidates, secondaryCandidates, sharedCandidates);
    assertEquals(primaryCandidates.size(), 1);
    assertEquals(secondaryCandidates.size(), 1);
    assertEquals(sharedCandidates.size(), 0);
    assertEquals(secondary, secondaryCandidates.first());
    policies.assignBroker(NamespaceName.get("pulsar/use1/testns-1"), shared, primaryCandidates, secondaryCandidates,
            sharedCandidates);
    assertEquals(primaryCandidates.size(), 1);
    assertEquals(secondaryCandidates.size(), 1);
    assertEquals(sharedCandidates.size(), 1);
    assertEquals(shared, sharedCandidates.first());
}
 
Example 13
Source File: AbstractWebSocketHandler.java    From pulsar with Apache License 2.0 4 votes vote down vote up
private TopicName extractTopicName(HttpServletRequest request) {
    String uri = request.getRequestURI();
    List<String> parts = Splitter.on("/").splitToList(uri);

    // V1 Format must be like :
    // /ws/producer/persistent/my-property/my-cluster/my-ns/my-topic
    // or
    // /ws/consumer/persistent/my-property/my-cluster/my-ns/my-topic/my-subscription
    // or
    // /ws/reader/persistent/my-property/my-cluster/my-ns/my-topic

    // V2 Format must be like :
    // /ws/v2/producer/persistent/my-property/my-ns/my-topic
    // or
    // /ws/v2/consumer/persistent/my-property/my-ns/my-topic/my-subscription
    // or
    // /ws/v2/reader/persistent/my-property/my-ns/my-topic

    checkArgument(parts.size() >= 8, "Invalid topic name format");
    checkArgument(parts.get(1).equals("ws"));

    final boolean isV2Format = parts.get(2).equals("v2");
    final int domainIndex = isV2Format ? 4 : 3;
    checkArgument(parts.get(domainIndex).equals("persistent") ||
            parts.get(domainIndex).equals("non-persistent"));


    final String domain = parts.get(domainIndex);
    final NamespaceName namespace = isV2Format ? NamespaceName.get(parts.get(5), parts.get(6)) :
            NamespaceName.get( parts.get(4), parts.get(5), parts.get(6));
    //The topic name which contains slashes is also split , so it needs to be jointed
    int startPosition = 7;
    boolean isConsumer = "consumer".equals(parts.get(2)) || "consumer".equals(parts.get(3));
    int endPosition = isConsumer ? parts.size() -1 : parts.size();
    StringBuilder topicName = new StringBuilder(parts.get(startPosition));
    while (++startPosition < endPosition) {
        if(StringUtils.isEmpty(parts.get(startPosition))){
           continue;
        }
        topicName.append("/").append(parts.get(startPosition));
    }
    final String name = topicName.toString();

    return TopicName.get(domain, namespace, name);
}
 
Example 14
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> setSubscriptionExpirationTimeAsync(String namespace, int expirationTime) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "subscriptionExpirationTime");
    return asyncPostRequest(path, Entity.entity(expirationTime, MediaType.APPLICATION_JSON));
}
 
Example 15
Source File: PulsarMetadataReader.java    From pulsar-flink with Apache License 2.0 4 votes vote down vote up
public static String objectPath2TopicName(ObjectPath objectPath) {
    NamespaceName ns = NamespaceName.get(objectPath.getDatabaseName());
    String topic = objectPath.getObjectName();
    TopicName fullName = TopicName.get(TopicDomain.persistent.toString(), ns, topic);
    return fullName.toString();
}
 
Example 16
Source File: SchemaCompatibilityCheckTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider =  "CanReadLastSchemaCompatibilityStrategy")
public void testConsumerCompatibilityCheckCanReadLastTest(SchemaCompatibilityStrategy schemaCompatibilityStrategy) throws Exception {
    final String tenant = PUBLIC_TENANT;
    final String topic = "test-consumer-compatibility";

        String namespace = "test-namespace-" + randomName(16);
        String fqtn = TopicName.get(
                TopicDomain.persistent.value(),
                tenant,
                namespace,
                topic
        ).toString();

        NamespaceName namespaceName = NamespaceName.get(tenant, namespace);

        admin.namespaces().createNamespace(
                tenant + "/" + namespace,
                Sets.newHashSet(CLUSTER_NAME)
        );

        admin.namespaces().setSchemaCompatibilityStrategy(namespaceName.toString(), schemaCompatibilityStrategy);
        admin.schemas().createSchema(fqtn, Schema.AVRO(Schemas.PersonOne.class).getSchemaInfo());
        admin.schemas().createSchema(fqtn, Schema.AVRO(SchemaDefinition.builder()
                .withAlwaysAllowNull(false).withPojo(Schemas.PersonTwo.class).build()).getSchemaInfo());

        Consumer<Schemas.PersonThree> consumerThree = pulsarClient.newConsumer(Schema.AVRO(
                SchemaDefinition.<Schemas.PersonThree>builder().withAlwaysAllowNull
                        (false).withSupportSchemaVersioning(true).
                        withPojo(Schemas.PersonThree.class).build()))
                .subscriptionName("test")
                .topic(fqtn)
                .subscribe();

        Producer<Schemas.PersonOne> producerOne = pulsarClient
                .newProducer(Schema.AVRO(Schemas.PersonOne.class))
                .topic(fqtn)
                .create();


        Schemas.PersonOne personOne = new Schemas.PersonOne();
        personOne.setId(1);

        producerOne.send(personOne);
        Message<Schemas.PersonThree> message = null;

        try {
            message = consumerThree.receive();
            message.getValue();
        } catch (Exception e) {
            Assert.assertTrue(e instanceof SchemaSerializationException);
            consumerThree.acknowledge(message);
        }

        Producer<Schemas.PersonTwo> producerTwo = pulsarClient
                .newProducer(Schema.AVRO(SchemaDefinition.<Schemas.PersonTwo>builder().withAlwaysAllowNull
                        (false).withSupportSchemaVersioning(true).
                        withPojo(Schemas.PersonTwo.class).build()))
                .topic(fqtn)
                .create();

        Schemas.PersonTwo personTwo = new Schemas.PersonTwo();
        personTwo.setId(1);
        personTwo.setName("Jerry");
        producerTwo.send(personTwo);

        message = consumerThree.receive();
        Schemas.PersonThree personThree = message.getValue();
        consumerThree.acknowledge(message);

        assertEquals(personThree.getId(), 1);
        assertEquals(personThree.getName(), "Jerry");

        consumerThree.close();
        producerOne.close();
        producerTwo.close();
}
 
Example 17
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> setSubscriptionDispatchRateAsync(String namespace, DispatchRate dispatchRate) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "subscriptionDispatchRate");
    return asyncPostRequest(path, Entity.entity(dispatchRate, MediaType.APPLICATION_JSON));
}
 
Example 18
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> unloadAsync(String namespace) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "unload");
    return asyncPutRequest(path, Entity.entity("", MediaType.APPLICATION_JSON));
}
 
Example 19
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> clearNamespaceBacklogAsync(String namespace) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "clearBacklog");
    return asyncPostRequest(path, Entity.entity("", MediaType.APPLICATION_JSON));
}
 
Example 20
Source File: NamespacesImpl.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Void> setDispatchRateAsync(String namespace, DispatchRate dispatchRate) {
    NamespaceName ns = NamespaceName.get(namespace);
    WebTarget path = namespacePath(ns, "dispatchRate");
    return asyncPostRequest(path, Entity.entity(dispatchRate, MediaType.APPLICATION_JSON));
}