Java 类org.apache.camel.Handler 实例源码

项目:logistimo-web-service    文件:EventProcessor.java   
@Handler
public void execute(EventData eventData) {
  try {
    EventGenerator eg = EventGeneratorFactory.getEventGenerator(eventData.domainId,
        eventData.objectType);
    if(eventData.eventId == IEvent.DELETED) {
      DomainConfig dc = DomainConfig.getInstance(eventData.domainId);
      eg.generateDeleteEvent(eg, eventData.eventObject, eventData.objectId, dc.getLocale(), dc.getTimezone(), eventData.params);
    } else {
      eg.generate(eventData.eventId, eventData.params, eventData.objectId,
          eventData.customOptions);
    }
  } catch (Exception e) {
    log.severe("Issue with submitted task {0} with error {1}", eventData, e.getMessage(), e);
    throw new RuntimeException(e);
  }
}
项目:iot-ocp    文件:MyHelper.java   
@Handler
public String enhanceMessage( String body,  Exchange exchange  ) {

    String[] topicParts = exchange.getIn().getHeader("CamelMQTTSubscribeTopic", String.class).split(TOPIC_SEPARTOR);

    if(topicParts.length != 4) {
        throw new IllegalArgumentException("Invalid number of topic components. Expected " + TOPIC_PART_SIZE + ". Was " + topicParts.length);
    }

    StringBuilder sb = new StringBuilder();
    sb.append(body);
    sb.append(COMMA);
    sb.append(topicParts[1]);
    sb.append(COMMA);
    sb.append(topicParts[2]);
    sb.append(COMMA);
    sb.append(topicParts[3]);

    return sb.toString();
}
项目:ml-camel-client    文件:CsvProcessor.java   
@Handler
public void processCsv(Exchange exchange) {
    // We assume Camel CSV is used beforehand to set the body to a List<List<String>>
    @SuppressWarnings("unchecked")
    List<List<String>> list = (List<List<String>>) exchange.getIn().getBody();

    List<String> tokens = list.get(0);

    // Build up a model for Velocity to use
    Map<String, Object> model = new HashMap<String, Object>();

    String[] nameParts = tokens.get(0).split(" ");
    model.put("firstName", nameParts[0]);
    model.put("lastName", nameParts[1]);
    model.put("birthDate", tokens.get(1));

    exchange.getIn().setBody(model);

    // Set the header required by ml-xcc for ingestion
    exchange.getIn().setHeader("MlXccUri", tokens.get(0) + ".xml");
}
项目:soluvas-scrape    文件:Fetcher.java   
@Handler
public FetchData fetch(ScrapeTemplate template,
                  Map<String, Object> actualParams) {
    LowerEnumSerializer.LOWER = false;
    final String uri = template.getUri();
    log.info("Fetching {} {} {} ...", template.getProtocol(), template.getProtocolVersion(),
            template.getUri());
    try {
        // FIXME: Use Retryer (with limit) when: Caused by: java.net.SocketException: Connection reset
        // at java.net.SocketInputStream.read(SocketInputStream.java:209)

        switch (template.getProtocol()) {
            case JSONRPC:
                return fetchJsonRpc(uri, template, actualParams);
            case HTTP:
                throw new UnsupportedOperationException("no HTTP support yet");
            default:
                throw new UnsupportedOperationException("Unsupported protocol: " + template.getProtocol());
        }
    } catch (Exception e) {
        throw new ScrapeException(e, "Cannot fetch %s", uri);
    }
}
项目:further-open-core    文件:DataSourceMock.java   
/**
 * Return a {@link DsMetaData} response.
 * 
 * @param inputString
 *            input message body
 * @return meta data XML entity instance
 */
