How to fetch liferay entity through custom-finder in custom plugin portlet? - sql

How can we fetch liferay entities through custom-finder using custom SQL?
Following is my sql query written in default.xml (I have trimmed down the query to the bare minimum so that the logic remains simple. Since it included a few functions and joins we couldn't use DynamicQuery API ):
SELECT
grp.*
FROM
Group_
WHERE
site = 1
AND active_ = 1
AND type_ <> 3
Relevant code in MyCustomGroupFinderImpl.java:
Session session = null;
try {
session = openSession();
// fetches the query string from the default.xml
String sql = CustomSQLUtil.get(FIND_ONLY_ACTIVE_SITES);
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addEntity("Group_", GroupImpl.class);
// sqlQuery.addEntity("Group_", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.GroupImpl"));
return (List<Group>) QueryUtil.list(sqlQuery, getDialect(), 0, QueryUtil.ALL_POS);
}
catch (Exception e) {
throw new SystemException(e);
}
finally {
closeSession(session);
}
This above code won't work as the GroupImpl class is present in portal-impl.jar and this jar cannot be used in custom portlet.
I also tried using sqlQuery.addEntity("Group_", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.GroupImpl"))
But this above code throws exception:
com.liferay.portal.kernel.exception.SystemException:
com.liferay.portal.kernel.dao.orm.ORMException:
org.hibernate.MappingException:
Unknown entity: com.liferay.portal.model.impl.GroupImpl
But the same code works for our custom-entity, if we write sqlQuery.addEntity("MyCustomGroup", MyCustomGroupImpl.class);.
Thanks

I found out from the liferay forum thread that instead of session = openSession();
we would need to fetch the session from liferaySessionFactory as follows to make it work:
// fetch liferay's session factory
SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
Session session = null;
try {
// open session using liferay's session factory
session = sessionFactory.openSession();
// fetches the query string from the default.xml
String sql = CustomSQLUtil.get(FIND_ONLY_ACTIVE_SITES);
SQLQuery sqlQuery = session.createSQLQuery(sql);
// use portal class loader, since this is portal entity
sqlQuery.addEntity("Group_", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.GroupImpl"));
return (List<Group>) QueryUtil.list(sqlQuery, getDialect(), 0, QueryUtil.ALL_POS);
}
catch (Exception e) {
throw new SystemException(e);
}
finally {
sessionFactory.closeSession(session); // edited as per the comment on this answer
// closeSession(session);
}
Hope this helps somebody on stackoverflow, also I found a nice tutorial regarding custom-sql which also uses the same approach.

Related

Register Hibernate 5 Event Listeners

I am working on a legacy non-Spring application, and it is being migrated from Hibernate 3 to Hibernate 5.6.0.Final (latest at this time). I have generally never used Hibernate Event Listeners in my work, so this is quite new to me, and I am studying these in Hibernate 5.
Currently in some test class we have defined the code this way for Hibernate 3:
protected static Configuration createSecuredDatabaseConfig() {
Configuration config = createUnrestrictedDatabaseConfig();
config.setListener("pre-insert", "com.app.server.services.db.eventlisteners.MySecurityHibernateEventListener");
config.setListener("pre-update", "com.app.server.services.db.eventlisteners.MySecurityHibernateEventListener");
config.setListener("pre-delete", "com.app.server.services.db.eventlisteners.MySecurityHibernateEventListener");
config.setListener("pre-load", "com.app.server.services.db.eventlisteners.EkoSecurityHibernateEventListener");
return config;
}
This is obviously no longer valid, and I believe I need to create a Hibernate Integrator, which I have done.
public class MyEventListenerIntegrator implements Integrator {
#Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {
EventListenerRegistry eventListenerRegistry = serviceRegistry.getService(EventListenerRegistry.class);
eventListenerRegistry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(new MySecurityHibernateEventListener());
eventListenerRegistry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(new MySecurityHibernateEventListener());
eventListenerRegistry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(new MySecurityHibernateEventListener());
eventListenerRegistry.getEventListenerGroup(EventType.PRE_LOAD).appendListener(new MySecurityHibernateEventListener());
}
So, now I believe the next step is to add this to the session via the registry builder. I am using this website to help me:
https://www.boraji.com/hibernate-5-event-listener-example
Because we were using older Hibernate 3, we had code to create our session factory as follows:
protected static SessionFactory buildSessionFactory(Database db)
{
if (db == null) {
throw new NullPointerException("Database specifier cannot be null");
}
try {
Configuration config = createSessionFactoryConfiguration(db);
String url = config.getProperty("connection.url");
String user = config.getProperty("connection.username");
String password = config.getProperty("connection.password");
try {
String dbDriver = config.getProperty("hibernate.connection.driver_class");
Class.forName(dbDriver);
Connection conn = DriverManager.getConnection(url, user, password);
}
catch (SQLException error) {
logger.info("Didn't find driver, on QA or production, so it's okay to assume we have DB connection");
error.printStackTrace();
}
SessionFactory sessionFactory = config.buildSessionFactory();
sessionFactoryConfigs.put(sessionFactory, config); // Cannot recover config from factory instance, must be stored.
return sessionFactory;
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
logger.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
The link that I referred to above has a much different way of creating the sessionfactory. So, I'll be testing that out to see if it works in our app.
Without Spring handling our sessions and transactions, in this app it is coded by hand the way it was done before Spring, and I haven't seen that kind of code in years.
I solved this issue with the help from the link I provided above. However, I didn't copy exactly what they did, but some of it helped. My solution is as follows:
protected static SessionFactory createSecuredDatabaseConfig() {
Configuration config = createUnrestrictedDatabaseConfig();
BootstrapServiceRegistry bootstrapRegistry =
new BootstrapServiceRegistryBuilder()
.applyIntegrator(new EkoEventListenerIntegrator())
.build();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry).applySettings(config.getProperties()).build();
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
This was it. I tried multiple different ways to register the events without the BootstrapServiceRegistry, but none of those worked. I did have to create the integrator. What I did NOT include was the following:
MetadataSources sources = new MetadataSources(serviceRegistry )
.addPackage("com.myproject.server.model");
Metadata metadata = sources.getMetadataBuilder().build();
// did not create the sessionFactory this way
sessionFactory = metadata.getSessionFactoryBuilder().build();
If I had gone further and use this method to create the sessionFactory, then all of my queries would have been complaining about not being able to find the parameterName, which is something else.
The Hibernate Integrator and this method to create the sessionFactory is all for the unit tests. Without registering these events, one unit test would fail, and now it doesn't. So, this solves my problem for now.

Issue of multiple SQL notifications in ASP.Net web application on page refresh

I am facing an issue while using SQL Server Notifications. I am developing a web application in ASP.net where one of the page needs to be notified about new entries in one of the tables in a SQL Server database. I am using SQL Server Notification services along with Signal R to achieve this functionality.All seems to work fine with my web page getting updates about new data entries.
The problem arises when the page using notification is refreshed. I find the no of notification for single entry in database go up by the number of refreshes. So if I refresh the page thrice, I get 3 notifications for one entry. I am bit concerned if this would be a burden on server when the no of connected users increases. Also if there is an error while processing the request to update the page with new entry, the user gets multiple error messages with same text. I tried debugging my code and found out that the on change event of SqlDependency object used is fired multiple time with different IDs every time. Below is brief overview of what my code is doing to use notifications -
I am using SQL Server 2012 and enable_broker is set for the database.
In global.asax, I am using application_start and application_stop events to start and stop SqlDependency.
In page code, I am setting a new SqlDependency object on page load using a command object to monitor the exact data field of the table.
When onchange of SqlDependency object fires, I am notifying the UI using Signal R hub class. Then I remove the OnChange handler of the SqlDependency object, call for SqlDependency.Stop(connectionstring), set SqlDependency object to nothing, call for SqlDependency.Start(connectionstring) and finally set up the SqlDependency object again using the command object for updated data. This whole set to nothing-stop-start-reset object is to continue monitoring the data for changes.
The above steps work fine but when I refresh the page, those are repeated for the number of refreshes. I tried a lot of things by changing code and debugging but nothing seems to resolve the issue. Now I am wondering if it is some setting somewhere that I missed.
Please help me resolve this issue. Also let me know if any other information such as environment, coding details etc are required.
Regards,
Tanmay
This is probably caused by connection pooling. It reurns a notification for each connection open in the pool. You can cancel the pooling for this specific service by changing the Connection String property:
Pooling = False;
i have resolved the following problem by using the below code, its works me.
SingletonDbConnect.cs
public class SingletonDbConnect
{
private static SingletonDbConnect dbInstance;
private static string connString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
private readonly SqlConnection conn = new SqlConnection(connString);
private SingletonDbConnect()
{
}
public static SingletonDbConnect getDbInstance()
{
if (dbInstance == null)
{
dbInstance = new SingletonDbConnect();
}
return dbInstance;
}
public SqlConnection getDbConnection()
{
try
{
conn.Close();
conn.Open();
}
catch (SqlException e)
{
}
finally
{
}
return conn;
}
}
SqlDependencyEvent.cs
public class SqlDependencyEvent
{
internal static int PageLoadCounter = 0;
public void getEmailMessagesByEmailId(Guid emailid)
{
SingletonDbConnect conn = SingletonDbConnect.getDbInstance();
using (MembersController.command = new SqlCommand(SQL.emailmessagesbyaccount_sql(), conn.getDbConnection()))
{
MembersController.command.Notification = null;
if (MembersController.dependency == null)
{
MembersController.dependency = new SqlDependency(MembersController.command);
MembersController.dependency.OnChange += new OnChangeEventHandler(emailMessages_OnChange);
}
var reader = MembersController.command.ExecuteReader();
}
PageLoadCounter++;
}
private void emailMessages_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
if (MembersController.dependency != null)
{
MembersController.dependency.OnChange -= emailMessages_OnChange;
}
NotificationHub.EmailUpdateRecords();
SingletonDbConnect conn = SingletonDbConnect.getDbInstance();
using (MembersController.command = new SqlCommand(SQL.emailmessagesbyaccount_sql(), conn.getDbConnection()))
{
MembersController.command.Parameters.Add(new SqlParameter("#emailaccountid", defaultemailid));
MembersController.command.Notification = null;
MembersController.dependency = new SqlDependency(MembersController.command);
MembersController.dependency.OnChange += new OnChangeEventHandler(emailMessages_OnChange);
var reader = MembersController.command.ExecuteReader();
}
PageLoadCounter++;
}
}
}
MembersController.cs
public class MembersController : Controller
{
SingletonDbConnect conn = SingletonDbConnect.getDbInstance();
internal static SqlCommand command = null;
internal static SqlDependency dependency = null;
//
// GET: /Members/
public ActionResult Index()
{
SqlDependency.Stop(conn.getDbConnection().ConnectionString);
SqlDependency.Start(conn.getDbConnection().ConnectionString);
return View();
}
}
its resolved my problem and its working me, even we refresh page more than 1, but SqlDependency will call only once.
i used one of the MembersController for SqlDependency start and stop, its your own logic, you can use the same code in Global.ascx instead of MembersController.cs
i hope it will help you and resolve issue. ask me if you have still any problem thanks.

Why I'm getting all history revisions when querying for Iterations or Releases?

I'm working with Rally REST API for Java
I want get the list of actual Iterations and Releases
here is the snippet
JsonObject projects = new JsonObject();
QueryRequest queryProjects = new QueryRequest("release");
queryProjects.setPageSize(1);
queryProjects.setLimit(1000);
queryProjects.setFetch(new Fetch("_refObjectName","Name"));
QueryResponse queryResponse;
try {
queryResponse = restApi.query(queryProjects);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new ServiceException(e);
}
In result I'm getting the list with a lot of duplicates. After closer inspection it seems I'm getting all versions of object - for the same Iteration/Release I have multiple versions - I can see different "_objectVersion" attribute for such duplicates.
Why is it so?
Can you please help me with the query which will retrieve distinct list of Iterations / Releases - I'm interested in just latest versions.
I can filter it out in Java but have a feeling there is more 'proper' way of doing this. Also getting the list with whole object history is not the best for code performance.
Thanks for any help!
When Releases and Iterations are created in Rally in a top project there is an option to propagate them throughout the project hierarchy. For example, if you have top project P1 with child project P2 and grandchild projects P21 and P22, you may create 4 releases with the same name and the same start and release dates. They are not identical releases: they have ObjectID and _ref unique to them. Please verify if this applies to your scenario.
To limit release query to a specific project set request project. Here is an example that returns only three releases that I have in a top project: R1,R2, and R3. Note
String projectRef = "/project/12352608219";
that is used later in the code:
releaseRequest.setProject(projectRef);
Note also the commented out
//String workspaceRef = "/workspace/12352608129";
and
// releaseRequest.setWorkspace(workspaceRef);
If I switch the comments: comment out project reference and uncomment workspace reference I will get what you called duplicates: multiple R1, R2 and R3 releases.
public class FindReleases {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String projectRef = "/project/12352608219";
//String workspaceRef = "/workspace/12352608129";
String applicationName = "RESTExampleFindReleasesByProject";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion()); //v.2.0 by default when using 2.0.2 jar and up
QueryRequest releaseRequest = new QueryRequest("Release");
releaseRequest.setFetch(new Fetch("Name"));
releaseRequest.setLimit(1000);
releaseRequest.setScopedDown(false);
releaseRequest.setScopedUp(false);
// releaseRequest.setWorkspace(workspaceRef);
releaseRequest.setProject(projectRef);
QueryResponse releaseQueryResponse = restApi.query(releaseRequest);
int numberOfReleasesInProject = releaseQueryResponse.getTotalResultCount();
System.out.println(numberOfReleasesInProject);
if(numberOfReleasesInProject >0){
for (int i=0;i<numberOfReleasesInProject;i++){
JsonObject releaseJsonObject = releaseQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println(releaseJsonObject.get("Name"));
}
}
}
finally{
if (restApi != null) {
restApi.close();
}
}
}
}

