Перая версия слушателя событий

Научил программу работать в двух потоках. Первый поток слушает все сообещния от сервера и записывает их в отдельный класс. Другой поток раз в какое-то время обращается к этому классу и что-то делает
This commit is contained in:
Mark Struchkov 2018-12-25 03:13:04 +03:00
parent 1ead58f169
commit 9a719d70b8
21 changed files with 255 additions and 154 deletions

View File

@ -0,0 +1,18 @@
package org.sadtech.consultant.entity;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
@Data
@Entity
public class Message {
@Id
private Long idMess;
private Long idUser;
private String text;
}

View File

@ -0,0 +1,8 @@
package org.sadtech.consultant.repository;
import org.sadtech.consultant.entity.Message;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MessageRepository extends JpaRepository<Message, Long> {
}

View File

@ -0,0 +1,8 @@
package org.sadtech.consultant.service;
import org.sadtech.consultant.entity.Message;
public interface MessageService {
void addMessage(Message message);
}

View File

@ -0,0 +1,16 @@
package org.sadtech.consultant.service.impl;
import org.sadtech.consultant.entity.Message;
import org.sadtech.consultant.repository.MessageRepository;
import org.sadtech.consultant.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
public class MessageServiceImpl implements MessageService {
@Autowired
private MessageRepository repository;
public void addMessage(Message message) {
repository.saveAndFlush(message);
}
}

View File

@ -1,7 +0,0 @@
package org.sadtech.vkbot;
public interface Observable {
void registerObserver(org.sadtech.vkbot.Observer o);
// void removeObserver(Observer o);
void notifyObservers();
}

View File

@ -1,39 +0,0 @@
package org.sadtech.vkbot;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
public class ResponseDataVk implements Observable, ResponsibleData {
private List<Observer> observers = new ArrayList<Observer>();
private List<JsonObject> jsonObjects = new ArrayList<JsonObject>();
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void notifyObservers() {
for (Observer observer:observers) {
observer.update(jsonObjects);
}
}
public void setJsonObjects(List<JsonObject> jsonObjects) {
this.jsonObjects = jsonObjects;
notifyObservers();
}
@Override
public void add(JsonObject jsonObject) {
}
@Override
public void remove(JsonObject jsonObject) {
}
}

View File

@ -1,10 +0,0 @@
package org.sadtech.vkbot;
import com.google.gson.JsonObject;
public interface ResponsibleData {
void add(JsonObject jsonObject);
void remove(JsonObject jsonObject);
}

View File

@ -1,20 +0,0 @@
package org.sadtech.vkbot;
import com.google.gson.JsonObject;
import java.util.List;
public class TestLogic implements Observer{
private ResponseDataVk responseData;
public TestLogic(ResponseDataVk responseData) {
this.responseData = responseData;
responseData.registerObserver(this);
}
@Override
public void update(List<JsonObject> jsonObjects) {
System.out.println(jsonObjects);
}
}

View File

@ -4,7 +4,6 @@ import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.GroupActor; import com.vk.api.sdk.client.actors.GroupActor;
import lombok.extern.log4j.Log4j; import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Log4j @Log4j
@Component @Component

View File