@Handler
@InOnly
public DsMetaData getDsMetaData(final String inputString)
{
    if (log.isDebugEnabled())
    {
        log.debug(getDataSourcePrefix() + "getDsMetaData()");
        // " inputString "
        // + inputString);
    }

    // For test assertion simplicity, the name field below does not depend on
    // the input string. Only the description field does.
    return new DsMetaData(name, name + ": " + inputString);
}
项目:secure-data-service    文件:FileEntryLatch.java   
@Handler
public boolean lastFileProcessed(Exchange exchange) throws Exception {
    FileEntryWorkNote workNote = exchange.getIn().getBody(FileEntryWorkNote.class);

    String batchJobId = workNote.getBatchJobId();
    TenantContext.setJobId(batchJobId);

    if (batchJobDAO.updateFileEntryLatch(workNote.getBatchJobId(), workNote.getFileEntry().getFileName())) {

        RangedWorkNote wn = RangedWorkNote.createSimpleWorkNote(batchJobId);
        exchange.getIn().setBody(wn, RangedWorkNote.class);
        return true;

    }

    return false;
}
项目:secure-data-service    文件:CommandProcessor.java   
@Handler
public void processCommand(Exchange exch) throws Exception {
    String command = exch.getIn().getBody().toString();
    LOG.info("Received: " + command);
    String[] chunks = command.split("\\|");

    if (JOB_COMPLETED.equals(chunks[0])) {

        LOG.info("Clearing cache at job completion.");


        dumpAspectTrackers(chunks);

    } else {
        LOG.error("Unsupported command");
    }
}
项目:camel-twitter-stream    文件:RetweetService.java   
@Handler
public List<String> getRetweetsWithScreenNames(@Header("statusId") Long statusId)
        throws TwitterException {
    return twitter.getRetweets(statusId).stream()
            .map(tweet -> tweet.getUser().getScreenName())
            .collect(Collectors.toList());
}
项目:syndesis    文件:__extension-name__Extension.java   
@Handler
public void log(@Body Object body){
    if(trace) {
        LOGGER.trace("Body is: {}",body);
    } else {
        LOGGER.info("Body is: {}",body);
    }
}
项目:logistimo-web-service    文件:JMSTaskProcessor.java   
@Handler
public void execute(TaskOptions taskOptions) {
  jmsMeter.mark();
  log.info("Submitting task with parameter{0}", taskOptions);
  //localQueue.add(taskOptions);
  Task simpleTask = new SimpleTask(taskOptions);
  try {
    ((Runnable) simpleTask).run();
  } catch (Exception e) {
    log.severe("Issue with submitted task {0} with error {1}", taskOptions, e.getMessage(), e);
    throw e;
  }
}
项目:logistimo-web-service    文件:AssetAlarmsMessagingProcessor.java   
@Handler
public void execute(AssetStatusRequest assetStatusRequest) throws ServiceException {

  jmsMeter.mark();

  List<AssetStatusModel> assetStatusModelList = assetStatusRequest.data;
  if (assetStatusModelList != null && !assetStatusModelList.isEmpty()) {
    AssetManagementService assetManagementService = Services
        .getService(AssetManagementServiceImpl.class);
    assetManagementService
        .updateAssetStatus(build(assetStatusModelList, assetManagementService));

  }

}
项目:boteco    文件:StatusRssProcessor.java   
@Handler
public void process(@XPath("//title") String title,
                    @XPath("//description") String description,
                    @XPath("//pubDate") String pubDate,
                    @XPath("//link") String link) {
  ZonedDateTime published = ZonedDateTime.parse(pubDate, DateTimeFormatter.RFC_1123_DATE_TIME);
  if (ChronoUnit.MINUTES.between(published,
      ZonedDateTime.now()) <= threshold) {
    bus.broadcast(parser.parse(description, title, link))
        .as("status.redhat");
  }
}
项目:flowable-engine    文件:ThrowBpmnExceptionBean.java   
@Handler
public void throwNonBpmnException() throws Exception {
    LOGGER.debug("throwing non bpmn bug");

    switch (getExceptionType()) {
    case NO_EXCEPTION:
        break;
    case NON_BPMN_EXCEPTION:
        throw new Exception("arbitrary non bpmn exception");
    case BPMN_EXCEPTION:
        throw new BpmnError("testError");
    }
}
项目:flowable-engine    文件:ThrowBpmnExceptionBean.java   
@Handler
public void throwNonBpmnException() throws Exception {
    LOGGER.debug("throwing non bpmn bug");

    switch (getExceptionType()) {
    case NO_EXCEPTION:
        break;
    case NON_BPMN_EXCEPTION:
        throw new Exception("arbitrary non bpmn exception");
    case BPMN_EXCEPTION:
        throw new BpmnError("testError");
    }
}
项目:Camel    文件:BeanWithXPathInjectionUsingHeaderValueTest.java   
@Handler
public void handler(@XPath("//response/text()") String response,
                    @XPath(headerName = "invoiceDetails", value = "//invoice/person/name/text()") String userName,
                    @XPath(headerName = "invoiceDetails", value = "//invoice/person/date", resultType = String.class) String date) {
    this.response = response;
    this.userName = userName;
    this.date = date;
}
项目:Camel    文件:JmsPollingConsumerTest.java   
@Handler
public String consume() {
    StringBuilder result = new StringBuilder();

    Exchange exchange;
    while ((exchange = consumer.receive("activemq:queue", 2000)) != null) {
        result.append(exchange.getIn().getBody(String.class));
    }

    return result.toString();

}
项目:Camel    文件:JaxbErrorLogTest.java   
@Handler
public void handle(@Body CannotMarshal body) {
    if (body.getMessageNo() == 2) {
        // fail on second message
        throw new RuntimeException("Kaboom");
    }
}
项目:Camel    文件:BeanWithXQueryInjectionUsingHeaderValueTest.java   
@Handler
public void handler(@XQuery("/response") String response,
                    @XQuery(headerName = "invoiceDetails", value = "/invoice/person/name") String userName,
                    @XQuery(headerName = "invoiceDetails", value = "/invoice/person/date") String date) {
    this.response = response;
    this.userName = userName;
    this.date = date;
}
项目:camelinaction2    文件:BookOrderExample.java   
@Handler
public void orderSomeBooks() throws Exception {
    log.info("-------------------------------------------------------------------------------------------------------------------------");
    log.info("Make sure to have Postgres database up and running, as configured in the src/test/resources/META-INF/persistence.xml file");
    log.info("-------------------------------------------------------------------------------------------------------------------------");

    BookOrder order = new BookOrder();
    order.setAmount(1);
    order.setTitle("Camel in Action 2nd ed");

    template.sendBody("jpa:camelinaction.BookOrder", order);

    Thread.sleep(5000);
    log.info("... sleeping for 5 seconds and then stopping the route");

    // now stop the route
    context.stopRoute("books");

    // insert a new order which will sit in the database
    BookOrder order2 = new BookOrder();
    order2.setAmount(3);
    order2.setTitle("ActiveMQ in Action");

    template.sendBody("jpa:camelinaction.BookOrder", order2);

    log.info("-------------------------------------------------------------------------------------------------------------------------");
    log.info("Now we want to provoke a connection error, so stop the postgres database - and then press ENTER to continue!");
    log.info("-------------------------------------------------------------------------------------------------------------------------");

    System.console().readLine();

    context.startRoute("books");
    log.info("... starting route which should indicate some errors, which the bridge error handler should catch and handle");
    log.info("Notice that the consumer will backoff and not poll so fast, instead of every second, it now runs x10 sec.");
    log.info("Press CTRL+C to exit this application!");
}
项目:sample_spring-boot-camel-mongo-jdk8    文件:ArchiveHandler.java   
@Handler
public void archive() {
  final List<Person> persons = personRepository.findAll();
  if ((persons == null) || persons.isEmpty()) {
    LOG.info("Nothing to backup");
    return;
  }

  LOG.info("Backup: {}", Archive.with(persons));
}
项目:cleverbus    文件:SyncHelloRoute.java   
@Handler
public SyncHelloResponse composeGreeting(@Body SyncHelloRequest req) {
    Assert.notNull(req, "req must not be null");

    String greeting = "Hello " + req.getName();

    SyncHelloResponse res = new SyncHelloResponse();
    res.setGreeting(greeting);
    return res;
}
项目:cleverbus    文件:AsyncHelloRoute.java   
@Handler
public void printGreeting(@Body AsyncHelloRequest req) {
    Assert.notNull(req, "req must not be null");

    String greeting = "Hello " + req.getName();

    Log.debug("Greeting: " + greeting);
}
项目:cleverbus    文件:AbstractBasicRoute.java   
/**
 * Handles specified exception.
 *
 * @param ex the thrown exception
 * @param asynch {@code true} if it's asynchronous message processing otherwise synchronous processing
 * @return next route URI
 */
