Here is my application.properties file:
spring.datasource.url=jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=BD_Name.mdb")
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=sun.jdbc.odbc.JdbcOdbcDriver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
and I use jdk7 which contains the driver sun.jdbc.odbc.JdbcOdbcDriver but when I start, springBoot return the exception "couldn't load driver".
First, you need the following dependencies
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Connecting MS Access with spring boot, use the below following configuration in application.properties
spring.datasource.url=jdbc:ucanaccess://C:/Users/FazalHaroon/Documents/JavaTest/accountsdb.accdb;openExclusive=false;ignoreCase=true
spring.datasource.driver-class-name=net.ucanaccess.jdbc.UcanaccessDriver
this is the example where i insert new data into my MS Access Database, then i use a select query to fetch all the records from the 'Account' table.
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
#SpringBootApplication
public class TaskApplication implements CommandLineRunner {
#Autowired
private JdbcTemplate template;
public static void main(String[] args) {
SpringApplication.run(NagarroTaskApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// template.update("INSERT INTO account(account_type, account_number) VALUES('test', '1233443543')");
List<Account> accountList = template.query("SELECT ID, account_type, account_number FROM account", new RowMapper<Account>() {
#Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Account(rs.getInt("ID"), rs.getString("account_type"), rs.getString("account_number"));
}
});
accountList.forEach(System.out::println);
}
}
It seems that you want to connect with MS Access, but the driver used is for JDBC.
Change the driver to the following and it should work:
spring.datasource.driver-class-name=net.ucanaccess.jdbc.UcanaccessDriver
Related
I'm doing a simple tutorial with flink + java using Table API. What I want to do is really simple - I want to read a csv file from a local filesystem, using a schema and print it out.
The way I'm doing this is this(the code below is compiled from samples from Flink's website tutorial section):
package p1;
import org.apache.flink.table.api.*;
import org.apache.flink.api.java.utils.ParameterTool;
public class CabAggregation {
public static void main(String[] args) throws Exception {
ParameterTool params = ParameterTool.fromArgs(args);
EnvironmentSettings settings = EnvironmentSettings
.newInstance()
.inBatchMode()
.build();
TableEnvironment tableEnv = TableEnvironment.create(settings);
final Schema schema = Schema.newBuilder()
.column("cab_id", DataTypes.INT())
.column("cab_plate", DataTypes.STRING())
.column("cab_make", DataTypes.STRING())
.column("cab_driver", DataTypes.STRING())
.column("active_trip", DataTypes.STRING())
.column("pickup_location", DataTypes.STRING())
.column("target_location", DataTypes.STRING())
.column("num_pass", DataTypes.INT())
.build();
tableEnv.createTemporaryTable("cabs",
TableDescriptor
.forConnector("filesystem")
.schema(schema)
.option("path", "file:///Users/virtual/Downloads/cabs.csv")
.format(FormatDescriptor.forFormat("csv").build())
.build());
Table result = tableEnv.from("cabs").select("*");
result.execute().print();
}
}
Running this gives me this:
Caused by: org.apache.flink.table.api.ValidationException: Could not find any factory for identifier 'filesystem' that implements 'org.apache.flink.table.factories.DynamicTableFactory' in the classpath.
Available factory identifiers are:
blackhole
datagen
print
Now, it seems evident that somehow CSV is not available as a factory identifier. I can't figure out why.
I'm building the project with maven.
You'll be needing these dependencies. Have you added them?
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-files</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-csv</artifactId>
<version>${flink.version}</version>
</dependency>
I have used below code for creating html reports , this code is present in after class of Junit Runner in a cucumber framework , but am getting error saying cucumber.json is not a valid cucumber report. I am assuming that report builder is trying to get the cucumber.json even before it is created completely,
I kept code in cucumber options to create Json file
#CucumberOptions(features = "features/",
glue = { "report"},
format = {"pretty","json:target/cucumber.json"},
tags = {"#testing" }, monochrome = true)
private void generateReportForJsonFiles(File reportOutputDirectory,
List<String> jsonFiles) {
String jenkinsBasePath = "";
String buildNumber = "1";
String projectName = project.getName();
Configuration configuration = new Configuration(reportOutputDirectory, projectName);
configuration.setParallelTesting(false);
configuration.setJenkinsBasePath(jenkinsBasePath);
configuration.setRunWithJenkins(false);
configuration.setBuildNumber(buildNumber);
ReportBuilder reportBuilder = new ReportBuilder(jsonFiles, configuration);
reportBuilder.generateReports();
}
Below is the error:
File 'target/cucumber.json' is not proper Cucumber report!
you should provide a small example (MCVE) which others can use to reproduce your problem
your code snippet configuration.setParallelTesting(false) and your answer cucumber report version is <version>4.2.0</version> do not match, as the method configuration.setParallelTesting was removed in version 4.1.0
Have a look at this small working snippet (based on the few information you provided).
Assume the following structure
pom.xml
src/main/java/CreateReport.java
src/main/resources/log4j2.properties
src/test/java/TestRunner.java
src/test/java/stepdefs/StepDefinitions.java
src/test/resource/features/demo.feature
pom.xml
...
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<!--
info.cukes:cucumber-java:1.2.5 is quite old and has been superseded by
io.cucumber:cucumber-java see: https://mvnrepository.com/artifact/io.cucumber/cucumber-java
-->
<version.cucumber>1.2.5</version.cucumber>
</properties>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
...
CreateReport.java
import java.io.File;
import java.util.Arrays;
import java.util.List;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
public class CreateReport {
private void generateReportForJsonFiles(File reportOutputDirectory, List<String> jsonFiles) {
String buildNumber = "1";
String projectName = "StackOverflow example";
Configuration configuration = new Configuration(reportOutputDirectory, projectName);
configuration.setParallelTesting(false);
// configuration.setJenkinsBasePath(jenkinsBasePath);
configuration.setRunWithJenkins(false);
configuration.setBuildNumber(buildNumber);
ReportBuilder reportBuilder = new ReportBuilder(jsonFiles, configuration);
reportBuilder.generateReports();
}
public static void main(String[] args) {
new CreateReport().generateReportForJsonFiles(new File("target/"),
Arrays.asList("target/cucumber.json"));
}
}
log4j2.properties
status = info
name = PropertiesConfig
appenders = console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%level] %m%n
rootLogger.level = info
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
TestRunner.java
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/test/resource/features"},
glue = {"stepdefs"},
plugin = {"json:target/cucumber.json"}
)
public class TestRunner {
}
StepDefinitions.java
package stepdefs;
import org.junit.Assert;
import cucumber.api.java.en.Given;
public class StepDefinitions {
#Given("^a successful step$")
public void aSuccessfulStep() throws Throwable {
System.out.println("a successful step");
}
#Given("^a not successful step$")
public void aNotSuccessfulStep() throws Throwable {
System.out.println("a not successful step");
Assert.fail();
}
}
demo.feature
Feature: Test cucumber reporting plugin
Scenario: Run a non failing scenario
Given a successful step
Scenario: Run a failing scenario
Given a not successful step
run the Cucumber test (this creates the target/cucumber.json file)
$ mvn clean test
run the report creator (
$ mvn exec:java -Dexec.mainClass=CreateReport
...
12:55:21 [INFO] --- exec-maven-plugin:1.6.0:java (default-cli) # cuke-test23.so ---
Dec 18, 2018 12:55:22 PM net.masterthought.cucumber.ReportParser parseJsonFiles
INFO: File 'target/cucumber.json' contains 1 features
the report is generated in target/cucumber-html-reports/overview-features.html
In Java project, I am using Sprig Boot 1.5.3.RELEASE. It is connecting with two databases i.e. MongoDB and Microsoft SQLServer. When I run it with spring-boot:run goal, it works fine. However, when I try to run it with package goal then below error is reported by test cases despite the fact that those test cases are not connecting to SQL Server database:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
.....
.....
MediationTest.java (Java class containing test cases generating above error)
#RunWith(SpringRunner.class)
#DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
#SpringBootTest(classes = { Application.class })
public class MediationTest {
#Autowired
private SwiftFormat swiftFormat;
......................
......................
MsqlDbConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "msqlEntityManagerFactory", transactionManagerRef = "msqlTransactionManager", basePackages = { "com.msql.data" })
public class MsqlDbConfig {
#Bean(name = "msqlDataSource")
#ConfigurationProperties(prefix = "msql.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "msqlEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean msqlEntityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("msqlDataSource") DataSource dataSource) {
return builder.dataSource(dataSource)
.packages("com.utils.msql.info")
.persistenceUnit("msql").build();
}
#Bean(name = "msqlTransactionManager")
public PlatformTransactionManager msqlTransactionManager(
#Qualifier("msqlEntityManagerFactory") EntityManagerFactory msqlEntityManagerFactory) {
return new JpaTransactionManager(msqlEntityManagerFactory);
}
}
application.properties
spring.data.mongodb.uri=mongodb://dev-abc-123:27017/db
msql.datasource.url=jdbc:sqlserver://ABC-SQL14-WXX;databaseName=dev
msql.datasource.username=dev
msql.datasource.password=*****
msql.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
msql.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
spring.jpa.show-sql=true
The spring-boot:run goal is defined by the Mojo included within the spring-boot-maven-plugin project. You can find it here. https://github.com/spring-projects/spring-boot/blob/8e3baf3130220a331d540cb07e1aca263b721b38/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java.
The requiresDependencyResolution scope is set to Test. This will include the dependencies from each phase on the classpath. Take a look at the specification here. https://maven.apache.org/developers/mojo-api-specification.html
The package goal provided by Maven wouldn't include these additional dependencies on the classpath and I believe that is the cause of your issues.
Spring Boot provides a repackage goal which is what should be used for building out executable spring-boot applications.
However, to get more to the point. I think if you update your test to exclude an additional class it might fix your problem.
#DataMongoTest(excludeAutoConfiguration = {EmbeddedMongoAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
I'm trying to start using Jetty with Camel.
I have added the dependency to my pom:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jetty</artifactId>
<version>2.15.5</version>
</dependency>
My CamelContext is initialized as follows:
public void startCamelContext() throws Exception {
CamelContext camelContext = new DefaultCamelContext();
camelContext.addComponent("jetty", new JettyHttpComponent8());
camelContext.start();
}
When I try to start up my service, which has a route with endpoint defined as:
jetty:http://0.0.0.0:9000/httpInput
I get an exception:
java.lang.NullPointerException: null
at org.apache.camel.component.jetty8.JettyHttpComponent8.createConnectorJettyInternal(JettyHttpComponent8.java:48)
at org.apache.camel.component.jetty.JettyHttpComponent.createConnector(JettyHttpComponent.java:585)
at org.apache.camel.component.jetty.JettyHttpComponent.getSocketConnector(JettyHttpComponent.java:527)
at org.apache.camel.component.jetty.JettyHttpComponent.getConnector(JettyHttpComponent.java:517)
at org.apache.camel.component.jetty.JettyHttpComponent.connect(JettyHttpComponent.java:320)
at org.apache.camel.component.http.HttpEndpoint.connect(HttpEndpoint.java:185)
at org.apache.camel.component.http.HttpConsumer.doStart(HttpConsumer.java:53)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.startService(DefaultCamelContext.java:2885)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRouteConsumers(DefaultCamelContext.java:3179)
at org.apache.camel.impl.DefaultCamelContext.doStartRouteConsumers(DefaultCamelContext.java:3115)
at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:3045)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRoutes(DefaultCamelContext.java:2813)
at org.apache.camel.impl.DefaultCamelContext.startAllRoutes(DefaultCamelContext.java:865)
The documentation on how to set up the Jetty component is lacking at best. I found a mailing-list entry where it was said that JettyHttpComponent has been made abstract since Camel 2.15 and now that component has to be configured using JettyHttpComponent8 or 9. link
In my case, I'm using Camel 2.15.5 and the JettyHttpComponent9 isn't available in the classpath, and using 8 gives the exception described above.
I also found related discussion here with no information on how to actually use that component.
That's typically not how the CamelContext is initialized/started. Please consider using an archetype to get started, then add the Jetty Maven dependency and see if the error can be reproduced.
Camel archetypes can be found here: http://camel.apache.org/camel-maven-archetypes.html
To start a camel context outside spring you need to create a continuous thread to keep camel alive, as explaine here: http://camel.apache.org/running-camel-standalone-and-have-it-keep-running.html
Don't worry, I have below some code that will setup a jetty on localhost:8081 for you:
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jetty</artifactId>
<version>2.16.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.16.1</version>
</dependency>
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.main.MainListenerSupport;
import org.apache.camel.main.MainSupport;
import java.util.Date;
/**
* Created by mkbrv on 22/06/16.
*/
public class CamelJetty {
private Main main;
public static void main(String[] args) throws Exception {
CamelJetty example = new CamelJetty();
example.boot();
}
public void boot() throws Exception {
// create a Main instance
main = new Main();
// bind MyBean into the registry
main.bind("foo", new MyBean());
// add routes
main.addRouteBuilder(new MyJettyRouteBuilder());
// add event listener
main.addMainListener(new Events());
// run until you terminate the JVM
System.out.println("Starting Camel. Use ctrl + c to terminate the JVM.\n");
main.run();
}
private static class MyJettyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
from("jetty:http://localhost:8081")
.process(exchange -> {
System.out.println("Invoked timer at " + new Date());
exchange.getOut().setBody("Hi, this is Camel!");
})
.bean("foo");
}
}
public static class MyBean {
public void callMe() {
System.out.println("MyBean.callMe method has been called");
}
}
public static class Events extends MainListenerSupport {
#Override
public void afterStart(MainSupport main) {
System.out.println("MainExample with Camel is now started!");
}
#Override
public void beforeStop(MainSupport main) {
System.out.println("MainExample with Camel is now being stopped!");
}
}
}
Next just go to http://localhost:8081 and you should see a welcome message.
Have fun tweaking this further more.
I'm trying to create a GWT app and I'm working with a local postgreSQL Database.
I'm working with GWT 2.4 on eclipse Juno.
I implemented in this way the Server-side implementation (TaskServiceImpl):
public class TaskServiceImpl extends ServiceImpl implements TaskService {
#Override
public List<Task> getAllTasks() {
em = this.getEntityManager();
Query q = em.createQuery("SELECT x FROM Task x");
List<Task> list = createList(q.getResultList().toArray(),
new ArrayList<Task>(), em);
em.close();
return list;
}
and this is the Database connection class in the client-side:
public class DatabaseConnection {
public static final TaskServiceAsync taskService;
static {
taskService = GWT.create(TaskService.class);
}
}
I try now to run a getAllTask() in this way
public void onModuleLoad() {
DatabaseConnection.taskService.getAllTasks(new AsyncCallback<List<Task>>() {
#Override
public void onSuccess(List<Task> result) {
System.out.println("Success!");
}
#Override
public void onFailure(Throwable caught) {
System.out.println("Fail!");
}
});
}
And always returns "fail!" and gives me this error:
com.google.appengine.tools.development.LocalResourceFileServlet doGet
WARNING: No file found for: /fantapgl/task
This is my web.xml
<servlet>
<servlet-name>taskServiceImpl</servlet-name>
<servlet-class>fieldProject.server.service.TaskServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>taskServiceImpl</servlet-name>
<url-pattern>/fantaPGL/task</url-pattern>
</servlet-mapping>
to open the connection to the DB I have this code in the persistence.xml:
<properties>
<property name="openjpa.jdbc.DBDictionary" value="postgres" />
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema()"/>
<property name="openjpa.ConnectionDriverName" value="org.postgresql.Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:postgresql://localhost:5432/db" />
<property name="openjpa.ConnectionUserName" value="postgres" />
<property name="openjpa.ConnectionPassword" value="password" />
</properties>
I don't understand where I'm wrong. Can someone plz help me!?
I'm not sure what the problem is. But the error messages seems to suggest you have google appengine enabled. That doesn't make sense because you would only need that if you want to deploy on Google app engine, and you are clearly developing for something else since you can't run PostgreSql on Google appengine.
Futhremore, make sure to close database connections by placing the close in a finally statement and prefer to return specific datatypes; that is, ArrayList instead of List. Otherwise the compiler will generate code for all subclasses of List, because at compile time the compiler can't know what subclass will be used.
Before executing the query:
1) Use jdbc driver
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Your PostgreSQL JDBC Driver is missing! "
+ "Include in your library path!");
e.printStackTrace();
return "error";
}
2) Connect to database
Connection connection = null;
connection =
DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/"YourDB",
"admin",
"pass" );
3) Then Execute the query
if (connection != null) { //Your query }
you need to add #RemoteServiceRelativePath annotation at the begin of the serviceImpl class.
please refer to https://developers.google.com/web-toolkit/doc/latest/tutorial/RPC
or if you have installed google eclipse plugin, create a new project with sample code, you can refer to the sample code as well.