I am trying to use DetachedCriteria to retreive Database details from the SQl server DB like below. the nvarcharID is of String Type
List<POJO> pojoObj = (List<POJO>) getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(
POJO.class).add(Restrictions.idEq(nvarcharID)));
In My POJO I have following attributes
#Id
#GeneratedValue
#Column(name = "ID")
private double ID;
#Nationalized
#Column(name = "Column1")
private String string1;
#Nationalized
#Column(name = "column2")
private String string2;
Both column1 and column 2 are of type nvarchar inSql serverDB. and nvarcharID used above in the Criteria is another field in DB which is of type nvarchar in DB and I have mapped it as String. While populating the POJO, I do not want navarcharID field to be part of my POJO.
For hibernate I have following dependencies in my gradle file
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '4.3.11.Final'
compile group: 'javax.validation', name: 'validation-api', version: '1.0.0.GA'
compile group: 'org.hibernate', name: 'hibernate-validator-annotation-processor', version: '4.3.2.Final'
compile group: 'org.hibernate', name: 'hibernate-validator', version: '4.3.2.Final'
compile 'org.hibernate:hibernate-core:4.3.11.Final'
and my Spring dependencies are
compile group: 'org.springframework', name: 'spring-orm', version:'4.1.6.RELEASE'
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.1.6.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-web', version: '4.0.2.RELEASE'
I am also setting following properties in my Hibernate config file for Dialect and ddl operations.
#Bean
public LocalSessionFactoryBean sessionFactoryBean() {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource);
localSessionFactoryBean.setPackagesToScan(new String[] { "com.wk.cdi" });
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServer2012Dialect");
properties.setProperty("hibernate.use_nationalized_character_data", "true");
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.format_sql", "true");
properties.setProperty("hibernate.show_sql", "true");
localSessionFactoryBean.setHibernateProperties(properties);
return localSessionFactoryBean;
}
When I try to use hibernateTemplate to retreive the data I am getting
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double and it throws the error while using DetachedCriteria ealborated above
PLease ignore this as there was something else.
It happens to be that the Restrcition.idEq needed to be replaced by Restrictions.eq
Related
I've been trying to use Resilience4j + OpenFeign to call services. When I get an error, the timeout is working properly, however, in case of success it always returning null and I couldn't find why. Can someone please help me on this?
Creating the builder:
public AgentesAPI getAPI(String name, String url) {
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults(name);
RateLimiter rateLimiter = RateLimiter.ofDefaults(name);
FeignDecorators decorators =
FeignDecorators.builder()
.withCircuitBreaker(circuitBreaker)
.withRateLimiter(rateLimiter)
.withFallback(new AgentesAPIFallback())
.build();
return Resilience4jFeign.builder(decorators)
.logger(new Slf4jLogger())
.logLevel(Level.BASIC)
.target(AgentesAPI.class, url);
}
Getting a CompletableFuture with RateLimiter:
public class AgentesAPITimeLimiterService {
public CompletableFuture getCompletableFuture(String name, long miliseconds, Supplier supplier) {
TimeLimiter timeLimiter = getTimeLimiter(name, miliseconds);
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
return timeLimiter.executeCompletionStage(
scheduler, () -> CompletableFuture.supplyAsync(supplier))
.toCompletableFuture();
}
private TimeLimiter getTimeLimiter(String name, long miliseconds) {
return TimeLimiter.of(name,
TimeLimiterConfig.custom().timeoutDuration(
Duration.ofMillis(miliseconds)).build());
}
}
Calling the service and getting always null results:
public Agencias getAgencias(Map<String, Integer> queryMap) {
try {
CompletableFuture<Agencias> result =
_agentesAPITimeLimiterService.getCompletableFuture(configuration.backendName(),
configuration.timeout(), (() -> agentesAPI.getAgencias(queryMap)));
return result.get();
} catch (Exception e) {
throw new RuntimeException("Error getting Agencias!");
}
}
public interface AgentesAPI {
#RequestLine("POST /obtiene_agencias")
#Headers("Content-Type: application/x-www-form-urlencoded")
Agencias getAgencias(#QueryMap Map<String, Integer> queryMap);
}
The API is returning something, however, I couldn't make work in this way. Is there something that I'm missing here?
I'm using the versions below:
compileInclude group: "io.github.openfeign", name: "feign-core", version: "11.0"
compileInclude group: "io.github.openfeign", name: "feign-gson", version: "11.0"
compileInclude group: "io.github.openfeign", name: "feign-slf4j", version: "11.0"
compileInclude group: "io.github.resilience4j", name: "resilience4j-all", version: "1.5.0"
compileInclude group: "io.github.resilience4j", name: "resilience4j-feign", version: "1.5.0"
compileInclude group: "io.github.resilience4j", name: "resilience4j-timelimiter", version: "1.5.0"
compileInclude group: "org.slf4j", name: "slf4j-api", version: "1.7.30"
compileInclude group: "org.slf4j", name: "slf4j-simple", version: "1.7.30"
Thanks in advance.
It was resolved adding a decoder to the builder.
newbie to Springboot with gradle, I am creating a restful service which queries the db2 database and returns the result in json.
The desired output
{
resource: {
results: [
{
currencyCode: "JPY",
conversionRateToUSD: "0.010286580",
conversionRateFromUSD: "97.214040040",
startDate: "2011-01-01",
endDate: "2011-01-29"
}
]
}
}
The api i am trying to build is http://localhost:8080/apis/exchange-rates/referenceDate=2015-01-01¤cyCode=JPY
I have created the below controller class
#RestController
#Slf4j
#RequestMapping("/apis")
public class IndividualExchangeRateController {
#Autowired
private IndividualExchangeRateService individualExchangeRateService;
public IndividualExchangeRateController(IndividualExchangeRateService individualExchangeRateService) {
this.individualExchangeRateService = individualExchangeRateService;
}
#RequestMapping(value = "/exchange-rates", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody IndividualResource getIndividual(#RequestParam("referenceDate") #DateTimeFormat(pattern = "YYYY-MM-DD")Date referenceDate,
#RequestParam(value = "currencyCode", required = false) String currencyCode){
try {
System.out.println("Inside Controller");
return individualExchangeRateService.getIndividualExchangeRate(referenceDate, currencyCode);
}
catch (HttpClientErrorException e){
throw new InvalidRequestException(e.getMessage());
}
}
}
I am getting the below error when i call the api
javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
Can anybody help out on this ?
As the output is json i do not have thymeleaf dependencies on my application
Below is the gradle build file
plugins {
id 'org.springframework.boot' version '2.1.7.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.abc.service'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
maven { url "http://artifactory.abcinc.dev/artifactory/maven-repos" }
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
compileOnly 'org.projectlombok:lombok:1.18.8'
annotationProcessor 'org.projectlombok:lombok:1.18.8'
runtime 'com.ibm.db2.jcc:db2jcc4:4.19.49'
compile group: 'org.springframework', name: 'spring-jdbc', version: '5.1.9.RELEASE'
compile group: 'com.zaxxer', name: 'HikariCP', version: '3.3.1'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.9'
}
public class IndividualExchangeRate {
private String currencyCode;
private double conversionRateFromUSD;
private double conversionRateToUSD;
}
public class IndividualResource {
private List<IndividualExchangeRate> individualExchangeRates;
}
All the classes are annotated with lombok.
Spring Boot uses a default Whitelabel error page in case server error.So there might be some code snippets which is breaking your appliaction flow.
Add server.error.whitelabel.enabled=false in your application.properties file .
OR add the following code snippets :
#Controller
public class AppErrorController implements ErrorController{
private static final String PATH = "/error";
#RequestMapping(value = PATH)
public String error() {
return "Error handling";
}
#Override
public String getErrorPath() {
return PATH;
}
}
I want to use test container with spock on my spring boot application.
these are my dependencies :
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-redis')
compile('org.springframework.boot:spring-boot-starter-web')
compile 'org.testcontainers:spock:1.8.3'
runtime('org.springframework.boot:spring-boot-devtools')
compile 'org.codehaus.groovy:groovy-all:2.4.15'
compileOnly('org.projectlombok:lombok')
compile 'org.testcontainers:testcontainers:1.8.3'
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile "org.spockframework:spock-core:1.1-groovy-2.4-rc-4"
testCompile "org.spockframework:spock-spring:1.1-groovy-2.4-rc-4"
testCompile 'com.github.testcontainers:testcontainers-spock:-SNAPSHOT'
}
I have initialized my test like below :
#SpringBootTest
#Testcontainers
class ProductRedisRepositoryTest extends Specification {
#Autowired
ProductRedisRepository productRedisRepository
#Autowired
TestComponent testComponent
static Consumer<CreateContainerCmd> cmd = { -> e.withPortBindings(new PortBinding(Ports.Binding.bindPort(6379), new ExposedPort(6379)))}
#Shared
public static GenericContainer redis =
new GenericContainer("redis:3.0.2")
//.withExposedPorts(6379)
.withCreateContainerCmdModifier(cmd)
def "check redis repository save and get"(){
given:
Product product = Product.builder()
.brand("brand")
.id("id")
.model("model")
.name( "name")
.build()
when:
productRedisRepository.save(product)
Product persistProduct = productRedisRepository.find("id")
then:
persistProduct.getName() == product.getName()
}
}
But it doesn't initiate redis container when I run test.
What is my mistake. How can I do that.
My springBootVersion = '2.0.4.RELEASE' and I am using Intelij.
This is the log output : LOG
Please remove the static keyword at your #Shared GenericContainer field.
Static fields won't be annotated with #FieldMetadata by the Spock Framework, hence they won't be considered as part of the spec's fields.
Testcontainers-Spock relies on those fields to recognise GenericContainers.
If you need the static modifier though, you can work around the issue like this:
...
public static GenericContainer staticRedis =
new GenericContainer("redis:3.0.2")
//.withExposedPorts(6379)
.withCreateContainerCmdModifier(cmd)
#Shared
public GenericContainer redis = staticRedis
...
I have elasticsearch v 5.4.0 running on mysite.com:9300,
With x-pack auth:
login: mylogin
password: mypassword
And I have java + kotlin application with Spring Data Elasticsearch v 3.0.0.M4:
compile group: 'org.springframework.data', name: 'spring-data-elasticsearch', version: '3.0.0.M4'
Is there any way to create application.yml to connect to elasticsearch?
I find only examples for elasticsearch-2.4.4 version:
spring:
data:
elasticsearch:
cluster-nodes: mysite.com:9300
properties:
shield:
user: "mylogin:mypassword"
In the official documentation they recommend to use JavaConfig:
#Bean
public TransportClient elasticsearchClient() throws UnknownHostException {
TransportClient client = new PreBuiltXPackTransportClient(Settings.builder()
.put("client.transport.nodes_sampler_interval", "5s")
.put("client.transport.sniff", false)
.put("transport.tcp.compress", true)
.put("request.headers.X-Found-Cluster", "myclustername")
.put("xpack.security.transport.ssl.enabled", false)
.put("cluster.name", "myclustername")
.put("xpack.security.user", "mylogin:mypassword")
.build())
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("mysite.com"), 9300));
return client;
}
Gradle dependencies:
compile group: 'org.elasticsearch.client', name: 'x-pack-transport', version: '5.4.0'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-elasticsearch'
I'm building an application that uses Spring boot and neo4j ogm.
When i run it from spring tool suite or from gradle boot run, it works fine. However, after packaging it into a jar I get this error.
java.lang.NullPointerException: null
at org.neo4j.ogm.session.delegates.LoadOneDelegate.lookup(LoadOneDelegate.java:56) ~[neo4j-ogm-core-2.0.4.jar!/:na]
at org.neo4j.ogm.session.delegates.LoadOneDelegate.load(LoadOneDelegate.java:49) ~[neo4j-ogm-core-2.0.4.jar!/:na]
at org.neo4j.ogm.session.Neo4jSession.load(Neo4jSession.java:142) ~[neo4j-ogm-core-2.0.4.jar!/:na]
at comds.service.GenericService.find(GenericService.java:32) ~[classes!/:na]
at comds.service.UserServiceImpl.find(UserServiceImpl.java:36) ~[classes!/:na]
at comds.service.UserServiceImpl.find(UserServiceImpl.java:25) ~[classes!/:na]
at comds.linkedIn.LinkedInSaveUser.saveUser(LinkedInSaveUser.java:84) ~[classes!/:na]
at comds.controller.LinkedInController.home(LinkedInController.java:64) ~[classes!/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) ~[spring-web-4.2.7.RELEASE.jar!/:4.2.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-4.2.7.RELEASE.jar!/:4.2.7.RELEASE]
I suspect this is to do with the ogm configuration as the packages are used to define the meta data in ogm, which seems to be null:
package comds;
import org.neo4j.ogm.config.Configuration;
import org.neo4j.ogm.session.Session;
import org.neo4j.ogm.session.SessionFactory;
public class Neo4jSessionFactory {
private final static String [] packages = {"comds.domain"};
private final static SessionFactory sessionFactory = new SessionFactory(getConfiguration(),packages);
private static Neo4jSessionFactory factory = new Neo4jSessionFactory();
public static Neo4jSessionFactory getInstance() {
return factory;
}
private Neo4jSessionFactory() {
}
private static Configuration getConfiguration() {
Configuration configuration = new Configuration();
configuration.driverConfiguration()
.setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver")
.setURI("http://neo4j:test#localhost:7474");
return configuration;
}
public Session getNeo4jSession() {
return sessionFactory.openSession();
}
}
For some reason the COMDS user class is not being read:
#Service("userService")
public class UserServiceImpl extends GenericService<COMDSUser> implements UserService{
#Override
public Class<COMDSUser> getEntityType() {
return COMDSUser.class;
}
#Override
public COMDSUser find(Long id) {
COMDSUser user = super.find(id);
if(user != null){
return applyPrivacySettings(user);
}
return null;
}
//... more stuff
public class COMDSUser extends COMDSEntity{
public enum privacySettings{
SHOW_ALL, HIDE_PERSONAL_INFO,HIDE_ALL;
}
private String firstName;
private String lastName;
/// .. more stuff
package comds.domain;
import org.neo4j.ogm.annotation.GraphId;
public abstract class COMDSEntity {
#GraphId
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || id == null || getClass() != o.getClass()) return false;
COMDSEntity entity = (COMDSEntity) o;
if (!id.equals(entity.id)) return false;
return true;
}
#Override
public int hashCode() {
return (id == null) ? -1 : id.hashCode();
}
}
And gradle build:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'
war {
baseName = 'COM_DS'
version = '0.1.0'
}
jar {
baseName = 'COM_DS'
version = '0.1.0'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/libs-release" }
maven{ url "https://mvnrepository.com/artifact"}
maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:1.3.6.RELEASE")
compile "io.springfox:springfox-swagger2:2.5.1-SNAPSHOT"
compile("io.springfox:springfox-swagger-ui:2.5.0")
compile 'org.neo4j.driver:neo4j-java-driver:1.0.1'
compile group: 'org.neo4j', name: 'neo4j', version: '3.0.3'
compile group: 'org.neo4j', name: 'neo4j-ogm-core', version: '2.0.4'
compile group: 'org.neo4j', name: 'neo4j-ogm-api', version: '2.0.4'
compile group: 'org.neo4j', name: 'neo4j-ogm-http-driver', version: '2.0.4'
compile group: 'org.neo4j', name: 'neo4j-ogm-bolt-driver', version: '2.0.4'
compile group: 'org.neo4j', name: 'neo4j-ogm-embedded-driver', version: '2.0.4'
compile group: 'com.voodoodyne.jackson.jsog', name: 'jackson-jsog', version: '1.1'
compile("org.hibernate:hibernate-validator")
compile("org.springframework.boot:spring-boot-starter-social-facebook")
compile('org.springframework.boot:spring-boot-devtools')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-test')
compile "org.springframework.social:spring-social-core:1.1.4.RELEASE"
compile("org.springframework.social:spring-social-security:1.1.4.RELEASE")
compile("org.springframework.social:spring-social-config:1.1.4.RELEASE")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile group: 'joda-time', name: 'joda-time', version: '2.9.4'
testCompile 'junit:junit:4.10'
compile group: 'org.springframework', name: 'spring-test', version: '4.3.2.RELEASE'
compile fileTree(dir: 'resources', include: ['*.jar'])
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}
Note Im a using a custom spring social linked in class, that is being imported in the last compile
Your help would be greatly appreciated :)
Found a work around solution. Instead of exporting to a war, I exported just a jar. The issue was that exporting the file as a war changed the file structure meaning the ogm mapping couldn't be done properly. My new gradle build looks like this:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar {
baseName = 'name'
version = '0.1.0'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/libs-release" }
maven{ url "https://mvnrepository.com/artifact"}
maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/'}
maven { url 'https://oss.sonatype.org/content/repositories/snapshots'}
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:1.3.6.RELEASE")
compile "io.springfox:springfox-swagger2:2.5.1-SNAPSHOT"
compile("io.springfox:springfox-swagger-ui:2.5.0")
compile 'org.neo4j.driver:neo4j-java-driver:1.0.1'
compile group: 'org.neo4j', name: 'neo4j', version: '3.0.3'
compile group: 'org.neo4j', name: 'neo4j-ogm-core', version: '2.0.4'
compile group: 'org.neo4j', name: 'neo4j-ogm-api', version: '2.0.4'
compile group: 'org.neo4j', name: 'neo4j-ogm-http-driver', version: '2.0.4'
compile group: 'org.neo4j', name: 'neo4j-ogm-bolt-driver', version: '2.0.4'
compile group: 'org.neo4j', name: 'neo4j-ogm-embedded-driver', version: '2.0.4'
compile group: 'org.pac4j', name: 'spring-webmvc-pac4j', version: '1.1.1'
compile group: 'org.pac4j', name: 'pac4j-oauth', version: '1.9.2-SNAPSHOT'
compile group: 'org.pac4j', name: 'pac4j-core', version: '1.9.2-SNAPSHOT'
compile group: 'com.voodoodyne.jackson.jsog', name: 'jackson-jsog', version: '1.1'
compile("org.hibernate:hibernate-validator")
compile('org.springframework.boot:spring-boot-devtools')
compile group: 'javax.servlet.jsp.jstl', name: 'jstl', version: '1.2'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper', version: '8.5.4'
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-test')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
testCompile 'junit:junit:4.10'
compile group: 'org.springframework', name: 'spring-test', version: '4.3.2.RELEASE'
compile fileTree(dir: 'resources', include: ['*.jar'])
}
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
}