@Handler
public String exceptionHandling(Exception ex, @Header(AsynchConstants.ASYNCH_MSG_HEADER) Boolean asynch) {
    Assert.notNull(ex, "the ex must not be null");
    Assert.isTrue(BooleanUtils.isTrue(asynch), "it must be asynchronous message");

    String nextUri;

    if (ExceptionUtils.indexOfThrowable(ex, ValidationException.class) >= 0
            || ExceptionUtils.indexOfThrowable(ex, ValidationIntegrationException.class) >= 0) {
        Log.warn("Validation error, no further processing - " + ex.getMessage());
        nextUri = AsynchConstants.URI_ERROR_FATAL;

    } else if (ExceptionUtils.indexOfThrowable(ex, BusinessException.class) >= 0) {
        Log.warn("Business exception, no further processing.");
        nextUri = AsynchConstants.URI_ERROR_FATAL;

    } else if (ExceptionUtils.indexOfThrowable(ex, NoDataFoundException.class) >= 0) {
        Log.warn("No data found, no further processing.");
        nextUri = AsynchConstants.URI_ERROR_FATAL;

    } else if (ExceptionUtils.indexOfThrowable(ex, MultipleDataFoundException.class) >= 0) {
        Log.warn("Multiple data found, no further processing.");
        nextUri = AsynchConstants.URI_ERROR_FATAL;

    } else if (ExceptionUtils.indexOfThrowable(ex, LockFailureException.class) >= 0) {
        Log.warn("Locking exception.");
        nextUri = AsynchConstants.URI_ERROR_HANDLING;

    } else {
        Log.error("Unspecified exception - " + ex.getClass().getSimpleName() + " (" + ex.getMessage() + ")");
        nextUri = AsynchConstants.URI_ERROR_HANDLING;
    }

    return nextUri;
}
项目:cleverbus    文件:ProcessArchivingDataRoute.java   
/**
 * Checks if ESB goes down or not.
 *
 * @return {@code true} if ESB is in "stopping mode" otherwise {@code false}
 */
