Tapestry 4: Asset Cache Control? - browser

I use Tapestry 4, and whenever we push a release that changes any assets (image, style sheet, JS library), we get problems because users still have the old version of the asset in their browser cache. I'd like to set up some easy way to allow caching, but force a new asset download when we update the application. Simply disallowing caching entirely for assets is not an acceptable solution.
I couldn't see any existing mechanism for doing this, but I was figuring that there might be some way to tell Tapestry to add the build number to the URL, something like this:
http://www.test.com/path/to/the/asset/asset.jpg?12345
That way, every new build would make it look like a different asset to the end user.
Does Tapestry provide an easy way to solve the cache problem that I'm not aware of? If not, how would one go about modifying the URL generated by Tapestry? And how would the code responsible for doing that get the build number? (I could get the build number into a Spring bean, for example, but how would the new URL building mechanism get at it?)

After stewing about this problem for a long time, I eventually solved it myself. This solution assumes you have the tapestry-spring library in your project.
In my case, I have a Spring bean that contains some of my application's global properties:
package myapp;
public class AppProperties {
private String build;
public String getBuild() {
return build;
}
public void setBuild(String build) {
this.build = build;
}
// other properties
}
Declare this bean in your Spring configuration:
<bean id="appProperties" class="myapp.AppProperties">
<property name="build" value="#BUILD_NUMBER#"/>
</bean>
You can set up your Ant build script to replace #BUILD_NUMBER# with the actual number (see the Copy task in the Ant manual for details).
Now create a class that will wrap IAssets and tack the build number onto the URL:
package myapp;
import java.io.InputStream;
import org.apache.hivemind.Location;
import org.apache.hivemind.Resource;
import org.apache.tapestry.IAsset;
public class BuildAwareAssetWrapper implements IAsset {
private IAsset wrapped;
private String build;
public BuildAwareAssetWrapper(IAsset wrapped, String build) {
this.wrapped = wrapped;
this.build = build;
}
public String buildURL() {
return addParam(wrapped.buildURL(), "build", build);
}
public InputStream getResourceAsStream() {
return wrapped.getResourceAsStream();
}
public Resource getResourceLocation() {
return wrapped.getResourceLocation();
}
public Location getLocation() {
return wrapped.getLocation();
}
private static String addParam(String url, String name, String value) {
if (url == null) url = "";
char sep = url.contains("?") ? '&' : '?';
return url + sep + name + '=' + value;
}
}
Next, we need to make Tapestry wrap all assets with our wrapper. The AssetSourceImpl class is responsible for providing IAsset instances to Tapestry. We'll extend this class and override the findAsset() method so that we can wrap the created assets with the wrapper class:
package myapp;
import java.util.Locale;
import org.apache.hivemind.Location;
import org.apache.hivemind.Resource;
import org.apache.tapestry.IAsset;
import org.apache.tapestry.asset.AssetSourceImpl;
public class BuildAwareAssetSourceImpl extends AssetSourceImpl {
private AppProperties props;
#Override
public IAsset findAsset(Resource base, String path, Locale locale, Location location) {
IAsset asset = super.findAsset(base, path, locale, location);
return new BuildAwareAssetWrapper(asset, props.getBuild());
}
public void setAppProperties(AppProperties props) {
this.props = props;
}
}
Notice that the implementation has a setter which can accept our Spring bean. The last step is to get Tapestry to use BuildAwareAssetSourceImpl to create assets instead of AssetSourceImpl. We do this by overriding the corresponding service point in hivemodule.xml:
<!-- Custom asset source -->
<implementation service-id="tapestry.asset.AssetSource">
<invoke-factory service-id="hivemind.BuilderFactory" model="singleton">
<construct class="myapp.BuildAwareAssetSourceImpl">
<set-object property="appProperties" value="spring:appProperties"/>
<set-configuration property="contributions" configuration-id="tapestry.asset.AssetFactories"/>
<set-service property="lookupAssetFactory" service-id="tapestry.asset.LookupAssetFactory"/>
<set-service property="defaultAssetFactory" service-id="tapestry.asset.DefaultAssetFactory"/>
</construct>
</invoke-factory>
</implementation>
That's it. If you run your application and view the source for any page that uses an asset, you will see that the URL will have the new build parameter on it.

