Unable to set authentication and authorization for my embedded database - derby

I have read the Derby documentation but couldn't find any solution.
I want to set a user id and password for my database in my application.
I have provided the user and password option in the connection URL but when I try to open it again with any password it is still opening. The URL is below
DriverManager.getConnection(
"jdbc:derby:database;user=admin;password=1234;create=true;");

Only database url with username and password will not work. You have to setup a embedded database first then set different properties to enable user authentication using Derby's built-in user authentication and user authorization.
You can read about derby authorization on its documentation-
https://db.apache.org/derby/docs/10.4/devguide/cdevcsecure36595.html#cdevcsecure36595
You have to enable authentication after creating the embedded database.
You can use this method to setup authentication--
public static void turnOnBuiltInUsers(Connection conn) throws SQLException {
System.out.println("Turning on authentication.");
Statement s = conn.createStatement();
// Setting and Confirming requireAuthentication
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.connection.requireAuthentication', 'true')");
ResultSet rs = s.executeQuery(
"VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(" +
"'derby.connection.requireAuthentication')");
rs.next();
System.out.println("Value of requireAuthentication is " +
rs.getString(1));
// Setting authentication scheme to Derby
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.authentication.provider', 'BUILTIN')");
// Creating some sample users
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.user.sa', 'ajaxj3x9')");
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.user.guest', 'java5w6x')");
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.user.mary', 'little7xylamb')");
// Setting default connection mode to no access
// (user authorization)
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.defaultConnectionMode', 'noAccess')");
// Confirming default connection mode
rs = s.executeQuery (
"VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(" +
"'derby.database.defaultConnectionMode')");
rs.next();
System.out.println("Value of defaultConnectionMode is " +
rs.getString(1));
// Defining read-write users
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.fullAccessUsers', 'sa,mary')");
// Defining read-only users
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.readOnlyAccessUsers', 'guest')");
// Confirming full-access users
rs = s.executeQuery(
"VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(" +
"'derby.database.fullAccessUsers')");
rs.next();
System.out.println("Value of fullAccessUsers is " + rs.getString(1));
// Confirming read-only users
rs = s.executeQuery(
"VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(" +
"'derby.database.readOnlyAccessUsers')");
rs.next();
System.out.println("Value of readOnlyAccessUsers is " +
rs.getString(1));
// We would set the following property to TRUE only
// when we were ready to deploy.
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.propertiesOnly', 'false')");
s.close();
}
You can use this link for complete a quick example of the same.

Related

org.hibernate.UnsupportedLockAttemptException: Lock mode not supported : Hibernate 4->5 Upgrade