@Handler
public boolean isNotInStoppingMode() {
    StopService stopService = getApplicationContext().getBean(StopService.class);

    Log.debug("ESB stopping mode is switched on: " + stopService.isStopping());

    return !stopService.isStopping();
}
项目:cleverbus    文件:PartlyFailedMessagesPoolRoute.java   
/**
 * Checks if ESB goes down or not.
 *
 * @return {@code true} if ESB is in "stopping mode" otherwise {@code false}
 */
@Handler
public boolean isNotInStoppingMode() {
    StopService stopService = getApplicationContext().getBean(StopService.class);

    Log.debug("ESB stopping mode is switched on: " + stopService.isStopping());

    return !stopService.isStopping();
}
项目:cleverbus    文件:AsynchMessageRoute.java   
/**
 * Checks if current message wasn't converted to other state or is being processed more times.
 * It can happen when message is long time in queue that repairing process converts message back
 * to PARTLY_FAILED state and evenly message can start with duplicate processing.
 *
 * @param msg the message
 * @return {@code true} when message is obsolete otherwise {@code false}
 */
@Handler
public boolean isMessageObsolete(@Body Message msg) {
    Assert.notNull(msg, "the msg must not be null");
    MessageService messageService = getBean(MessageService.class);

    Message dbMsg = messageService.findMessageById(msg.getMsgId());

    Assert.notNull(dbMsg, "there must be message with ID=" + msg.getMsgId());

    return dbMsg.getState() != MsgStateEnum.PROCESSING
            && dbMsg.getLastUpdateTimestamp().before(msg.getLastUpdateTimestamp());
}
项目:cleverbus    文件:AsynchMessageRoute.java   
@Handler
public void logStartProcessing(@Body Message msg,
        @Nullable @Header(AsynchConstants.MSG_QUEUE_INSERT_HEADER) Long msgInsertTime) {

    Log.debug("Starts processing of the message {}, waited in queue for {} ms", msg.toHumanString(),
            msgInsertTime != null ? (System.currentTimeMillis() - msgInsertTime) : "-");
}
项目:cleverbus    文件:AsynchMessageRoute.java   
/**
 * Sets {@link AsynchConstants#OBJECT_ID_HEADER} and {@link AsynchConstants#ENTITY_TYPE_HEADER}
 * headers if there are available corresponding values in message.
 *
 * @param msg the message
 * @param headers the headers
 */