Related

How to configure environment variable for particular cucumber feature file in eclipse?

I am using Cucumber in Java with JUnit and building the project with Maven. I want to use environment variable in the project that should access my entire project. Is there any way to do it?
Your problem title says for a particular cucumber feature file and description of your question says in your whole projects the environment variable should be accessible.
Can you confirm what you want for a particular feature file or for whole project?
In case if you want your environment variables to be accessed in whole project with static value than you can do following things:
Create Single ton class and getter and setter methods to access those environment variables as below
public class GlobalClass {
private static GlobalClass ourInstance;
private HashMap<String, Object> sessionState = new HashMap<>();
public static GlobalClass getInstance() {
if (ourInstance == null) {
return ourInstance = new ThisRun();
}
return ourInstance;
}
public void add(String key, Object value) {
sessionState.put(key, value);
}
public String getAsString(String key) {
return sessionState.get(key).toString();
}
}
so you can add the key and values in this single ton class and can access anywhere in the project

Using StructureMap[4.7.0] Setter Injection in my MVC5 Controller

I am trying to inject the IApplicationConfigurationSection implementation into this MVC5 Controller, so that I can have access to some of the information (various strings) from my web.config custom section in all of my views:
public class BaseController : Controller
{
public IApplicationConfigurationSection AppConfig { get; set; }
public BaseController()
{
ViewBag.AppConfig = AppConfig; // AppConfig is always null
}
}
I want to use setter injection so I don't have to clutter up my derived Controller constructors with parameters that they don't really care about.
Note: If there is a better way to inject base class dependencies, please let me know. I admit I may not be on the right track here.
In my Global.asax I load my StructureMap configurations:
private static IContainer _container;
protected void Application_Start()
{
_container = new Container();
StructureMapConfig.Configure(_container, () => Container ?? _container);
// redacted other registrations
}
My StructureMapConfig class loads my registries:
public class StructureMapConfig
{
public static void Configure(IContainer container, Func<IContainer> func)
{
DependencyResolver.SetResolver(new StructureMapDependencyResolver(func));
container.Configure(cfg =>
{
cfg.AddRegistries(new Registry[]
{
new MvcRegistry(),
// other registries redacted
});
});
}
}
My MvcRegistry provides the mapping for StructureMap:
public class MvcRegistry : Registry
{
public MvcRegistry()
{
For<BundleCollection>().Use(BundleTable.Bundles);
For<RouteCollection>().Use(RouteTable.Routes);
For<IPrincipal>().Use(() => HttpContext.Current.User);
For<IIdentity>().Use(() => HttpContext.Current.User.Identity);
For<ICurrentUser>().Use<CurrentUser>();
For<HttpSessionStateBase>()
.Use(() => new HttpSessionStateWrapper(HttpContext.Current.Session));
For<HttpContextBase>()
.Use(() => new HttpContextWrapper(HttpContext.Current));
For<HttpServerUtilityBase>()
.Use(() => new HttpServerUtilityWrapper(HttpContext.Current.Server));
For<IApplicationConfigurationSection>()
.Use(GetConfig());
Policies.SetAllProperties(p => p.OfType<IApplicationConfigurationSection>());
}
private IApplicationConfigurationSection GetConfig()
{
var config = ConfigurationManager.GetSection("application") as ApplicationConfigurationSection;
return config; // this always returns a valid instance
}
}
I have also "thrown my hands up" and tried using the [SetterProperty] attribute on the BaseController - that technique failed as well.
Despite my best efforts to find a solution, the AppConfig property in my controller's constructor is always null. I thought that
`Policies.SetAllProperties(p => p.OfType<IApplicationConfigurationSection>());`
would do the trick, but it didn't.
I have found that if I discard setter injection and go with constructor injection, it works as advertised. I'd still like to know where I'm going wrong, but I'd like to stress that I'm not a StructureMap guru - there may be a better way to avoid having to constructor-inject my base class dependencies. If you know how I should be doing this but am not, please share.
While constructor injection in this scenario appears to be the better solution to the stated problem as it follows The Explicit Dependencies Principle
Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.
The mention of only needing to access the AppConfig in your views leads me to think that this is more of an XY problem and a cross cutting concern.
It appears that the controllers themselves have no need to use the dependency so stands to reason that there is no need to be injecting them into the controller explicitly just so that the dependency is available to the View.
Consider using an action filter that can resolve the dependency and make it available to the View via the same ViewBag as the request goes through the pipeline.
public class AccessesAppConfigAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
var resolver = DependencyResolver.Current;
var appConfig = (IApplicationConfigurationSection)resolver.GetService(typeof(IApplicationConfigurationSection));
filterContext.Controller.ViewBag.AppConfig = appConfig;
}
}
This now makes the required information available to the views with out tight coupling of the controllers that may have a use for it. Removing the need to inject the dependency into derived classes.
Either via adorning Controller/Action with the filter attribute
[AccessesAppConfig] //available to all its actions
public class HomeController : Controller {
//[AccessesAppConfig] //Use directly if want to isolate to single action/view
public ActionResult Index() {
//...
return View();
}
}
or globally for all requests.
public class FilterConfig {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new AccessesAppConfigAttribute());
}
}
At this point it really does not matter which IoC container is used. Once the dependency resolver has been configured, Views should have access to the required information in the ViewBag

