How to access configuration properties in spring webflow in cas-login flow - cas

This might be a very simple Spring EL question. I have defined a new end-state in cas login-flow as follows:
https://myhost:8443/mymodule/somepage" />
We need to use a URL defined in cas.properties instead of hard coding the URL in externalRedirect new name. Is it possible to use something
and define myurl in cas.properties.
We are usign CAS 3.5.2

I've struggled the same problem, but found a much nicer solution.
<view-state id="orderExternalView" view="externalRedirect:#{propertyConfigurer.getProperty('link.externalOrderView')}" />

Maybe this isn't the solution that you are looking for, but I made it work with a bean defined in cas-servlet.xml.
<bean id="loadUrls" class="yourpackage.LoadUrls" c:url="${cas.property.myUrl}"/>
Then, in the LoadUrls class I have the following code:
public class LoadUrls{
private String url;
public LoadUrls(String url) {
this.url= url;
}
public void loadUrlsFromWebflow(RequestContext context) {
// [I used flowScope, you can use any other if you want]
context.getFlowScope().put("urlWebflow", this.url);
}
}
The last thing you need is to invoke this method from the webflow:
<action-state id="stateLoadUrl">
<evaluate expression="loadUrls.loadUrlsFromWebflow(flowRequestContext)"/>
<transition to="redirectAction"/>
</action-state>
<end-state id="redirectAction" view="externalRedirect:#{flowScope.urlWebflow}"/>
This is just an idea, you can tweak it to fit your needs. An by the way, if you find the solution using just an EL Spring expression, let me know, because I need the same exact thing!

Related

Like operator not working, using spring mvc and hibernate

Ok, so I'm still somewhat of a newbie to Java and hibernate and I'm trying to search for a question/answer set in my database, and I can pull up the set just fine if I type in the exact question, but when I use the like operator nothing works, and I'm really not sure what to do. I'm only searching for the question, and it's part of the same object as the answer, so I just pull up the answer with it as well.
Here's my code in my QuestionAnswerDao
public QuestionAnswerSet getQuestionAnswerSetByQuestion(String question)
{
Session session = (Session) em.getDelegate();
return (QuestionAnswerSet) session.createCriteria(QuestionAnswerSet.class).add(Restrictions.eq("question", "%"+question+"%")).uniqueResult();
}
Also here's my code in my controller
#RequestMapping(value="search", method=RequestMethod.GET)
public String searchGet (ModelMap model, HttpServletRequest request)
{
SearchForm searchForm = new SearchForm();
model.put("searchForm", searchForm);
return "app/search";
}
#RequestMapping(value="search", method=RequestMethod.POST)
public String searchPost (#ModelAttribute("searchForm") SearchForm searchForm, ModelMap model, HttpServletRequest request)
{
QuestionAnswerSet questionAnswerSetByQuestion = questionAnswerDao.getQuestionAnswerSetByQuestion(searchForm.getSearchString());
model.put("searchResult", questionAnswerSetByQuestion);
return "app/search";
}
If anyone could help me out with this that would be great, thanks.
I don't see a "like" in your example but I assume you simply need to change
Restrictions.eq ro Restrictions.like.
So if using Hibernate 4.3 this would be this method:
https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/criterion/Restrictions.html#like(java.lang.String, java.lang.Object)
I think a bit worrying is the "uniqueResult" afterwards, if you search with a wildcard I would always assume there might be more then one result. And in case there is the uniqueResult method might throw an Exception.
Also it always helps to enable "show_sql" in the Hibernate config to see the actual sql generated by Hibernate during development.

Sitecore Configuration Factory - Call method with more than one argument

I have read John West's article on the Site Configuration Factory (http://www.sitecore.net/unitedkingdom/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2011/02/The-Sitecore-ASPNET-CMS-Configuration-Factory.aspx)
I'm trying implement it in a custom link provider.
I want the Configuration Factory to call the following method in the link provider:
public void AddSitePath(String site, String path)
{
// do stuff
}
Here's the config (although I've tried several similar variations).
<add name="sitecore" type="MyProject.Providers.CustomLinkProvider, MyProject" addAspxExtension="false" alwaysIncludeServerUrl="false" encodeNames="true" languageEmbedding="never" languageLocation="filePath" shortenUrls="true" useDisplayName="false">
<sitePaths hint="list:AddSitePath">
<sitePath>
<site>SiteOneName</site>
<path>/product-range/</path>
</sitePath>
<sitePath >
<site>SiteTwoName</site>
<path>/items-for-sale/</path>
</sitePath>
</sitePaths>
</add >
I'm getting the following error message:
Could not find add method: AddSitePath (type: MyProject.Providers.CustomLinkProvider)
I suspected that the problem was that I was trying to pass 2 parameters into the method, and sure enough, when I tested it with a single parameter version it worked.
What do I need to change in either the config or the class code to achieve what I need?
So it looks like you can't supply 2 arguments. Instead, you pass in a single XmlNode object, which contains everything you you need. You have to extract the information from the XmlNode within the method.
Something along the lines of:
public void AddSitePath(XmlNode arg)
{
// pick apart the XmlNode and do stuff
}
<sitePaths hint="raw:AddSitePath">
<sitePath site="SiteNameOne" path="/product-range/">
<sitePath site="SiteNameTwo" path="/items-for-sale/">
</sitePaths>
Note that you have to use the 'raw' prefix instead of 'list'

