Example usage for org.springframework.util ErrorHandler ErrorHandler

List of usage examples for org.springframework.util ErrorHandler ErrorHandler

Introduction

In this page you can find the example usage for org.springframework.util ErrorHandler ErrorHandler.

Prototype

ErrorHandler

Source Link

Usage

From source file:com.joshlong.esb.springintegration.modules.net.sftp.Main.java

static void run(SFTPSessionFactory sftpSessionFactory, String lp, String rp) throws Throwable {
    // local path
    File local = new File(lp); // obviously this is just for test. Do what you need to do in your own

    // we are testing, after all
    if (local.exists() && (local.list().length > 0)) {
        for (File f : local.listFiles()) {
            if (!f.delete()) {
                logger.debug("couldn't delete " + f.getAbsolutePath());
            }/*from   w  ww  .j  av a  2 s  .c om*/
        }
    }

    Resource localDirectory = new FileSystemResource(local);

    // pool
    QueuedSFTPSessionPool queuedSFTPSessionPool = new QueuedSFTPSessionPool(sftpSessionFactory);
    queuedSFTPSessionPool.afterPropertiesSet();

    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setPoolSize(10);
    taskScheduler.setErrorHandler(new ErrorHandler() {
        public void handleError(Throwable t) {
            logger.debug("error! ", t);
        }
    });

    taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    taskScheduler.initialize();

    // synchronizer
    final SFTPInboundSynchronizer sftpInboundSynchronizer = new SFTPInboundSynchronizer();
    sftpInboundSynchronizer.setLocalDirectory(localDirectory);
    sftpInboundSynchronizer.setRemotePath(rp);
    sftpInboundSynchronizer.setAutoCreatePath(true);
    sftpInboundSynchronizer.setPool(queuedSFTPSessionPool);
    sftpInboundSynchronizer.setShouldDeleteDownloadedRemoteFiles(false);
    sftpInboundSynchronizer.setTaskScheduler(taskScheduler);
    sftpInboundSynchronizer.afterPropertiesSet();
    sftpInboundSynchronizer.start();

    /*
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(60 * 1000); // 1 minute
            
                    sftpInboundSynchronizer.stop();
            
                } catch (InterruptedException e) {
                    // don't care
                }
            }
        }).start();
    */
}

From source file:org.openbaton.autoscaling.core.decision.DecisionManagement.java

@PostConstruct
public void init() throws SDKException {
    this.actionMonitor = new ActionMonitor();
    this.taskScheduler = new ThreadPoolTaskScheduler();
    this.taskScheduler.setPoolSize(10);
    this.taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    this.taskScheduler.setRemoveOnCancelPolicy(true);
    this.taskScheduler.setErrorHandler(new ErrorHandler() {
        protected Logger log = LoggerFactory.getLogger(this.getClass());

        @Override/*from www  . j a  v a2s .  c  o  m*/
        public void handleError(Throwable t) {
            log.error(t.getMessage(), t);
        }
    });
    this.taskScheduler.initialize();
}

From source file:org.openbaton.autoscaling.core.execution.ExecutionManagement.java

@PostConstruct
public void init() throws SDKException {
    this.actionMonitor = new ActionMonitor();
    this.executionEngine.setActionMonitor(actionMonitor);
    this.taskScheduler = new ThreadPoolTaskScheduler();
    this.taskScheduler.setPoolSize(10);
    this.taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    this.taskScheduler.setRemoveOnCancelPolicy(true);
    this.taskScheduler.setErrorHandler(new ErrorHandler() {
        protected Logger log = LoggerFactory.getLogger(this.getClass());

        @Override/*  www  . j ava  2 s.c o m*/
        public void handleError(Throwable t) {
            log.error(t.getMessage(), t);
        }
    });
    this.taskScheduler.initialize();
}

From source file:org.openbaton.autoscaling.core.detection.DetectionManagement.java

@PostConstruct
public void init() throws SDKException {
    this.actionMonitor = new ActionMonitor();
    this.detectionTasks = new HashMap<>();
    this.taskScheduler = new ThreadPoolTaskScheduler();
    this.taskScheduler.setPoolSize(10);
    this.taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    this.taskScheduler.setRemoveOnCancelPolicy(true);
    this.taskScheduler.setErrorHandler(new ErrorHandler() {
        protected Logger log = LoggerFactory.getLogger(this.getClass());

        @Override/*from   w  w  w . jav  a2s  .com*/
        public void handleError(Throwable t) {
            log.error(t.getMessage(), t);
        }
    });
    this.taskScheduler.initialize();
}