Unable to query a different workspace

I was trying to follow this post to query a testcase in a workspace("/workspace/6749437088") that is not the default workspace but the query is not returning that testcase and in fact, not returning anything. Below is the code I am using. If I do a query with 'not equal' the test cases, I notice that it is returning test cases in the user's default workspace. I am using C# and using Rally Rest API Runtime v4.0.30319 and ver 1.0.15.0. Any suggestions? Thanks.
Inserting test case result using Java Rally Rest API failing when workspace is different from default set on account
private string GetRallyObj_Ref(string ObjFormttedId)
{
string tcref = string.Empty;
try
{
string reqType = _Helper.GetRallyRequestType(ObjFormttedId.Substring(0, 2).ToLower());
Request request = new Request(reqType);
request.Workspace = "/workspace/6749437088";
request.Fetch = new List<string>()
{
//Here other fields can be retrieved
"Workspace",
"Name",
"FormattedID",
"ObjectID"
};
//request.Project = null;
string test = request.Workspace;
request.Query = new Query("FormattedID", Query.Operator.Equals, ObjFormttedId);
QueryResult qr = _RallyApi.Query(request);
string objectid= string.Empty;
foreach (var rslt in qr.Results)
{
objectid = rslt.ObjectID.ToString();
break;
}
tcref = "/"+reqType+"/" + objectid;
}
catch (Exception ex)
{
throw ex;
}
return tcref;
Sorry, I found out the issue. I was feeding the code a project ref#, not a workspace ref #. I found out the correct workspace by using pieces of the code in the answer part of this post: Failed when query users in workspace via Rally Rest .net api by querying the workspace refs of the username I am using and there I found out the correct workspace ref. Thanks, Kyle anyway.
The code above seems like it should work. This may be a defect- I'll look into that. In the meantime if you are just trying to read a specific object from Rally by Object ID you should be able to do so like this:
restApi.GetByReference('/testcase/12345',
'Results, 'Verdict', 'Duration' //fetch fields);

Execute a SQL stored procedure before every query generated by EntityFramework

I need to execute a SQL stored procedure every time before I query my ObjectContext. What I want to achieve is setting the CONTEXT_INFO to a value which will be later on used with most of my queries.
Has anyone done that? Is that possible?
[EDIT]
Currently I'm achieving this by opening the connection and executing the stored procedure in my ObjectContext constructor like this:
public partial class MyEntitiesContext
{
public MyEntitiesContext(int contextInfo) : this()
{
if (Connection.State != ConnectionState.Open)
{
Connection.Open(); // open connection if not already open
}
var connection = ((EntityConnection)Connection).StoreConnection;
using (var cmd = connection.CreateCommand())
{
// run stored procedure to set ContextInfo to contextInfo
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[dbo].[SetContextInfo]";
cmd.Parameters.Add(new SqlParameter("#ci", _contextInfo));
cmd.ExecuteNonQuery();
}
// leave the connection open to reuse later
}
}
Then in my integration test:
[TestMethod]
public void TestMethod1()
{
using (var ctx = new MyEntitiesContext(1))
{
Assert.AreEqual(2, ctx.Roles.ToList().Count);
Assert.AreEqual(2, ctx.Users.ToList().Count);
}
}
But this requires me to leave the connection open - this is error prone since I will always need CONTEXT_INFO, and another developer might easily do:
[TestMethod]
public void TestMethod2()
{
using (var ctx = new MyEntitiesContext(1))
{
// do something here
// ... more here :)
ctx.Connection.Close(); // then out of the blue comes Close();
// do something here
Assert.AreEqual(2, ctx.Roles.ToList().Count);
Assert.AreEqual(2, ctx.Users.ToList().Count); // this fails since the where
// clause will be:
// WHERE ColumnX = CAST(CAST(CONTEXT_INFO() AS BINARY(4)) AS INT)
// and CONTEXT_INFO is empty - there are no users with ColumnX set to 0
// while there are 2 users with it set to 1 so this test should pass
}
}
The above means that I can write the code like in my test and everthing is green (YAY!) but then my colleague uses the code from TestMethod2 somewhere in his business logic and it's all f'd up - and nobody knows where and why since all tests are green :/
[EDIT2]
This blog post certainly does not answer my question but actually solves my problem. Maybe going with NHibernate will be better suited for my purpose :)
We have used this pattern.
But the way we did it was to call the stored procedure as the first opperation inside each db context.
Finally I found the answer. I can wrap the connection using the EFProvider wraper toolkit from EFProviderWrappers.
To do this I mostly have to derive from EFProviderWrapperConnection and override the DbConnection.Open() method. I already tried it with the Tracing provider and it works fine. Once I test it with my solution I will add more information.