com.rationaldevelopers.oss.ApplicationConfiguration.java Source code

Java tutorial

Introduction

Here is the source code for com.rationaldevelopers.oss.ApplicationConfiguration.java

Source

/*
 * Copyright 2016 Ryan McGuinness
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.rationaldevelopers.oss;

import com.hazelcast.config.*;
import com.hazelcast.core.*;
import com.rationaldevelopers.oss.domain.DataSerializer;
import com.rationaldevelopers.oss.domain.SimpleItem;
import com.rationaldevelopers.oss.service.SimpleItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author Ryan McGuinness [rmcguinness@walmartlabs.com]
 * @version 8/31/16
 */
@Configuration
@ComponentScan
@EnableJpaRepositories("com.rationaldevelopers.oss.data")
public class ApplicationConfiguration {
    private static final Logger log = LoggerFactory.getLogger(ApplicationConfiguration.class);
    private static final String CACHE_NAME = "simple-item-cache";
    private static final String LOCK_NAME = "simple-lock";
    private static final String QUEUE_NAME = "inbound-queue";

    @Bean(name = "serverIpAddresses")
    public List<String> getServerAddresses() {
        String[] addresses = { "127.0.0.1" };
        return Collections.unmodifiableList(Arrays.asList(addresses));
    }

    @Bean
    public Config getHazelcastConfig(@Qualifier("serverIpAddresses") final List<String> serverIpAddresses) {

        final Logger log = LoggerFactory.getLogger(Application.class);
        final int port = Integer.parseInt(System.getProperty("hazelcast.port", "5701"));
        final String clusterName = "test:cluster";

        Config config = new Config();
        config.getGroupConfig().setName(clusterName);
        config.getNetworkConfig().setPort(port).setPortAutoIncrement(false).setReuseAddress(true);

        GroupConfig groupConfig = new GroupConfig();
        groupConfig.setName(clusterName);
        groupConfig.setPassword("password");
        config.setGroupConfig(groupConfig);

        SecurityConfig securityConfig = new SecurityConfig();
        securityConfig.setEnabled(false);
        config.setSecurityConfig(securityConfig);

        JoinConfig join = config.getNetworkConfig().getJoin();
        join.getMulticastConfig().setEnabled(false);

        serverIpAddresses.forEach(item -> join.getTcpIpConfig().addMember(item));

        SerializationConfig serializationConfig = new SerializationConfig();
        serializationConfig.addDataSerializableFactory(1, new DataSerializer());

        config.setSerializationConfig(serializationConfig);

        join.getTcpIpConfig().setEnabled(true);

        return config;
    }

    @Bean(destroyMethod = "shutdown")
    public HazelcastInstance getHazelcastInstance(final Config config) {
        return Hazelcast.newHazelcastInstance(config);
    }

    @Bean
    public IMap<String, SimpleItem> getCache(final HazelcastInstance hazelcastInstance) {
        return hazelcastInstance.getMap(CACHE_NAME);
    }

    @Bean
    public ILock getSimpleLock(final HazelcastInstance hazelcastInstance) {
        return hazelcastInstance.getLock(LOCK_NAME);
    }

    @Bean
    public IQueue<SimpleItem> inboundQueue(final HazelcastInstance hazelcastInstance,
            final SimpleItemService simpleItemService, final IMap<String, SimpleItem> cache) {

        IQueue<SimpleItem> queue = hazelcastInstance.getQueue(QUEUE_NAME);
        queue.addItemListener(new ItemListener<SimpleItem>() {
            @Override
            public void itemAdded(ItemEvent<SimpleItem> itemEvent) {
                SimpleItem i = itemEvent.getItem();
                try {
                    simpleItemService.saveOrUpdate(i);
                    cache.put(i.getSid(), i, 2, TimeUnit.MINUTES);
                    queue.remove(i);
                } catch (Exception e) {
                    i.incrementCount();
                    if (i.getCount() >= 10) {
                        //Effectively handling a poison message or dead letter
                        queue.remove(i);
                    }
                }
            }

            @Override
            public void itemRemoved(ItemEvent<SimpleItem> itemEvent) {
                System.out.println("Item Processed: {}" + itemEvent.getItem().getName());
            }
        }, true);
        log.info("=========================== Created Queue ======== {}", queue);
        return queue;
    }

}