Bundle Helper for bundling and splitting coffeescript

I was experimenting with Bundle and Minification in MVC4 and came across an interesting problem.
I am using Coffeescript and I would like a Render helper that works a bit like the #Scripts.Render() method.
For example, let's say I have this bundle config:
new ScriptBundle("~/bundle/appfiles").Include(
"~/Scripts/app/sample.js",
"~/Scripts/app/myApp.js");
In the cshtml, when I do #Scripts.Render() I get different results based on the debug setting in the web.config. If debug is true I get one script tag per file, otherwise I get a single script tag that returns the bundled and minified js. This is fine.
Let-s assume now that I want to do the same with my Coffeescripts. I create a bundle like this:
new Bundle("~/bundle/appfiles", new CoffeeBundler(), new JsMinify()).Include(
"~/Scripts/app/sample.coffee",
"~/Scripts/app/myApp.coffee");
The problem now is that if I use #Scripts.Render() I get, while in debug, one script per file but this is not transformed at all. The only use I could do is this:
<script type="text/javascript" src="#(BundleTable.Bundles.ResolveBundleUrl("~/bundle/appfiles"))"></script>
But this will, even in debug mode, bundle everything together and then minify, which of course is not what I want.
I have tried to create a Coffee.Render() helper similar to the Scripts one but it uses the AssetManager class which is internal to the System.Web.Optimization assembly.
I was wondering if you have an idea on how to do this in a clean way (i.e: using the available public classes, not copying and pasting the whole AssetManager code, not doing fancy Directory.EnumerateFiles when creating the bundle).
Thanks!
PS: I know that a quicker solution would be to use Mindscape Workbench and bundle the generated js files, I am looking for something that uses what the framework has, maybe also avoiding to have to tell the team to install a tool that people may not like...
In the end I went for a HtmlHelper solution for this. Still in early stage but working as I would like. It is detailed in a blog post for the time being.
Here is the full Helper code in case the blog goes lost...
public static class HtmlHelperExtensions
{
public static MvcHtmlString RenderCoffeeBundle(this HtmlHelper htmlHelper, string virtualPath)
{
if (String.IsNullOrEmpty(virtualPath))
throw new ArgumentException("virtualPath must be defined", "virtualPath");
var list = GetPathsList(virtualPath);
//TODO: Nice and cleaner EliminateDuplicatesAndResolveUrls(list);
var stringBuilder = new StringBuilder();
foreach (string path in list)
{
stringBuilder.Append(RenderScriptTag(path));
stringBuilder.Append(Environment.NewLine);
}
return MvcHtmlString.Create(stringBuilder.ToString());
}
private static IEnumerable<string> GetPathsList(string virtualPath)
{
var list = new List<string>();
if (BundleResolver.Current.IsBundleVirtualPath(virtualPath))
{
if (!BundleTable.EnableOptimizations)
{
foreach (var path in BundleResolver.Current.GetBundleContents(virtualPath))
{
var bundlePath = "~/autoBundle" + ResolveVirtualPath(path.Replace("coffee", "js"));
BundleTable.Bundles.Add(new Bundle(bundlePath, new CoffeeBundler()).Include(path));
// TODO: Get the actual CustomTransform used in the Bundle
// rather than forcing "new CoffeeBundler()" like here
list.Add(bundlePath);
}
}
else
list.Add(BundleResolver.Current.GetBundleUrl(virtualPath));
}
else
list.Add(virtualPath);
return list.Select(ResolveVirtualPath).ToList();
}
private static string RenderScriptTag(string path)
{
return "<script src=\"" + HttpUtility.UrlPathEncode(path) + "\"></script>";
}
private static string ResolveVirtualPath(string virtualPath)
{
return VirtualPathUtility.ToAbsolute(virtualPath);;
}
}
I'm sorry I'm not addressing your exact question, but I do want to speak to your PS at the end of the post.
At this time, I don't really think we have a "no tools" story, but I do agree with the sentiment of "using what the framework has".
To that end, I would strongly recommend using TypeScript. You don't have to learn a new language (like you do with CoffeeScript) and yet it gives you a strongly-typed version of JavaScript that you can use a lot more like c# (with type validation etc.).
It will take you 20 mins to go through some of the tutorials:
http://www.typescriptlang.org/Playground/
Or, better yet, have a look at the BUILD session from the fall:
http://channel9.msdn.com/Events/Build/2012/3-012
Btw...if this isn't a direction you are wanting to go, no worries...I just find a lot of devs don't even know about TypeScript yet as an option.
Hope this helps in your quest to simplify things for your team.
Cheers.