We've just upgraded Hibernate 4->5 in our application. The following code used to work in Hibernate 4. There is a job which fetches some data from MAIL_HISTORY_T and can optionally write into MAIL_HISTORY_T as well in the same transaction.
#Transactional(readOnly = false)
#Scheduled(cron = "${mail.cron.reviewer.task.reminder}")
public void sendPendingReviewerTaskRemainderEmail() {
//...
for(Reviewers reviewer: pendingTasks) {
// Read from MAIL_HISTORY_T
MailHistory mh = mailHistoryDAO.getMailHistoryByReqId(reviewer.getReqId());
//...
if (someCondition) {
// Write to MAIL_HISTORY_T
mailHistoryDAO.createNewMailHistory(reviewer.getReqId(), params);
}
}
}
Error:
org.hibernate.UnsupportedLockAttemptException: Lock mode not supported
at org.hibernate.engine.internal.ImmutableEntityEntry.setLockMode(ImmutableEntityEntry.java:128) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.event.internal.DefaultRefreshEventListener.onRefresh(DefaultRefreshEventListener.java:220) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.event.internal.DefaultRefreshEventListener.onRefresh(DefaultRefreshEventListener.java:52) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.internal.SessionImpl.fireRefresh(SessionImpl.java:1295) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at org.hibernate.internal.SessionImpl.refresh(SessionImpl.java:1247) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final]
at app.mcs.dao.MailHistoryDAO.persist(MailHistoryDAO.java:40) ~[classes/:]
Both the Read and Write operations on MAIL_HISTORY_T reference the same Request ID.
Any thoughts?
Somehow your code is creating ImmutableEntityEntry which is new introduction in Hibernate 5.
As per ImmutableEntityEntry code, it only support LockMode.NONE & LockMode.READ (see ImmutableEntityEntry#setLockMode method).
Your code is reading & updating same entity so it is most likely hibernate is setting LockMode as LockMode.PESSIMISTIC_WRITE which is not supported by ImmutableEntityEntry.
Can you please check which AbstractEntityEntry instance you were receiving prior to Hibernate 5 update.
Edit :- There already exists a bug in hibernate regarding this https://hibernate.atlassian.net/browse/HHH-13601.
Currently,I am not sure how you can obtain MutableEntityEntry in your case which will help you to change your entity.
We fixed this by rewriting the Write operation as Native SQL. The Read operation remains unchanged as before.
Therefore, the previous Hibernate-based createNewMailHistory() is now Native SQL:
sessionFactory.getCurrentSession().createNativeQuery("insert "
+ " into "
+ " MAIL_HISTORY_T "
+ " (ID, MAIL_TEMPLATE_ID, MAIL_IDENTIFIER, REQUEST_ID, SYSTEM_COMMENTS, CREATED_DATE, CREATED_BY) "
+ " values "
+ " (nextval('mh_seq'), :mailTemplateId, :mailIdentifier, :requestId, :systemComments, :createdDate, :createdBy)")
.setParameter("mailTemplateId", mailTemplateDAO.findByShortIdentifier(mailIdentifier).getId())
.setParameter("mailIdentifier", mailIdentifier)
.setParameter("requestId", req.getId())
.setParameter("systemComments", systemComments)
.setParameter("createdDate", new Date())
.setParameter("createdBy", null)
.executeUpdate();
}

i want to use simba.spark.jdbc driver in sprint boot to connect to databricks with token

want to use simba spark jdbc driver in spring boot to connect to data bricks with token
so that i can leverage the code over the "JDBC" boiler plate code and using row mapper and can fetch data from data bricks database , what will be user and password in case of connecting to data bricks
database using token as there is no user and password .and reference or code is welcome
You just not need to set username & password explicitly - just provide URL. Here is a simple working example that uses Databricks SQL endpoint (full example is here):
String host = "adb-123.11.azuredatabricks.net";
String httpPath = "/sql/1.0/endpoints/...";
String token = "your_token";
String query = "select count(1) from default.table";
String jdbcUrl = "jdbc:spark://" + host +
":443/default;transportMode=http;ssl=1;httpPath=" +
httpPath + ";AuthMech=3;UID=token;PWD=" + token;
SimpleDriverDataSource ds = new SimpleDriverDataSource();
ds.setDriver(new Driver());
ds.setUrl(jdbcUrl);
JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
int numRows = jdbcTemplate.queryForObject(query, Integer.class);

HTTP Sampler to manage iteration for retrieved data(Stored using BeanShell Sampler) from DB

I've created one BeanShell samplet as below, to store retrieved values from DB.
ArrayList username = vars.getObject("username");
for (HashMap table : username) {
for (Object column1 : table.keySet()) {
log.info(column1 + "=" + table.get(column1));
String strusername = table.get(column1).toString();
log.info("Username fethced from DB is=" + strusername);
vars.put("strusername", new String(strusername));
}
}
ArrayList password = vars.getObject("password");
for (HashMap table : password) {
for (Object column2 : table.keySet()) {
log.info(column2 + "=" + table.get(column2));
String strpassword = table.get(column2).toString();
log.info("Password fethced from DB is=" + strpassword);
vars.put("strpassword", new String(strpassword));
}
}
Here as a output i am getting "String strusername & strpassword" having last retrieved value from DB, but previous values i can see in Jmeter log viewer, but cannot use them to perform login.
Now my query is how could i manage HTTP Sampler to perform login for each set of username, password?
Can you use foreach controller here, if yes what could be structure and where should i use it? or do i need to do modifications in above shown BeanShell Sampler?
Also, is there any way to user multiple variable in foreach controller?
I have resolved this by adding multiple HTTP request to pass data... Actually cookie manager passing same data for same page's post requests & that's why loop/ for each logic controller does not working. Also, if we remove cookie manager then it will not maintain user's session.
So, only solution is to create multiple HTTP sampler for multiple thread(users).
Thanks.

