GET products/_search
{
"query": {
"multi_match" : {
"query": "novel",
"fields": [ "description", "name","id" ,"price"]
}
}
}
This query i want to fire on my spring boot application to search keyword searching
This is my conreoller class which function i will use
package com.pixelTrice.elastic.search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
#RestController
public class ElasticSearchController {
#Autowired
private ElasticSearchQuery elasticSearchQuery;
#PostMapping("/createOrUpdateDocument")
public ResponseEntity<Object> createOrUpdateDocument(#RequestBody Product product) throws IOException {
String response = elasticSearchQuery.createOrUpdateDocument(product);
return new ResponseEntity<>(response, HttpStatus.OK);
}
#GetMapping("/getDocument")
public ResponseEntity<Object> getDocumentById(#RequestParam String productId) throws IOException {
Product product = elasticSearchQuery.getDocumentById(productId);
return new ResponseEntity<>(product, HttpStatus.OK);
}
#DeleteMapping("/deleteDocument")
public ResponseEntity<Object> deleteDocumentById(#RequestParam String productId) throws IOException {
String response = elasticSearchQuery.deleteDocumentById(productId);
return new ResponseEntity<>(response, HttpStatus.OK);
}
#GetMapping("/searchDocument")
public ResponseEntity<Object> searchAllDocument() throws IOException {
List<Product> products = elasticSearchQuery.searchAllDocuments();
return new ResponseEntity<>(products, HttpStatus.OK);
}
#GetMapping("/searching")
public ResponseEntity<Object> searching() throws IOException{
List<Product> products = elasticSearchQuery.searching();
return new ResponseEntity<>(products,HttpStatus.OK);
}
}
This is my query class as I want to to write java query:
package com.pixelTrice.elastic.search;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.Hit;
import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Repository;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
#Repository
public class ElasticSearchQuery {
#Autowired
private ElasticsearchClient elasticsearchClient;
private final String indexName = "products";
public String createOrUpdateDocument(Product product) throws IOException {
IndexResponse response = elasticsearchClient.index(i -> i
.index(indexName)
.id(product.getId())
.document(product)
);
if (response.result().name().equals("Created")) {
return new StringBuilder("Document has been successfully created.").toString();
} else if (response.result().name().equals("Updated")) {
return new StringBuilder("Document has been successfully updated.").toString();
}
return new StringBuilder("Error while performing the operation.").toString();
}
public Product getDocumentById(String productId) throws IOException {
Product product = null;
GetResponse<Product> response = elasticsearchClient.get(g -> g
.index(indexName)
.id(productId),
Product.class
);
if (response.found()) {
product = response.source();
System.out.println("Product name " + product.getName());
} else {
System.out.println("Product not found");
}
return product;
}
public String deleteDocumentById(String productId) throws IOException {
DeleteRequest request = DeleteRequest.of(d -> d.index(indexName).id(productId));
DeleteResponse deleteResponse = elasticsearchClient.delete(request);
if (Objects.nonNull(deleteResponse.result()) && !deleteResponse.result().name().equals("NotFound")) {
return new StringBuilder("Product with id " + deleteResponse.id() + " has been deleted.").toString();
}
System.out.println("Product not found");
return new StringBuilder("Product with id " + deleteResponse.id() + " does not exist.").toString();
}
public List<Product> searchAllDocuments() throws IOException {
SearchRequest searchRequest = SearchRequest.of(s -> s.index(indexName));
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Product.class);
List<Hit> hits = searchResponse.hits().hits();
List<Product> products = new ArrayList<>();
for (Hit object : hits) {
System.out.print(((Product) object.source()));
products.add((Product) object.source());
}
return products;
}
public List<Product> searching() throws IOException{
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(indexName);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
QueryBuilder cluase0 = QueryBuilders.multiMatchQuery(queryString,
"name",
"id",
"description",
"price");
MultiMatchQueryBuilder multiMatchQueryBuilder1 = new MultiMatchQueryBuilder(queryString, "firstName", "lastName",
"password", "emailId", "userId", "mobileNumber");
multiMatchQueryBuilder1.operator(Operator.AND);
searchSourceBuilder.query(multiMatchQueryBuilder1);
}
GET products/_search
{
"query": {
"multi_match" : {
"query": "novel",
"fields": [ "description", "name","id" ,"price"]
}
}
}
i tried this on kibana and get my desired keyword search on "novel" it showed me my desired result now i want to convert this into java api but couldnot think how can i write its sysntax on java
SearchRequest searchRequest = SearchRequest.of(s -> s.index("products").from(from).size(size).query(q -> q.multiMatch(
t -> t .fields("description","name").query(text)))
);
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Product.class);
List<Hit> hits = searchResponse.hits().hits();
List<Product> products = new ArrayList<>();
for(Hit object : hits){
products.add(p);
}
Related
Scenario: a Spring WebFlux triggering CommandLineRunner.run in order to load data to MongoDb for testing purpose.
Goal: when starting the microservice locally it is aimed to read a json file and load documents to MongDb.
Personal knowledge: "bufferedReader.lines().filter(l -> !l.trim().isEmpty()" reads each json node and return it as stream. Then I can map it to "l" and access the get methods. I guess I don't have to create a list and then stream it since I have already load it as stream by "new InputStreamReader(getClass().getClassLoader().getResourceAsStream()" and I assume I can use lines() since it node will result in a string line. Am I in right direction or I am messing up some idea?
This is a json sample file:
{
"Extrato": {
"description": "credit",
"value": "R$1.000,00",
"status": 11
},
"Extrato": {
"description": "debit",
"value": "R$2.000,00",
"status": 99
}
}
model
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Extrato {
#Id
private String id;
private String description;
private String value;
private Integer status;
public Extrato(String id, String description, String value, Integer status) {
super();
this.id = id;
this.description = description;
this.value = value;
this.status = status;
}
... getters and setter accordinly
Repository
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import com.noblockingcase.demo.model.Extrato;
import reactor.core.publisher.Flux;
import org.springframework.data.domain.Pageable;
public interface ExtratoRepository extends ReactiveCrudRepository<Extrato, String> {
#Query("{ id: { $exists: true }}")
Flux<Extrato> retrieveAllExtratosPaged(final Pageable page);
}
command for loading from above json file
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.noblockingcase.demo.model.Extrato;
import com.noblockingcase.demo.repository.ExtratoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
#Component
public class TestDataLoader implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(TestDataLoader.class);
private ExtratoRepository extratoRepository;
TestDataLoader(final ExtratoRepository extratoRepository) {
this.extratoRepository = extratoRepository;
}
#Override
public void run(final String... args) throws Exception {
if (extratoRepository.count().block() == 0L) {
final LongSupplier longSupplier = new LongSupplier() {
Long l = 0L;
#Override
public long getAsLong() {
return l++;
}
};
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(getClass().getClassLoader().getResourceAsStream("carga-teste.txt")));
//*** THE ISSUE IS NEXT LINE
Flux.fromStream(bufferedReader.lines().filter(l -> !l.trim().isEmpty())
.map(l -> extratoRepository.save(new Extrato(String.valueOf(longSupplier.getAsLong()),
l.getDescription(), l.getValue(), l.getStatus()))))
.subscribe(m -> log.info("Carga Teste: {}", m.block()));
}
}
}
Here is the MongoDb config althought I don't think it is relevant
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mongodb.MongoClientOptions;
#Configuration
public class MongoDbSettings {
#Bean
public MongoClientOptions mongoOptions() {
return MongoClientOptions.builder().socketTimeout(2000).build();
}
}
If I tried my original code and adjust it for reading a text file I can successfully read text file instead of json. Obvisouly it doesn't fit my demand since I want read json file. By the way, it can clarify a bit more where I am blocked.
load-test.txt (available in https://github.com/jimisdrpc/webflux-worth-scenarious/blob/master/demo/src/main/resources/carga-teste.txt)
crédito de R$1.000,00
débito de R$100,00
snippet code working with simple text file
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(getClass().getClassLoader().getResourceAsStream("carga-teste.txt")));
Flux.fromStream(bufferedReader.lines().filter(l -> !l.trim().isEmpty())
.map(l -> extratoRepository
.save(new Extrato(String.valueOf(longSupplier.getAsLong()), "Qualquer descrição", l))))
.subscribe(m -> log.info("Carga Teste: {}", m.block()));
Whole project working succesfully reading from text file: https://github.com/jimisdrpc/webflux-worth-scenarious/tree/master/demo
Docker compose for booting MongoDb https://github.com/jimisdrpc/webflux-worth-scenarious/blob/master/docker-compose.yml
To summarize, my issue is: I didn't figure out how read a json file and insert the data into MongoDb during CommandLineRunner.run()
I found an example with Flux::using Flux::fromStream to be helpful for this purpose. This will read your file into a Flux and then you can subscribe to and process with .flatmap or something. From the Javadoc
using(Callable resourceSupplier, Function> sourceSupplier, Consumer resourceCleanup)
Uses a resource, generated by a supplier for each individual Subscriber, while streaming the values from a Publisher derived from the same resource and makes sure the resource is released if the sequence terminates or the Subscriber cancels.
and the code that I put together:
private static Flux<Account> fluxAccounts() {
return Flux.using(() ->
new BufferedReader(new InputStreamReader(new ClassPathResource("data/ExportCSV.csv").getInputStream()))
.lines()
.map(s->{
String[] sa = s.split(" ");
return Account.builder()
.firstname(sa[0])
.lastname(sa[1])
.build();
}),
Flux::fromStream,
BaseStream::close
);
}
Please note your json is invalid. Text data is not same as json. Json needs a special handling so always better to use library.
carga-teste.json
[
{"description": "credit", "value": "R$1.000,00", "status": 11},
{"description": "debit","value": "R$2.000,00", "status": 99}
]
Credits goes to article here - https://www.nurkiewicz.com/2017/09/streaming-large-json-file-with-jackson.html.
I've adopted to use Flux.
#Override
public void run(final String... args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(getClass().getClassLoader().getResourceAsStream("carga-teste.json")));
ObjectMapper mapper = new ObjectMapper();
Flux<Extrato> flux = Flux.generate(
() -> parser(bufferedReader, mapper),
this::pullOrComplete,
jsonParser -> {
try {
jsonParser.close();
} catch (IOException e) {}
});
flux.map(l -> extratoRepository.save(l)).subscribe(m -> log.info("Carga Teste: {}", m.block()));
}
}
private JsonParser parser(Reader reader, ObjectMapper mapper) {
JsonParser parser = null;
try {
parser = mapper.getFactory().createParser(reader);
parser.nextToken();
} catch (IOException e) {}
return parser;
}
private JsonParser pullOrComplete(JsonParser parser, SynchronousSink<Extrato> emitter) {
try {
if (parser.nextToken() != JsonToken.END_ARRAY) {
Extrato extrato = parser.readValueAs(Extrato.class);
emitter.next(extrato);
} else {
emitter.complete();
}
} catch (IOException e) {
emitter.error(e);
}
return parser;
}
I have myBatis setup for my account. This by using the migrate command in the command line (in Jenkins). Now I want to integrate this with the application itself (Spring boot). Currently I have different sql files with #Undo and up sql code.
So When I start the Sping boot application I want to run the migrate up command without changing the sql files that I already have? Is this possible in MyBatis and Spring?
This is about MyBatis-Migrations, right?
Spring Boot does not provide out-of-box support, however, it seems to be possible to write a custom DatabasePopulator.
Here is a simple implementation.
It uses Migrations' Runtime Migration feature.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.TreeSet;
import java.util.stream.Collectors;
import javax.sql.DataSource;
import org.apache.ibatis.migration.Change;
import org.apache.ibatis.migration.DataSourceConnectionProvider;
import org.apache.ibatis.migration.MigrationException;
import org.apache.ibatis.migration.MigrationLoader;
import org.apache.ibatis.migration.MigrationReader;
import org.apache.ibatis.migration.operations.UpOperation;
import org.apache.ibatis.migration.options.DatabaseOperationOption;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ScriptException;
import org.springframework.jdbc.datasource.init.UncategorizedScriptException;
#Configuration
public class MyBatisMigrationsConfig {
private static final String scriptsDir = "scripts";
private static final String changelogTable = "changelog";
#Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
Properties properties = new Properties();
properties.setProperty("changelog", changelogTable);
DatabaseOperationOption options = new DatabaseOperationOption();
options.setChangelogTable(changelogTable);
MyBatisMigrationsPopulator populator = new MyBatisMigrationsPopulator(dataSource, scriptsDir, properties, options,
new PathMatchingResourcePatternResolver());
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource);
dataSourceInitializer.setDatabasePopulator(populator);
return dataSourceInitializer;
}
private static class MyBatisMigrationsPopulator implements DatabasePopulator {
private final DataSource dataSource;
private final String scriptsDir;
private final Properties properties;
private final DatabaseOperationOption options;
private final ResourcePatternResolver resourcePatternResolver;
public MyBatisMigrationsPopulator(DataSource dataSource, String scriptsDir,
Properties properties, DatabaseOperationOption options, ResourcePatternResolver resourcePatternResolver) {
super();
this.dataSource = dataSource;
this.scriptsDir = scriptsDir;
this.properties = properties;
this.options = options;
this.resourcePatternResolver = resourcePatternResolver;
}
public void populate(Connection connection) throws SQLException, ScriptException {
try {
new UpOperation().operate(new DataSourceConnectionProvider(dataSource),
createMigrationsLoader(), options, System.out);
} catch (MigrationException e) {
throw new UncategorizedScriptException("Migration failed.", e.getCause());
}
}
protected MigrationLoader createMigrationsLoader() {
return new SpringMigrationLoader(resourcePatternResolver, scriptsDir, "utf-8", properties);
}
}
private static class SpringMigrationLoader implements MigrationLoader {
protected static final String BOOTSTRAP_SQL = "bootstrap.sql";
protected static final String ONABORT_SQL = "onabort.sql";
private ResourcePatternResolver resourcePatternResolver;
private String path;
private String charset;
private Properties properties;
public SpringMigrationLoader(
ResourcePatternResolver resourcePatternResolver,
String path,
String charset,
Properties properties) {
this.resourcePatternResolver = resourcePatternResolver;
this.path = path;
this.charset = charset;
this.properties = properties;
}
#Override
public List<Change> getMigrations() {
Collection<String> filenames = new TreeSet<>();
for (Resource res : getResources("/*.sql")) {
filenames.add(res.getFilename());
}
filenames.remove(BOOTSTRAP_SQL);
filenames.remove(ONABORT_SQL);
return filenames.stream()
.map(this::parseChangeFromFilename)
.collect(Collectors.toList());
}
#Override
public Reader getScriptReader(Change change, boolean undo) {
try {
return getReader(change.getFilename(), undo);
} catch (IOException e) {
throw new MigrationException("Failed to read bootstrap script.", e);
}
}
#Override
public Reader getBootstrapReader() {
try {
return getReader(BOOTSTRAP_SQL, false);
} catch (FileNotFoundException e) {
// ignore
} catch (IOException e) {
throw new MigrationException("Failed to read bootstrap script.", e);
}
return null;
}
#Override
public Reader getOnAbortReader() {
try {
return getReader(ONABORT_SQL, false);
} catch (FileNotFoundException e) {
// ignore
} catch (IOException e) {
throw new MigrationException("Failed to read onabort script.", e);
}
return null;
}
protected Resource getResource(String pattern) {
return this.resourcePatternResolver.getResource(this.path + "/" + pattern);
}
protected Resource[] getResources(String pattern) {
try {
return this.resourcePatternResolver.getResources(this.path + pattern);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
protected Change parseChangeFromFilename(String filename) {
try {
String name = filename.substring(0, filename.lastIndexOf("."));
int separator = name.indexOf("_");
BigDecimal id = new BigDecimal(name.substring(0, separator));
String description = name.substring(separator + 1).replace('_', ' ');
Change change = new Change(id);
change.setFilename(filename);
change.setDescription(description);
return change;
} catch (Exception e) {
throw new MigrationException("Error parsing change from file. Cause: " + e, e);
}
}
protected Reader getReader(String fileName, boolean undo) throws IOException {
InputStream inputStream = getResource(fileName).getURL().openStream();
return new MigrationReader(inputStream, charset, undo, properties);
}
}
}
Here is an executable demo project.
You may need to modify the datasource settings in application.properties.
Hope this helps!
For Spring:
import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.migration.ConnectionProvider;
import org.apache.ibatis.migration.FileMigrationLoader;
import org.apache.ibatis.migration.operations.UpOperation;
import org.apache.ibatis.migration.options.DatabaseOperationOption;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ScriptException;
#Configuration
public class MyBatisMigrationRuntimeConfiguration {
private static final String CHANGELOG_TABLE = "changelog";
private static final String MIGRATION_SCRIPTS = "migration/scripts";
#Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource);
dataSourceInitializer.setDatabasePopulator(new Populator());
return dataSourceInitializer;
}
private DatabaseOperationOption getOption() {
DatabaseOperationOption options = new DatabaseOperationOption();
options.setChangelogTable(CHANGELOG_TABLE);
return options;
}
private Properties getProperties() {
Properties properties = new Properties();
properties.setProperty("changelog", CHANGELOG_TABLE);
return properties;
}
private File getScriptDir() {
URL url = getClass().getClassLoader().getResource(MIGRATION_SCRIPTS);
if (url == null) {
throw new IllegalArgumentException("file is not found!");
} else {
return new File(url.getFile());
}
}
private class Populator implements DatabasePopulator {
#Override
public void populate(Connection connection) throws SQLException, ScriptException {
new UpOperation().operate(
new SimplyConnectionProvider(connection),
new FileMigrationLoader(getScriptDir(), "utf-8", getProperties()),
getOption(),
System.out
);
}
}
private static class SimplyConnectionProvider implements ConnectionProvider {
private final Connection connection;
public SimplyConnectionProvider(Connection connection) {
this.connection = connection;
}
public Connection getConnection() {
return connection;
}
}
}
I am working on a web dev project right now using netbeans 8.2 + glassfish 4.1
My code seems to be good since it is not showing any type of errors. However, when I try to run it and I paste the code in google postman my response look like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<clubss></clubss>
Just to make sure, my project is on football teams. I currently have a table with 3 team only, just to keep it short. A weird thing that I noticed is the last line - "clubss". I searched through my code and could not find the word "clubss" anywhere - I do have loats of "club" + "clubs" but nowhere a "clubss".
However, most important thing to me at the moment is to get the whole thing running and to display the 3 teams in postman.
If you require any code just let me know. I did not paste them in in the first place because
a) it might turned out it is not needed
b) they are fairly long and it would make the post look bad.
However if you do need it I will update it immediately.
Thanks in advance, any help appreciated. UPDATE
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name="clubs")
// define the field order
#XmlType(propOrder={"id", "name", "year", "country", "league",
"picture", "description"})
public class Clubs {
private int id;
private String name, year, country, league, picture, description;
// JAXB requires a default ctor
public Clubs(){
}
public Clubs(int id, String name, String year, String country, String league, String picture, String description) {
this.id = id;
this.name = name;
this.country = country;
this.year = year;
this.league = league;
this.picture = picture;
this.description = description;
}
#XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
#XmlElement
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#XmlElement
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
#XmlElement
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
#XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Clubs{" + "id=" + id + ", name=" + name + ", country=" + country + ", league=" + league + ", year=" + year + ", picture=" + picture + ", description=" + description + '}';
}
}
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClubsDAO {
private Connection con = null;
public static void main(String[] args) {
ClubsDAO dao = new ClubsDAO();
int nextId = dao.getNextClubId();
System.out.println(nextId);
}
public ClubsDAO() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/CD_WD3_DB",
"sean", "sean");
System.out.println("OK");
} catch (ClassNotFoundException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("ClassNotFoundException");
ex.printStackTrace();
} catch (SQLException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
}
public int updateClubs(Clubs clubs){
int rowsUpdated=0;
try{
PreparedStatement ps = con.prepareStatement(
"UPDATE APP.CLUB SET NAME=?, YR=?, COUNTRY=?,"
+ "LEAGUE=?, DESCRIPTION=?, PICTURE=? WHERE "
+ "ID = ?");
ps.setString(1, clubs.getName());
ps.setString(2, clubs.getYear());
ps.setString(4, clubs.getCountry());
ps.setString(5, clubs.getLeague());
ps.setString(6, clubs.getDescription());
ps.setString(7, clubs.getPicture());
ps.setInt(8, clubs.getId());
rowsUpdated = ps.executeUpdate();
}catch (Exception e){
System.err.println("Exception in executeUpdate()");
e.printStackTrace();
return -1;
}
return rowsUpdated;// 1
}
public int addClubs(Clubs clubs){
int numRowsInserted=0;
try{
PreparedStatement ps = con.prepareStatement(
"INSERT INTO APP.CLUB " // CLUBS??
+ "(ID, NAME, YR, COUNTRY, "
+ "LEAGUE, DESCRIPTION, PICTURE) "
+ "VALUES (?,?,?,?,?,?,?)");
ps.setString(1, clubs.getName());
ps.setString(2, clubs.getYear());
ps.setString(4, clubs.getCountry());
ps.setString(5, clubs.getLeague());
ps.setString(6, clubs.getDescription());
ps.setString(7, clubs.getPicture());
ps.setInt(8, clubs.getId());
numRowsInserted = ps.executeUpdate();
}catch (Exception e){
e.printStackTrace();
return -1;
}
return numRowsInserted;
}
public int getNextClubId(){
int nextClubId = -1;
try{
PreparedStatement ps =
con.prepareStatement(
"SELECT MAX(ID) AS MAX_ID FROM APP.CLUB");
ResultSet rs = ps.executeQuery();
if(!rs.next()){ // set the db cursor
return -1;
}
nextClubId = rs.getInt("MAX_ID") + 1;
}catch(Exception e){
e.printStackTrace();
return -1;
}
return nextClubId;
}
public List<Clubs> findAll() {
List<Clubs> list
= new ArrayList<>();
try {
PreparedStatement pstmt
= con.prepareStatement("SELECT * FROM APP.CLUB ORDER BY ID");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
return list;
}
public Clubs processRow(ResultSet rs) throws SQLException {
Clubs clubs = new Clubs();
clubs.setId(rs.getInt("id"));
clubs.setName(rs.getString("name"));
clubs.setCountry(rs.getString("country"));
clubs.setLeague(rs.getString("league"));
clubs.setYear(rs.getString("yr"));
clubs.setPicture(rs.getString("picture"));
clubs.setDescription(rs.getString("description"));
return clubs;
}
public Clubs findById(int clubId) {
Clubs club = null;
try {
PreparedStatement pstmt
= con.prepareStatement("SELECT * FROM APP.CLUB WHERE ID=?");
pstmt.setInt(1, clubId);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) { // !F => T
return null;
}
// we have a record
club = processRow(rs);
} catch (SQLException ex) {
//Logger.getLogger(ClubDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
return club;
}
public List<Clubs> findByName(String name) {
List<Clubs> list
= new ArrayList<Clubs>();
try {
PreparedStatement pstmt
= con.prepareStatement(
"SELECT * FROM APP.CLUB "
+ "WHERE UPPER(NAME) "
+ "LIKE ? ORDER BY NAME");
pstmt.setString(1, "%" + name.toUpperCase() + "%");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return list;
}
public int deleteById(int clubId){
int numRowsDeleted=0;
try{
PreparedStatement pstmt =
con.prepareStatement("DELETE FROM APP.CLUB WHERE ID=?");
pstmt.setInt(1, clubId);
numRowsDeleted = pstmt.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}
return numRowsDeleted; // 0 == failure; 1 == success
}
public int deleteAllClubs(){
int result=0;
try{
PreparedStatement pstmt =
con.prepareStatement("DELETE FROM APP.CLUB");
result = pstmt.executeUpdate(); // 0 == failure; >=1 == success
}catch (Exception e){
e.printStackTrace();
}
return result; // 0 == failure; >=1 == success
}
}
package rest.clubs;
// link into JAX-RS
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/rest")
public class RestConfig extends Application{
#Override
public Set<Class<?>> getClasses(){
final Set<Class<?>> classes =
new HashSet<Class<?>>();
classes.add(ClubsResource.class);
return classes;
}
}
package rest.clubs;
import dao.Clubs;
import dao.ClubsDAO;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
#Path("/clubs")
public class ClubsResource {
// this class responds to ".../rest/clubs"
private static ClubsDAO dao = new ClubsDAO();
#Context
private UriInfo context;
public ClubsResource() {
}
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getAllClubs() {
System.out.println("get all");
List<Clubs> clubList
= dao.findAll();
GenericEntity<List<Clubs>> entity;
entity = new GenericEntity<List<Clubs>>(clubList) {
};
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(entity)
.build();
}
#POST
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response addClubs(Clubs newClubs) {
System.out.println("POST - " + newClubs);
// the 'id' field in the request entity body is ignored!
int nextClubId = dao.getNextClubId();
newClubs.setId(nextClubId);
System.out.println("POST: nextClubId == " + nextClubId);
// now, our Clubobject is set up; insert into db
dao.addClubs(newClubs);
// now set up the HTTP response as per the HTTP spec
return Response
.status(Response.Status.CREATED)
.header("Location",
String.format("%s%s",
context.getAbsolutePath().toString(),
newClubs.getId()))
.header("Access-Control-Allow-Origin", "*")
.entity(newClubs)
.build();
}
#OPTIONS
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response optionsForAllClubs() {
System.out.println("OPTIONS for all");
// what is the verb set for this URI?
// what is the API supported?
Set<String> api = new TreeSet<>();
api.add("GET");// get all
api.add("POST");// add
api.add("DELETE");// delete all
api.add("HEAD");// get with no entity body
return Response
.noContent()
.allow(api)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
#OPTIONS
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response optionsForOneClub() {
System.out.println("OPTIONS for one");
// what is the verb set for this URI?
// what is the API supported?
Set<String> api = new TreeSet<>();
api.add("GET");// get one
api.add("PUT");// update (or add)
api.add("DELETE");// delete one
api.add("HEAD");// get with no entity body
return Response
.noContent()
.allow(api)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "DELETE, PUT, GET")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
#PUT
#Path("{clubId}")
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response updateOneClub(Clubs updateClub, #PathParam("clubId") int clubId) {
System.out.println("PUT - " + updateClub);
if (clubId == updateClub.getId()) {
// entity body id == id in URI
if (dao.findById(clubId) == null) {
// id not in db, create
dao.addClubs(updateClub);
// now set up the HTTP response as per the HTTP spec
return Response
.status(Response.Status.CREATED)
.header("Location",context.getAbsolutePath().toString())
.header("Access-Control-Allow-Origin", "*")
.entity(updateClub)
.build();
} else {
// id in db, update
dao.updateClubs(updateClub);
return Response
.status(Response.Status.OK)
.entity(updateClub)
.build();
}
} else {
// id in xml <> id in URI
return Response
.status(Response.Status.CONFLICT)
.entity("<conflict idInURI='"+clubId+"' idInEntityBody='"+updateClub.getId()+"' />")
.build();
}
}
#HEAD
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response headerForAllClubs() {
System.out.println("HEAD");
return Response
.noContent()
.build();
}
#HEAD
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response headerForOneClub(#PathParam("clubId") String clubId) {
return Response
.noContent()
.build();
}
#DELETE
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response deleteAllClubs() {
System.out.println("delete all");
int rowsDeleted = dao.deleteAllClubs();
if (rowsDeleted > 0) { // success
// now set up the HTTP response message
return Response
.noContent()
.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*")
.build();
} else {
// error
return Response
.status(Response.Status.NOT_FOUND)
.entity("<error rowsDeleted='" + rowsDeleted + "' />")
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
#GET
#Path("{clubId}")
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getOneClub(#PathParam("clubId") String clubId) {
System.out.println("getOneClub::" + clubId);
Clubs club
= dao.findById(Integer.parseInt(clubId));
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(club)
.build();
}
#GET
#Path("search/{name}") // /clubs/search/Real
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getByName(#PathParam("name") String name) {
System.out.println("getByName: " + name);
List<Clubs> clubList
= dao.findByName(name);
GenericEntity<List<Clubs>> entity;
entity = new GenericEntity<List<Clubs>>(clubList) {
};
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(entity)
.build();
}
#DELETE
#Path("{clubId}") // Path Param i.e. /clubs/1
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response deleteOneClub(#PathParam("clubId") String clubId) {
System.out.println("deleteOneClub(): " + clubId);
// delete the row from the db where the id={clubId}
int numRowsDeleted = dao.deleteById(Integer.parseInt(clubId));
if (numRowsDeleted == 1) { // success
return Response
.noContent()
.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*")
.build();
} else {// error
return Response
.status(Response.Status.NOT_FOUND)
.entity("<idNotInDB id='" + clubId + "' />")
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
}
I have put a GWT-CellTree in a DataGrid. It works except for one thing: When clicking on the tree-expand-icon, nothing happens. I have tried to minimize the
code needed to reproduce the problem...
How can this be fixed ?
best regards, Magnus
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
DataGrid grid= (DataGrid) new NodesGrid().getTable();
grid.setWidth("100%");
SimpleLayoutPanel slp = new SimpleLayoutPanel();
slp.add(grid);
RootLayoutPanel.get().add(slp);
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.view.client.ListDataProvider;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
public class NodesGrid {
private AbstractCellTable<Node> table = new DataGrid<>();
private Column nameColumn;
private Column<Node, String> showBlocksColumn;
private final Set<Integer> showBlocks = new HashSet<>();
public Column getNameColumn() {
return nameColumn;
}
public AbstractCellTable<Node> getTable() {
return table;
}
public NodesGrid() {
table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
table.setWidth("100%");
CustomCellTableBuilder c = new CustomCellTableBuilder(this, table);
table.setTableBuilder(c);
Node nodes = new Node();
nodes.setName("hello");
nodes.setId(123);
Node n2 = new Node();
n2.setName("testing");
nodes.getBlocks().add(n2);
ListDataProvider<Node> dataProvider = new ListDataProvider<>();
dataProvider.addDataDisplay(table);
List<Node> list = dataProvider.getList();
list.add(nodes);
addShowBlocks();
nameColumn = getSorter(list, "Name", Comparator.comparing(Node::getName), Node::getName);
}
private Column getSorter(List<Node> list,
String name,
Comparator<Node> cmp,
Function<Node, String> supplier) {
TextColumn<Node> column = new TextColumn<Node>() {
#Override
public String getValue(Node object) {
return supplier.apply(object);
}
};
table.addColumn(column, name);
column.setSortable(true);
ColumnSortEvent.ListHandler<Node> columnSortHandler = new ColumnSortEvent.ListHandler<>(list);
columnSortHandler.setComparator(column, cmp);
table.addColumnSortHandler(columnSortHandler);
table.getColumnSortList().push(column);
return column;
}
public Column<Node, String> getShowBlocksColumn() {
return showBlocksColumn;
}
public Set<Integer> getShowBlocks() {
return showBlocks;
}
void addShowBlocks() {
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
#Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("(<a href=\"javascript:;\">").appendEscaped(object)
.appendHtmlConstant("</a>)");
return sb.toSafeHtml();
}
};
showBlocksColumn = new Column<Node, String>(new ClickableTextCell(anchorRenderer)) {
#Override
public String getValue(Node node) {
if (showBlocks.contains(node.getId())) {
return "hide blocks";
} else {
return "show blocks";
}
}
};
showBlocksColumn.setFieldUpdater(new FieldUpdater<Node, String>() {
#Override
public void update(int index, Node node, String value) {
if (showBlocks.contains(node.getId())) {
showBlocks.remove(node.getId());
} else {
showBlocks.add(node.getId());
}
table.redrawRow(index);
}
});
table.addColumn(showBlocksColumn);
table.setColumnWidth(0, 10, Style.Unit.EM);
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TreeNode;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;
import java.util.ArrayList;
import java.util.List;
public class NodesTree {
private CellTree tree;
public NodesTree(Node node) {
TreeViewModel model = new CustomTreeModel(node);
tree = new CellTree(model, null);
tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
TreeNode rootNode = tree.getRootTreeNode();
openAll(rootNode);
}
private static class TopLevel {
private final String name;
private List<Node> blocks = new ArrayList<>();
public TopLevel(String name) {
this.name = name;
}
public TopLevel(String name, List<Node> blocks) {
this.name = name;
this.blocks = blocks;
}
public String getName() {
return name;
}
public List<Node> getBlocks() {
return blocks;
}
}
private static class CustomTreeModel implements TreeViewModel {
private final List<TopLevel> topLevels;
private final SingleSelectionModel<String> selectionModel
= new SingleSelectionModel<>();
public CustomTreeModel(Node node) {
topLevels = new ArrayList<>();
{
TopLevel blocksNode = new TopLevel("Blocks", new ArrayList(node.getBlocks()));
topLevels.add(blocksNode);
}
{
TopLevel outgoing = new TopLevel("Outgoing");
topLevels.add(outgoing);
}
{
TopLevel incoming = new TopLevel("Incoming");
topLevels.add(incoming);
}
}
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
// LEVEL 0.
ListDataProvider<TopLevel> dataProvider
= new ListDataProvider<>(
topLevels);
Cell<TopLevel> cell = new AbstractCell<TopLevel>() {
#Override
public void render(Context context, TopLevel value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(value.getName());
}
};
return new DefaultNodeInfo<>(dataProvider, cell);
} else if (value instanceof TopLevel) {
// LEVEL 1.
ListDataProvider<Node> dataProvider = new ListDataProvider<>(((TopLevel) value).getBlocks());
Cell<Node> cell = new AbstractCell<Node>() {
#Override
public void render(Context context, Node value, SafeHtmlBuilder sb) {
if (value != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped("(" + value.getName() + ")");
}
}
};
return new DefaultNodeInfo<>(dataProvider, cell);
} else if (value instanceof Node) {
// LEVEL 2 - LEAF.
String params = "test";
ArrayList<String> str = new ArrayList<>();
str.add(params);
ListDataProvider<String> dataProvider = new ListDataProvider<>(str);
return new DefaultNodeInfo<>(dataProvider, new TextCell(), selectionModel, null);
}
return null;
}
public boolean isLeaf(Object value) {
if (value instanceof String) {
return true;
}
return false;
}
}
private void openAll(TreeNode rootNode) {
if (rootNode == null) return;
for (int i = 0; i < rootNode.getChildCount(); i++) {
TreeNode node = rootNode.setChildOpen(i, true);
openAll(node);
}
}
public Widget getWidget() {
return tree;
}
}
package com.raybased.gwt.configtool.client.grid;
import com.google.gwt.dom.builder.shared.DivBuilder;
import com.google.gwt.dom.builder.shared.TableCellBuilder;
import com.google.gwt.dom.builder.shared.TableRowBuilder;
import com.google.gwt.dom.client.Style;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.AbstractCellTable;
import com.google.gwt.user.cellview.client.AbstractCellTableBuilder;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.view.client.SelectionModel;
public class CustomCellTableBuilder extends AbstractCellTableBuilder<Node> {
NodesGrid nodesGrid;
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
/**
* Construct a new table builder.
*
* #param cellTable the table this builder will build rows for
*/
public CustomCellTableBuilder(NodesGrid nodesGrid, AbstractCellTable<Node> cellTable) {
super(cellTable);
this.nodesGrid = nodesGrid;
AbstractCellTable.Style style = cellTable.getResources().style();
rowStyle = style.evenRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell() + " " + style.evenRowCell();
selectedCellStyle = " " + style.selectedRowCell();
}
#Override
protected void buildRowImpl(Node rowValue, int absRowIndex) {
// Calculate the row styles.
SelectionModel<? super Node> selectionModel = cellTable.getSelectionModel();
boolean isSelected =
(selectionModel == null || rowValue == null) ? false : selectionModel
.isSelected(rowValue);
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
buildRow(row, rowValue, cellStyles, nodesGrid.getShowBlocksColumn());
buildRow(row, rowValue, cellStyles, nodesGrid.getNameColumn());
row.endTR();
if (nodesGrid.getShowBlocks().contains(rowValue.getId())) {
buildBlockRow(rowValue, cellStyles);
}
}
void buildRow(TableRowBuilder row, Node rowValue, String cellStyles, Column column) {
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
renderCell(td, createContext(0), column, rowValue);
td.endTD();
}
private void buildBlockRow(Node rowValue, String cellStyles) {
TableRowBuilder row = startRow();
buildCell(rowValue, cellStyles, row);
row.endTR();
}
private void buildCell(Node rowValue, String cellStyles, TableRowBuilder row) {
NodesTree hw = new NodesTree(rowValue);
TableCellBuilder td = row.startTD().colSpan(5);
td.className(cellStyles);
DivBuilder div = td.startDiv();
String t = hw.getWidget().getElement().getInnerHTML();
div.html(SafeHtmlUtils.fromTrustedString(t));
div.end();
td.endTD();
}
}
package com.raybased.gwt.configtool.client.grid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Node implements Serializable {
String name;
List<Node> blocks = new ArrayList<>();
String params;
int id;
public Node() {
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Node> getBlocks() {
return blocks;
}
}
I am trying to extract data from the Samples namespace that comes with Intersystems Cache install. Specifically, I am trying to retrieve Sample.Company global data using XEP. Inorder to achieve this, I created Sample.Company class like this -
package Sample;
public class Company {
public Long id;
public String mission;
public String name;
public Long revenue;
public String taxId;
public Company(Long id, String mission, String name, Long revenue,
String taxId) {
this.id = id;
this.mission = mission;
this.name = name;
this.revenue = revenue;
this.taxId = taxId;
}
public Company() {
}
}
XEP related code looks like this -
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import Sample.Company;
import com.intersys.xep.Event;
import com.intersys.xep.EventPersister;
import com.intersys.xep.EventQuery;
import com.intersys.xep.EventQueryIterator;
import com.intersys.xep.PersisterFactory;
import com.intersys.xep.XEPException;
#Service
public class CompanyService {
public List<Company> fetch() {
EventPersister myPersister = PersisterFactory.createPersister();
myPersister.connect("SAMPLES", "user", "pwd");
try { // delete any existing SingleStringSample events, then import
// new ones
Event.isEvent("Sample.Company");
myPersister.deleteExtent("Sample.Company");
String[] generatedClasses = myPersister.importSchema("Sample.Company");
for (int i = 0; i < generatedClasses.length; i++) {
System.out.println("Event class " + generatedClasses[i]
+ " successfully imported.");
}
} catch (XEPException e) {
System.out.println("import failed:\n" + e);
throw new RuntimeException(e);
}
EventQuery<Company> myQuery = null;
List<Company> list = new ArrayList<Company>();
try {
Event newEvent = myPersister.getEvent("Sample.Company");
String sql = "Select * from Sample.Company";
myQuery = newEvent.createQuery(sql);
newEvent.close();
myQuery.execute();
EventQueryIterator<Company> iterator = myQuery.getIterator();
while (iterator.hasNext()) {
Company c = iterator.next();
System.out.println(c);
list.add(c);
}
myQuery.close();
myPersister.close();
return list;
} catch (XEPException e) {
System.out.println("createQuery failed:\n" + e);
throw new RuntimeException(e);
}
}
}
When I try executing the fetch() method of the above class, I am seeing the following exception -
com.intersys.xep.XEPException: Cannot import - extent for Sample.Company not empty.
at com.intersys.xep.internal.Generator.generate(Generator.java:52)
at com.intersys.xep.EventPersister.importSchema(EventPersister.java:954)
at com.intersys.xep.EventPersister.importSchema(EventPersister.java:363)
I got the simple string example working. Does it mean, we can not read the existing data using XEP? If we can read, Could some please help me in resolving the above issue? Thanks in advance.
You are trying to create a new class named Sample.Company in your instance:
String[] generatedClasses = myPersister.importSchema("Sample.Company");
But you still have data and an existing class there.