From source file:org.openbaton.autoscaling.core.features.pool.PoolManagement.java

@PostConstruct
public void init() throws SDKException {
    this.actionMonitor = new ActionMonitor();
    this.poolTasks = new HashMap<>();
    this.taskScheduler = new ThreadPoolTaskScheduler();
    this.taskScheduler.setPoolSize(10);
    this.taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    this.taskScheduler.setRemoveOnCancelPolicy(true);
    this.taskScheduler.setErrorHandler(new ErrorHandler() {
        protected Logger log = LoggerFactory.getLogger(this.getClass());

        @Override//  w ww .jav a 2s.  c o m
        public void handleError(Throwable t) {
            log.error(t.getMessage(), t);
        }
    });
    this.taskScheduler.initialize();

    reservedInstances = new HashMap<>();
}

From source file:io.lavagna.config.PersistenceAndServiceConfig.java

@Bean(destroyMethod = "shutdown")
public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setErrorHandler(new ErrorHandler() {
        @Override/*from w  w w . j  av a  2s  . c om*/
        public void handleError(Throwable t) {
            LogManager.getLogger().error("error while handling job", t);
        }
    });
    scheduler.initialize();
    return scheduler;
}

From source file:com.joshlong.esb.springintegration.modules.net.sftp.config.SFTPMessageSourceFactoryBean.java

@Override
protected SFTPMessageSource createInstance() throws Exception {
    try {//ww  w  . ja va  2s .c o m
        if ((localWorkingDirectory == null) || StringUtils.isEmpty(localWorkingDirectory)) {
            File tmp = SystemUtils.getJavaIoTmpDir();
            File sftpTmp = new File(tmp, "sftpInbound");
            this.localWorkingDirectory = "file://" + sftpTmp.getAbsolutePath();
        }
        assert !StringUtils
                .isEmpty(this.localWorkingDirectory) : "the local working directory mustn't be null!";

        // resource for local directory
        ResourceEditor editor = new ResourceEditor(this.resourceLoader);
        editor.setAsText(this.localWorkingDirectory);
        this.localDirectoryResource = (Resource) editor.getValue();

        fileReadingMessageSource = new FileReadingMessageSource();

        synchronizer = new SFTPInboundSynchronizer();

        if (null == taskScheduler) {
            Map<String, TaskScheduler> tss = null;

            if ((tss = applicationContext.getBeansOfType(TaskScheduler.class)).keySet().size() != 0) {
                taskScheduler = tss.get(tss.keySet().iterator().next());
            }
        }

        if (null == taskScheduler) {
            ThreadPoolTaskScheduler ts = new ThreadPoolTaskScheduler();
            ts.setPoolSize(10);
            ts.setErrorHandler(new ErrorHandler() {
                public void handleError(Throwable t) {
                    // todo make this forward a message onto the error channel (how does that work?)
                    logger.debug("error! ", t);
                }
            });

            ts.setWaitForTasksToCompleteOnShutdown(true);
            ts.initialize();
            this.taskScheduler = ts;
        }

        SFTPSessionFactory sessionFactory = SFTPSessionUtils.buildSftpSessionFactory(this.getHost(),
                this.getPassword(), this.getUsername(), this.getKeyFile(), this.getKeyFilePassword(),
                this.getPort());

        QueuedSFTPSessionPool pool = new QueuedSFTPSessionPool(15, sessionFactory);
        pool.afterPropertiesSet();
        synchronizer.setRemotePath(this.getRemoteDirectory());
        synchronizer.setPool(pool);
        synchronizer.setAutoCreatePath(this.isAutoCreateDirectories());
        synchronizer.setShouldDeleteDownloadedRemoteFiles(this.isAutoDeleteRemoteFilesOnSync());

        SFTPMessageSource sftpMessageSource = new SFTPMessageSource(fileReadingMessageSource, synchronizer);

        sftpMessageSource.setTaskScheduler(taskScheduler);

        if (null != this.trigger) {
            sftpMessageSource.setTrigger(trigger);
        }

        sftpMessageSource.setLocalDirectory(this.localDirectoryResource);
        sftpMessageSource.afterPropertiesSet();
        sftpMessageSource.start();

        return sftpMessageSource;
    } catch (Throwable thr) {
        logger.debug("error occurred when trying to configure SFTPmessageSource ", thr);
    }

    return null;
}

From source file:org.springframework.integration.handler.advice.AdvisedMessageHandlerTests.java