kerberos auth and connection pooling in jdbc

I've got Java web application running on Tomcat with SSO via SPNEGO/Kerberos and I want to pass kerberos ticket to database, Oracle DB in my case (like impersonation in MS products). I've found an example of implementation (http://docs.oracle.com/cd/B28359_01/java.111/b31224/clntsec.htm):
Connection conn = (Connection)Subject.doAs(specificSubject, new PrivilegedExceptionAction({
public Object run() {
Connection con = null;
Properties prop = new Properties();
prop.setProperty(AnoServices.AUTHENTICATION_PROPERTY_SERVICES,"("+AnoServices.AUTHENTICATION_KERBEROS5 + ")");
try {
OracleDriver driver = new OracleDriver();
con = driver.connect(url, prop);
}catch (Exception except){
except.printStackTrace();
}
return con;
}
});
String auth = ((OracleConnection)conn).getAuthenticationAdaptorName();
System.out.println("Authentication adaptor="+auth);
printUserName(conn);
conn.close();
But as it is known to create a new connection is an expensive operation. To solve this problem commonly used connection pooling (like c3p0), but I cant find example, how to combine code above and connection pool. Is there any example?

How to Get OAuth Access Token for Pinterest?

I am accessing Pinterest API for getting user's information by using this url but I can not find that how to generate an access token for Pinterest.
According to this blog post, it says that
Pinterest uses OAuth2 to authenticate users
Can you please tell me, from where I can generate OAuth access tokens for Pinterest?
First, register for an app and set up a redirect URI:
https://developers.pinterest.com/manage/
Then, find your client secret under Signature Tester:
https://developers.pinterest.com/tools/signature/
Bring the user to the OAuth dialog like this:
https://www.pinterest.com/oauth/?consumer_id=[client_id]&response_type=[code_or_token]&scope=[list_of_scopes]
If response type if token, it will be appended as a hash in the redirect URI.
If response type is code, see the post below for details on how to exchange code for token:
What's the auth code endpoint in Pinterest?
You need to register a client app under manager Apps option in Dropdown menu when you login
or
https://developers.pinterest.com/manage/
Register your app and you get AppID.
This follow the process in this link you have
http://wiki.gic.mx/pinterest-developers/
Hope this helps
**USING C#**
public string GetOAuthToken(string data)
{
string strResult = string.Empty;
try
{
string Clientid = WebConfigurationManager.AppSettings["Pinterest_Clientid"];
string ClientSecret = WebConfigurationManager.AppSettings["Pinterest_ClientSecret"];
string uri_token = WebConfigurationManager.AppSettings["Pinterest_Uri_Token"];
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri_token);
string parameters = "grant_type=authorization_code"
+ "&client_id="
+ Clientid
+ "&client_secret="
+ ClientSecret
+ "&code="
+ data;
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
System.IO.Stream os = null;
req.ContentLength = bytes.Length;
os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
System.Net.WebResponse webResponse = req.GetResponse();
System.IO.Stream stream = webResponse.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string response = reader.ReadToEnd();
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(response);
strResult = "SUCCESS:" + o["access_token"].ToString();
}
catch (Exception ex)
{
strResult = "ERROR:" + ex.Message.ToString();
}
return strResult;
}
Refer
Pinterest uses the User Flow or Oauth2
When you have an app you ant to use the app flow with an access token
So you need to create the flow yourself or use this tool online
https://frederik.today/codehelper/tools/oauth-access-token-pinterest
To make it yourself
Request Token
Exchange code for Acces Token
https://developers.pinterest.com/docs/api/v5/

Resources