Java 类org.apache.camel.builder.LoggingErrorHandlerBuilder 实例源码

项目:lumen    文件:JournalBatteryRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
        final String avatarId = "nao1";
//        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + AvatarChannel.DATA_BATTERY.key(avatarId) + "&routingKey=" + AvatarChannel.DATA_BATTERY.key(avatarId))
//                .sample(1, TimeUnit.SECONDS)
//                .to("log:IN." + AvatarChannel.DATA_BATTERY.key(avatarId) + "?showHeaders=true&showAll=true&multiline=true")
//                .process(it -> {
//                    final JsonNode inBodyJson = toJson.getMapper().readTree(it.getIn().getBody(byte[].class));
//                    final BatteryState batteryState = toJson.getMapper().convertValue(inBodyJson, BatteryState.class);
//                    final Node nodeResult = new TransactionTemplate(txMgr).execute(tx -> {
//                        final DateTime now = new DateTime();
//                        final Map<String, Object> props = new HashMap<String, Object>();
//                        final Node node = neo4j.createNode(props, ImmutableSet.of("JournalBatteryState"));
//                        log.debug("Created JournalBatteryState {} from {}", node, props);
//                        return node;
//                    });
//                    it.getOut().setBody(nodeResult.getId());
//                })
//                .bean(toJson)
//                .to("log:OUT." + AvatarChannel.DATA_BATTERY.key(avatarId) + "?showAll=true&multiline=true");
    }
