jdbc ant run build.xml classpath - jdbc

I'm having trouble running from ant. When I run straight from the class
file as follows it compiles and runs
Jasons-MacBook-Pro:src js$ java Hw5
Student ID: 1
First Name: Jason
Last Name: S
Phone: 555-220-5169
Email: js#ucsd.edu
Personal Tagline: Never say never
The following line of code is used when it runs correctly as above
Connection connection = DriverManager.getConnection("jdbc:derby:/Users/js/Desktop/JavaDevelopmentAnt/HW5_JDBC/lib/Hw5Db");
my code
import java.sql.*;
import java.util.Enumeration;
public class Hw5{
public static void main (String [] args){
try{
Connection connection = DriverManager.getConnection("jdbc:derby:/Users/js/Desktop/JavaDevelopmentAnt/HW5_JDBC/lib/Hw5Db");
//Connection connection = DriverManager.getConnection("jdbc:derby:Hw5Db");//ant file code
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM STUDENT");
while(resultSet.next()){
int studentID = resultSet.getInt("STUDENT_ID");
String firstName = resultSet.getString("FIRSTNAME");
String lastName = resultSet.getString("LASTNAME");
String phone = resultSet.getString("PHONE");
String email = resultSet.getString("EMAIL");
String mantra = resultSet.getString("PERSONAL_TAGLINE");
System.out.println("Student ID: " + studentID + "\n" +
"First Name: " + firstName + "\n" +
"Last Name: " + lastName + "\n" +
"Phone: " + phone + "\n" +
"Email: " + email + "\n" +
"Personal Tagline: " + mantra + "\n");
}
resultSet.close();
statement.close();
connection.close();
}
catch(SQLException sqle){
System.err.println("SQL Exception: " + sqle);
}
}
}
but when I try from my build.xml i change the following line of code to
Connection connection = DriverManager.getConnection("jdbc:derby:Hw5Db");
because i think database jar file (Hw5Db) is in the classpath of my build.xml
my build.xml
<?xml version="1.0"?>
<project name="Hw5" default="compile" basedir=".">
<property environment="env"/>
<property name="src" value="${basedir}/src"/>
<property name="bin" value="${basedir}/bin"/>
<property name="lib" value="${basedir}/lib"/>
<property name="doc" value="${basedir}/doc"/>
<property name="build" value="${basedir}/build"/>
<target name="prepare" description="Setting up temporary directory to support build">
<mkdir dir="${build}"/>
<mkdir dir="${bin}"/>
</target>
<target name="compile" depends="prepare" description="compile java sources">
<javac srcdir="${src}" destdir="${build}" includes="**/*.java" listfiles="yes" includeantruntime="false">
</javac>
</target>
<target name="deploy" depends="compile">
<jar destfile="${bin}/Hw5.jar" basedir="${build}"/>
<jar destfile="${bin}/Hw5Db.jar" basedir="${lib}"/>
</target>
<target name="run" depends="deploy" description="run the project">
<java fork="true" classname="Hw5">
<classpath path="${bin}/Hw5.jar"/>
<classpath path="${bin}/Hw5Db.jar"/>
</java>
</target>
<target name="clean">
<delete dir="${build}"/>
<delete dir="${bin}"/>
</target>
</project>
Jasons-MacBook-Pro:HW5_JDBC jsteindorf$ ant run
Buildfile: /Users/js/Desktop/JavaDevelopmentAnt/HW5_JDBC/build.xml
prepare:
[mkdir] Created dir: /Users/js/Desktop/JavaDevelopmentAnt/HW5_JDBC/build
[mkdir] Created dir: /Users/js/Desktop/JavaDevelopmentAnt/HW5_JDBC/bin
compile:
[javac] Compiling 1 source file to /Users/js/Desktop/JavaDevelopmentAnt/HW5_JDBC/build
[javac] /Users/js/Desktop/JavaDevelopmentAnt/HW5_JDBC/src/Hw5.java
deploy:
[jar] Building jar: /Users/jsteindorf/Desktop/JavaDevelopmentAnt/HW5_JDBC/bin/Hw5.jar
[jar] Building jar: /Users/jsteindorf/Desktop/JavaDevelopmentAnt/HW5_JDBC/bin/Hw5Db.jar
run:
[java] SQL Exception: java.sql.SQLException: No suitable driver found for jdbc:derby:Hw5Db
BUILD SUCCESSFUL
Total time: 2 seconds
I'm trying, I just can't get it to work

Not sure but maybe you need register the driver before use it.
Class.forName("class_of_driver").getInstance();
And after:
Connection connection = DriverManager.getConnection("jdbc:derby:./Hw5Db");