@Test
public void testInappropriateAdvice() throws Exception {
    final AtomicBoolean called = new AtomicBoolean(false);
    Advice advice = new AbstractRequestHandlerAdvice() {
        @Override/*from  w  ww.  j a  v a  2s.co  m*/
        protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message)
                throws Exception {
            called.set(true);
            return callback.execute();
        }
    };
    PollableChannel inputChannel = new QueueChannel();
    PollingConsumer consumer = new PollingConsumer(inputChannel, new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
        }
    });
    consumer.setAdviceChain(Collections.singletonList(advice));
    consumer.setTaskExecutor(
            new ErrorHandlingTaskExecutor(Executors.newSingleThreadExecutor(), new ErrorHandler() {
                @Override
                public void handleError(Throwable t) {
                }
            }));
    consumer.afterPropertiesSet();

    Callable<?> pollingTask = TestUtils.getPropertyValue(consumer, "poller.pollingTask", Callable.class);
    assertTrue(AopUtils.isAopProxy(pollingTask));
    Log logger = TestUtils.getPropertyValue(advice, "logger", Log.class);
    logger = spy(logger);
    when(logger.isWarnEnabled()).thenReturn(Boolean.TRUE);
    final AtomicReference<String> logMessage = new AtomicReference<String>();
    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            logMessage.set((String) invocation.getArguments()[0]);
            return null;
        }
    }).when(logger).warn(Mockito.anyString());
    DirectFieldAccessor accessor = new DirectFieldAccessor(advice);
    accessor.setPropertyValue("logger", logger);

    pollingTask.call();
    assertFalse(called.get());
    assertNotNull(logMessage.get());
    assertTrue(logMessage.get()
            .endsWith("can only be used for MessageHandlers; " + "an attempt to advise method 'call' in "
                    + "'org.springframework.integration.endpoint.AbstractPollingEndpoint$1' is ignored"));
}

From source file:org.springframework.integration.jms.JmsOutboundGatewayTests.java

@Test
public void testReplyContainerRecovery() throws Exception {
    JmsOutboundGateway gateway = new JmsOutboundGateway();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestDestinationName("foo");
    gateway.setUseReplyContainer(true);//from w  w  w  .j  a  v  a 2  s  .co m
    ReplyContainerProperties replyContainerProperties = new ReplyContainerProperties();
    final List<Throwable> errors = new ArrayList<Throwable>();
    ErrorHandlingTaskExecutor errorHandlingTaskExecutor = new ErrorHandlingTaskExecutor(
            Executors.newFixedThreadPool(10), new ErrorHandler() {

                @Override
                public void handleError(Throwable t) {
                    logger.info("Error:", t);
                    errors.add(t);
                    throw new RuntimeException(t);
                }
            });
    replyContainerProperties.setTaskExecutor(errorHandlingTaskExecutor);
    replyContainerProperties.setRecoveryInterval(100L);
    gateway.setReplyContainerProperties(replyContainerProperties);
    final Connection connection = mock(Connection.class);
    final AtomicInteger connectionAttempts = new AtomicInteger();
    doAnswer(new Answer<Connection>() {

        @SuppressWarnings("serial")
        @Override
        public Connection answer(InvocationOnMock invocation) throws Throwable {
            int theCount = connectionAttempts.incrementAndGet();
            if (theCount > 1 && theCount < 4) {
                throw new JmsException("bar") {
                };
            }
            return connection;
        }
    }).when(connectionFactory).createConnection();
    Session session = mock(Session.class);
    when(connection.createSession(false, 1)).thenReturn(session);
    MessageConsumer consumer = mock(MessageConsumer.class);
    when(session.createConsumer(any(Destination.class), anyString())).thenReturn(consumer);
    when(session.createTemporaryQueue()).thenReturn(mock(TemporaryQueue.class));
    final Message message = mock(Message.class);
    final AtomicInteger count = new AtomicInteger();
    doAnswer(new Answer<Message>() {

        @SuppressWarnings("serial")
        @Override
        public Message answer(InvocationOnMock invocation) throws Throwable {
            int theCount = count.incrementAndGet();
            if (theCount > 1 && theCount < 4) {
                throw new JmsException("foo") {
                };
            }
            if (theCount > 4) {
                Thread.sleep(100);
                return null;
            }
            return message;
        }
    }).when(consumer).receive(anyLong());
    when(message.getJMSCorrelationID()).thenReturn("foo");
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    beanFactory.registerSingleton("taskScheduler", taskScheduler);
    gateway.setBeanFactory(beanFactory);
    gateway.afterPropertiesSet();
    gateway.start();
    Thread.sleep(1000);
    assertTrue(count.get() > 4);
    assertEquals(0, errors.size());
}