项目:lumen    文件:ServicesRouter.java   
@Override
public void configure() throws Exception {
    errorHandler(new LoggingErrorHandlerBuilder(log));
    from("direct:" + LumenChannel.PERSISTENCE_FACT.key())
            .process(exchange -> {
                final BeanInvocation invocation = exchange.getIn().getBody(BeanInvocation.class);
                final FactRequest factRequest = new FactRequest();
                factRequest.setOperation(FactServiceOperation.valueOf(invocation.getMethod().getName()));
                log.info("Invoking {} {}", invocation.getMethod(), invocation.getArgs());
                for (int i = 0; i < invocation.getArgs().length; i++) {
                    final String simpleExpr = invocation.getMethod().getParameters()[i].getAnnotation(Simple.class).value();
                    final String paramName = StringUtils.substringAfter(simpleExpr, "body.");
                    PropertyUtils.setProperty(factRequest, paramName, invocation.getArgs()[i]);
                }
                exchange.getIn().setBody(factRequest);
                exchange.setPattern(ExchangePattern.InOut);
                //exchange.getIn().setHeader(RabbitMQConstants.REPLY_TO, );
            })
            .bean(toJson)
            .to("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&skipQueueDeclare=true&routingKey=" +
                    LumenChannel.PERSISTENCE_FACT.key())
            .to("log:REPLY." + LumenChannel.PERSISTENCE_FACT.key());
}
项目:avatar-nao    文件:PoseRouter.java   
@Override
public void configure() throws Exception {
    onException(Exception.class).bean(asError).bean(toJson).handled(true);
    errorHandler(new LoggingErrorHandlerBuilder(log));
    final int period = 1000;
    log.info("robotPose capture timer with period = {}ms", period);
    for (final String avatarId : naoConfig.getControllerAvatarIds()) {
        final NaoController nao = naoConfig.get(avatarId);
        final ALRobotPoseProxy robotPoseProxy = nao.getRobotPose();
        from("timer:robotPose?period=" + period)
                .process(exchange -> {
                    final RobotPoseState robotPoseState = new RobotPoseState();
                    for (int i = 0; i < robotPoseProxy.getPoseNames().getSize(); i++) {
                        robotPoseState.getPoseNames().add(robotPoseProxy.getPoseNames().getElement(i).toString());
                    }
                    robotPoseState.setActualPoseName(robotPoseProxy.getActualPoseAndTime().getElement(0).toString());
                    robotPoseState.setActualPoseTime(robotPoseProxy.getActualPoseAndTime().getElement(1).toFloat());
                    exchange.getIn().setBody(robotPoseState);
                })
                .bean(toJson)
                .to("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&skipQueueDeclare=true&routingKey=avatar." + avatarId + ".data.robotpose")
                .to("log:" + PoseRouter.class.getName() + "." + avatarId + "?level=TRACE&showAll=true&multiline=true");
    }
}
项目:avatar-nao    文件:BatteryRouter.java   
@Override
public void configure() throws Exception {
    onException(Exception.class).bean(asError).bean(toJson).handled(true);
    errorHandler(new LoggingErrorHandlerBuilder(log));
    final int period = 1000;
    log.info("Battery capture timer with period = {}ms", period);
    for (final String avatarId : naoConfig.getControllerAvatarIds()) {
        final NaoController nao = naoConfig.get(avatarId);
        final ALBatteryProxy batteryProxy = nao.getBattery();
        from("timer:battery?period=" + period)
                .process(exchange -> {
                    final BatteryState batteryState = new BatteryState();
                    batteryState.setPercentage((double) batteryProxy.getBatteryCharge());
                    batteryState.setDateCreated(new DateTime());
                    exchange.getIn().setBody(batteryState);
                })
                .bean(toJson)
                .to("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&skipQueueDeclare=true&autoDelete=false&routingKey=avatar." + avatarId + ".data.battery")
                .to("log:" + BatteryRouter.class.getName() + "." + avatarId + "?level=TRACE&showAll=true&multiline=true");
    }
}
项目:avatar-nao    文件:SonarRouter.java   
@Override
public void configure() throws Exception {
    onException(Exception.class).bean(asError).bean(toJson).handled(true);
    errorHandler(new LoggingErrorHandlerBuilder(log));
    final int period = 1000;
    log.info("Sonar capture timer with period = {}ms", period);
    for (final String avatarId : naoConfig.getControllerAvatarIds()) {
        final NaoController nao = naoConfig.get(avatarId);
        final ALSonarProxy sonarProxy = nao.getSonar();
        from("timer:sonar?period=" + period)
                .process(exchange -> {
                    final SonarState sonarState = new SonarState();
                    // sonarState. setPercentage((double) batteryProxy.getBatteryCharge());
                    sonarState.setLeftSensor((double) sonarProxy.getCurrentPrecision());
                    sonarState.setRightSensor((double) sonarProxy.getCurrentPrecision());
                    //  sonarState.setDateCreated(new DateTime());
                    sonarState.setDateCreated(new DateTime());
                    exchange.getIn().setBody(sonarState);
                })
                .bean(toJson)
                .to("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&skipQueueDeclare=true&autoDelete=false&routingKey=avatar." + avatarId + ".data.sonar")
                .to("log:" + SonarRouter.class.getName() + "." + avatarId + "?level=TRACE&showAll=true&multiline=true");
    }
}
项目:switchyard    文件:CamelExchangeBusTest.java   
@Test @Ignore
public void testCustomErrorHandler() throws InterruptedException {
    final AtomicBoolean fired = new AtomicBoolean();
    _camelContext.getWritebleRegistry().put("custom error handler", new LoggingErrorHandlerBuilder() {
        @Override
        public Processor createErrorHandler(RouteContext routeContext, final Processor processor) {
            fired.compareAndSet(false, true);
            return super.createErrorHandler(routeContext, processor);
        }
    });
    ServiceReference ref = registerInOutService("inOut", new RuntimeErrorInHandler());
    Exchange exchange = sendMessage(ref, TEST_CONTENT);

    assertTrue(fired.get());
    assertCause("Runtime error", exchange);
}
项目:camel-cdi    文件:XmlErrorHandlerFactoryBean.java   
@Override
public ErrorHandlerBuilder create(CreationalContext<ErrorHandlerBuilder> creationalContext) {
    try {
        ErrorHandlerBuilder builder = handler.getType().getTypeAsClass().newInstance();

        switch (handler.getType()) {
            case DefaultErrorHandler:
            case DeadLetterChannel:
                setProperties((DefaultErrorHandlerBuilder) builder);
                break;
            case LoggingErrorHandler:
                setProperties((LoggingErrorHandlerBuilder) builder);
                break;
            case NoErrorHandler:
                // No configuration required
                break;
            case TransactionErrorHandler:
                break;
        }

        return builder;
    } catch (Exception cause) {
        throw new CreationException("Error while creating instance for " + this, cause);
    }
}
项目:Camel    文件:XmlErrorHandlerFactoryBean.java   
@Override
public ErrorHandlerBuilder create(CreationalContext<ErrorHandlerBuilder> creationalContext) {
    try {
        ErrorHandlerBuilder builder = handler.getType().getTypeAsClass().newInstance();

        switch (handler.getType()) {
        case DefaultErrorHandler:
        case DeadLetterChannel:
            setProperties((DefaultErrorHandlerBuilder) builder);
            break;
        case LoggingErrorHandler:
            setProperties((LoggingErrorHandlerBuilder) builder);
            break;
        case NoErrorHandler:
            // No configuration required
            break;
        case TransactionErrorHandler:
            break;
        default:
            break;
        }

        return builder;
    } catch (Exception cause) {
        throw new CreationException("Error while creating instance for " + this, cause);
    }
}
项目:lumen    文件:JointRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
//        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&durable=false&autoDelete=true&routingKey=avatar.nao1.data.joint")
//                .sample(1, TimeUnit.SECONDS)
//                .to("log:IN.avatar.nao1.data.joint?showHeaders=true&showAll=true&multiline=true")
//                .process(it -> {
//                            final JsonNode inBodyJson = toJson.getMapper().readTree(it.getIn().getBody(byte[].class));
//                            final JointSetLegacy jointSet = toJson.getMapper().convertValue(inBodyJson, JointSetLegacy.class);
//                            final List<Node> nodesResult = new TransactionTemplate(txMgr).execute(tx -> {
//                                final DateTime now = new DateTime();
//                                final List<Node> nodes = new ArrayList<>();
//                                for (String jointName : jointSet.getNames()) {
//                                    final Map<String, Object> props = new HashMap<String, Object>();
//                                    final Node node = neo4j.createNode(props, new ArrayList<String>(Arrays.asList("JournalJoint")));
//                                    nodes.add(node);
//                                }
//                                log.debug("Created {} JournalJoint(s) {} from {}", nodes, jointSet);
//                                return nodes;
//                            });
//                            it.getOut().setBody(nodesResult.stream().map(Node::getId).collect(Collectors.toList()));
//                        }
//                )
//                .bean(toJson)
//                .to("log:OUT.avatar.nao1.data.joint?showAll=true&multiline=true");
    }