The duplicate classpath on the java task looks a bit strange to me. Try the following instead:
<java fork="true" classname="Hw5">
<classpath path="${bin}/Hw5.jar:${bin}/Hw5Db.jar"/>
</java>

i fixed the issue, the build.xml wasn't finding to the database drivers
classpath path="${env.DERBY_HOME}/lib/derby.jar
classpath path="${env.DERBY_HOME}/lib/derbytools.jar
and the connection path to the database should have been
jdbc:derby:./lib/Hw5Db

Related

Unable to debug Azure Function that targets .NET 5.0

I wrote a simple Azure Function from the template using the .NET CORE 3.1 as target framework.
After that I migrated the target framework to .NET 5.0 using the guide
After the migration I'm not able to debug the Azure Function. I get the usual message "the breakpoint will not currently be hit".
The csproj is this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.2.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
local.settings.json is this:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
}
}
program.cs is this:
class Program
{
static Task Main(string[] args)
{
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{
})
.Build();
return host.RunAsync();
}
}
The simple function is:
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
namespace FunctionAppNet50
{
public static class Function1
{
[Function("Function1")]
public static async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req)
{
var response = req.CreateResponse(System.Net.HttpStatusCode.OK);
return response;
}
}
}
Is this related to the ".NET isolated process" model or did I do something wrong?
Thanks... found the solution in the suggested articles by marc_c and Douglas.
I installed the Azure Function Core Tools using choco with the command "choco install azure-functions-core-tools-3";
run the function in a shell with "func start –-dotnet-isolated-debug";
attached the debugger at the PID showed in the window
here is an article that similar steps: https://dev.to/kenakamu/debug-net-5-function-with-visual-studio-visual-studio-code-5235

Servicemix using Oracle ojdbc

I want to use jdbc directly in a project for service mix.
I have tried to install ojdbc7.jar with
bundle:install wrap:file:F:/tmp/ojdbc7.jar
after starting I get
264 | Active | 80 | 0 | wrap_file_F__tmp_ojd
bc7.jar
My code is:
try (final Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/orcl2", "bla", "bla")) {
String sql = "Insert INTO message values('" + fall.getMessageid() + "','" + fall.getXml() + "')";
final Statement statement = con.createStatement();
statement.executeUpdate(sql);
} catch (Exception e) {
String msg = "Error while trying to persist Fall with msgid " + fall.getMessageid();
log.error(msg, e);
throw new AdvisException(msg, e);
}
I get
java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:#localhost:1521/orcl2
Do I have to add some extra configuration or something?
edit:
I think I must import the installed bundle somehow in the MANIFEST.MF
Problem 1:
I have declared the dependency
<dependency>
<groupId>com.oracle</groupId>
<artifactId>oracle-jdbc</artifactId>
<version>6.0.0</version>
</dependency>
and use
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.5.3</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Import-Package>*</Import-Package>
<Private-Package>de.iteos</Private-Package>
</instructions>
</configuration>
but the ojdbc6 does not show up the imports:
Import-Package: javax.jws,javax.xml.bind,javax.xml.bind.annotation,javax
.xml.bind.annotation.adapters,javax.xml.datatype,javax.xml.namespace,ja
vax.xml.parsers,javax.xml.transform,javax.xml.transform.stream,javax.xm
l.ws,javax.xml.xpath,org.apache.activemq,org.apache.activemq.camel.comp
onent,org.apache.camel;version="[2.16,3)",org.slf4j;version="[1.7,2)",o
rg.w3c.dom,org.xml.sax
Why?
Problem 2:
the name of the bundle after the install is probably not compatible
How can I change this?
I have solved the problem by copying the ojdbc driver to
apache-servicemix-7.0.1\lib\ext

gradle: how to invoke ant.javac with multiple includes defined at runtime?

