use of org.joda.time.Period in project azure-sdk-for-java by Azure.
the class ServiceBusPublishSubscribeAdvanceFeatures method runSample.
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
public static boolean runSample(Azure azure) {
// New resources
final String rgName = SdkContext.randomResourceName("rgSB04_", 24);
final String namespaceName = SdkContext.randomResourceName("namespace", 20);
final String topic1Name = SdkContext.randomResourceName("topic1_", 24);
final String topic2Name = SdkContext.randomResourceName("topic2_", 24);
final String subscription1Name = SdkContext.randomResourceName("subs_", 24);
final String subscription2Name = SdkContext.randomResourceName("subs_", 24);
final String subscription3Name = SdkContext.randomResourceName("subs_", 24);
final String sendRuleName = "SendRule";
final String manageRuleName = "ManageRule";
try {
//============================================================
// Create a namespace.
System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "...");
ServiceBusNamespace serviceBusNamespace = azure.serviceBusNamespaces().define(namespaceName).withRegion(Region.US_WEST).withNewResourceGroup(rgName).withSku(NamespaceSku.PREMIUM_CAPACITY1).withNewTopic(topic1Name, 1024).create();
System.out.println("Created service bus " + serviceBusNamespace.name());
Utils.print(serviceBusNamespace);
System.out.println("Created topic following topic along with namespace " + namespaceName);
Topic firstTopic = serviceBusNamespace.topics().getByName(topic1Name);
Utils.print(firstTopic);
//============================================================
// Create a service bus subscription in the topic with session and dead-letter enabled.
System.out.println("Creating subscription " + subscription1Name + " in topic " + topic1Name + "...");
ServiceBusSubscription firstSubscription = firstTopic.subscriptions().define(subscription1Name).withSession().withDefaultMessageTTL(new Period().withMinutes(20)).withMessageMovedToDeadLetterSubscriptionOnMaxDeliveryCount(20).withExpiredMessageMovedToDeadLetterSubscription().withMessageMovedToDeadLetterSubscriptionOnFilterEvaluationException().create();
System.out.println("Created subscription " + subscription1Name + " in topic " + topic1Name + "...");
Utils.print(firstSubscription);
//============================================================
// Create another subscription in the topic with auto deletion of idle entities.
System.out.println("Creating another subscription " + subscription2Name + " in topic " + topic1Name + "...");
ServiceBusSubscription secondSubscription = firstTopic.subscriptions().define(subscription2Name).withSession().withDeleteOnIdleDurationInMinutes(20).create();
System.out.println("Created subscription " + subscription2Name + " in topic " + topic1Name + "...");
Utils.print(secondSubscription);
//============================================================
// Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription.
System.out.println("Creating second topic " + topic2Name + ", with De-duplication and AutoDeleteOnIdle features...");
Topic secondTopic = serviceBusNamespace.topics().define(topic2Name).withNewSendRule(sendRuleName).withPartitioning().withNewSubscription(subscription3Name).create();
System.out.println("Created second topic in namespace");
Utils.print(secondTopic);
System.out.println("Creating following authorization rules in second topic ");
PagedList<TopicAuthorizationRule> authorizationRules = secondTopic.authorizationRules().list();
for (TopicAuthorizationRule authorizationRule : authorizationRules) {
Utils.print(authorizationRule);
}
//============================================================
// Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule.
System.out.println("Updating second topic " + topic2Name + "...");
secondTopic = secondTopic.update().withDeleteOnIdleDurationInMinutes(5).withoutAuthorizationRule(sendRuleName).withNewManageRule(manageRuleName).apply();
System.out.println("Updated second topic to change its auto deletion time");
Utils.print(secondTopic);
System.out.println("Updated following authorization rules in second topic, new list of authorization rules are ");
authorizationRules = secondTopic.authorizationRules().list();
for (TopicAuthorizationRule authorizationRule : authorizationRules) {
Utils.print(authorizationRule);
}
//=============================================================
// Get connection string for default authorization rule of namespace
PagedList<NamespaceAuthorizationRule> namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list();
System.out.println("Number of authorization rule for namespace :" + namespaceAuthorizationRules.size());
for (NamespaceAuthorizationRule namespaceAuthorizationRule : namespaceAuthorizationRules) {
Utils.print(namespaceAuthorizationRule);
}
System.out.println("Getting keys for authorization rule ...");
AuthorizationKeys keys = namespaceAuthorizationRules.get(0).getKeys();
Utils.print(keys);
// Send a message to topic.
try {
Configuration config = Configuration.load();
config.setProperty(ServiceBusConfiguration.CONNECTION_STRING, keys.primaryConnectionString());
ServiceBusContract service = ServiceBusService.create(config);
service.sendTopicMessage(topic1Name, new BrokeredMessage("Hello World"));
} catch (Exception ex) {
}
//=============================================================
// Delete a topic and namespace
System.out.println("Deleting topic " + topic1Name + "in namespace " + namespaceName + "...");
serviceBusNamespace.topics().deleteByName(topic1Name);
System.out.println("Deleted topic " + topic1Name + "...");
System.out.println("Deleting namespace " + namespaceName + "...");
// This will delete the namespace and topic within it.
try {
azure.serviceBusNamespaces().deleteById(serviceBusNamespace.id());
} catch (Exception ex) {
}
System.out.println("Deleted namespace " + namespaceName + "...");
return true;
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
return false;
}
use of org.joda.time.Period in project azure-sdk-for-java by Azure.
the class ServiceBusQueueAdvanceFeatures method runSample.
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
public static boolean runSample(Azure azure) {
// New resources
final String rgName = SdkContext.randomResourceName("rgSB04_", 24);
final String namespaceName = SdkContext.randomResourceName("namespace", 20);
final String queue1Name = SdkContext.randomResourceName("queue1_", 24);
final String queue2Name = SdkContext.randomResourceName("queue2_", 24);
final String sendRuleName = "SendRule";
try {
//============================================================
// Create a namespace.
System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "...");
ServiceBusNamespace serviceBusNamespace = azure.serviceBusNamespaces().define(namespaceName).withRegion(Region.US_WEST).withNewResourceGroup(rgName).withSku(NamespaceSku.PREMIUM_CAPACITY1).create();
System.out.println("Created service bus " + serviceBusNamespace.name());
Utils.print(serviceBusNamespace);
//============================================================
// Add a queue in namespace with features session and dead-lettering.
System.out.println("Creating first queue " + queue1Name + ", with session, time to live and move to dead-letter queue features...");
Queue firstQueue = serviceBusNamespace.queues().define(queue1Name).withSession().withDefaultMessageTTL(new Period().withMinutes(10)).withExpiredMessageMovedToDeadLetterQueue().withMessageMovedToDeadLetterQueueOnMaxDeliveryCount(40).create();
Utils.print(firstQueue);
//============================================================
// Create second queue with Deduplication and AutoDeleteOnIdle feature
System.out.println("Creating second queue " + queue2Name + ", with De-duplication and AutoDeleteOnIdle features...");
Queue secondQueue = serviceBusNamespace.queues().define(queue2Name).withSizeInMB(2048).withDuplicateMessageDetection(new Period().withMinutes(10)).withDeleteOnIdleDurationInMinutes(10).create();
System.out.println("Created second queue in namespace");
Utils.print(secondQueue);
//============================================================
// Update second queue to change time for AutoDeleteOnIdle.
secondQueue = secondQueue.update().withDeleteOnIdleDurationInMinutes(5).apply();
System.out.println("Updated second queue to change its auto deletion time");
Utils.print(secondQueue);
//=============================================================
// Update first queue to disable dead-letter forwarding and with new Send authorization rule
secondQueue = firstQueue.update().withoutExpiredMessageMovedToDeadLetterQueue().withNewSendRule(sendRuleName).apply();
System.out.println("Updated first queue to change dead-letter forwarding");
Utils.print(secondQueue);
//=============================================================
// Get connection string for default authorization rule of namespace
PagedList<NamespaceAuthorizationRule> namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list();
System.out.println("Number of authorization rule for namespace :" + namespaceAuthorizationRules.size());
for (NamespaceAuthorizationRule namespaceAuthorizationRule : namespaceAuthorizationRules) {
Utils.print(namespaceAuthorizationRule);
}
System.out.println("Getting keys for authorization rule ...");
AuthorizationKeys keys = namespaceAuthorizationRules.get(0).getKeys();
Utils.print(keys);
//=============================================================
// Update first queue to remove Send Authorization rule.
firstQueue.update().withoutAuthorizationRule(sendRuleName).apply();
try {
Configuration config = Configuration.load();
config.setProperty(ServiceBusConfiguration.CONNECTION_STRING, keys.primaryConnectionString());
ServiceBusContract service = ServiceBusService.create(config);
BrokeredMessage message = new BrokeredMessage("Hello");
message.setSessionId("23424");
service.sendQueueMessage(queue1Name, message);
} catch (Exception ex) {
}
//=============================================================
// Delete a queue and namespace
System.out.println("Deleting queue " + queue1Name + "in namespace " + namespaceName + "...");
serviceBusNamespace.queues().deleteByName(queue1Name);
System.out.println("Deleted queue " + queue1Name + "...");
System.out.println("Deleting namespace " + namespaceName + "...");
// This will delete the namespace and queue within it.
try {
azure.serviceBusNamespaces().deleteById(serviceBusNamespace.id());
} catch (Exception ex) {
}
System.out.println("Deleted namespace " + namespaceName + "...");
return true;
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
return false;
}
use of org.joda.time.Period in project perun by CESNET.
the class PerunNotifTemplateManagerImpl method processPoolMessages.
@Override
public Set<Integer> processPoolMessages(Integer templateId, List<PoolMessage> notifMessages) {
if (notifMessages == null || notifMessages.isEmpty() || templateId == null) {
return null;
}
List<PerunNotifMessageDto> messageDtoList = new ArrayList<PerunNotifMessageDto>();
logger.info("Starting to process messages for template with id:" + templateId);
PerunNotifTemplate template = allTemplatesById.get(templateId);
switch(template.getNotifyTrigger()) {
case ALL_REGEX_IDS:
for (PoolMessage dto : notifMessages) {
// Test for all regexIds present
logger.info("Starting to process dto for templateId: " + templateId + " and keyAttributes: " + dto.getKeyAttributes());
Set<Integer> foundRegexIds = new HashSet<Integer>();
for (PerunNotifPoolMessage poolMessage : dto.getList()) {
foundRegexIds.add(poolMessage.getRegexId());
}
boolean allRegexes = true;
for (PerunNotifRegex regex : template.getMatchingRegexs()) {
if (!foundRegexIds.contains(regex.getId())) {
logger.info("Not all regexes found for templateId: " + templateId + ", and keyAttributes: " + dto.getKeyAttributes() + " missing:" + regex.getId());
allRegexes = false;
}
}
if (allRegexes) {
logger.info("All regexes found for templateId: " + templateId + " and keyAttribute: " + dto.getKeyAttributes() + " starting to create message.");
try {
messageDtoList.addAll(createMessageToSend(template, dto));
} catch (Exception ex) {
logger.error("Error during creating message to send.", ex);
}
}
}
break;
// - need to ensure delivery of all the msgs required by the template message
case STREAM:
DateTime now = new DateTime();
DateTime oldestTime = new DateTime(now.getMillis() - template.getOldestMessageTime());
DateTime youngestTime = new DateTime(now.getMillis() - template.getYoungestMessageTime());
for (PoolMessage parentDto : notifMessages) {
List<PerunNotifPoolMessage> poolMessages = parentDto.getList();
if (poolMessages != null) {
// Test for oldest message first message in list is oldest,
// messages
// are sorted from sql query
PerunNotifPoolMessage oldestPoolMessage = poolMessages.get(0);
if (oldestPoolMessage.getCreated().compareTo(oldestTime) < 0) {
// we have and send it
try {
logger.debug("Oldest message is older than oldest time for template id " + template.getId() + " message will be sent.");
messageDtoList.addAll(createMessageToSend(template, parentDto));
} catch (Exception ex) {
logger.error("Error during creating of messages to send.", ex);
}
} else {
// We test youngest message so we now nothing new will
// propably come in close future
PerunNotifPoolMessage youngestPoolMessage = poolMessages.get(poolMessages.size() - 1);
if (youngestPoolMessage.getCreated().compareTo(youngestTime) < 0) {
// Youngest message is older
try {
logger.debug("Youngest message is older than youngest time for template id " + template.getId() + " message will be sent.");
messageDtoList.addAll(createMessageToSend(template, parentDto));
} catch (Exception ex) {
logger.error("Error during creating of messages to send.", ex);
}
} else {
Period oldestPeriod = new Period(oldestPoolMessage.getCreated().getMillis() - oldestTime.getMillis());
Period youngestPeriod = new Period(youngestPoolMessage.getCreated().getMillis() - youngestTime.getMillis());
Period period = oldestPeriod.getMillis() < youngestPeriod.getMillis() ? oldestPeriod : youngestPeriod;
String remainingTime = "";
if (period.getDays() > 0) {
remainingTime += period.getDays() + " days ";
}
if (period.getHours() > 0) {
remainingTime += period.getHours() + " hours ";
}
if (period.getMinutes() > 0) {
remainingTime += period.getMinutes() + " minutes ";
}
if (period.getSeconds() > 0) {
remainingTime += period.getSeconds() + " sec.";
}
logger.debug("The time limits for messages are greater that messages creation time for template id " + template.getId() + ", the message will not be sent yet. " + "Provided no messages is created, the notification will be sent in " + remainingTime);
}
}
}
}
break;
}
Map<PerunNotifTypeOfReceiver, List<PerunNotifMessageDto>> messagesToSend = new HashMap<PerunNotifTypeOfReceiver, List<PerunNotifMessageDto>>();
Set<Integer> processedIds = new HashSet<Integer>();
for (PerunNotifMessageDto messageToSend : messageDtoList) {
List<PerunNotifMessageDto> list = messagesToSend.get(messageToSend.getReceiver().getTypeOfReceiver());
if (list == null) {
list = new ArrayList<PerunNotifMessageDto>();
list.add(messageToSend);
messagesToSend.put(messageToSend.getReceiver().getTypeOfReceiver(), list);
} else {
list.add(messageToSend);
}
}
for (PerunNotifTypeOfReceiver typeOfReceiver : messagesToSend.keySet()) {
PerunNotifSender handlingSender = null;
for (PerunNotifSender sender : notifSenders) {
if (sender.canHandle(typeOfReceiver)) {
handlingSender = sender;
}
}
if (handlingSender != null) {
logger.debug("Found handling sender: {}", handlingSender.toString());
processedIds.addAll(handlingSender.send(messagesToSend.get(typeOfReceiver)));
logger.debug("Messages send by sender: {}", handlingSender.toString());
} else {
logger.error("No handling sender found for: {}", typeOfReceiver);
}
}
return processedIds;
}
use of org.joda.time.Period in project azure-sdk-for-java by Azure.
the class ServiceBusOperationsTests method canCreateNamespaceThenCRUDOnTopic.
@Test
public void canCreateNamespaceThenCRUDOnTopic() {
Region region = Region.US_EAST;
Creatable<ResourceGroup> rgCreatable = resourceManager.resourceGroups().define(RG_NAME).withRegion(region);
String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15);
ServiceBusNamespace namespace = serviceBusManager.namespaces().define(namespaceDNSLabel).withRegion(region).withNewResourceGroup(rgCreatable).withSku(NamespaceSku.STANDARD).create();
Assert.assertNotNull(namespace);
Assert.assertNotNull(namespace.inner());
String topicName = generateRandomResourceName("topic1-", 15);
Topic topic = namespace.topics().define(topicName).create();
Assert.assertNotNull(topic);
Assert.assertNotNull(topic.inner());
Assert.assertNotNull(topic.name());
Assert.assertTrue(topic.name().equalsIgnoreCase(topicName));
Period dupDetectionDuration = topic.duplicateMessageDetectionHistoryDuration();
Assert.assertNotNull(dupDetectionDuration);
Assert.assertEquals(10, dupDetectionDuration.getMinutes());
// Default message TTL is TimeSpan.Max, assert parsing
//
Assert.assertEquals("10675199.02:48:05.4775807", topic.inner().defaultMessageTimeToLive());
Period msgTtlDuration = topic.defaultMessageTtlDuration();
Assert.assertNotNull(msgTtlDuration);
// Assert the default ttl TimeSpan("10675199.02:48:05.4775807") parsing
//
Assert.assertEquals(10675199, msgTtlDuration.getDays());
Assert.assertEquals(2, msgTtlDuration.getHours());
Assert.assertEquals(48, msgTtlDuration.getMinutes());
// Assert the default max size In MB
//
Assert.assertEquals(1024, topic.maxSizeInMB());
PagedList<Topic> topicsInNamespace = namespace.topics().list();
Assert.assertNotNull(topicsInNamespace);
Assert.assertTrue(topicsInNamespace.size() > 0);
Topic foundTopic = null;
for (Topic t : topicsInNamespace) {
if (t.name().equalsIgnoreCase(topic.name())) {
foundTopic = t;
break;
}
}
Assert.assertNotNull(foundTopic);
foundTopic = foundTopic.update().withDefaultMessageTTL(new Period().withMinutes(20)).withDuplicateMessageDetectionHistoryDuration(new Period().withMinutes(15)).withDeleteOnIdleDurationInMinutes(25).apply();
Period ttlDuration = foundTopic.defaultMessageTtlDuration();
Assert.assertNotNull(ttlDuration);
Assert.assertEquals(20, ttlDuration.getMinutes());
Period duplicateDetectDuration = foundTopic.duplicateMessageDetectionHistoryDuration();
Assert.assertNotNull(duplicateDetectDuration);
Assert.assertEquals(15, duplicateDetectDuration.getMinutes());
Assert.assertEquals(25, foundTopic.deleteOnIdleDurationInMinutes());
// Delete
namespace.topics().deleteByName(foundTopic.name());
}
use of org.joda.time.Period in project azure-sdk-for-java by Azure.
the class ServiceBusOperationsTests method canPerformCRUDOnSubscriptions.
@Test
public void canPerformCRUDOnSubscriptions() {
Region region = Region.US_EAST;
Creatable<ResourceGroup> rgCreatable = resourceManager.resourceGroups().define(RG_NAME).withRegion(region);
String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15);
String topicName = generateRandomResourceName("topic1-", 15);
String subscriptionName = generateRandomResourceName("sub1-", 15);
// Create NS with Topic
//
ServiceBusNamespace namespace = serviceBusManager.namespaces().define(namespaceDNSLabel).withRegion(region).withNewResourceGroup(rgCreatable).withSku(NamespaceSku.PREMIUM_CAPACITY1).withNewTopic(topicName, 1024).create();
// Create Topic subscriptions and list it
//
Topic topic = namespace.topics().getByName(topicName);
ServiceBusSubscription subscription = topic.subscriptions().define(subscriptionName).withDefaultMessageTTL(new Period().withMinutes(20)).create();
Assert.assertNotNull(subscription);
Assert.assertNotNull(subscription.inner());
Assert.assertEquals(20, subscription.defaultMessageTtlDuration().getMinutes());
subscription = topic.subscriptions().getByName(subscriptionName);
Assert.assertNotNull(subscription);
Assert.assertNotNull(subscription.inner());
PagedList<ServiceBusSubscription> subscriptionsInTopic = topic.subscriptions().list();
Assert.assertTrue(subscriptionsInTopic.size() > 0);
boolean foundSubscription = false;
for (ServiceBusSubscription s : subscriptionsInTopic) {
if (s.name().equalsIgnoreCase(subscription.name())) {
foundSubscription = true;
break;
}
}
Assert.assertTrue(foundSubscription);
topic.subscriptions().deleteByName(subscriptionName);
subscriptionsInTopic = topic.subscriptions().list();
Assert.assertTrue(subscriptionsInTopic.size() == 0);
}
Aggregations