Jibx always gives "Error during validation: null"

I'm really stumped on this incredibly simple mapping. It looks just like one of the examples even. If I comment out the internal structure, it'll run the binding compiler successfully. If I put the internal structure back in, it fails. Note that the internal structure is just defining the XML. This is basically example5 of the JIBX tutorial examples.
<binding>
<mapping name="RequestTransaction" class="TransactionRequest">
<value name="version" set-method="setVersion" get-method="getVersion" style="attribute" />
<structure name="transHeader">
<value name="requestCount" set-method="setRequestCount" get-method="getRequestCount"/>
</structure>
</mapping>
<binding>
Then I get the following error on the jibx compile:
Error: Error during validation: null; on mapping element at (line 2, col 97, in jibx-binding.xml)
I'm absolutely stumped and out of ideas. Google shows nothing useful.
The <structure> is arguably the most important concept in JiBX binding because it allows you to map arbitrary XML to your Java classes without forcing you to create bloated and ugly layers of nested Java objects and classes to match the XML design.
In this case your binding declares that you have an XML element named <transHeader> that will not be present in your Java class.
With some slight fixes to your XML format, your binding works perfectly. I assume the fact that your binding has two <binding> open tags rather than and open and close <binding></binding> is a typo, because you said you got it to work without the structure. Also add <?xml version="1.0"?> at the top of your binding file. Those two XML mods allow the JiBX 1.2 binding compiler to work with the following Java class:
(Note: you didn't provide the Java class this binding is for so I had to reconstruct it from the info you put in the binding file. The obvious side effect of this is that I reconstructed a class that will work with this binding. But the simple fact is that a JiBX binding by design contains all the info you need to know about the class and the XML.)
public class TransactionRequest {
private String version;
private int requestCount;
public void setVersion(String ver) {
version = ver;
}
public String getVersion() {
return version;
}
public void setRequestCount(int count) {
requestCount = count;
}
public int getRequestCount() {
return requestCount;
}
}
compile the class then run the binding compiler with:
>java -jar jibx-bind.jar jibx-binding.xml
To test it I used the following sample.xml:
(Note: you also didn't provide the XML you are trying to map so again I created a sample based on what you did provide)
<?xml version="1.0"?>
<RequestTransaction version="0.1">
<transHeader>
<requestCount>3</requestCount>
</transHeader>
</RequestTransaction>
Running the test uses the following code:
public static void main(String[] argz) {
String fileName = "./sample.xml";
IBindingFactory bfact = null;
IUnmarshallingContext uctx = null;
TransactionRequest sample = null;
try {
bfact = BindingDirectory.getFactory(TransactionRequest.class);
uctx = bfact.createUnmarshallingContext();
InputStream in = new FileInputStream(fileName);
sample = (TransactionRequest)uctx.unmarshalDocument(in, null);
System.out.println(sample.getRequestCount());
System.out.println(sample.getVersion());
}
catch (Exception e) {
e.printStackTrace();
}
}
And it runs successfully.
It's been a while now, but I found it was related to inheritance. I needed to give mappings for everything in the inheritance tree, including interfaces as I recall.
I ended up creating a wrapper object, which I've found seems to be the easiest way to use JIBX in general. Trying to map a true domain class causes tendrils into every class that class touches and I have to unjar everything so JIBX can find the classes, including 3rd party libs.

How to register a uri dependency to return HttpContext.Current.Request.Url using Castle Windsor?

I'm new to Castle Windsor, so go easy!!
I am developing an MVC web app and one of my controllers has a dependency on knowing the current request Url.
So in my Application_Start I initialise a WindsorContainer (container below), register my controllers and then try the following...
container.AddFacility<FactorySupportFacility>();
container.Register(Component.For<Uri>().LifeStyle.PerWebRequest.UsingFactoryMethod(() => HttpContext.Current.Request.Url));
However when I run up my web app I get an exception that my controller...
is waiting for the following dependencies:
Keys (components with specific keys)
- uri which was not registered.
The controller it is trying to instantiate has the following signature:
public MyController(Uri uri)
For some reason it is not running my factory method?
However if I change the controller signature to:
public MyController(HttpContext httpContext)
and change the registration to:
container.Register(Component.For<HttpContext>().LifeStyle.PerWebRequest.UsingFactoryMethod(() => HttpContext.Current));
Then everything works a treat!!
What am I missing when trying to register a Uri type? Its seems exactly the same concept to me? I must be missing something!?
Updated:
I have done some more debugging and have registered both the Uri and the HttpContext using the factory methods shown above. I have added both types as parameters on my Controller constructor.
So to clarify I have a both Uri and HttpContext types registered and both using the FactoryMethods to return the relevant types from the current HttpContext at runtime. I also have registered my controller that has a dependency on these types.
I have then added a breakpoint after I have registration and have taken a look at the GraphNodes on the kernal as it looks like it stores all the dependencies. Here it is:
[0]: {EveryPage.Web.Controllers.BaseController} / {EveryPage.Web.Controllers.BaseController}
[1]: {EveryPage.Web.Controllers.WebpagesController} / {EveryPage.Web.Controllers.WebpagesController}
[2]: {System.Web.HttpContext} / {System.Web.HttpContext}
[3]: {Castle.MicroKernel.Registration.GenericFactory1[System.Web.HttpContext]} / {Castle.MicroKernel.Registration.GenericFactory1[System.Web.HttpContext]}
[4]: {System.Uri} / {System.Uri}
[5]: {Castle.MicroKernel.Registration.GenericFactory1[System.Uri]} / {Castle.MicroKernel.Registration.GenericFactory1[System.Uri]}
It looks as though it has registered my Controller and both the types, plus it has the Factories. Cool.
Now if I drill into the WebpagesController and take a look at its dependencies it only has 1 registered:
[0]: {System.Web.HttpContext} / {System.Web.HttpContext}
Now shouldn't this have 2 registered dependencies as it takes a HttpContext and Uri on its constructor??
Any ideas? Am I barking up the wrong tree?
UPDATE3:
There's new extension point in Windsor trunk now that you can use easily for that.
UPDATE2:
Turns out that I was right from the start (well kind of). Uri is a class, but Windsor treats it as a primitive. There are still at least two quick solutions to this:
Wrap the Uri in some kind of IHasUri or something and take dependency on that interface in your controller
public class FooController
{
public IHasUri CurrentUri { get; set; }
public void SomeAction()
{
var currentUri = CurrentUri.GetCurrentUri();
// do something with the uri
}
}
Tell the Windsor you don't want it to treat Uris like some primitive (but like a lady).
You need a IContributeComponentModelConstruction implementation for that:
public class UriIsAServiceNotAParameter:IContributeComponentModelConstruction
{
public void ProcessModel(IKernel kernel, ComponentModel model)
{
if (model.Service != typeof(UsesUri)) // your controller type here
return;
foreach (var constructor in model.Constructors)
{
foreach (var dependency in constructor.Dependencies)
{
if(dependency.TargetType ==typeof(Uri))
{
dependency.DependencyType = DependencyType.Service;
}
}
}
}
}
and add it to the container:
container.Kernel.ComponentModelBuilder.AddContributor(new UriIsAServiceNotAParameter());
There's also the most correct way of doing this, which means telling Windsor not to register Uris as primitives in the first place, rather than fixing this afterwards, but this would require reaching into the deepest guts of the kernel, and the result is far more code (though a straightforwad one) than the workarounds outlined above.