项目:lumen    文件:TactileRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
        final String avatarId = "nao1";
//        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + AvatarChannel.DATA_TACTILE.key(avatarId) + "&routingKey=" + AvatarChannel.DATA_TACTILE.key(avatarId))
//                .sample(1, TimeUnit.SECONDS)
//                .to("log:IN." + AvatarChannel.DATA_TACTILE.key(avatarId) + "?showHeaders=true&showAll=true&multiline=true")
//                .process(it -> {
//                    final JsonNode inBodyJson = toJson.getMapper().readTree(it.getIn().getBody(byte[].class));
//                    final TactileSetLegacy tactileSet = toJson.getMapper().convertValue(inBodyJson, TactileSetLegacy.class);
//                    final List<Node> nodesResult = new TransactionTemplate(txMgr).execute(tx -> {
//                        final DateTime now = new DateTime();
//                        final List<Node> nodes = new ArrayList<>();
//                        for (String tactileName : tactileSet.getNames()) {
//                            final Map<String, Object> props = new HashMap<>();
//                            final Node node = neo4j.createNode(props, ImmutableSet.of("JournalTactile"));
//                            nodes.add(node);
//                        }
//                        log.debug("Created {} JournalTactile(s) {} from {}", nodes, tactileSet);
//                        return nodes;
//                    });
//                    it.getOut().setBody(nodesResult.stream().map(Node::getId).collect(Collectors.toList()));
//                })
//                .bean(toJson)
//                .to("log:OUT." + AvatarChannel.DATA_TACTILE.key(avatarId) + "?showAll=true&multiline=true");
    }
项目:lumen    文件:JournalSonarRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
        final String avatarId = "nao1";
//        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + AvatarChannel.DATA_SONAR.key(avatarId) + "&routingKey=" + AvatarChannel.DATA_SONAR.key(avatarId))
//                .sample(1, TimeUnit.SECONDS)
//                .to("log:IN." + AvatarChannel.DATA_SONAR.key(avatarId) + "?showHeaders=true&showAll=true&multiline=true")
//                .process(it -> {
//                    final JsonNode inBodyJson = toJson.getMapper().readTree(it.getIn().getBody(byte[].class));
//                    final SonarState sonarState = toJson.getMapper().convertValue(inBodyJson, SonarState.class);
//                    final Node nodeResult = new TransactionTemplate(txMgr).execute(tx -> {
//                        final DateTime now = new DateTime();
//                        final Map<String, Object> props = new HashMap<String, Object>();
//                        final Node node = neo4j.createNode(props, ImmutableSet.of("JournalSonarState"));
//                        log.debug("Created JournalSonarState {} from {}", node, props);
//                        return node;
//                    });
//                    it.getOut().setBody(nodeResult.getId());
//
////                    it.out.headers['rabbitmq.ROUTING_KEY'] = Preconditions.checkNotNull(it.in.headers['rabbitmq.REPLY_TO'],
////                            '"rabbitmq.REPLY_TO" header must be specified, found headers: %s', it.in.headers)
////                    it.out.headers['rabbitmq.EXCHANGE_NAME'] = ''
//                })
//                .bean(toJson)
//                .to("log:OUT." + AvatarChannel.DATA_SONAR.key(avatarId) + "?showAll=true&multiline=true");
    }