@Handler
public void setEntityInfo(@Body Message msg, @Headers Map<String, Object> headers) {
    Assert.notNull(msg, "the msg must not be null");

    if (msg.getObjectId() != null) {
        headers.put(OBJECT_ID_HEADER, msg.getObjectId());
    }
    if (msg.getEntityType() != null) {
        headers.put(ENTITY_TYPE_HEADER, msg.getEntityType());
    }
}
项目:cleverbus    文件:AsynchMessageRoute.java   
/**
 * Returns {@code true} if failed count exceeds limit for failing.
 *
 * @param msg the message
 * @return {@code true} when limit was exceeded, otherwise {@code false}
 */
@Handler
public boolean checkFailedLimit(@Header(MSG_HEADER) Message msg) {
    Assert.notNull(msg, "the msg must not be null");

    return msg.getFailedCount() >= countPartlyFailsBeforeFailed;
}
项目:cleverbus    文件:AsynchMessageRoute.java   
/**
  * Sends notification mail to admin(s).
  */
 @Handler
 public void sendMailToAdmin(@Header(MSG_HEADER) Message msg) {
     Assert.notNull(msg, "the msg must not be null");

     EmailService emailService = lookup(EmailService.BEAN, EmailService.class);

     String body = "The following message " + msg.toHumanString() + " FAILED.\n\nBody:\n" + msg.getEnvelope();

     emailService.sendEmailToAdmins("Notification about FAILED message", body);
}
项目:cleverbus    文件:ContextCallRoute.java   
/**
 * Makes call.
 *
 * @param callId Call ID for getting call parameters from {@link ContextCallRegistry}
 */
@Handler
public void makeCall(@Header(CALL_ID_HEADER) String callId) {
    Assert.hasText(callId, "the callId must not be empty");

    // get params
    ContextCallParams params = callRegistry.getParams(callId);

    Object res = ReflectionCallUtils.invokeMethod(params, getApplicationContext());

    // save response
    callRegistry.addResponse(callId, res);

    Log.debug("Response of the call ID '" + callId + "' was saved: " + res);
}
项目:cleverbus    文件:DirectCallWsRoute.java   
/**
 * Sets request header if available.
 *
 * @param callId Call ID for getting call parameters from {@link DirectCallRegistry}
 * @param exchange Camel exchange
 */
@Handler
public void setHeader(@Header(CALL_ID_HEADER) String callId, Exchange exchange) {
    Assert.hasText(callId, "the callId must not be empty");

    DirectCallParams params = callRegistry.getParams(callId);

    if (params.getHeader() != null) {
        Log.debug("Direct WS call: header=" + params.getHeader());

        exchange.getIn().setHeader(SpringWebserviceConstants.SPRING_WS_SOAP_HEADER, params.getHeader());
    }
}
项目:cleverbus    文件:DirectCallWsRoute.java   
/**
 * Gets request to external system.
 *
 * @param callId Call ID for getting call parameters from {@link DirectCallRegistry}
 * @return request
 */
@Handler
public Object getRequest(@Header(CALL_ID_HEADER) String callId) {
    Assert.hasText(callId, "the callId must not be empty");

    DirectCallParams params = callRegistry.getParams(callId);

    Log.debug("Direct WS call: uri= " + params.getUri() + ",\nsenderRef= " + params.getSenderRef()
            + ",\nsoapAction= " + params.getSoapAction() + ",\nbody: " + params.getBody());

    return params.getBody();
}
项目:cleverbus    文件:DirectCallWsRoute.java   
/**
 * Gets URI for calling external system.
 *
 * @param callId Call ID for getting call parameters from {@link DirectCallRegistry}
 * @return WS URI
 */
