/** * The split message method returns something that is iteratable such as a java.util.List. * * @param header the header of the incoming message with the name user * @param body the payload of the incoming message * @return a list containing each part splitted */ public List<Message> splitMessage(@Header(value = "user") String header, @Body String body) { // we can leverage the Parameter Binding Annotations // http://camel.apache.org/parameter-binding-annotations.html // to access the message header and body at same time, // then create the message that we want, splitter will // take care rest of them. // *NOTE* this feature requires Camel version >= 1.6.1 List<Message> answer = new ArrayList<Message>(); String[] parts = header.split(","); for (String part : parts) { DefaultMessage message = new DefaultMessage(); message.setHeader("user", part); message.setBody(body); answer.add(message); } return answer; }
/** * Generate ratings for the items * <p/> * Notice how the items is mapped to @Header with the name ids, which * refers to the context-path {ids} in the rest-dsl service */ public List<RatingDto> ratings(@Header("ids") String items) { System.out.println("Rating items " + items); List<RatingDto> answer = new ArrayList<>(); for (String id : items.split(",")) { RatingDto dto = new RatingDto(); answer.add(dto); dto.setItemNo(Integer.valueOf(id)); // generate some random ratings dto.setRating(new Random().nextInt(100)); } return answer; }
public void processOrder(Exchange exchange, InputOrder order, @Header(Exchange.REDELIVERED) Boolean redelivered) throws Exception { // simulate CPU processing of the order by sleeping a bit Thread.sleep(1000); // simulate fatal error if we refer to a special no if (order.getRefNo().equals("FATAL")) { throw new IllegalArgumentException("Simulated fatal error"); } // simulate fail once if we have not yet redelivered, which means its the first // time processOrder method is called if (order.getRefNo().equals("FAIL-ONCE") && redelivered == null) { throw new IOException("Simulated failing once"); } // processing is okay }
public boolean isFliped(@Header("reflectivity") int reflectivity) { if(flipFlop){ if(reflectivity>3000){ log.debug("FLIP-Reflectivity: " + reflectivity); flipFlop=false; return true; } }else { if(reflectivity<3000){ log.debug("FLOP-Reflectivity: " + reflectivity); flipFlop=true; } } return false; }
public void authenticate(@Header("user") String user, @Body String pass, Exchange exchange) throws AuthenticationException { if (StringUtils.isBlank(user) || StringUtils.isBlank(pass)) { LOG.info("User '{}' attempted to login with a blank username or password.", user); throw new AuthenticationException("User was not logged in."); } try { authenticationProvider.authenticateUser(user, pass); } catch (Exception e) { throw new AuthenticationException(e); } AuthDetails authDetails = new AuthDetails(user); tokens.put(authDetails.getToken().toString(), authDetails); Map<String, String> response = new HashMap<String, String>(); response.put("error",""); response.put("token",authDetails.getToken().toString()); exchange.getOut().setHeader("authDetails",authDetails); exchange.getOut().setBody(response); }
public void canAccessReport( @Header("authToken") String authToken , @Header("reportId") String reportId , Exchange exchange) throws AuthorizationException, AuthenticationException { if (tokens.containsKey(authToken) && tokens.get(authToken).getLoggedIn()) { User user = authenticationProvider.getUser(tokens.get(authToken).getUsername()); Collection<String> reports = authenticationProvider.getUserReports(user); exchange.getIn().setHeader("groups", user.getGroups()); exchange.getIn().setHeader("userExtra", user.getExtraOptions()); if (reports.contains(reportId)) return; throw new AuthorizationException("User is not logged in."); } throw new AuthenticationException("User is not logged in."); }
@Override public boolean shouldProcess(@Header(HL7Constants.HL7_SENDING_APPLICATION) String sendingApplication, @Header(HL7Constants.HL7_SENDING_FACILITY) String sendingFacility, @Header(HL7Constants.HL7_RECEIVING_APPLICATION) String receivingApplication, @Header(HL7Constants.HL7_RECEIVING_FACILITY) String receivingFacility, @Header(HL7Constants.HL7_MESSAGE_TYPE) String messageType, @Header(HL7Constants.HL7_TRIGGER_EVENT) String triggerEvent, @Header(HL7AdditionalConstants.HL7_EXTERNAL_PATIENT_ID) String externalPatientId, @Header(HL7AdditionalConstants.HL7_INTERNAL_PATIENT_ID) String internalPatientId) { return this.isFiltered( sendingApplication, sendingFacility, receivingApplication, receivingFacility, messageType, triggerEvent, externalPatientId, internalPatientId); }
public void dispatchProcessFixture(@Header(HL7AdditionalConstants.HL7_SOURCE_MESSAGE) ADT_A01 from, @Body ADT_A01 to) throws HL7Exception { this.changeMessageEventType(to, "A11"); this.tranformPid(to.getPID()); Segment zrf = this.promoteZrfSegment(from); this.transformZrf(zrf, to.getPV1()); this.transform(to.getPV1(), zrf); to.addNonstandardSegment("ZRF"); Segment toZrf = (Segment) to.insertRepetition("ZRF", 0); DeepCopy.copy(zrf, toZrf); }
public void dispatchProcessFixture(@Header(HL7AdditionalConstants.HL7_SOURCE_MESSAGE) ADT_A01 from, @Body ADT_A01 to) throws HL7Exception { this.changeMessageEventType(to, "A12"); this.tranformPid(to.getPID()); Segment zrf = this.promoteZrfSegment(from); this.transformZrf(zrf, to.getPV1()); this.transform(to.getPV1(), zrf); to.addNonstandardSegment("ZRF"); Segment toZrf = (Segment) to.insertRepetition("ZRF", 0); DeepCopy.copy(zrf, toZrf); }
@Handler public List<String> getRetweetsWithScreenNames(@Header("statusId") Long statusId) throws TwitterException { return twitter.getRetweets(statusId).stream() .map(tweet -> tweet.getUser().getScreenName()) .collect(Collectors.toList()); }
@SuppressWarnings("unused") public String forward(String body, @Headers Map<String, Object> headers, @Properties Map<String, Object> properties, @Header(Exchange.SLIP_ENDPOINT) String previous) { if (previous == null) { Object routing = headers.get("router-header"); return routing != null ? ("direct:" + routing) : null; } // no more so return null return null; }
public Object main(String body, @Header("name") String name) { if (name != null) { return "Hello " + name + ". I got payload `" + body + "` and I am on host: " + System.getenv("HOSTNAME"); } else { return "What is your name? Specify a name using ?name=foo as query parameter. I am on host: " + System.getenv("HOSTNAME"); } }
public boolean retry(@Header(Exchange.REDELIVERY_COUNTER) Integer counter, @Body String body, @ExchangeException Exception causedBy) { // NOTE: counter is the redelivery attempt, will start from 1 invoked.incrementAndGet(); // we can of course do what ever we want to determine the result but this is a unit test so we end after 3 attempts return counter < 3; }
/** * Use this method to compute dynamic where we should route next. * * @param body the message body * @param headers the message headers where we can store state between invocations * @param previous the previous slip * @return endpoints to go, or <tt>null</tt> to indicate the end */ public String slip(String body, @Headers Map<String, Object> headers, @Header(Exchange.SLIP_ENDPOINT) String previous) { bodies.add(body); if (previous != null) { previouses.add(previous); } // get the state from the message headers and keep track how many times // we have been invoked int invoked = 0; Object current = headers.get("invoked"); if (current != null) { invoked = Integer.valueOf(current.toString()); } invoked++; // and store the state back on the headers headers.put("invoked", invoked); if (invoked == 1) { return "mock:a"; } else if (invoked == 2) { return "mock:b,mock:c"; } else if (invoked == 3) { return "direct:foo"; } else if (invoked == 4) { return "mock:result"; } // no more so return null return null; }
public boolean retry(@Header(Exchange.REDELIVERY_COUNTER) Integer counter, @Body String body, @ExchangeException Exception causedBy) { // NOTE: counter is the redelivery attempt, will start from 1 invoked++; assertEquals("Hello World", body); assertTrue(causedBy instanceof MyFunctionalException); // we can of course do what ever we want to determine the result but this is a unit test so we end after 3 attempts return counter < 3; }
/** * Use this method to compute dynamic where we should route next. * * @param body the message body * @param previous the previous slip * @return endpoints to go, or <tt>null</tt> to indicate the end */ public String slip(String body, @Header(Exchange.SLIP_ENDPOINT) String previous) { if (previous == null) { return "mock:a"; } else if ("mock://a".equals(previous)) { return "mock:b"; } else if ("mock://b".equals(previous)) { return "mock:result"; } // no more so return null return null; }
@DynamicRouter public String route(@Header(Exchange.SLIP_ENDPOINT) String previous) { if (previous == null) { return target; } else { return null; } }
public void addDataBackIn(Exchange exchange, @Header("claimCheck") String claimCheck) { // query the data store using the claim check as the key and add the data // back into the message body exchange.getIn().setBody(dataStore.get(claimCheck)); // remove the message data from the data store dataStore.remove(claimCheck); // remove the claim check header exchange.getIn().removeHeader("claimCheck"); }
public void someMethod(String body, @Header("foo") String header, @ExchangeProperty("cheese") String cheese) throws ValidationException { assertEquals("old", cheese); if ("bar".equals(header)) { LOG.info("someMethod() called with valid header and body: " + body); } else { throw new ValidationException(null, "Invalid header foo: " + header); } }
public String slip(String body, @Header(Exchange.SLIP_ENDPOINT) String previous) { if (previous == null) { return "mock:a,mock:b"; } else if ("mock://b".equals(previous)) { return "mock:c"; } // no more so return null return null; }
public String route(String methodName, @Header(Exchange.SLIP_ENDPOINT) String previous) { if (previous != null && previous.startsWith("bean://myBean?method")) { // we get the result here and stop routing return null; } else { return "bean:myBean?method=" + methodName; } }
@Consume(uri = "activemq:queue:foo") public void doSomething(@Header("JMSReplyTo") Destination jmsReplyTo, @Body String body) throws Exception { assertEquals("Hello World", body); String endpointName = "activemq:" + jmsReplyTo.toString(); endpointName = endpointName.replaceAll("//", ":"); tempName = endpointName; latch.countDown(); template.sendBody(tempName, "Bye World"); }
@Consume(uri = "activemq:queue:foo") public void doSomething(@Header("JMSReplyTo") Destination jmsReplyTo, @Body String body) throws Exception { assertEquals("Hello World", body); String endpointName = "activemq:" + jmsReplyTo.toString(); template.sendBody(endpointName, "Bye World"); }
public String dynamicRoute(Exchange exchange, @Header(Exchange.SLIP_ENDPOINT) String previous) { if (previous == null) { return "file://target/outbox"; } else { //end slip return null; } }
public String hello(@Body String body, @Header("foo") String foo, @Headers Map<String, Object> headers) { String s = body.replaceFirst("Hello", "Bye"); if (!foo.equals("ABC")) { throw new IllegalArgumentException("Foo has not expected value ABC but " + foo); } headers.put("foo", 123); return s; }
public void addItem(@Header("sessionId") String sessionId, @Body CartDto dto) { LOG.info("addItem {} {}", sessionId, dto); Set<CartDto> dtos = content.get(sessionId); if (dtos == null) { dtos = new LinkedHashSet<>(); content.put(sessionId, dtos); } dtos.add(dto); }
public void removeItem(@Header("sessionId") String sessionId, @Header("itemId") String itemId) { LOG.info("removeItem {} {}", sessionId, itemId); Set<CartDto> dtos = content.get(sessionId); if (dtos != null) { dtos.remove(itemId); } }
public Set<CartDto> getItems(@Header("sessionId") String sessionId) { LOG.info("getItems {}", sessionId); Set<CartDto> answer = content.get(sessionId); if (answer == null) { answer = Collections.EMPTY_SET; } return answer; }
public String combine(@Header("ERP") String erp, @Header("CRM") String crm, @Header("SHIPPING") String shipping) { StringBuilder sb = new StringBuilder("Customer overview"); sb.append("\nERP: " + erp); sb.append("\nCRM: " + crm); sb.append("\nSHIPPING: " + shipping); return sb.toString(); }
public void insertAuditLog(String order, @Header("JMSRedelivered") boolean redelivery) throws Exception { // using old-school JdbcTemplate to perform a SQL operation from Java code with spring-jdbc JdbcTemplate jdbc = new JdbcTemplate(dataSource); String orderId = "" + ++counter; String orderValue = order; String orderRedelivery = "" + redelivery; jdbc.execute(String.format("insert into bookaudit (order_id, order_book, order_redelivery) values ('%s', '%s', '%s')", orderId, orderValue, orderRedelivery)); }
public Order getOrder(@Header("id") String id) { if ("123".equals(id)) { Order order = new Order(); order.setId(123); order.setAmount(1); order.setMotor("Honda"); return order; } else { return null; } }
public void sendMail(String body, @Header("to") String to) { // simulate fatal error if we refer to a special no if (to.equals("FATAL")) { throw new IllegalArgumentException("Simulated fatal error"); } // simulate CPU processing of the order by sleeping a bit try { Thread.sleep(1000); } catch (InterruptedException e) { // ignore } }
public PurchaseOrder lookup(@Header("id") String id) { LOG.info("Finding purchase order for id " + id); // just return a fixed response PurchaseOrder order = new PurchaseOrder(); order.setPrice(69.99); order.setAmount(1); order.setName("Camel in Action"); return order; }
/** * The method invoked by Dynamic Router EIP to compute where to go next. * <p/> * Notice this method has been annotated with @DynamicRouter which means Camel turns this method * invocation into a Dynamic Router EIP automatically. * * @param body the message body * @param previous the previous endpoint, is <tt>null</tt> on the first invocation * @return endpoint uri where to go, or <tt>null</tt> to indicate no more */ @DynamicRouter public String route(String body, @Header(Exchange.SLIP_ENDPOINT) String previous) { if (previous == null) { // 1st time return "mock://a"; } else if ("mock://a".equals(previous)) { // 2nd time - transform the message body using the simple language return "language://simple:Bye ${body}"; } else { // no more, so return null to indicate end of dynamic router return null; } }