@ -3,7 +3,6 @@ package org.sadtech.vkbot.config;
import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@ -39,14 +38,13 @@ public class DataConfig {
@Value("${db.hibernate.hbm2ddl.auto}") @Value("${db.hibernate.hbm2ddl.auto}")
private String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO; private String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO;
@Bean @Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class); entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN); entityManagerFactoryBean.setPackagesToScan(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(hibernateProp()); entityManagerFactoryBean.setJpaProperties(hibernateProp());
return entityManagerFactoryBean; return entityManagerFactoryBean;
} }
@ -54,19 +52,16 @@ public class DataConfig {
public JpaTransactionManager transactionManager() { public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager(); JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager; return transactionManager;
} }
@Bean @Bean
public DataSource dataSource() { public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(); DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(PROPERTY_NAME_DATABASE_DRIVER); dataSource.setDriverClassName(PROPERTY_NAME_DATABASE_DRIVER);
dataSource.setUrl(PROPERTY_NAME_DATABASE_URL); dataSource.setUrl(PROPERTY_NAME_DATABASE_URL);
dataSource.setUsername(PROPERTY_NAME_DATABASE_USERNAME); dataSource.setUsername(PROPERTY_NAME_DATABASE_USERNAME);
dataSource.setPassword(PROPERTY_NAME_DATABASE_PASSWORD); dataSource.setPassword(PROPERTY_NAME_DATABASE_PASSWORD);
return dataSource; return dataSource;
} }

View File

@ -8,9 +8,8 @@ import com.vk.api.sdk.exceptions.ApiException;
import com.vk.api.sdk.exceptions.ClientException; import com.vk.api.sdk.exceptions.ClientException;
import com.vk.api.sdk.httpclient.HttpTransportClient; import com.vk.api.sdk.httpclient.HttpTransportClient;
import com.vk.api.sdk.objects.groups.responses.GetLongPollServerResponse; import com.vk.api.sdk.objects.groups.responses.GetLongPollServerResponse;
import org.sadtech.vkbot.ResponseDataVk; import org.sadtech.vkbot.listener.data.impl.ResponseDataVk;
import org.sadtech.vkbot.TestLogic; import org.sadtech.vkbot.listener.impl.EventListenerVk;
import org.sadtech.vkbot.VkOpenMethod;
import org.sadtech.vkbot.service.UserService; import org.sadtech.vkbot.service.UserService;
import org.sadtech.vkbot.service.impl.UserServiceImpl; import org.sadtech.vkbot.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -18,12 +17,19 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import java.util.concurrent.Executors;
@Configuration @Configuration
@PropertySource("classpath:config.properties")
@ComponentScan("org.sadtech.vkbot")
@EnableAsync @EnableAsync
@PropertySource("classpath:config.properties")
@ComponentScan("org.sadtech.vkbot.listener")
@EnableScheduling
public class SpringConfigVk { public class SpringConfigVk {
@Value("${vk.groupID}") @Value("${vk.groupID}")
@ -80,23 +86,14 @@ public class SpringConfigVk {
} catch (ClientException e) { } catch (ClientException e) {
e.printStackTrace(); e.printStackTrace();
} }
// System.out.println("server: "+getLongPollServerResponse);
return getLongPollServerResponse; return getLongPollServerResponse;
} }
@Bean
public UserService userService() {
return new UserServiceImpl();
}
@Bean @Bean
public ResponseDataVk responseDataVk() { public TaskExecutor taskExecutor() {
return new ResponseDataVk(); return new ConcurrentTaskExecutor(Executors.newFixedThreadPool(5));
} }
@Bean
public TestLogic testLogic() {
return new TestLogic(responseDataVk());
}
} }

View File

@ -0,0 +1,17 @@
package org.sadtech.vkbot.config;
import org.sadtech.vkbot.listener.EventListenable;
import org.sadtech.vkbot.listener.Observable;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestMain {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfigVk.class);
context.register(DataConfig.class);
EventListenable eventListener = context.getBean(EventListenable.class);
eventListener.listen();
Observable dispetcherHandler = context.getBean(Observable.class);
dispetcherHandler.packaging();
}
}

View File

