Mybatis hybrid configuration system - mybatis

I am writing a CLI app with Mybatis. In my app, when i go to different menus, it prompts for the user and password for the particular database that menu goes against.
I want to use Guice and Mybatis to handle all this but i have a slight problem. I want to use the XML config file to handle the mybatis config per database, but the user and pass from each connection has to come from the UI. So basically, i want to load mybatis xml file for a particular connection, then insert the credentials for the particular connection the user typed in, then bind those to the guice injector for that set of menus.
I can do it in java with a property object pretty easy, but i can't figure out how to do it with loading the XML first, then augmenting it with certain settings before loading.
Has anyone tried this?

If you are using mybatis guice this can be done by providing your dataSourceProvider for MyBatisModule like this:
Class<? extends Provider<DataSource>> dataSourceProviderType = YourDataSourceProvider.class;
Injector injector = Guice.createInjector(
new MyBatisModule() {
#Override
protected void initialize() {
bindDataSourceProviderType(dataSourceProviderType);
// other initialization ...
}
},
// other modules
);
YourDataSourceProvider should be able to create DataSource using credentials gotten from UI.
In this case you still can use xml mappers for mybatis.

Related

TYPO3 7.6 load backend user info

I've added my own scheduler task to the TYPO3 that will, for example, create new page if necessary. The scheduler runs by a special _cli_scheduler user and if I create new pages with it, other editors may not see it.
I'm using the DataHandler (former TCE) to create new pages. The start() method accepts an optional parameter - alternative user object that will be used as a creator of the page.
Having uid of an editor user, how can I fully instantiate the \TYPO3\CMS\Core\Authentication\BackendUserAuthentication object which then I provide to the DataHandler::start()?
I was thinking of using the object manager to get new instance of the mentioned class and just set the uid on it, but the DataHandler checks some other properties of the BackendUserAuthentication object, like permissions, etc.
What is the correct way for getting BackendUserAuthentication object will all user data? Is there any factory or a repository I could use?
No one was able to help me with this, so I started digging. After some reverse engineering I have found a complete way for loading any backend user as long as you know their ID. I have created a read-only repository with the following method:
public function fetchById($userId)
{
/** #var BackendUserAuthentication $user */
$user = $this->objectManager->get(BackendUserAuthentication::class);
$user->setBeUserByUid($userId);
$user->resetUC();
$user->fetchGroupData();
$user->getFileStorages();
$user->workspaceInit();
$user->setDefaultWorkspace();
return $user;
}
It will do the following:
Load user record from database and store it internally in the $user property
Load the UC of the user
Load user/group permissions
Initialize file storage
Initialize workspace
I've dumped user created by this method and compared with the currently logged-in user and it seems that all necessary properties have been set up.
Please let me know if I missed something.

enverse-how to customize user id in customized revision listner

i am using jpa with hibernate envers of micro service.
i tried
public class MyRevisionEntityListener implements RevisionListener {
#Override
public void newRevision(Object revisionEntity) {
// If you use spring security, you could use SpringSecurityContextHolder.
final UserContext userContext = UserContextHolder.getUserContext();
MyRevisionEntity mre = MyRevisionEntity.class.cast( revisionEntity );
mre.setUserName( userContext.getUserName() );
}
}
it saves username better.but i want to save user name as"by system" when updates the record by another micro service and when user updates should save the user name as above.how to customize above code as my requirement
It would seem the most logical based on your supplied code might be to simply add a boolean flag to your UserContext thread local variable and simply check that inside the listener.
By default this flag would be false but for your special microservice or business use case, you could alter that state temporarily, run your process, and clear that state after you've finished, very much like a web filter chain works in web applications.

Alternate way of configuring data sources in quartz scheduler properties file

We are configuring the Quartz Scheduler data sources as specified in the documentation that is by providing all the details without encrypting the data base details. By this the data base details are exposed to the other users and any one who have access to the file system can easily get hands on.
So are there any other ways to provide the data sources details using API or provide the database details by encrypting and providing the details as part of quartz.properties file
On class "StdSchedulerFactory" you can call the method "initialize(Properties props)" to set needed propertries by API. Then you don't need a property-file. (See: StdSchedulerFactory API)
Example:
public Scheduler createSchedulerWithProperties(Properties props)
throws SchedulerException {
StdSchedulerFactory factory = new StdSchedulerFactory(props);
return factory.getScheduler();
}
But then you have to set all properties of SchedulerFactory. Also the properties, that have a default value with default constructor. (Search for 'quartz.properties' inside of 'quartz-2.2.X.jar' to get default property values of quartz.)

Creating a REST service in Sitecore

