Setting spring ldap base dynamically for a new connection each usage - spring-ldap

This question is on best practice and if possible.
I need to know if I can dynamically change the base of ldap context source within code?
With my ldap bean wired with the following
<ldap:context-source
url="ldap://<url>"
base="dc=example,dc=local"
username="<user>#example.local"
password="<pass>"
/>
can I in code change the context source to another base depending on a given dynamically changing parameter?
For instance if i want to change base to dc=example2,dc=local .
If I was programmatically setting up LdapContextSource this would be no problem.

So this was simpler and easier than I thought.
All i had to do was go ahead and create
LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl("ldap://<url>");
ctxSrc.setBase("dc=example,dc=local");
ctxSrc.setUserDn("<user>#example.local");
ctxSrc.setPassword("<pass>");
ctxSrc.afterPropertiesSet(); // this method should be called.
LdapTemplate tmpl = new LdapTemplate(ctxSrc);
setLdapTemplate(tmpl);
and base my LdapContextSource values on the properties that in my case is a dynamic source.
I was thinking that there was something more Spring like to do .

Related

Creating JHipster blueprint to extend the field type prompt

I have already created a test blueprint that works, so I kinda got the idea, but I would like to make sure that I am approaching this correctly.
I want to extend the field type prompt to offer custom types alongside String, int, boolean etc.
This means I need to modify the templates, like templates/src/main/java/package/domain/Entity.java.ejs
My blueprint only had generators/client and generators/entity-client, so I guess I have to:
create generators/entity-server
create index.js
create files.js (can I copy that from here https://github.com/jhipster/generator-jhipster/blob/master/generators/entity-server/files.js ?)
create the templates in entity-server/templates
create generators/entity
copy and modify generators/entity/prompts.js: do I have to just write a new prompts.js, or do I have to copy over everything in generators/entity and only change what I would like to change ?
For the templates, can I copy them from the JHipster repo ?
Should I ? If not, why not and what is the alternative ?
If copying them is the right move, do I have to copy everything ? Or just the ones I want to modify ? (I haven't checked yet if I will need to modify everything)
When JHipster is updated, I suppose either I manually merge the new files, or I risk that slowly my code will differ more and more from the JHipster code ?
Is there a simpler method to achieve what I am trying to do ?
It would be nice if I could just say I want to add TypeX and TypeY to that prompt and provide limited templates that only cover those types, like a template for the import, one for the field, and one for the setter and getter, and if only the import is provided, a generic template is used.
I'll try to answer to all your questions.
First to create Blueprint I suggest to use https://github.com/jhipster/generator-jhipster-blueprint even in another folder and copy all you need for your current project. I think it's easier and you could choose which generator you want to add e.g. entity-server and entity.
Prompts phase
If you want to modify prompt phase you can merge your phase with the JHipster one like that
get prompting() {
const phaseFromJHipster = super._prompting();
const phaseFromMe = {
askForTheme: prompts.askForTheme,
setMySharedConfigOptions() {
this.configOptions.theme = this.theme;
}
};
return { ...phaseFromJHipster, ...phaseFromMe };
}
(source: https://github.com/avdev4j/samSuffit/tree/master/generators/client)
But by doing this you can't modify existing questions, for this case you should copy all existing questions into your blueprint.
Templates management
Your blueprint is linked with a JHipster version. As I used to say (in my talks) is that you should copy and modify templates from JHipster except for configuration files because it's a bit tricky to handle. For them, I prefer to use JHipster API like 'replaceContent()' or the needle API which allowed you to insert some code into some files (like a dependency in the pom.xml file).
Of course you can use the way you want, but with experiences I prefer to control my templates and merge them when I upgrade the JHipster version.
You should only copy the templates you want to modify, merge JHipster and your writing phase. JHipster use yeoman, which use memfs to handle file generation. Every files are created in memory and dumped at the final step. You can easily override a file without performance compromise.
get writing() {
const phaseFromJHipster = super._writing();
/* eslint-disable */
const phaseFromSam = {
writeSamFiles() {
if (this.clientFramework === 'angularX') {
return writeAngularFiles.call(this);
}
}
};
/* eslint-enable */
return { ...phaseFromJHipster, ...phaseFromSam };
}
JHipster upgrade
I suggest you to check templates when upgrading JHipster and apply modifications if needed. Otherwise, you could have bugs. Also, I suggest to set a definitive (like 6.1.0) version of JHipster in your blueprint package.json.
As far I know there is no way to do what you want to do. I'm thinking of a way to modify prompts easily without copying all other questions, if you want to contribute ;).
You can check my blueprint sample I use to show in my talks:
https://github.com/avdev4j/samSuffit/
I hope It can help you can, feel free to ask more.
regards,

CodedUI- Best way to create and use UIObject Repository( that requires minimum effort when UI changes)

I started working with CodedUI few months before to automate a desktop Application(WPF).
Just checking out for the best ways to create a framework for my Application.
As, I have seen in other automation tools, I feel the heart of an automation framework using any tool(UI Based) is the way it's object Repository is created i.e. how well the UI objects are defined. A Cleaner and well defined Object Repository always proves to be very helpful when it comes to updating your tests.
I am trying to discover the best way to store my UIObjects so that in case of any UI changes in my Application, I have to put minimum effort to update my automation test.
Also, If an Object changes in application, updating it only at one place should solve the problem.
This can be any kind of change like :
->change in just a property(This I feel would be very easy to update in automation Test. The best and Easiet way I feel is to simply update the .uitest file(the xml file) if possible.)
->change in hierarchy and position
->entirely new object added
For the 2nd and 3rd changes, updating scripts become a difficult job, esp if the UIObject is being referred at may places, in many TestMethods, or Modules.
Also, I have generally seen that in Test Methods, Variable Declarations are done to create a reference to the UIMap objects and those variables are further used in the TestMethod Code.
So, in this case If the UI of my application changes, I will have to update the variable decalaration in each of the Test Methods. I want to reduce this effort to changing the variable decalaration only at one place. OfCourse, I cannot have all the code inside only one Test Method. One way that came to my mind is as:
Can't I have simply one common place for all these Variable decalarations. We can give a unique and understandable name to each UIObject e.g.: The decalratoions will look like:
UITabPage UITabPage = this.UIMap.UISimWindow.UISelectEquipmentTabList.UITabPage;
WpfRow UIRow = this.UIMap.UISimWindow.UISelectEquipmentTabList.UITabPage.UIEquipmentDetailsTable.UIRow;
WpfText UIEquipmentTagText = this.UIMap.UISimWindow.UISelectEquipmentTabList.UITabPage.UIEquipmentDetailsTable.UIRow.UITagCell.UIEquipmentTagText;
WpfCheckBox UIEquipmentCheckBox = this.UIMap.UISimWindow.UISelectEquipmentTabList.UITabPage.UIEquipmentDetailsTable.UIRow.UICheckBoxCell.UICheckBox;
....
....
and use these variables wherever required. Hence, In case of any chnages also, there will be only one place where you will need to update thse objects.
But for this, These varaibles must be made STATIC. What can be problem with making these Object Variables static?
Please provide your suggestion on this topic. May be what I am thinking is not possible or practical. I just want to choose the best way to start with before I go too far with the automation scripts and realize later that my approach wasn't a good one.
Thanks in Advance,
Shruti
Look into using descriptive programming instead of using the UIMaps.
Make a static class with generic functions to assist. Going to give you some examples of how to set it up.
For example:
public WinWindow parentwin(string ParentControlName)
{
var parentwin = new WinWindow();
parentwin.SearchProperties.Add("Control Name", ParentControlName);
return parentwin;
}
public WinWindow childwin(string ChildWinControlName, string ParentControlName)
{
var childwin = new WinWindow(parentwin(ParentControlName));
childwin.SearchProperties.Add("Control Name", ChildWinControlName);
return childwin;
}
public WinButton button(string ButtonName,string ChildWinControlName, string ParentControlName)
{
var childwin = childwin(ChildWinControlName,ParentControlName);
var button = new WinButton(childwin);
button.SearchProperties.Add("Name", ButtonName);
}
public void ClickButton(string ButtonName,string ChildWinControlName, string ParentControlName)
{
var button = button(ButtonName,ChildWinControlName,ParentControlName);
Mouse.Click(button);
}
public void ChangeFocus(WinWindow NewFocus)
{
var NewFocus = new NewFocus();
NewFocus.SetFocus();
}
public void ChangeFocus(WinWindow NewFocusChild, string c)
{
var a = new NewFocus();
a.SetFocus();
}
ChangeFocus(childwin("WelcomeForm", "MainForm");
ClickButton("&OK", "WelcomeForm", "MainForm");

Hibernate validator programmatic constraints declaration and JSF

I Have a JSF-2.2 web app on a WildFly 8.1 app server shiping Hibernate-validator 5.1
I want to set some constrainst programmaticaly using the fluent API, because they depends on the case for example a min and max of a #Size constraint could vary or a field could be #NotNull or not...
so I try to programmaticaly configure constraints such as describe here : http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html_single/#section-programmatic-api
I do somthing like that to try (in a EJB #Singleton #Startup):
HibernateValidatorConfiguration configuration = Validation
.byProvider( HibernateValidator.class )
.configure();
ConstraintMapping constraintMapping = configuration.createConstraintMapping();
constraintMapping
.type( Car.class )
.property( "manufacturer", FIELD )
.constraint( new NotNullDef() )
.property( "licensePlate", FIELD )
.ignoreAnnotations()
.constraint( new NotNullDef() )
.constraint( new SizeDef().min( 2 ).max( 14 ) );
Validator validator = configuration.addMapping( constraintMapping )
.buildValidatorFactory()
.getValidator();
But then JSF don't use this new constraints mapping.
I can submit forms without problem even if I break the constraints programmaticaly set
I don't know how to configure the Validator or ValidatorFactory JSF is using or how to provide to JSF an other Validator or ValidatorFactory...
Or may be It's more about configuring WildFly server, something to do in a config file or JNDI, I don't have a clue...
EDIT
I try to bind new Validator and validator factory in JNDI
But I can't because "Naming context is read-only"
Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(jndiProperties);
context.bind("java:comp/Validator", factory.getValidator());
context.bind("java:comp/ValidatorFactory", factory);
Thank you Hardy
As you proposed I post Hibenate Validator improvement
https://hibernate.atlassian.net/browse/HV-955
There is no way atm to do what you are after. Hibernate Validator has indeed the programmatic mapping, but it is a Hibernate Validator specific feature. There is no way to bootstrap this functionality in a Bean Validation way. I am saying this, since the only way to customize your ValidatorFactory and hence Validator instance within the container is via validation.xml. And there is no mechanism for the fluent API in this configuration file.
Your JNDI idea is in principal good, but as you say, it is only read only.
validation.xml allows for vendor specific properties though. One could imagine a property like org.hibernate.validator.config_factory=acme.MyConfig. The value of the property would point to a fully specified class which would contain some sort of factory method which returns the programmatic mapping to be added to the configuration. Unfortunately, such a property does not yet exist. You could open an issue here though ;-)

How to use ObjectContext with Model Builder?

Is there a way we can use ObjectContext with DbContext's ModelBuilder? We don't want to use POCO because we have customized property code that does not modify entire object in update, but only update modified properties. Also we have lots of serialisation and auditing code that uses EntityObject.
Since poco does create a proxy with EntityObject, we want our classes to be derived from EntityObject. We don't want proxy. We also heavily use CreateSourceQuery. The only problem is EDMX file and its big connection string syntax web.config.
Is there any way I can get rid of EDMX file? It will be useful as we can dynamically compile new class based on reverse engineering database.
I would also like to use DbContext with EntityObject instead of poco.
Internal Logic
Access Modified Properties in Save Changes which is available in ObjectStateEntry and Save them onto Audit with Old and New Values
Most of times we need to only check for Any condition on Navigation Property for example
User.EmailAddresses.CreateSourceQuery()
.Any( x=> x.EmailAddress == givenAddress);
Access Property Attributes, such as XmlIgnore etc, we rely heavily on attributes defined on the properties.
A proxy for a POCO is a dynamically created class which derives from (inherits) a POCO. It adds functionality previously found in EntityObject, namely lazy loading and change tracking, as long as a POCO meets requirements. A POCO or its proxy does not contain an EntityObject as the question suggests, but rather a proxy contains functionality of EntityObject. You cannot (AFAIK) use ModelBuilder with EntityObject derivatives and you cannot get to an underlying EntityObject from a POCO or a proxy, since there isn't one as such.
I don't know what features of ObjectContext does your existing serialisation and auditing code use, but you can get to ObjectContext from a DbContext by casting a DbContext to a IObjectContextAdapter and accessing IObjectContextAdapter.ObjectContext property.
EDIT:
1. Access Modified Properties in Save Changes which is available in ObjectStateEntry and Save them onto Audit with Old and New Values
You can achieve this with POCOs by using DbContext.ChangeTracker. First you call DbContext.ChangeTracker.DetectChanges to detect the changes (if you use proxies this is not needed, but can't hurt) and then you use DbCotnext.Entries.Where(e => e.State != EntityState.Unchanged && e.State != EntityState.Detached) to get DbEntityEntry list of changed entities for auditing. Each DbEntityEntry has OriginalValues and CurrentValues and the actual Entity is in property Entity.
You also have access to ObjectStateEntry, see below.
2. Most of times we need to only check for Any condition on Navigation Property for example:
User.EmailAddresses.CreateSourceQuery().Any( x=> x.EmailAddress == givenAddress);
You can use CreateSourceQuery() with DbContext by utilizing IObjectContextAdapter as described previously. When you have ObjectContext you can get to the source query for a related end like this:
public static class DbContextUtils
{
public static ObjectQuery<TMember> CreateSourceQuery<TEntity, TMember>(this IObjectContextAdapter adapter, TEntity entity, Expression<Func<TEntity, ICollection<TMember>>> memberSelector) where TMember : class
{
var objectStateManager = adapter.ObjectContext.ObjectStateManager;
var objectStateEntry = objectStateManager.GetObjectStateEntry(entity);
var relationshipManager = objectStateManager.GetRelationshipManager(entity);
var entityType = (EntityType)objectStateEntry.EntitySet.ElementType;
var navigationProperty = entityType.NavigationProperties[(memberSelector.Body as MemberExpression).Member.Name];
var relatedEnd = relationshipManager.GetRelatedEnd(navigationProperty.RelationshipType.FullName, navigationProperty.ToEndMember.Name);
return ((EntityCollection<TMember>)relatedEnd).CreateSourceQuery();
}
}
This method uses no dynamic code and is strongly typed since it uses expressions. You use it like this:
myDbContext.CreateSourceQuery(invoice, i => i.details);

Axis SecureSocketFactory - Setting the constructor attributes

I have a customer SecureSocketFactory set to be used by Axis when making an https connection using the following property:
AxisProperties.setProperty("axis.socketSecureFactory",
"com.metavante.csp.model.manager.mobilepayments.MonitiseSSLSocketFactory");
When this class is instantiated by Axis, the constructor with a Hashtable (attributes) is called. I see the timeout attribute is set in this table. Is there anyway to set more values in this?
I would like to be able to configure the Socket Factory on a per-instance scenario instead of globally by using static or system properties.
Edit: I found out these attributes are actually the HttpSender (BasicHandler) options. I still am unable to set these dynamically though.
I figured out a way around the problem. In my code where I wanted to set the property I use:
serviceLocator.getEngine().setOption(USE_CERT_PROPERTY, new Boolean(true));
where getEngine returns the AxisEngine in use. Then in the socket factory I can:
Boolean useSMS = (Boolean) MessageContext.getCurrentContext().getProperty(OtherClass.USE_CERT_PROPERTY);
I could set the object to whatever, maybe I'll go with the certificate name I needed. Hope this helps someone.
You can retrieve the SocketFactory instance and then change or add attributes, if you are interested in modify SocketFactory behavior. But if you do this, you also should inject the HashTable attribute (with the timeout). I think there is not a final and pretty solution.
AxisProperties.setProperty("org.apache.axis.components.net.SecureSocketFactory", MyAxisSocketFactory.class.getName());
MyAxisSocketFactory factory = (MyAxisSocketFactory) SocketFactoryFactory.getFactory("https", myHashTableParams);
factory.setMyStuff();
After this code, the instance of SocketFactory will be created and configured, and ready to use in web services, or whatever ^_^

Resources