Can I register Orchard resources in an HtmlHelper?

I am aware that this violates the MVC principle and best practices.
I have a whole bunch of custom Angular components that each take a whole bunch of optional parameters and each require a different remote stylesheet and javascript file. I would like to render these with an HtmlHelper without having to manually include the right resources everywhere I use them.
I was hoping that this would do the trick but it doesn't
public static class HtmlExtensions
{
private static IResourceManager _resourceManager;
// Executed in the Activated method of an OrchardShellEvents implementation
public static void SetResourceManager(IResourceManager resourceManager)
{
_resourceManager = resourceManager;
}
public static MvcHtmlString Angular(this HtmlHelper helper, CustomAngularComponent component)
{
// Require the resources
var _styleRegister = new ResourceRegister(helper.ViewDataContainer, _resourceManager, "Style");
var _scriptRegister = new ResourceRegister(helper.ViewDataContainer, _resourceManager, "Script");
_styleRegister.Require(component.StyleSheet).AtHead();
if (!string.IsNullOrEmpty(component.Script))
{
_scriptRegister.Require(component.Script).AtFoot();
}
// Create tag
var tag = new TagBuilder(component.Tag);
tag.MergeAttributes(component.Parameters);
return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
}
}
I could use an arbitrary Shape as a helper, something like:
#Display(New.Angular(Model: new CustomAngularComponent(...)))
but a helper with strongly typed parameters feels a lot better.
This comment on another Orchard question tipped me off. As it turns out, simply injecting Work<IResourceManager> and using it directly was enough to make my setup work. Please note that this does not conform to best MVC practices, by doing this I sacrifice maintainability in favor of readability.
public static class HtmlExtensions
{
private static Work<IResourceManager> _resourceManager;
// Executed in the Activated method of an OrchardShellEvents implementation
public static void SetResourceManager(Work<IResourceManager> resourceManager)
{
_resourceManager = resourceManager;
}
public static MvcHtmlString Angular(this HtmlHelper helper, CustomAngularComponent component)
{
// Require the resources
_resourceManager.Value.Require("stylesheet", component.StyleSheet).AtHead();
if (!string.IsNullOrEmpty(component.Script))
{
_resourceManager.Value.Require("script", component.Script).AtFoot();
}
// Create tag
var tag = new TagBuilder(component.Tag);
tag.MergeAttributes(component.Parameters);
return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
}
}