项目:lumen    文件:VisualCaptureRouter.java   
@Override
public void configure() throws Exception {
    onException(Exception.class).bean(asError).bean(toJson).handled(true);
    errorHandler(new LoggingErrorHandlerBuilder(log));
    final String avatarId = "nao1";
    from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + AvatarChannel.CAMERA_MAIN.key(avatarId) + "&routingKey=" + AvatarChannel.CAMERA_MAIN.key(avatarId))
            .process(exchange -> {
                final ImageObject imageObject = toJson.getMapper().readValue(
                        exchange.getIn().getBody(byte[].class), ImageObject.class);
                final DataUri dataUri = DataUri.parse(imageObject.getContentUrl(), StandardCharsets.UTF_8);
                cameraMain = dataUri.getData();
                cameraMainType = dataUri.getMime();
                log.debug("Got nao1.camera.main {} {} bytes", cameraMainType, cameraMain.length);
            });
}
项目:lumen    文件:DroolsRouter.java   
@Override
public void configure() throws Exception {
    onException(Exception.class).bean(asError).bean(toJson).handled(true);
    errorHandler(new LoggingErrorHandlerBuilder(log));
    from("seda:greetingReceived")
            .process(exchange -> {
                final GreetingReceived greetingReceived = exchange.getIn().getBody(GreetingReceived.class);
                kieSession.insert(greetingReceived);
                kieSession.fireAllRules();
            })
            .to("log:echo");
}
项目:lumen    文件:FacebookTimelineRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
        FluentIterable.from(agentRepo.findAll())
                .forEach(ag -> {
                    final String facebookFeed = UriComponentsBuilder.fromUriString("facebook://postStatusMessage?oAuthAppId={facebookAppId}&oAuthAppSecret={facebookAppSecret}&oAuthAccessToken={facebookAccessToken}")
                            .buildAndExpand(ag.getFacebookSys().getFacebookAppId(), ag.getFacebookSys().getFacebookAppSecret(), ag.getFacebookSys().getFacebookAccessToken()).toString();
                    final String twitterTimelineUser = UriComponentsBuilder.fromUriString("twitter://timeline/user?consumerKey={twitterApiKey}&consumerSecret={twitterApiSecret}&accessToken={twitterToken}&accessTokenSecret={twitterTokenSecret}")
                            .buildAndExpand(ag.getTwitterSys().getTwitterApiKey(), ag.getTwitterSys().getTwitterApiSecret(), ag.getTwitterSys().getTwitterToken(), ag.getTwitterSys().getTwitterTokenSecret()).toString();
                    from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + LumenChannel.FACEBOOK_TIMELINE_OUT.key(ag.getId()) + "&routingKey=" + LumenChannel.FACEBOOK_TIMELINE_OUT.key(ag.getId()))
                            .to("log:" + LumenChannel.FACEBOOK_TIMELINE_OUT.key(ag.getId()))
                            .process((Exchange it) -> {
                                final CommunicateAction communicateAction = toJson.getMapper().readValue((byte[]) it.getIn().getBody(), CommunicateAction.class);
                                it.getIn().setHeader("network.id", "facebook");
                                it.getIn().setHeader("CamelFacebook.message", communicateAction.getObject());
                                it.getIn().setBody(null);
//                                final StatusUpdate statusUpdate = toJson.mapper.readValue((byte[]) it.getIn().getBody(), StatusUpdate.class);
//                                switch (statusUpdate.getChannel().getThingId()) {
//                                    case "facebook":
//                                        it.getIn().setHeader("network.id", "facebook");
//                                        it.getIn().setHeader("CamelFacebook.message", statusUpdate.getMessage());
//                                        it.getIn().setBody(null);
//                                        break;
//                                    case "twitter":
//                                        it.getIn().setHeader("network.id", "twitter");
//                                        it.getIn().setBody(statusUpdate.getMessage());
//                                        break;
//                                }
                            }).choice()
                            .when(header("network.id").isEqualTo("facebook")).to(facebookFeed).to("log:" + LumenChannel.FACEBOOK_TIMELINE_OUT.key(ag.getId()) + "-postStatusMessage")
                            .when(header("network.id").isEqualTo("twitter")).to(twitterTimelineUser).to("log:twitter-timeline-user")
                            .otherwise().to("log:socmed-unknown");
                });
    }