for some reasons I don't use the java plugin for gradle, but I invoke ant.javacdynamically. How can I build a dynamic javac include() based on a list ?
for example:
def srcToCompile=["**/File1.java","**/File2.java","**/FileN.java"];
(...)
ant.javac(
destdir: tmpDir,
srcdir: srcDir
includeantruntime:false,
failonerror: true,
fork: true,
classpath : classpath1,
debug: true
) {
include(name: srcToCompile) //<< DOESN'T WORK, I also tested srcToCompile.join(":")
}
thanks.
EDIT: by 'doesn't work', I mean ant.javac doesn't interpret a List or a colon-separated-string: no source is found and nothing is compiled. ant.javac expects something like
include(name:"**/File1.java")
include(name:"**/File2.java")
include(name:"**/FileN.java")
but I want to generate this list of include when gradle is invoked.
If you look an ant javac docs you'll see that includes and include both accept a string but you are trying to pass a collection
Eg:
<javac destdir="${build}"
classpath="xyz.jar"
debug="on">
<src path="${src}"/>
<src path="${src2}"/>
<include name="mypackage/p1/**"/>
<include name="mypackage/p2/**"/>
<exclude name="mypackage/p1/testpackage/**"/>
</javac>
and
<javac srcdir="${src}"
destdir="${build}"
includes="mypackage/p1/**,mypackage/p2/**"
excludes="mypackage/p1/testpackage/**"
classpath="xyz.jar"
debug="on"/>
In Gradle this would be
ant.javac(includes: srcToCompile.join(','), ...)
or
ant.javac(
...
) {
srcToCompile.each {
include(name: it)
}
}

Can not delete directory by mask in Gradle

I try to delete directory in 'foo/dir' with name 'public-someHash'. 'SomeHash' was created dynamically (eg 'dsflsdfn') and always new. I tried to use 'fileTree' but directory still present. There is my code:
tasks.create(name: 'delete', type : Delete) {
delete fileTree(dir: 'foo/dir/', include: 'public-*/**')
}
What is wrong with my mask?
UDP: I have similar task in Ant and all works fine:
<target name="delete">
<delete includeemptydirs="true">
<fileset dir="foo/dir/">
<include name="public-*/**"/>
</fileset>
</delete>
</target>
EDIT: Apologies, as original answer was based on a misreading of the question.
Here's one way to do it, but not the most elegant:
task myDelete(type: Delete) {
def files = new HashSet()
new File('foo/dir').eachFile { file ->
if (file.isDirectory() && (file.name ==~ /public-.*/)) {
files << file
}
}
delete files
}

Query failed with error code 13 and error message 'not authorized on [db] to execute command { find:

I am using the following
Mongo 3.2.7
Spring 4.3.1 release
I have created following user with the below privileges.
> use admin
switched to db admin
> db.getUser("UserAdminNew")
{
"_id" : "admin.UserAdminNew",
"user" : "UserAdminNew",
"db" : "admin",
"roles" : [
{
"role" : "readWrite",
"db" : "admin"
},
{
"role" : "root",
"db" : "admin"
},
{
"role" : "readWrite",
"db" : "NEWTest"
}
]
}
In DB NEWTest I have the below mentioned collections
> use NEWTest
switched to db NEWTest
> show collections
Friends
users
usersD
If I am inserting & trying to find the document in to usersD from console it works fine.
where as when I am trying to do the same from spring.Even if I am able to insert the document the find fails with the following error stack.
1. user : UserD [id=578deb8a0c58602128ead56a, username=Dhara, password=password_000]
1.1. user : UserD [id=578deb8a0c58602128ead56b, username=Subrat Dash, password=password_111]
query1 - Query: { "username" : "Dhara"}, Fields: null, Sort: null
Exception in thread "main" org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 13 and error message 'not authorized on NEWTest to execute command { find: "usersD", filter: { username: "Dhara" }, limit: 1, singleBatch: true }' on server 127.0.0.1:27017; nested exception is com.mongodb.MongoQueryException: Query failed with error code 13 and error message 'not authorized on NEWTest to execute command { find: "usersD", filter: { username: "Dhara" }, limit: 1, singleBatch: true }' on server 127.0.0.1:27017
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:107)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2114)
at org.springframework.data.mongodb.core.MongoTemplate.executeFindOneInternal(MongoTemplate.java:1904)
at org.springframework.data.mongodb.core.MongoTemplate.doFindOne(MongoTemplate.java:1712)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:586)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:581)
at com.mydhara.core.App.main(App.java:60)
Caused by: com.mongodb.MongoQueryException: Query failed with error code 13 and error message 'not authorized on NEWTest to execute command { find: "usersD", filter: { username: "Dhara" }, limit: 1, singleBatch: true }' on server 127.0.0.1:27017
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:492)
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:482)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:239)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:212)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:482)
at com.mongodb.operation.FindOperation.execute(FindOperation.java:79)
at com.mongodb.Mongo.execute(Mongo.java:772)
at com.mongodb.Mongo$2.execute(Mongo.java:759)
at com.mongodb.DBCollection.findOne(DBCollection.java:777)
at com.mongodb.DBCollection.findOne(DBCollection.java:747)
at com.mongodb.DBCollection.findOne(DBCollection.java:694)
at org.springframework.data.mongodb.core.MongoTemplate$FindOneCallback.doInCollection(MongoTemplate.java:2143)
at org.springframework.data.mongodb.core.MongoTemplate$FindOneCallback.doInCollection(MongoTemplate.java:2127)
at org.springframework.data.mongodb.core.MongoTemplate.executeFindOneInternal(MongoTemplate.java:1901)
... 4 more
App.java
package com.mydhara.core;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.mydhara.config.SpringMongoConfig;
import com.mydhara.config.SpringMongoConfig1;
import com.mydhara.model.Friends;
import com.mydhara.model.UserD;
import org.springframework.context.support.GenericXmlApplicationContext;
public class App {
public static void main(String[] args) {
// For XML
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
// For Annotation
//ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig1.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
UserD user = new UserD("Dhara", "password_000");
// save
mongoOperation.save(user);
UserD user1 = new UserD("Subrat Dash", "password_111");
// save
mongoOperation.save(user1);
// now user object got the created id.
System.out.println("1. user : " + user);
System.out.println("1.1. user : " + user1);
// query to search user
Query searchUserQuery = new Query(Criteria.where("username").is("Dhara"));
// BasicQuery searchUserQuery = new BasicQuery("{ username:'Dhara'}");
System.out.println("query1 - " + searchUserQuery.toString());
// find the saved user again.
//UserD savedUser =mongoOperation.findOne(username:'Dhara', UserD.class);
UserD savedUser = mongoOperation.findOne(searchUserQuery, UserD.class);
System.out.println("2. find - savedUser : " + savedUser);
// update password
mongoOperation.updateFirst(searchUserQuery, Update.update("password", "new password"),
UserD.class);
// find the updated user object
UserD updatedUser = mongoOperation.findOne(
new Query(Criteria.where("username").is("Dhara")), UserD.class);
System.out.println("3. updatedUser : " + updatedUser);
// delete
// mongoOperation.remove(searchUserQuery, User.class);
// List, it should be empty now. but added subrat so 1
List<UserD> listUser = mongoOperation.findAll(UserD.class);
//rnd
String[] originalId =new String[4];
int i=0;
for(UserD userN : listUser) {
originalId[i]=userN.getId();
System.out.println("value of i-------------"+i+"--------"+originalId[i]);
i++;
}
//adding a friend
Friends friend = new Friends("Anjusha", "password_000" , originalId[1]);
mongoOperation.save(friend);
Friends friend2 = new Friends("Martin", "password_111" , originalId[1]);
mongoOperation.save(friend2);
Friends friend3 = new Friends("Geo George", "password_222" , originalId[0]);
mongoOperation.save(friend3);
//ends
System.out.println("4. Number of user = " + listUser.size());
System.out.println("5. All User = " + listUser);
List<Friends> listFriends = mongoOperation.findAll(Friends.class);
System.out.println("6. Number of Friends = " + listFriends.size());
System.out.println("7. All Friends = " + listFriends);
// query to search friends
Query searchUserQueryN = new Query(Criteria.where("userId").is(originalId[1]));
List<Friends> savedUser1 = mongoOperation.find(searchUserQueryN, Friends.class);
System.out.println("--- find - friends of Subrat Dash : " + savedUser1);
Query searchUserQueryM = new Query(Criteria.where("userId").is(originalId[0]));
List<Friends> savedUser2 = mongoOperation.find(searchUserQueryM, Friends.class);
System.out.println("--- find - friends of Dhara : " + savedUser2);
// save
mongoOperation.save(user);
}
}
springconfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="NEWTest" username="UserAdminNew"
password="Dhara123" /> <!-- orig NEWTest -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<!-- <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
-->
<!-- <property name="writeResultChecking" value="EXCEPTION"/>
<property name="writeConcern" value="FSYNC_SAFE"/> -->
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="NEWTest" />
<!-- added to chk auth feature -->
<constructor-arg name="userCredentials" ref="userCredentials"/>
</bean>
<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
<constructor-arg name="username" value="UserAdminNew" />
<constructor-arg name="password" value="Dhara123" />
</bean>
<!-- added to chk auth feature ENDS HERE -->
</beans>
Any suggestions on what might me the issue here.(As per my understanding the role readWrite is capable of doing a find & i can do the same from mongo console as well but not from spring)
Thanks In Advance
Try this for your Spring xml config
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:mongo-client credentials="UserAdminNew:Dhara123#admin" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo" />
<constructor-arg name="databaseName" value="NEWTest" />
</bean>
</beans>

Resources