@ -1,27 +1,32 @@
package org.sadtech.vkbot.config; //package org.sadtech.vkbot.config;
//
import org.springframework.context.annotation.ComponentScan; //import com.vk.api.sdk.exceptions.ApiException;
import org.springframework.context.annotation.Configuration; //import com.vk.api.sdk.exceptions.ClientException;
import org.springframework.web.WebApplicationInitializer; //import org.sadtech.vkbot.listener.EventListenable;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; //import org.sadtech.vkbot.listener.Observable;
import org.springframework.web.servlet.DispatcherServlet; //import org.sadtech.vkbot.listener.impl.EventListenerVk;
//import org.springframework.context.annotation.ComponentScan;
import javax.servlet.ServletContext; //import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletException; //import org.springframework.web.WebApplicationInitializer;
import javax.servlet.ServletRegistration; //import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
//import org.springframework.web.servlet.DispatcherServlet;
@Configuration //
@ComponentScan("org.sadtech.vkbot.listener") //import javax.servlet.ServletContext;
public class WebConfig implements WebApplicationInitializer { //import javax.servlet.ServletException;
//
@Override //@Configuration
public void onStartup(ServletContext servletContext) throws ServletException { //public class WebConfig implements WebApplicationInitializer {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); //
context.register(SpringConfigVk.class, WebConfig.class, DataConfig.class); // @Override
context.setServletContext(servletContext); // public void onStartup(ServletContext servletContext) throws ServletException {
// AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context)); // context.register(SpringConfigVk.class, DataConfig.class, WebConfig.class);
dispatcher.setLoadOnStartup(1); //
dispatcher.addMapping("/"); //// context.setServletContext(servletContext);
} ////
} ////
//// ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
//// dispatcher.setLoadOnStartup(1);
//// dispatcher.addMapping("/");
// }
//}

View File

@ -1,6 +1,5 @@
package org.sadtech.vkbot.listener; package org.sadtech.vkbot.listener;
public interface EventListenable public interface EventListenable {
{
void listen() throws Exception; void listen() throws Exception;
} }

View File

@ -0,0 +1,10 @@
package org.sadtech.vkbot.listener;
public interface Observable {
void registerObserver(Observer o);
// void removeObserver(Observer o);
void notifyObservers();
void packaging() throws Exception;
}

View File

@ -1,4 +1,4 @@
package org.sadtech.vkbot; package org.sadtech.vkbot.listener;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;

View File

@ -0,0 +1,17 @@
package org.sadtech.vkbot.listener.data;
import com.google.gson.JsonObject;
import java.util.List;
public interface ResponsibleData {
void add(JsonObject jsonObject);
void remove(int id);
void cleanAll();
List<JsonObject> getJsonObjects();
}

View File

@ -0,0 +1,33 @@
package org.sadtech.vkbot.listener.data.impl;
import com.google.gson.JsonObject;
import org.sadtech.vkbot.listener.data.ResponsibleData;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class ResponseDataVk implements ResponsibleData {
private List<JsonObject> jsonObjects = new ArrayList<JsonObject>();
@Override
public void add(JsonObject jsonObject) {
jsonObjects.add(jsonObject);
}
@Override
public void remove(int id) {
jsonObjects.remove(id);
}
@Override
public void cleanAll() {
jsonObjects.clear();
}
public List<JsonObject> getJsonObjects() {
return jsonObjects;
}
}

View File

@ -0,0 +1,48 @@
package org.sadtech.vkbot.listener.handlers;
import com.google.gson.JsonObject;
import lombok.extern.log4j.Log4j;
import org.sadtech.vkbot.listener.Observable;
import org.sadtech.vkbot.listener.Observer;
import org.sadtech.vkbot.listener.data.ResponsibleData;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Log4j
@Component
public class DispetcherHandler implements Observable {
private ResponsibleData date;
private List<Observer> observers = new ArrayList<Observer>();
private List<JsonObject> objects;
public DispetcherHandler(ResponsibleData date) {
this.date = date;
}
@Scheduled(fixedRate = 5000)
public void packaging() {
objects = new ArrayList<JsonObject>(date.getJsonObjects());
date.cleanAll();
for (JsonObject object : objects) {
System.out.println(object);
}
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
//observer.update();
}
}
}

View File