项目:avatar-nao    文件:MotionRouter.java   
@Override
public void configure() throws Exception {
    onException(Exception.class).bean(asError).bean(toJson).handled(true);
    errorHandler(new LoggingErrorHandlerBuilder(log));
    final int period = 1000;
    log.info("Motion capture timer with period = {}ms", period);
    for (final String avatarId : naoConfig.getControllerAvatarIds()) {
        final NaoController nao = naoConfig.get(avatarId);
        final ALMotionProxy motionProxy = nao.getMotion();
        final String[] angleNames = motionProxy.getJointNames("Body");
        from("timer:motion?period=" + period)
                .process(exchange -> {
                    final MotionState motionState = new MotionState();
                    final float[] angles = motionProxy.getAngles(new Variant("Body"), true);
                    for (int i = 0; i < angles.length; i++) {
                        final JointState jointState = new JointState();
                        jointState.setName(angleNames[i]);
                        jointState.setAngle((double) angles[i]);
                        motionState.getAngles().add(jointState);
                    }

                    motionState.setDateCreated(new DateTime());
                    exchange.getIn().setBody(motionState);
                })
                .bean(toJson)
                .to("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&skipQueueDeclare=true&autoDelete=false&routingKey=avatar." + avatarId + ".data.motion")
                .to("log:" + MotionRouter.class.getName() + "." + avatarId + "?level=TRACE&showAll=true&multiline=true");
    }
}
项目:avatar-nao    文件:LedsRouter.java   
@Override
public void configure() throws Exception {
    onException(Exception.class).bean(asError).bean(toJson).handled(true);
    errorHandler(new LoggingErrorHandlerBuilder(log));
    for (final String avatarId : naoConfig.getControllerAvatarIds()) {
        final NaoController nao = naoConfig.get(avatarId);
        final ALLedsProxy ledsProxy = nao.getLeds();
        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + AvatarChannel.LEDS.key(avatarId) + "&routingKey=" + AvatarChannel.LEDS.key(avatarId))
                .to("log:IN." + AvatarChannel.LEDS.key(avatarId) + "?showHeaders=true&showAll=true&multiline=true")
                .process(exchange -> {
                    final LumenThing thing = toJson.getMapper().readValue(exchange.getIn().getBody(byte[].class), LumenThing.class);
                    log.info("Got LED command: {}", thing);
                    if (thing instanceof LedOperation) {
                        final LedOperation ledOp = (LedOperation) thing;
                        final String ledName = ledOp.getNames().stream().findFirst().orElse("FaceLeds");
                        if (ledOp.getKind() == LedOperationKind.OFF) {
                            ledsProxy.off(ledName);
                        } else if (ledOp.getKind() == LedOperationKind.ON) {
                            ledsProxy.on(ledName);
                        } else if (ledOp.getKind() == LedOperationKind.FADE) {
                            //final Color rgb = Color.web(ledOp.getColor());
                            ledsProxy.fade(ledName, ledOp.getIntensity().floatValue(), ledOp.getDuration().floatValue());
                        } else if (ledOp.getKind() == LedOperationKind.FADE_RGB) {
                            final Color rgb = Color.web(ledOp.getColor());
                            final int rgbi = ((int) (rgb.getRed() * 0xff) << 16) | ((int) (rgb.getGreen() * 0xff) << 8) | (int) (rgb.getBlue() * 0xff);
                            ledsProxy.fadeRGB(ledName, rgbi, ledOp.getDuration().floatValue());
                        } else if (ledOp.getKind() == LedOperationKind.RANDOM_EYES) {
                            ledsProxy.randomEyes(ledOp.getDuration().floatValue());
                        } else if (ledOp.getKind() == LedOperationKind.RASTA) {
                            ledsProxy.rasta(ledOp.getDuration().floatValue());
                        }
                        exchange.getIn().setBody(new Status());
                    } else {
                        exchange.getOut().setBody(null);
                    }
                })
                .bean(toJson);
    }
}
项目:avatar-nao    文件:NaoSpeechSynthesisRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
        // lumen.speech.expression
        // TODO: we should delay e.g. 500ms to see if speech-expression handles it (and notifies with actionStatus=ACTIVE_ACTION_STATUS),
        // otherwise NAO TTS will handle it
        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + LumenChannel.SPEECH_SYNTHESIS.key() + "&routingKey=" + LumenChannel.SPEECH_SYNTHESIS.key())
                .to("log:IN.lumen.speech.synthesis?showHeaders=true&showAll=true&multiline=true")
                .process(exchange -> {
                    final LumenThing thing = toJson.getMapper().readValue(
                            exchange.getIn().getBody(byte[].class), LumenThing.class);
                    log.info("Got speech.synthesis command: {}", thing);
                    if (thing instanceof CommunicateAction) {
                        final CommunicateAction communicateAction = (CommunicateAction) thing;
                        if (naoConfig.getControllerAvatarIds().contains(communicateAction.getAvatarId())) {
                            final Locale lang = Optional.ofNullable(communicateAction.getInLanguage()).orElse(Locale.US);
                            if ("en".equals(lang.getLanguage())) {
                                log.info("Speaking {} for {}: {}", lang.toLanguageTag(), communicateAction.getAvatarId(), communicateAction.getObject());
                                naoConfig.get(communicateAction.getAvatarId()).getTts().say(communicateAction.getObject());
                                log.debug("Spoken {} for {}: {}", lang.toLanguageTag(), communicateAction.getAvatarId(), communicateAction.getObject());
                            } else {
                                log.info("Language '{}' not supported by {}, skipping: {}",
                                        lang.toLanguageTag(), communicateAction.getAvatarId(), communicateAction.getObject());
                            }
                        }
                        exchange.getIn().setBody(new Status());
                    } else {
                        exchange.getOut().setBody(null);
                    }
                })
                .bean(toJson);
//                .to("log:OUT.lumen.speech.synthesis");
    }