JSF update managed bean with ServletContext listener for testing

In a JSF 2.2 application, I want to build a war file for testing with Selenium. In that webtest.war, I want to replace a central class, called the NodeCache, with a mock version, called the WebtestNodeCache, to keep the database and other external dependencies out of the tests.
NodeCache is a managed bean:
#javax.faces.bean.ManagedBean(name = NodeCache.INSTANCE)
#javax.faces.bean.ApplicationScoped
public class NodeCache {
public static final String INSTANE = "nodecache";
// ...
}
To sneak in WebtestNodeCache, I use a ServletContextListener like this:
public class WebtestContextListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent event) {
WebtestNodeCache nodeCache = new WebtestNodeCache();
ServletContext context = event.getServletContext();
context.setAttribute(NodeCache.INSTANCE, nodeCache);
}
#Override
public void contextDestroyed(ServletContextEvent sce) {}
}
In normal builds, WebtestContextListener and WebtestNodeCache are excluded from the war file, in test builds, they are included.
This seems to work: when I log in, I get dummy nodes from the WebtestNodeCache.
Is this a reliable way to replace a bean in application context or did I just get lucky?
Is there a better way to sneak in test dummies?
Using both an #ManagedBean annotation and a Listener to replace the object did not work. The code was always using the unmocked production code managed bean.
Defining a new #ManagedBean with the same name is an error and prevents deployment.
I ended up with this:
Put the #ManagedBean annotation with the same name on both the real bean and its mock.
When building, only include the mocks when building the webtest.war, but not in the regular build.
When building, have the build script (Gradle in my case) copy and filter the sources, looking for a special comment behind the #ManagedBean declaration in the production code and taking out these lines to remove the #ManagedBean declaration on the production code so that only the ones in the mock remains.
So the original NodeCache looks like this now:
#javax.faces.bean.ManagedBean(name = NodeCache.INSTANCE) // webtest:remove
#javax.faces.bean.ApplicationScoped // webtest:remove
public class NodeCache {
public static final String INSTANE = "nodecache";
// ...
}
and the mocked version has the same annotations, just without the comment:
#javax.faces.bean.ManagedBean(name = NodeCache.INSTANCE)
#javax.faces.bean.ApplicationScoped
public class WebtestNodeCache extends NodeCache {
// ...
}
Here is the relevant part of the Gradle build script:
boolean isWebtest = false
gradle.taskGraph.whenReady { taskGraph ->
isWebtest = taskGraph.hasTask(compileWebtestWarJava);
}
task copySrc(type: Copy) {
from "src"
into "${buildDir}/src"
outputs.upToDateWhen {
// Always execute this task so that resources do or don't get filtered
// when switching between normal war file and webtests.
false
}
filter { String line ->
isWebtest && line.contains("webtest:remove") ? null : line;
}
}
This solves the problem for me. Hope someone else finds it useful.

Implement Unity MVC 5 dependency injection in ActionFilter

I'm trying to inject this user service via Unity (mvc5) in an actionfilter but it is null. How can I implement this?
public class TestFilter : ActionFilterAttribute
{
// this is always null
[Dependency]
public IUserService UserService { get; set; }
// other members
}
You must register UnityFilterAttributeFilterProvider as a FilterProvider first.
Modify the App_Start > UnityMvcActivator's Start method like this:
public static void Start()
{
var container = UnityConfig.GetConfiguredContainer();
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}
If you could not find the method. You probably installed wrong or out of date package. consider installing Install-Package Unity.Mvc on the package manager console.

Resources