I'm trying to build a REST service in a Sitecore root. My application start looks like this:
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional });
}
And my URL looks like this:
http://{mydomain}/api/books
I have the correct controller and all that.
But Sitecore keeps redirecting me to the 404 page. I've added the path to the IgnoreUrlPrefixes node in the web.config, but to no avail. If I had to guess, I'd think that Sitecore's handler is redirecting before my code gets the chance to execute, but I really don't know.
Does anybody have any idea what might be wrong?
Your assessment is correct. You need a processor in the httpRequestBegin pipeline to abort Sitecore's processing. See the SystemWebRoutingResolver in this answer:
Sitecore and ASP.net MVC
It's also described in this article:
http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/10/Sitecore-MVC-Crash-Course.aspx
But I'll include the code here as well. :)
public class SystemWebRoutingResolver : Sitecore.Pipelines.HttpRequest.HttpRequestProcessor
{
public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args)
{
RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(args.Context));
if (routeData != null)
{
args.AbortPipeline();
}
}
}
Then in your httpRequestBegin configuration:
<processor type="My.SystemWebRoutingResolver, My.Classes" />
You might want to have a look at Sitecore Web Api
It's pretty much the same you are building.
Another option, which I've used to good effect, is to use the content tree, the "star" item, and a sublayout/layout combination dedicated to this purpose:
[siteroot]/API/*/*/*/*/*/*/*/*/*
The above path allows you to have anywhere between 1 and 9 segments - if you need more than that, you probably need to rethink your process, IMO. This also retains all of the Sitecore context. Sitecore, when unable to find an item in a folder, attempts to look for the catch-all star item and if present, it renders that item instead of returning a 404.
There are a few ways to go about doing the restful methods and the sublayout (or sublayouts if you want to segregate them by depth to simplify parsing).
You can choose to follow the general "standard" and use GET, PUT, and POST calls to interact with these items, but then you can't use Sitecore Caching without custom backend caching code). Alternately, you can split your API into three different trees:
[siteroot]/API/GET/*/*/*/*/*/*/*/*/*
[siteroot]/API/PUT/*/*/*/*/*/*/*/*/*
[siteroot]/API/POST/*/*/*/*/*/*/*/*/*
This allows caching the GET requests (since GET requests should only retrieve data, not update it). Be sure to use the proper caching scheme, essentially this should cache based on every permutation of the data, user, etc., if you intend to use this in any of those contexts.
If you are going to create multiple sublayouts, I recommend creating a base class that handles general methods for GET, PUT, and POST, and then use those classes as the base for your sublayouts.
In your sublayouts, you simply get the Request object, get the path (and query if you're using queries), split it, and perform your switch case logic just as you would with standard routing. For PUT, use Response.ReadBinary(). For POST use the Request.Form object to get all of the form elements and iterate through them to process the information provided (it may be easiest to put all of your form data into a single JSON object, encapsulated as a string (so .NET sees it as a string and therefore one single property) and then you only have one element in the post to deserialize depending on the POST path the user specified.
Complicated? Yes. Works? Yes. Recommended? Well... if you're in a shared environment (multiple sites) and you don't want this processing happening for EVERY site in the pipeline processor, then this solution works. If you have access to using MVC with Sitecore or have no issues altering the pipeline processor, then that is likely more efficient.
One benefit to the content based method is that the context lifecycle is exactly the same as a standard Sitecore page (logins, etc.), so you've got all the same controls as any other item would provide at that point in the lifecycle. The negative to this is that you have to deal with the entire page lifecycle load before it gets to your code... the pipeline processor can skip a lot of Sitecore's process and just get the data you need directly, making it faster.
you need to have a Pipeline initializer for Routing:
It will be like :
public class Initializer
{
public void Process(PipelineArgs args)
{
RouteCollection route = RouteTable.Routes;
route.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
}
}
On config file you will have :
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<initialize>
<processor type="_YourNameSpace.Initializer,_YourAssembly" />
</initialize>
</pipelines>
</sitecore>
</configuration>
Happy coding

lift Session management

I am new to lift. I have been working with MVC model so far and using basic session management model i.e. storing a token in the session and check on each request.
I am trying to do the same with lift, but my session getting expired abruptly. even some time I just logged in and it logged out. I have analysis that whenever I gets log message like this:
INFO - Session ucjrn5flnq9q1ke52z5zixgtt expired
I have searched but I couldn't find any step by step tutor
Sessions are managed by your servlet container. Which one are you using? You should look at the container's documentation.
Do not attempt to use S.get et al to access session bound information. This is just plain dangerous. Do it like this:
class Thing {
object SessionThing extends SessionVar[Box[String]](Empty)
...
def someMethod = {
...
SessionThing.is // returns you a Box[String].
// operates on the session variable if it exists,
// otherwise provides a sensible default
SessionThing.is.map(_.toLowerCase).openOr("default")
...
}
}
You need to understand the snippet and state lifecycles really, as it seems you're not fully understanding how lift's session mechanics work.
I found the solution of the problem. I was using embedded jetty server, where I was using ServletContextHandler to register lift filter. I changed it to WebAppContext and it started working fine.
Puneet