项目:Camel    文件:XmlErrorHandlerFactoryBean.java   
private void setProperties(LoggingErrorHandlerBuilder builder) {
    builder.setLevel(handler.getLevel());
    builder.setLogName(handler.getLogName());
}
项目:Camel    文件:ErrorHandlerDefinitionParserTest.java   
public void testLoggingErrorHandler() {
    LoggingErrorHandlerBuilder errorHandler = ctx.getBean("loggingErrorHandler", LoggingErrorHandlerBuilder.class);
    assertNotNull(errorHandler);
    assertEquals("The log level should be INFO", LoggingLevel.INFO, errorHandler.getLevel());
    assertEquals("The log name should be foo", "foo", errorHandler.getLogName());
}
项目:lumen    文件:ImageRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
        final String avatarId = "nao1";
//        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + AvatarChannel.CAMERA_MAIN.key(avatarId) + "&routingKey=" + AvatarChannel.CAMERA_MAIN.key(avatarId))
//                .sample(1, TimeUnit.SECONDS)
//                .to("log:IN." + AvatarChannel.CAMERA_MAIN.key(avatarId) + "?showHeaders=true&showAll=true&multiline=true")
//                .process(it -> {
//                    final JsonNode inBodyJson = toJson.getMapper().readTree(it.getIn().getBody(byte[].class));
//                    final ImageObjectLegacy imageObject = toJson.getMapper().convertValue(inBodyJson, ImageObjectLegacy.class);
//                    new TransactionTemplate(txMgr).execute(tx -> {
//                        final DateTime now = new DateTime();// FIXME: NaoServer should send ISO formatted timestamp
//                        final Map<String, Object> props = new HashMap<>();
//                        final String contentType = Preconditions.checkNotNull(imageObject.getContentType(), "ImageObject.contentType must be specified");
//                        final String upContentUrl = imageObject.getContentUrl();
//                        if (upContentUrl != null && upContentUrl.startsWith("data:")) {
//                            final String base64 = StringUtils.substringAfter(upContentUrl, ",");
//                            final byte[] content = Base64.decodeBase64(base64);
//                            final String ext = Preconditions.checkNotNull(extensionMap.get(contentType),
//                                    "Cannot get extension for MIME type \"%s\". Known MIME types: %s", contentType, extensionMap.keySet());
//                            // IIS disables double escaping, so avoid '+0700' in filename
//                            final String fileName = avatarId + "_journalimage_" + new DateTime(DateTimeZone.UTC).toString("yyyy-MM-dd'T'HH-mm-ssZ") + "." + ext;
//                            final File file = new File(mediaUploadPath, fileName);
//                            log.debug("Writing {} ImageObject to {} ...", contentType, file);
//                            try {
//                                FileUtils.writeByteArrayToFile(file, content);
//                            } catch (IOException e) {
//                                throw new RuntimeException("Cannot write to " + file, e);
//                            }
//                            props.put("contentUrl", mediaUploadPrefix + fileName);
//                        } else {
//                            props.put("contentUrl", upContentUrl);
//                        }
//
//                        final Node node = neo4j.createNode(props, ImmutableList.of("JournalImageObject"));
//                        log.debug("Created JournalImageObject {} from {} {}", node, imageObject.getName(), now);
//                        return node;
//                    });
//                    it.getIn().setBody(new Status());
//                })
//                .bean(toJson)
//                .to("log:OUT." + AvatarChannel.CAMERA_MAIN.key(avatarId) + "?showAll=true&multiline=true");
    }
项目:lumen    文件:FactRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + LumenChannel.PERSISTENCE_FACT.key() + "&routingKey=" + LumenChannel.PERSISTENCE_FACT.key())
                .to("log:IN." + LumenChannel.PERSISTENCE_FACT.key() + "?showHeaders=true&showAll=true&multiline=true")
                .process(it -> {
                    final FactRequest factRequest = toJson.getMapper().readValue(it.getIn().getBody(byte[].class), FactRequest.class);
                    it.getIn().setHeader("CamelBeanMethodName", factRequest.getOperation().name());
                    it.getIn().setBody(factRequest);
                })
                .bean(factService)
                .bean(toJson)
                .to("log:OUT." + LumenChannel.PERSISTENCE_FACT.key() + "?showAll=true&multiline=true");

