List of usage examples for javax.jms TextMessage getText
String getText() throws JMSException;
From source file:org.apache.servicemix.jms.JmsMarshalerTest.java
public void testMarshalTextMessage() throws Exception { JmsComponent jms = new JmsComponent(); jms.getConfiguration().setConnectionFactory(connectionFactory); JmsEndpoint ep = new JmsEndpoint(); ep.setService(ReceiverComponent.SERVICE); ep.setEndpoint("jms"); ep.setTargetService(ReceiverComponent.SERVICE); ep.setTargetEndpoint(ReceiverComponent.ENDPOINT); ep.setRole(MessageExchange.Role.CONSUMER); ep.setDestinationStyle(AbstractJmsProcessor.STYLE_QUEUE); ep.setDestination(queue);/*from w w w .j ava2 s . c om*/ ep.setDefaultMep(JbiConstants.IN_ONLY); ep.setMarshaler(new DefaultJmsMarshaler(ep)); jms.setEndpoints(new JmsEndpoint[] { ep }); container.activateComponent(jms, "servicemix-jms"); ReceiverComponent receiver = new ReceiverComponent(); container.activateComponent(receiver, "receiver"); QueueConnection qConn = connectionFactory.createQueueConnection(); QueueSession qSess = qConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); QueueSender qSender = qSess.createSender(queue); TextMessage message = qSess .createTextMessage("<?xml version=\"1.0\" encoding=\"UTF-8\"?><hello>world</hello>"); qSender.send(message); receiver.getMessageList().assertMessagesReceived(1); List msgs = receiver.getMessageList().flushMessages(); NormalizedMessage msg = (NormalizedMessage) msgs.get(0); assertEquals("Messages match", message.getText(), new SourceTransformer().contentToString(msg)); // Wait for DONE status Thread.sleep(50); }
From source file:it.cnr.isti.labse.glimpse.manager.GlimpseManager.java
public void onMessage(Message arg0) { TextMessage msg = null; try {//from w w w . j ava2 s . c o m msg = (TextMessage) arg0; DebugMessages.line(); DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "receive " + msg.getText()); DebugMessages.line(); String XMLRule = msg.getText(); String sender = msg.getStringProperty("SENDER"); /* * check if the message contains a ComplexEventRule or a Model * in the second case, it must be forwarded to the new component * Transformer that will convert Model to Drools rule * */ ComplexEventRuleActionType rules; if (XMLRule.contains("ComplexEventRuleActionList")) { //if the message contains a rule represented through ComplexEventRule XSD ComplexEventRuleActionListDocument ruleDoc; ruleDoc = ComplexEventRuleActionListDocument.Factory.parse(XMLRule); rules = ruleDoc.getComplexEventRuleActionList(); } else { //if the message contains a rule represented through a model (CPMM) Transformer transformer = new TransformerImpl(null); /*TODO: as parameter of the transformerImpl, we must put the * path of the metamodel file. */ rules = transformer.convertInputModel(XMLRule).getComplexEventRuleActionList(); } //the topic where the listener will give analysis results answerTopic = "answerTopic" + "#" + this.getName() + "#" + System.nanoTime(); DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Create answerTopic"); connectionTopic = publishSession.createTopic(answerTopic); //tPub = publishSession.createPublisher(connectionTopic); DebugMessages.ok(); DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Setup ComplexEventProcessor with Enabler request."); try { Object[] loadedKnowledgePackage = rulesManager.loadRules(rules); //inserisco la coppia chiave valore dove la chiave il KnowledgePackage //caricato, generato da DroolsRulesManager con la loadRules //e il valore l'enabler che l'ha inviata //(il KnowledgePackage array dovrebbe avere sempre dimensione 1 essendo creato ad ogni loadrules) for (int i = 0; i < loadedKnowledgePackage.length; i++) { KnowledgePackageImp singleKnowlPack = (KnowledgePackageImp) loadedKnowledgePackage[i]; Rule singleRuleContainer[] = new Rule[singleKnowlPack.getRules().size()]; singleRuleContainer = singleKnowlPack.getRules().toArray(singleRuleContainer); for (int j = 0; j < singleRuleContainer.length; j++) { requestMap.put(singleRuleContainer[j].getName(), new ConsumerProfile(sender, answerTopic)); } DebugMessages.ok(); DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "KnowledgeBase packages loaded: " + rulesManager.getLoadedKnowledgePackageCardinality()); } DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Communicate the answerTopic to the enabler"); sendMessage(createMessage("AnswerTopic == " + answerTopic, sender)); DebugMessages.ok(); } catch (IncorrectRuleFormatException e) { sendMessage(createMessage("PROVIDED RULE CONTAINS ERRORS", sender)); } } catch (NullPointerException asd) { try { sendMessage(createMessage("PROVIDED RULE IS NULL, PLEASE PROVIDE A VALID RULE", msg.getStringProperty("SENDER"))); } catch (JMSException e) { e.printStackTrace(); } } catch (XmlException e) { try { sendMessage(createMessage("PROVIDED XML CONTAINS ERRORS", msg.getStringProperty("SENDER"))); } catch (JMSException e1) { e1.printStackTrace(); } } catch (JMSException ee) { ee.printStackTrace(); } DebugMessages.line(); }
From source file:uk.co.jassoft.markets.crawler.CrawlerListener.java
@Override @JmsListener(destination = "Crawler", concurrency = "5") public void onMessage(final Message message) { if (message instanceof TextMessage) { final TextMessage textMessage = (TextMessage) message; try {// w w w . j ava 2s.c o m message.acknowledge(); final Story story = mapper.readValue(textMessage.getText(), Story.class); Source source = sourceRepository.findOne(story.getParentSource()); if (source.isDisabled()) { LOG.info("Source [{}] is Disabled", source.getName()); final Link link = linkService.findOneByLink(story.getUrl().toString()); if (link != null) { linkService.delete(link); } return; } if (SourceUtils.matchesExclusion(source.getExclusionList(), story.getUrl().toString())) { LOG.info("Story Link Matches Exclusion for Source [{}]", source.getName()); final Link link = linkService.findOneByLink(story.getUrl().toString()); if (link != null) { linkService.delete(link); } return; } if (isbaseURL(source.getUrls(), story.getUrl().toString())) { SourceUrl currentSourceUrl = source.getUrls().parallelStream() .filter(sourceUrl -> sourceUrl.getUrl().equals(story.getUrl().toString())).findFirst() .get(); if (!currentSourceUrl.isEnabled() || (currentSourceUrl.getDisabledUntil() != null && currentSourceUrl.getDisabledUntil().after(new Date()))) { LOG.info("Source URL [{}] is Disabled", currentSourceUrl.getUrl()); final Link link = linkService.findOneByLink(story.getUrl().toString()); if (link != null) { linkService.delete(link); } return; } } try (InputStream inputStream = network.read(story.getUrl().toString(), "GET", !isbaseURL(source.getUrls(), story.getUrl().toString()))) { Document doc = Jsoup.parse(inputStream, "UTF-8", story.getUrl().toString()); Elements links = doc.select("a[href]"); doc = null; LOG.debug("Found [{}] Links in [{}]", links.size(), story.getUrl().toString()); AtomicInteger newLinkCount = new AtomicInteger(0); links.stream().map(link -> { String linkHref = link.attr("abs:href"); if (linkHref.contains("#")) linkHref = linkHref.substring(0, linkHref.indexOf("#")); return new ImmutablePair<String, Element>(linkHref, link); }).filter(isNotGlobalExclusion()).filter(isValidUrl(source)) .filter(doesNotMatchExclusion(source)).filter(isNewLink(linkService, storyRepository)) .forEach(link -> { try { LOG.debug("{} - {}", link.getKey(), link.getValue().text()); Story storyFound = new Story(link.getValue().text(), new URL(link.getKey()), new Date(), story.getParentSource()); crawlLink(storyFound); newLinkCount.incrementAndGet(); Story existingStory = storyRepository .findOneByUrl(storyFound.getUrl().toString()); if (existingStory != null) return; if (link.getKey().getBytes().length < 1000) { storyRepository.save(storyFound); collectStory(storyFound.getId()); linkService.save(new Link(link.getKey())); } else { LOG.warn("Link too long to persist. Not Persisting. {} - {}", link.getKey(), link.getValue().text()); } } catch (final Exception exception) { LOG.error("Error found with Link {} - {}", link.getKey(), link.getValue().text() + ": " + exception.getLocalizedMessage()); } }); if (newLinkCount.get() > 0) { LOG.info("Found [{}] New Links in [{}]", newLinkCount.get(), story.getUrl().toString()); } links = null; } catch (IOException exception) { LOG.warn("IOException Crawling Link [{}] - [{}]", story.getUrl().toString(), exception.getMessage()); sourceErrorRepository.save(new SourceError(source.getId(), new Date(), story.getUrl().toString(), null, exception.getMessage())); return; } if (isbaseURL(source.getUrls(), story.getUrl().toString())) { SourceUrl currentSourceUrl = source.getUrls().parallelStream() .filter(sourceUrl -> sourceUrl.getUrl().equals(story.getUrl().toString())).findFirst() .get(); currentSourceUrl.setLastCrawled(new Date()); currentSourceUrl.setPendingCrawl(false); if (currentSourceUrl.getCrawlInterval() == null) { currentSourceUrl.setCrawlInterval(60); } mongoTemplate.updateFirst( Query.query(Criteria.where("id").is(source.getId()).and("urls.url") .is(story.getUrl().toString())), new Update().set("urls.$", currentSourceUrl), Source.class); } } catch (IOException exception) { LOG.warn(exception.getLocalizedMessage()); return; } catch (final Exception exception) { LOG.error(exception.getLocalizedMessage(), exception); throw new RuntimeException(exception); } } }
From source file:org.apache.stratos.cloud.controller.topic.instance.status.InstanceStatusEventMessageDelegator.java
@Override public void run() { log.info("Instance status event message delegator started"); while (true) { try {/*from w w w .j av a 2s. co m*/ TextMessage message = InstanceStatusEventMessageQueue.getInstance().take(); // retrieve the header String type = message.getStringProperty(Constants.EVENT_CLASS_NAME); log.info(String.format("Instance status event message received from queue: %s", type)); if (InstanceStartedEvent.class.getName().equals(type)) { // retrieve the actual message String json = message.getText(); TopologyBuilder.handleMemberStarted( (InstanceStartedEvent) Util.jsonToObject(json, InstanceStartedEvent.class)); } else if (InstanceActivatedEvent.class.getName().equals(type)) { // retrieve the actual message String json = message.getText(); TopologyBuilder.handleMemberActivated( (InstanceActivatedEvent) Util.jsonToObject(json, InstanceActivatedEvent.class)); } else if (InstanceReadyToShutdownEvent.class.getName().equals(type)) { //retrieve the actual message String json = message.getText(); TopologyBuilder.handleMemberReadyToShutdown((InstanceReadyToShutdownEvent) Util .jsonToObject(json, InstanceReadyToShutdownEvent.class)); } else if (InstanceMaintenanceModeEvent.class.getName().equals(type)) { //retrieve the actual message String json = message.getText(); TopologyBuilder.handleMemberMaintenance((InstanceMaintenanceModeEvent) Util.jsonToObject(json, InstanceMaintenanceModeEvent.class)); } else { log.warn("Event message received is not InstanceStartedEvent or InstanceActivatedEvent"); } } catch (Exception e) { String error = "Failed to retrieve the instance status event message"; log.error(error, e); // Commenting throwing the error. Otherwise thread will not execute if an exception is thrown. //throw new RuntimeException(error, e); } } }
From source file:org.dawnsci.commandserver.core.producer.ProcessConsumer.java
/** * WARNING - starts infinite loop - you have to kill * @param uri/*from w w w . ja v a 2 s. co m*/ * @param submitQName * @param statusTName * @param statusQName * @throws Exception */ private void monitorSubmissionQueue(URI uri, String submitQName, String statusTName, String statusQName) throws Exception { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(submitQName); final MessageConsumer consumer = session.createConsumer(queue); connection.start(); System.out.println("Starting consumer for submissions to queue " + submitQName); while (isActive()) { // You have to kill it or call stop() to stop it! try { // Consumes messages from the queue. Message m = consumer.receive(1000); if (m != null) { // TODO FIXME Check if we have the max number of processes // exceeded and wait until we dont... TextMessage t = (TextMessage) m; ObjectMapper mapper = new ObjectMapper(); final StatusBean bean = mapper.readValue(t.getText(), getBeanClass()); if (bean != null) { // We add this to the status list so that it can be rendered in the UI if (!isHandled(bean)) continue; // Consume it and move on // Now we put the bean in the status queue and we // start the process RemoteSubmission factory = new RemoteSubmission(uri); factory.setLifeTime(t.getJMSExpiration()); factory.setPriority(t.getJMSPriority()); factory.setTimestamp(t.getJMSTimestamp()); factory.setQueueName(statusQName); // Move the message over to a status queue. factory.submit(bean, false); final ProgressableProcess process = createProcess(uri, statusTName, statusQName, bean); if (process != null) { if (process.isBlocking()) { System.out.println("About to run job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")"); } processCount++; process.start(); if (process.isBlocking()) { System.out.println( "Ran job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")"); } else { System.out.println("Started job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")"); } } } } } catch (Throwable ne) { // Really basic error reporting, they have to pipe to file. ne.printStackTrace(); setActive(false); } } }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java
private JMSResponse resolveMessage(Request request, long timeStarted, Message messageSend, Message messageReceive) throws JMSException { if (messageReceive instanceof TextMessage) { TextMessage textMessageReceive = (TextMessage) messageReceive; return new JMSResponse(textMessageReceive.getText(), messageSend, textMessageReceive, request, timeStarted);//w ww .j a v a 2 s .c o m } else if (messageReceive instanceof MapMessage) { MapMessage mapMessageReceive = (MapMessage) messageReceive; return new JMSResponse(JMSUtils.extractMapMessagePayloadToXML(mapMessageReceive), messageSend, mapMessageReceive, request, timeStarted); } else if (messageReceive instanceof BytesMessage) { BytesMessage bytesMessageReceive = (BytesMessage) messageReceive; String bytesMessageAsString = new String(JMSUtils.extractByteArrayFromMessage(bytesMessageReceive)); // if message seems to be XML make xml response if (XmlUtils.seemsToBeXml(bytesMessageAsString)) { return new JMSResponse(bytesMessageAsString, messageSend, bytesMessageReceive, request, timeStarted); } else { JMSResponse jmsResponse = new JMSResponse("", messageSend, bytesMessageReceive, request, timeStarted); addAttachment(request, bytesMessageReceive, jmsResponse); return jmsResponse; } } return null; }
From source file:eu.learnpad.simulator.mon.manager.GlimpseManager.java
public void onMessage(Message messagePayload) { TextMessage msg = null; try {/*from w w w . ja v a 2s . c o m*/ msg = (TextMessage) messagePayload; DebugMessages.line(); DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "receive " + msg.getText()); DebugMessages.line(); String xmlMessagePayload = msg.getText(); String sender = msg.getStringProperty("SENDER"); ComplexEventRuleActionListDocument ruleDoc; // check if the paylod of the message is a bpmn to be used for path // extraction and rules generation // or if the xml is already a rule to inject into the engine if (xmlMessagePayload.contains("http://www.omg.org/spec/BPMN/20100524/MODEL")) { DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "The message sent seems to contain a BPMN - Forwarding it to the LearnPAd Assessment Manager"); @SuppressWarnings("unchecked") List<String> learnersIDs = (List<String>) msg.getObjectProperty("USERSINVOLVEDID"); String bpmnID = msg.getObjectProperty("BPMNID").toString(); String sessionID = msg.getObjectProperty("SESSIONID").toString(); Vector<Learner> learnersInvolved = learnerAssessmentManager.getDBController() .getOrSetLearners(learnersIDs); DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Creating Session Score Buffer"); sessionScoreBuffer = new ScoreTemporaryStorage(learnersInvolved, sessionID); if (sessionScoreBuffer != null) DebugMessages.ok(); ruleDoc = learnerAssessmentManager.elaborateModel(xmlMessagePayload, learnersInvolved, sessionID, bpmnID); } else { ruleDoc = ComplexEventRuleActionListDocument.Factory.parse(xmlMessagePayload); } ComplexEventRuleActionType rules = ruleDoc.getComplexEventRuleActionList(); // the topic where the listener will give analysis results answerTopic = "answerTopic" + "#" + this.getName() + "#" + System.nanoTime(); DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Create answerTopic"); connectionTopic = publishSession.createTopic(answerTopic); // tPub = publishSession.createPublisher(connectionTopic); DebugMessages.ok(); DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Setting up ComplexEventProcessor with new rule."); try { Object[] loadedKnowledgePackage = rulesManagerOne.loadRules(rules); //Object[] loadedKnowledgePackage = rulesManagerOne.vandaLoadRules(rules); // inserisco la coppia chiave valore dove la chiave il KnowledgePackage // caricato, generato da DroolsRulesManager con la loadRules // e il valore l'enabler che l'ha inviata // (il KnowledgePackage array dovrebbe avere sempre dimensione 1 // essendo creato ad ogni loadrules) for (int i = 0; i < loadedKnowledgePackage.length; i++) { KnowledgePackageImp singleKnowlPack = (KnowledgePackageImp) loadedKnowledgePackage[i]; Rule[] singleRuleContainer = new Rule[singleKnowlPack.getRules().size()]; singleRuleContainer = singleKnowlPack.getRules().toArray(singleRuleContainer); for (int j = 0; j < singleRuleContainer.length; j++) { requestMap.put(singleRuleContainer[j].getName(), new ConsumerProfile(sender, answerTopic)); } } DebugMessages.println(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "KnowledgeBase packages loaded: " + rulesManagerOne.getLoadedKnowledgePackageCardinality()); DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(), "Communicate the answerTopic to the requester"); sendMessage(createMessage("AnswerTopic == " + answerTopic, sender)); DebugMessages.ok(); } catch (IncorrectRuleFormatException e) { sendMessage(createMessage("PROVIDED RULE CONTAINS ERRORS", sender)); } } catch (NullPointerException asd) { try { sendMessage(createMessage("PROVIDED RULE IS NULL, PLEASE PROVIDE A VALID RULE", msg.getStringProperty("SENDER"))); } catch (JMSException e) { e.printStackTrace(); } } catch (XmlException e) { try { sendMessage(createMessage("PROVIDED XML CONTAINS ERRORS", msg.getStringProperty("SENDER"))); } catch (JMSException e1) { e1.printStackTrace(); } } catch (JMSException ee) { ee.printStackTrace(); } DebugMessages.line(); }
From source file:org.eclipse.scanning.event.SubscriberImpl.java
private MessageConsumer createConsumer(final String topicName, final Class<?> beanClass) throws JMSException { Topic topic = super.createTopic(topicName); final MessageConsumer consumer = session.createConsumer(topic); MessageListener listener = new MessageListener() { public void onMessage(Message message) { TextMessage txt = (TextMessage) message; try { String json = txt.getText(); json = JsonUtil.removeProperties(json, properties); try { Object bean = service.unmarshal(json, beanClass); schedule(new DiseminateEvent(bean)); } catch (Exception ne) { logger.error("Error processing message {} on topic {} with beanClass {}", message, topicName, beanClass, ne); ne.printStackTrace(); // Unit tests without log4j config show this one. }/* w w w . j a v a2s .co m*/ } catch (JMSException ne) { logger.error("Cannot get text from message " + txt, ne); } } }; consumer.setMessageListener(listener); return consumer; }
From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java
public void dotestJAASSecurityManagerAuthorizationPositive(String jaasConfigScope, String artemisRoleName) throws Exception { createArtemisServer(jaasConfigScope); Set<Role> roles = new HashSet<>(); roles.add(new Role(artemisRoleName, true, true, true, true, true, true, true, true, true, true)); server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles); server.start();/* w w w.ja va2 s .c o m*/ JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory( "amqp://localhost:5672?amqp.saslMechanisms=GSSAPI"); Connection connection = jmsConnectionFactory.createConnection("client", null); try { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue(QUEUE_NAME); // PRODUCE final String text = RandomUtil.randomString(); try { MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage(text)); } catch (Exception e) { e.printStackTrace(); Assert.fail("should not throw exception here"); } // CONSUME try { MessageConsumer consumer = session.createConsumer(queue); TextMessage m = (TextMessage) consumer.receive(1000); Assert.assertNotNull(m); Assert.assertEquals(text, m.getText()); } catch (Exception e) { Assert.fail("should not throw exception here"); } } finally { connection.close(); } }
From source file:com.mdmserver.managers.ControllerFacade.java
public void lockPhone(int accountId) throws IOException { Account account = databaseManager.getAccountByAccountId(accountId); Context ctx;//from w ww. j av a 2 s . c o m try { ctx = new InitialContext(); ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("jms/mdmConnectionFactory"); Queue queue = (Queue) ctx.lookup("jms/mdmQueue"); MessageProducer messageProducer; System.out.println("Naming success"); try { javax.jms.Connection connection = connectionFactory.createConnection(); javax.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); messageProducer = session.createProducer(queue); TextMessage message = session.createTextMessage(); message.setStringProperty(Account.FIELD_NAME_CLOUD_ID, account.getCloudId()); ControlClient cClient = new ControlClient(); cClient.setCommandType(ControlClient.LOCK_PHONE_CONTROL); Gson gson = new Gson(); message.setStringProperty(ControlClient.CONTROL_CLIENT_KEY, gson.toJson(cClient)); System.out.println("It come from Servlet:" + message.getText()); messageProducer.send(message); System.out.println("JMS success"); } catch (JMSException ex) { // Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex); System.out.println("JMS exception"); } } catch (NamingException ex) { // Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Naming exception"); } }