@Handler
public String getWsUri(@Header(CALL_ID_HEADER) String callId) {
    Assert.hasText(callId, "the callId must not be empty");

    DirectCallParams params = callRegistry.getParams(callId);

    return getOutWsUri(params.getUri(), params.getSenderRef(), params.getSoapAction());
}
项目:servicemix    文件:ActivitiRouteBuilder.java   
@Handler
public Map getProcessVariables(@Body String body,
                               @Header(Exchange.FILE_NAME) String filename,
                               @Simple("${date:now:yyyy-MM-dd kk:mm:ss}") String timestamp) {
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("message", body);
    variables.put("orderid", filename);
    variables.put("timestamp", timestamp);
    return variables;
}
项目:further-open-core    文件:DataSourceMock.java   
/**
 * Process a string body.
 * 
 * @param inputString
 *            input message body
 * @return processed input string. Contains this data source's details for easy test
 *         assertions
 */
@Handler
@InOnly
public String process(final String inputString)
{
    if (log.isTraceEnabled())
    {
        log.trace(getDataSourcePrefix() + "process() " + inputString);
    }
    return name + ": " + inputString;
}
项目:further-open-core    文件:DataSourceMock.java   
/**
 * @param inputString
 * @return processed input string
 */
@Handler
public QueryContext processQueryContext(final @Body QueryContext parentContext)
{
    Validate.notNull(parentContext);
    if (log.isDebugEnabled())
    {
        log.debug(getDataSourcePrefix() + "processQueryContext() " + parentContext);
        log.debug("QC Data Source ID: " + parentContext.getDataSourceId());
        log.debug("Search criteria: " + parentContext.getQuery());
    }

    // This section mocks a data source's creation of a new child context, queuing it
    // and setting its parent.
    QueryContextEntity childContext = QueryContextEntity
            .newInstanceWithExecutionId();
    childContext.setDataSourceId(name);
    childContext.setParent(QueryContextEntity.newCopy(parentContext));
    // Assuming the search query's first criterion is of type [EQ,
    // desiredNumRecordsBackFromThisDataSource, value]. Set value (parameter #2
    // (0-based index) on the parameter list)as our output records.
    //
    // If there are two criteria, using the second criterion's value instead.
    final Long numRecords = getNumRecordsFromQuery(parentContext);

    childContext.setNumRecords(numRecords.longValue());
    childContext = (QueryContextEntity) contextService.queue(childContext);
    childContext.start();
    childContext.finish();

    final long sleepValue = getSleepValue();
    if (log.isDebugEnabled())
    {
        log.debug("Sleeping for " + sleepValue + " miliseconds");
    }
    IoUtil.sleep(sleepValue);

    return QueryContextToImpl.newCopy(childContext);
}
项目:further-open-core    文件:CamelLifeCycleController.java   
/**
 * @param commandTypeLabel
 * @param input
 * @return
 * @see edu.utah.further.ds.api.lifecycle.controller.LifeCycleController#triggerCommand(java.lang.String,
 *      java.io.Serializable)
 */
@Override
// Optional here, yet a useful annotation
@Handler
public Object triggerCommand(
        @Header(MessageHeader.COMMAND_TYPE_NAME) final String commandTypeLabel,
        @Body final Serializable input)
{
    return triggerCommandHelper(commandTypeLabel, input);
}
项目:gytheio    文件:HeartbeatMonitorImpl.java   
@Override
@Handler
public void onReceive(Object message)
{
    if (!(message instanceof Heartbeat))
    {
       logger.warn("Heartbeat message expected but received: " + message.toString());
       return;
    }
    heartbeatDao.record((Heartbeat) message);
}
项目:syndesis    文件:FunctionTest.java   
@Handler
public String configure(@Body String body, @Header("ExtensionHeader") String header) {
    return String.join("-", body, header, message);
}