//        final String agentId = "arkan";
//                    final JsonNode inBodyJson = toJson.getMapper().readTree(it.getIn().getBody(byte[].class));
//                    final String switchArg = inBodyJson.path("@type").asText();
//                    if ("FindAllQuery".equals("FindAllQuery")) {
//                        final FindAllQuery findAllQuery = toJson.getMapper().convertValue(inBodyJson, FindAllQuery.class);
//                        final String classAbbrevRef = Optional.ofNullable(RdfUtils.getPREFIX_MAP().abbreviate(findAllQuery.getClassRef())).orElse(findAllQuery.getClassRef());
//                        final Resources<IndexedResource> resources = new TransactionTemplate(txMgr).execute(tx -> {
//                            final String cypher = "MATCH (e:Resource) -[:rdf_type*]-> (:Resource {href: {classAbbrevRef}}) RETURN e LIMIT {itemsPerPage}";
//                            final Map<String, Object> params = new HashMap<>();
//                            log.debug("Querying using {}: {}", params, cypher);
//                            final Result<Map<String, Object>> rs = neo4j.query(cypher, params);
//                            try {
//                                final List<Node> rsList = FluentIterable.from(rs).transform(x -> (Node) x.get("e")).toList();
//                                log.debug("{} rows in result set for {}: {}", rsList.size(), classAbbrevRef, rsList);
//                                final List<IndexedResource> indexedResources = rsList.stream().map(it2 -> {
//                                    final IndexedResource indexedRes = new IndexedResource();
//                                    indexedRes.setHref((String) it2.getProperty("href"));
//                                    indexedRes.setPrefLabel((String) it2.getProperty("prefLabel"));
//                                    indexedRes.setIsPreferredMeaningOf((String) it2.getProperty("isPreferredMeaningOf"));
//                                    return indexedRes;
//                                }).collect(Collectors.toList());
//                                return new Resources<>(indexedResources);
//                            } finally {
//                                rs.finish();
//                            }
//                        });
//                        it.getIn().setBody(resources);
//                    } else if ("CypherQuery".equals(switchArg)) {
//                        final CypherQuery cypherQuery = toJson.getMapper().convertValue(inBodyJson, CypherQuery.class);
//                        final Resources<ResultRow> resources = new TransactionTemplate(txMgr).execute(tx -> {
//                            log.debug("Querying using {}: {}", cypherQuery.getParameters(), cypherQuery.getQuery());
//                            final Result<Map<String, Object>> rs = neo4j.query(cypherQuery.getQuery(), cypherQuery.getParameters());
//                            try {
//                                final ImmutableList<Map<String, Object>> rsList = ImmutableList.copyOf(rs);
//                                log.debug("{} rows in result set: {}", rsList.size(), rsList);
//                                final List<ResultRow> resultRowList = rsList.stream().map(row ->
//                                        new ResultRow(row.entrySet().stream().map(entry -> {
//                                                    if (entry.getValue() instanceof Node) {
//                                                        return new ResultCell(entry.getKey(), new Neo4jNode((Node) entry.getValue()));
//                                                    } else if (entry.getValue() instanceof Relationship) {
//                                                        return new ResultCell(entry.getKey(), new Neo4jRelationship((Relationship) entry.getValue()));
//                                                    } else {
//                                                        return new ResultCell(entry.getKey(), entry.getValue());
//                                                    }
//                                                }
//                                        ).collect(Collectors.toList()))).collect(Collectors.toList());
//                                return new Resources<>(resultRowList);
//                            } finally {
//                                rs.finish();
//                            }
//                        });
//                        it.getIn().setBody(resources);
//                    } else {
//                        throw new Exception("Unknown JSON message: " + inBodyJson);
//                    }

    }
项目:lumen    文件:ReasonerRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
//        from("timer:hello?period=3s")
//                .process(exchange -> {
//                    exchange.getIn().setBody(new GreetingReceived("Hendy"));
//                })
//                .to("seda:greetingReceived");

//        from("timer:tell me a good story?period=1s&repeatCount=1")
//                .process(exchange -> {
//                    final AgentResponse agentResponse = aimlService.process(Locale.US, "tell me a good story", logChannel);
//                    droolsService.process(agentResponse);
//                });

        final String agentId = "arkan";
        from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + AvatarChannel.CHAT_INBOX.wildcard() + "&routingKey=" + AvatarChannel.CHAT_INBOX.wildcard())
                .process(exchange -> {
                    final long startTime = System.currentTimeMillis();
                    final CommunicateAction inCommunicate = toJson.getMapper().readValue(
                            exchange.getIn().getBody(byte[].class), CommunicateAction.class);
                    inCommunicate.setAvatarId(AvatarChannel.getAvatarId((String) exchange.getIn().getHeader(RabbitMQConstants.ROUTING_KEY)));
                    log.info("Chat inbox for {}: {}", inCommunicate.getAvatarId(), inCommunicate);

                    final Optional<Locale> origLocale = Optional.ofNullable(inCommunicate.getInLanguage());
                    final float[] speechTruthValue = Optional.ofNullable(inCommunicate.getSpeechTruthValue()).orElse(new float[]{0f, 0f, 0f});
                    final boolean speechInput = speechTruthValue.length >= 2 && speechTruthValue[1] > 0f;

                    // AIML style
//                    final AgentResponse agentResponse = aimlService.process(origLocale, inCommunicate.getObject(),
//                            chatChannel, inCommunicate.getAvatarId(), speechInput);
//                    if (!agentResponse.getCommunicateActions().isEmpty()) {
//                        for (final CommunicateAction communicateAction : agentResponse.getCommunicateActions()) {
//                            chatChannel.express(inCommunicate.getAvatarId(), communicateAction, null);
//                        }
//                    } else if (agentResponse.getUnrecognizedInput() != null) {
//                        chatChannel.express(inCommunicate.getAvatarId(), Proposition.I_DONT_UNDERSTAND, true, null);
//                    }
//                    droolsService.process(agentResponse);

                    final InteractionSession session = sessionManager.getOrCreate(chatChannel, inCommunicate.getAvatarId());
                    session.receiveUtterance(origLocale, inCommunicate.getObject(), inCommunicate.getAvatarId(), factService, taskRepo, scriptRepo);
                    session.update(chatChannel, inCommunicate.getAvatarId());

                    // FIXME: re-implement SocialJournal
//                    final SocialJournal socialJournal = new SocialJournal();
//                    socialJournal.setFromResponse(origLocale, inCommunicate.getAvatarId(),
//                            inCommunicate.getObject(), SocialChannel.DIRECT,
//                            agentResponse, Duration.millis(System.currentTimeMillis() - startTime));
//                    socialJournalRepo.save(socialJournal);

                    exchange.getIn().setBody(new Status());
                })
                .bean(toJson);
    }