@ -0,0 +1,21 @@
package org.sadtech.vkbot.listener.handlers;
import com.google.gson.JsonObject;
import org.sadtech.vkbot.listener.Observer;
import java.util.List;
public class MessageHandlerVk implements Observer {
private DispetcherHandler dispetcherHandler;
public MessageHandlerVk(DispetcherHandler dispetcherHandler) {
this.dispetcherHandler = dispetcherHandler;
dispetcherHandler.registerObserver(this);
}
@Override
public void update(List<JsonObject> jsonObjects) {
}
}

View File

@ -1,4 +1,4 @@
package org.sadtech.vkbot.listener; package org.sadtech.vkbot.listener.impl;
import com.vk.api.sdk.actions.LongPoll; import com.vk.api.sdk.actions.LongPoll;
import com.vk.api.sdk.callback.longpoll.queries.GetLongPollEventsQuery; import com.vk.api.sdk.callback.longpoll.queries.GetLongPollEventsQuery;
@ -9,15 +9,14 @@ import com.vk.api.sdk.exceptions.ApiException;
import com.vk.api.sdk.exceptions.ClientException; import com.vk.api.sdk.exceptions.ClientException;
import com.vk.api.sdk.objects.groups.responses.GetLongPollServerResponse; import com.vk.api.sdk.objects.groups.responses.GetLongPollServerResponse;
import lombok.extern.log4j.Log4j; import lombok.extern.log4j.Log4j;
import org.sadtech.vkbot.ResponsibleData; import org.sadtech.vkbot.listener.EventListenable;
import org.sadtech.vkbot.listener.data.ResponsibleData;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Log4j @Log4j
@Service @Component
public class EventListenerVk implements EventListenable, Runnable { public class EventListenerVk implements EventListenable {
private VkApiClient vk; private VkApiClient vk;
private GroupActor actor; private GroupActor actor;
@ -34,41 +33,28 @@ public class EventListenerVk implements EventListenable, Runnable {
longPoll = new LongPoll(vk); longPoll = new LongPoll(vk);
} }
public void run() {
try {
listen();
} catch (ClientException e) {
e.printStackTrace();
} catch (ApiException e) {
e.printStackTrace();
}
}
private void initServer() throws ClientException, ApiException { private void initServer() throws ClientException, ApiException {
server = vk.groups().getLongPollServer(actor).execute(); server = vk.groups().getLongPollServer(actor).execute();
String key = server.getKey(); String key = server.getKey();
String serverUrl = server.getServer(); String serverUrl = server.getServer();
Integer ts = server.getTs(); Integer ts = server.getTs();
longPoll = new LongPoll(vk); longPoll = new LongPoll(vk);
longPollEventsQuery = longPoll.getEvents(serverUrl, key, ts).waitTime(20); longPollEventsQuery = longPoll.getEvents(serverUrl, key, ts).waitTime(20);
} }
@Async @Async
@PostConstruct
public void listen() throws ClientException, ApiException { public void listen() throws ClientException, ApiException {
initServer(); initServer();
do { do {
GetLongPollEventsResponse eventsResponse; GetLongPollEventsResponse eventsResponse;
eventsResponse = longPollEventsQuery.execute(); eventsResponse = longPollEventsQuery.execute();
log.info(eventsResponse);
if (eventsResponse.getUpdates().toArray().length != 0) { if (eventsResponse.getUpdates().toArray().length != 0) {
responseData.add(eventsResponse.getUpdates().get(0));
//responseData.setJsonObjects(eventsResponse.getUpdates()); // log.info(eventsResponse.getUpdates());
log.info(eventsResponse.getUpdates());
} }
longPollEventsQuery = longPoll.getEvents(server.getServer(), server.getKey(), eventsResponse.getTs()).waitTime(20); longPollEventsQuery = longPoll.getEvents(server.getServer(), server.getKey(), eventsResponse.getTs()).waitTime(20);
} while (true); } while (true);
} }
} }