项目:avatar-nao    文件:CommandRouter.java   
@Override
    public void configure() throws Exception {
        onException(Exception.class).bean(asError).bean(toJson).handled(true);
        errorHandler(new LoggingErrorHandlerBuilder(log));
        // avatar.*.command
        for (final String avatarId : naoConfig.getControllerAvatarIds()) {
            final NaoController nao = naoConfig.get(avatarId);
            final ALAudioDeviceProxy audioDevice = nao.getAudioDevice();
            final ALTextToSpeechProxy tts = nao.getTts();
            final ALMotionProxy motion = nao.getMotion();
            final ALRobotPostureProxy robotPosture = nao.getRobotPosture();
            final ALAudioPlayerProxy audioPlayer = nao.getAudioPlayer();
            from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=" + AvatarChannel.COMMAND.key(avatarId) + "&routingKey=" + AvatarChannel.COMMAND.key(avatarId))
                    .to(String.format("log:IN.%s?showHeaders=true&showAll=true&multiline=true", AvatarChannel.COMMAND.key(avatarId)))
                    .process(exchange -> {
                        final LumenThing thing = toJson.getMapper().readValue(
                                exchange.getIn().getBody(byte[].class), LumenThing.class);
                        log.info("Got avatar.nao* command: {}", thing);
                        if (thing instanceof AudioVolume) {
                            log.info("Set volume {}", thing);
                            final int volumePct = (int) Math.round(((AudioVolume) thing).getVolume() * 100);
                            audioDevice.setOutputVolume(volumePct);
                            tts.say("My volume is now " + volumePct + "%");
                        } else if (thing instanceof WakeUp) {
                            log.info("Waking up...");
                            motion.wakeUp();
                            log.info("Woke up");
                        } else if (thing instanceof PostureChange) {
                            log.info("Changing posture {}", thing);
                            robotPosture.goToPosture(((PostureChange) thing).getPostureId(),
                                    (float) (double) ((PostureChange) thing).getSpeed());
                            log.info("Posture changed.");
                        } else if (thing instanceof Rest) {
                            log.info("Resting...");
                            motion.rest();
                            log.info("Rested");
                        } else if (thing instanceof MoveTo) {
                            final MoveTo moveTo = (MoveTo) thing;
                            final float naoMoveToX = (float) (-moveTo.getBackDistance());
                            final float naoMoveToY = (float) -moveTo.getRightDistance();
                            final float naoMoveToTheta = (float) Math.toRadians(moveTo.getTurnCcwDeg());
                            log.info("Moving {} as NAO: x={} y={} theta={} ...",
                                    moveTo, naoMoveToX, naoMoveToY, naoMoveToTheta);
                            motion.moveTo(naoMoveToX, naoMoveToY, naoMoveToTheta);
                            log.info("Moved");
                        } else if (thing instanceof JointInterpolateAngle) {
                            final JointInterpolateAngle jointInterpolateAngle = (JointInterpolateAngle) thing;
                            final float naoAngle = (float) Math.toRadians(jointInterpolateAngle.getTargetCcwDeg());
                            log.info("Interpolate {} as NAO: angle={} ...", jointInterpolateAngle, naoAngle);
                            motion.angleInterpolation(new Variant(jointInterpolateAngle.getJointId().name()),
                                    new Variant(naoAngle), new Variant((float) (double) jointInterpolateAngle.getDuration()), true);
                            log.info("Interpolated.");
                        }

                        // reply
                        exchange.getIn().setBody(new Status());
                    })
                    .bean(toJson);
//                .to("log:OUT.avatar.nao1.command");
        }
    }
项目:OLE-INST    文件:DocStoreCamelContext.java   
public LoggingErrorHandlerBuilder getErrorHandler() {
    return errorHandler;
}
项目:camel-cdi    文件:XmlErrorHandlerFactoryBean.java   
private void setProperties(LoggingErrorHandlerBuilder builder) {
    builder.setLevel(handler.getLevel());
    builder.setLogName(handler.getLogName());
}