DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Frameworks Topics

article thumbnail
@Autowired + PowerMock: Fixing Some Spring Framework Misuse/Abuse
Unfortunately, I have seen it misused several times when a better design would be the solution.
November 19, 2013
by Alied Pérez
· 30,569 Views · 5 Likes
article thumbnail
Spring Static Application Context
Introduction I had an interesting conversation the other day about custom domain-specific languages and we happened to talk about a feature of Spring that I’ve used before but doesn’t seem to be widely known: the static application context. This post illustrates a basic example I wrote that introduces the static application context and shows how it might be useful. It’s also an interesting topic as it shows some of the well-architected internals of the Spring framework. Most uses of Spring start with XML or annotations and wind up with an application context instance. Behind the scenes, Spring has been working hard to instantiate objects, inject properties, invoke context aware listeners, and so forth. There are a set of classes internal to Spring to help this process along, as Spring needs to hold all of the configuration data about beans before any beans are instantiated. (This is because the beans may be defined in any order, and Spring doesn’t have the exhaustive set of dependencies until all beans are defined.) Spring Static Application Context Spring offers a class called StaticApplicationContext that gives programmatic access from Java to this whole configuration and registration process. This means we can define an entire application context from pure Java code, without using XML or Java annotations or any other tricks. The Javadoc for StaticApplicationContext is here, but an example is coming. Why might we use this? As the Javadoc says, it’s mainly useful for testing. Spring uses it for its own testing, but I’ve found it useful for testing applications that use Spring or other dependency management frameworks. Often, for unit testing, we want to inject different objects into a class from those used in production (e.g. mock objects, or objects that simulate remote invocation, database, or messaging). Of course, we can just keep a separate Spring XML configuration file for testing, but it’s very nice to have our whole configuration right there in the Java unit test class as it makes it easier to maintain. Example I’ve added an example to my intro-to-java repository on GitHub. I created aStaticContext class that provides a very basic Java domain-specific language (DSL) for Spring beans. This is just to make it easier to use from the unit test. The DSL only includes the most basic Spring capabilities: register a bean, set properties, and wire dependencies. package org.anvard.introtojava.spring; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.support.StaticApplicationContext; public class StaticContext { public class BeanContext { private String name; private Class beanClass; private ConstructorArgumentValues args; private MutablePropertyValues props; private BeanContext(String name, Class beanClass) { this.name = name; this.beanClass = beanClass; this.args = new ConstructorArgumentValues(); this.props = new MutablePropertyValues(); } public BeanContext arg(Object arg) { args.addGenericArgumentValue(arg); return this; } public BeanContext arg(int index, Object arg) { args.addIndexedArgumentValue(index, arg); return this; } public BeanContext prop(String name, Object value) { props.add(name, value); return this; } public BeanContext ref(String name, String beanRef) { props.add(name, new RuntimeBeanReference(beanRef)); return this; } public void build() { RootBeanDefinition def = new RootBeanDefinition(beanClass, args, props); ctx.registerBeanDefinition(name, def); } } private StaticApplicationContext ctx; private StaticContext() { this.ctx = new StaticApplicationContext(); } public static StaticContext create() { return new StaticContext(); } public ApplicationContext build() { ctx.refresh(); return ctx; } public BeanContext bean(String name, Class beanClass) { return new BeanContext(name, beanClass); } } This class uses several classes that are normally internal to Spring: StaticApplicationContext: Holds bean definitions and provides regular Java methods for registering beans. ConstructorArgumentValues: A smart list for a bean’s constructor arguments. Can hold both wire-by-type and indexed constructor arguments. MutablePropertyValues: A smart list for a bean’s properties. Can hold regular objects and references to other Spring beans. RuntimeBeanReference: A reference by name to a bean in the context. Used for wiring beans together because it allows Spring to delay resolution of a dependency until it’s been instantiated. The StaticContext class uses the builder pattern and provides for method chaining. This makes for cleaner use from our unit test code. Here’s the simplest example: @Test public void basicBean() { StaticContext sc = create(); sc.bean("basic", InnerBean.class).prop("prop1", "abc"). prop("prop2", "def").build(); ApplicationContext ctx = sc.build(); assertNotNull(ctx); InnerBean bean = (InnerBean) ctx.getBean("basic"); assertNotNull(bean); assertEquals("abc", bean.getProp1()); assertEquals("def", bean.getProp2()); } A slightly more realistic example that includes wiring beans together is not much more complicated: @Test public void innerBean() { StaticContext sc = create(); sc.bean("outer", OuterBean.class).prop("prop1", "xyz"). ref("inner", "inner").build(); sc.bean("inner", InnerBean.class).prop("prop1", "ghi"). prop("prop2", "jkl").build(); ApplicationContext ctx = sc.build(); assertNotNull(ctx); InnerBean inner = (InnerBean) ctx.getBean("inner"); assertNotNull(inner); assertEquals("ghi", inner.getProp1()); assertEquals("jkl", inner.getProp2()); OuterBean outer = (OuterBean) ctx.getBean(OuterBean.class); assertNotNull(outer); assertEquals("xyz", outer.getProp1()); assertEquals(inner, outer.getInner()); } Note that once we build the context, we can use it like any other Spring application context, including fetching beans by name or type. Also note that the two contexts we created here are completely separate, which is important for unit testing. Conclusion Much like my post on custom Spring XML, the static application context is a specialty feature that isn’t intended for everyday users of Spring. But I’ve found it convenient when unit testing and it provides an interesting peek into how Spring works.
November 13, 2013
by Alan Hohn
· 34,626 Views · 6 Likes
article thumbnail
Show Heap Status in Eclipse
A quick overview on how to see your heaps in Eclipse.
November 5, 2013
by Erich Styger
· 71,843 Views · 8 Likes
article thumbnail
Android 4.4 KitKat, the Browser and the Chrome WebView
Android 4.4 has made a big change in the OS’ internals for HTML5 development: it has replaced its original WebKit-based WebView with modern Chromium. The new Android Browser is also powered by Chromium, but it’s not clear yet its future. Besides the good news, not everything looks exciting in these changes: let’s see why. Every web developer that has played with native webapps, PhoneGap and the Android’s WebView knows how terrible it was in terms of performance and HTML5 compatibility. These are the same problems that most web developers suffer right now with the Android Browser, which is reported to be 32% of the mobile web browsing market share, compared with just 5% of the modern Chrome for Android according to Akamai. I’ve been talking about this problem in a recent post this year: Android Browser: the eternal mobile browser. Therefore I’m the first one to celebrate the beginning of the end for this dying web platform and the Chrome team now in charge of Android’s web runtimes. Chroming Android From Android 4.4, Chromium 30 is the web engine for the WebView native widget, including the V8 JavaScript engine. Let’s start with good news: Support for remote debugging Support for new HTML5 features Better performance Now why we should take this change with moderated excitement: We will still deal with the old WebView for a couple of years. It won’t be upgraded without an OS upgrade There might be some compatibility issues Where is My Browser? Everybody at Android and Chrome team is talking about the new WebView but nobody is even mentioning what will happen to the browser. We all want Chrome as the default browser, but it seems it’s not there yet (licenses issues, I guess). I’ve even seen a couple of members of the Chrome team saying that the stock Android Browser didn’t exist in the latest previous versions, which is not true. From Google’s perspective, Android Browser sounds much like IE6 and nobody wants to talk about it. They give us the idea that Chrome has been powering web browsing in Android for a while, but that is only true for some particular Android devices - Nexuses and devices from top manufactures. However, as I’ve mentioned before, the relationship between users browsing with Android Browser and Chrome is still 7 to 1. Besides what some people believe, the previous version of Android, 4.3, included minor upgrades to the Browser, so it is there for sure. The question is: what will happen on 4.4 with the stock browser? We know that the Nexus 5 has Google Chrome by default; the question here is what will happen with other devices having in mind that average users don’t download browsers from the store and use what the devices offers for browsing. Based on the emulator, the Android Browser is still there on the emulator and it’s using the classic browser UI with the Chromium 30 engine (it can coexist with Chrome but they will be radically different) Unfortunately, there is no mention of this on docs and blogs on Android 4.4. I hope we can get a real answer from the Android team soon about the future of the browser itself. The Good News Remote debugging Finally we have the ability to debug remotely Android native webviews, including PhoneGap apps, and the Android Browser works smoothly both from real devices and from the emulator. When we have an Android app opened with a web view or the Android Browser, the Chrome remote debugger tools will recognize it as a “Chrome 30” session and we have the full package of excellent tools for debug, profile and test our webapps. HTML5 new features Compared with the classic web view and the Android Browser until 4.3, we now have support for: Server Sent events Web Sockets Web Workers Advanced form input selectors, such as date and time FileSystem API IndexedDB MediaCapture Stream ??? test Animation Timing API Page Visibility API Canvas Blend modes CSS3 Flexbox (latest version) CSS3 Filters Even matching Chrome 30 for Android, the Web View (and potentially the Android Browser) will not have support (no reasons given) for: WebGL WebRTC WebAudio FullScreen Form validation Compared with the classic Web View, the new one doesn’t have Network Information API Performance difference Having V8 as the JavaScript engine for the new web view, the JavaScript performance if much better, besides general performance on CSS thanks to hardware acceleration. The Not so Good News The Classic Web View is still alive Don’t get so excited. We will deal with the old Web View (known as “classic”) for a couple of years. In fact, some devices such as Galaxy Nexus that are today on 4.3 will not get the update. And remember that still today 30% of Android users are on 2.x after 2 years of being replaced by 4.0, so it’s fair to guess that at the beginning of 2016 we will still have around a third of the users on the “classic” WebView that we hate today. The migration on the market will be slow based on Android’s fragmentation. WebView upgrade The KitKat WebView is based on Chromium 30 and it won’t be updated. That means you are stuck with it unless to get an upgrade in the future of the whole OS to next version. Even Google has announced OS delta updates without vendors’ intervention, but it seems the WebView will not get that deal yet. Therefore and based on Chrome's release cycle, in one year we will have Chrome 40 and the WebView will still be in 30. In a couple of years we might be complaining about an “old and outdated” webview again Compatibility issues Because there are changes between the old WebKit-based rendering engine and the modern Chromium engine, you should test your native webapp on KitKat to make sure it’s still working great. To reduce problems, if our app was packaged before KitKat the WebView will enter a “quirks mode” (any similarity with IE6 is pure coincidence) that will reduce the risk of incompatibilities while still getting the new APIs. In fact, this compatibility mode will get in action if the configuration file of your app has a target SDK lower than 19 (the API number for KitKat). To get more detailed information on migration and compatibility issues you can try the new Guides at Android and Chrome websites: http://developer.android.com/guide/webapps/migrating.html http://developers.google.com/chrome/mobile/docs/webview Looking Forward I’m really looking forward to remove the old WebKit and Android Browser from the market. The Chrome team is doing a great job empowering the mobile web (just remember homescreen webapps from Chrome 31), but sometimes the Android ecosystem is slowing down HTML5 penetration and helping promoting companies to avoid using web technologies. I hope this is the beginning of a change.
November 4, 2013
by Maximiliano Firtman
· 34,899 Views
article thumbnail
JMS-style selectors on Amazon SQS with Apache Camel
This blog post demonstrates how easy it is to use Apache Camel and its new json-path component along with the camel-sqs component to produce and consume messages on Amazon SQS. Amazon Web Services SQS is a message queuing “software as a service” (SaaS) in the cloud. To be able to use it, you need to sign up for AWS. It’s primary access mechanism is XML over HTTP through various AWS SDK clients provided by Amazon. Please check out the SQS documentation for more. And as “luck” would have it, one of the users in the Apache Camel community created a component to be able to integrate with SQS. This makes it trivial to add a producer or consumer to an SQS queue and plugs in nicely with the Camel DSL. SQS, however, is not a “one-size fits all” queueing service; you must be aware of your use case and make sure it fits (current requirements as well as somewhat into the future…). There are limitations that, if not studied and accounted for ahead of time, could come back to sink your project. An example of a viable alternative, and one that more closely fits the profile of a high performance and full featured message queue is Apache ActiveMQ. For example, one limitation to keep in mind is that unlike traditional JMS consumers, you cannot create a subscription to a queue that filters messages based on some predicate (at least not using the AWS-SQS API — you’d have to build that into your solution). Some other things to keep in mind when using SQS: The queue does not preserve FIFO messaging That is, message order is not preserved. They can arrive out of order from when they were sent. Apache Camel can help with its resequencer pattern. Bilgin Ibryam, now a colleague of mine at Red Hat, has written a great blog post about how to restore message order using the resequencer pattern. Message size is limited to 256K This is probably sufficient, but if your message sizes are variable, or contain more data that 256K, you will have to chunk them and send in smaller chunks. No selector or selective consumption If you’re familiar with JMS, you know that you can specify consumers to use a “selector” or a predicate expression that is evaluated on the broker side to determine whether or not a specific message should be dispatched to a specific consumer. For example, Durability constraints Some use cases call for the message broker to store messages until consumers return. SQS allows a limit of up to 14 days. This is most likely sufficient, but something to keep in mind. Binary payloads not allowed SQS only allows text-based messages, e.g., XML, JSON, fixed format text, etc. Binary such as Avro, Protocol Buffers, or Thrift are not allowed. For some of these limitations, you can work around them by building out the functionality yourself. I would always recommend taking a look at how an integration library like Apache Camel can help — which has out-of-the-box support for doing some of these things. Doing JMS-style selectors So the basic problem is we want to subscribe to a SQS queue, but we want to filter which messages we process. For those messages that we do not process, those should be left in the queue. To do this, we will make use of Apache Camel’s Filter EIP as well as the visibility timeouts available on the SQS queue. By default, SQS will dispatch all messages in its queue when it’s queried. We cannot change this, and thus not avoid the message being dispatched to us — we’ll have to do the filtering on our side (this is different than how a full-featured broker like ActiveMQ does it, i.e., filtering is done on the broker side so the consumer doesn’t even see the message it does not want to see). Once SQS dispatches a message, it does not remove it from the queue unless the consumer has acknowledged that it has it and is finished with it. The consumer does this by sending a DeleteMessage command. Until the DeleteMessage command is sent, the message is always in the queue, however visibility comes in to play here. When a message is dispatched to a consumer, there is a period of time which it will not be visible to other consumers. So if you browsed the queue, you would not see it (it should appear in the stats as “in-flight”). However, there is a configurable period of time you can specify for how long this “visibility timeout” should be active. So if you set the visibility to a lower time period (default is 30 seconds), you can more quickly get messages re-dispatched to consumers that would be able to handle the message. Take a look at the following Camel route which does just that: @Override public void configure() throws Exception { // every two seconds, send a message to the "demo" queue in SQS from("timer:kickoff?period=5000") .setBody().method(this, "generateJsonString") .to("aws-sqs://demo?amazonSQSClient=#sqsClient&defaultVisibilityTimeout=2"); } In the above Camel Route, we create a new message every 5 seconds and send it to an SQS queue named demo — note we set the defaultVisibilityTimeout to 2 seconds. This means that after a message gets dispatched to a consumer, SQS will wait about 2 seconds before considering it eligible to be dispatched to another consumer if it has not been deleted. On the consumer side, we take advantage of a couple Apache Camel conveniences Using JSON Path + Filter EIP Camel has an excellent new component named JSON-Path. Claus Ibsen tweeted about it when he hacked it up. This allows you to do Content-Based Routing on a JSON payload very easily by using XPath-style expressions to pick out and evaluate attributes in a JSON encoded object. So in the following example, we can test an attribute named ‘type’ to be equal to ‘LOGIN’ and use Camel’s Filter EIP to allow only those messages that match to go through and continue processing: public class ConsumerRouteBuilder extends RouteBuilder { @Override public void configure() throws Exception { from("aws-sqs://demo?amazonSQSClient=#sqsClient&deleteIfFiltered=false") .setHeader("identity").jsonpath("$['type']") .filter(simple("${header.identity} == 'login'")) .log("We have a message! ${body}") .to("file:target/output?fileName=login-message-${date:now:MMDDyy-HHmmss}.json"); } } To complete the functionality, we have to pay attention to a new configuration option added for the Camel-SQS component: deleteIfFiltered — Whether or not to send the DeleteMessage to the SQS queue if an exchange fails to get through a filter. If ‘false’ and exchange does not make it through a Camel filter upstream in the route, then don’t send DeleteMessage. By default, Camel will send the “DeleteMessage” command to SQS after a route has completed successfully (without an exception). However, in this case, we are specifying to not send the DeleteMessage command if the message had been previously filtered by Camel. This example demonstrates how easy it is to use Apache Camel and its new json-path component along with the camel-sqs component to produce and consume messages on Amazon SQS. Please take a look at the source code on my github repo to play with the live code and try it out yourself.
October 28, 2013
by Christian Posta
· 12,093 Views
article thumbnail
Extracting File Metadata with C# and the .NET Framework
How to extract extended image metadata using C# and the Windows API Code Pack, simplifying access to detailed file properties typically seen in Windows Explorer.
October 26, 2013
by Rob Sanders
· 39,935 Views · 2 Likes
article thumbnail
Including Custom XML in Spring Configuration
Introduction One of the nice recent features of Spring (2.x era) is support for custom XML. This is the way that Spring itself has added all kinds of new tags such as and . The way this works is pretty elegant, to the point that it makes an interesting alternative for configuring Java using XML, particularly if the application already uses Spring. I’ve written an example application to try to give an easily-copied example of how it’s done. The example uses Spring and a custom XML parser to build dynamic Swing menus. It makes a nice comparison to doing dynamic Swing menus using the Digester version I posted a while back. Of course, this is not a good way to make Java menus in general! In most applications, this would be an example of Soft Coding. This would really only make sense in an application where it was really important to be able to add or remove menus without changing Java code. So treat it as a nice example, but please don’t start making your GUIs this way. Spring Custom XML Custom XML works in a Spring configuration file because Spring can dynamically validate and parse XML. To do this, Spring first has to be able to validate the XML it parses against a schema. It does this by looking for all files on the classpath called META-INF/spring.schemas. These files provide a location on the classpath for the XML schema that goes with a given namespace. For example, the “core” XML for Spring is defined in the beansnamespace. The META-INF/spring.schemas file in the spring-beans JAR has entries like this one: http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd So when we use the beans schema in our Spring XML, it knows where on the classpath to hunt down the schema so it can validate that XML. Once the schema is validated, Spring needs to find a “handler” that knows how to make Spring beans based on the XML. Spring finds handlers by looking through all the files on the classpath called META-INF/spring.handlers. Thespring.handlers file in the spring-beans JAR has entries like this one: http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler It’s really the job of the handler to make bean definitions, not the regular Java objects that will live as beans in the Spring application context. This is because Spring still has to manage things like beans depending on other beans, which means Spring has to parse all the XML to figure out the dependency graph before any objects can be instantiated. Example Application Our example application has several parts: The spring.schemas and spring.handlers files in META-INF. An XML schema defining what is valid in our custom namespace. MenuNamespaceHandler, the entry class that allows us to register what XML elements go with what parser classes. MenuDefinitionParser, the actual XML parser for our custom XML namespace. A regular Spring XML configuration file that also includes our custom XML. A main class to get the whole thing kicked off. There’s also a Java class called MenuItem that we use to store the ID, the title, and any children of the menu item. It doesn’t know anything about Spring or XML; it’s just a POJO. Defining the custom XML The spring.schemas file is pretty simple. Note that it’s matching to a file on the classpath; Spring is not going to be looking out on the Internet for your XML schema at runtime. http\://anvard.org/springxml/menu.xsd=org/anvard/springxml/menu.xsd The spring.handlers file is also pretty simple. It just points to the right handler class: http\://anvard.org/springxml/menu=org.anvard.springxml.MenuNamespaceHandler The XML schema is omitted here; it’s an XML schema and not much need be said. Of note is that it allows for arbitrary nesting of elements inside other elements. One more piece of boilerplate; the namespace handler. Since our namespace is really simple and only contains one top-level element (menu), it’s a one-liner: public void init() { registerBeanDefinitionParser("menu", new MenuDefinitionParser()); } The parser is where it gets interesting. The parser will get called while Spring is reading the XML file, whenever it comes across an element that belongs to the matching namespace. However, it will only be called for the top-level element; it’s up to us to handle any nested elements as required. protected AbstractBeanDefinition parseInternal(Element element, ParserContext context) { BeanDefinitionBuilder builder = parseItem(element); List childElements = DomUtils.getChildElementsByTagName( element, "menu"); if (null != childElements && childElements.size() > 0) { ManagedList children = new ManagedList<>( childElements.size()); for (Element child : childElements) { children.add(parseInternal(child, context)); } builder.addPropertyValue("children", children); } return builder.getBeanDefinition(); } private BeanDefinitionBuilder parseItem(Element element) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .rootBeanDefinition(MenuItem.class); String id = element.getAttribute("id"); if (StringUtils.hasText(id)) { builder.addPropertyValue("id", id); } String title = element.getAttribute("title"); if (StringUtils.hasText(title)) { builder.addPropertyValue("title", title); } String listener = element.getAttribute("listener"); if (StringUtils.hasText(listener)) { builder.addPropertyReference("listener", listener); } return builder; } In this case, because we allowed for the idea that a menu could contain child menus, we have to handle that here with some recursion. Note that for every element at whatever level, we are creating a separate Spring bean definition (that’s one purpose of the rootBeanDefinition() static method call). The really important thing to notice is that as we build the bean definition, we are not creating a MenuItem object directly, nor are we setting any properties directly. In fact, in the case of the children property, we are not even building a list of the correct type, as the MenuItem class expects to receive a list of MenuItem children, but we are building a list ofAbstractBeanDefinition. Spring handles all of the necessary wiring when it actually instantiates our MenuList objects, including looking up each of the references in the list and populating a new list with the real objects. One other thing that’s slightly confusing is that a reference to a single other Spring bean uses addPropertyReference(), while a managed list of Spring bean definitions uses addPropertyValue(). Using the custom XML Now that these items are in place, we can use the custom XML just the same as any other XML in a Spring configuration file. For example: Note that we can make our custom XML the default namespace so we don’t have to prefix our XML elements; we can also make the bean namespace the default as is more typical in a Spring XML configuration file. We can mix our custom XML freely with standard Spring XML. Also note that our custom XML can make references back to ordinary Spring beans as long as we do the right thing in our parser to make this work. We use a list called toplevel as a handy way of finding the outermost menu items for our menu bar. Once the XML is parsed, the beans are all loaded into the Spring application context and the structure of the XML no longer really applies. Using this file from our main class looks just the same as any Spring code: ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/menuDefinition.xml"); All of our menu items are available in the Spring application context, so we could do ctx.getBean("menu9") and get back the menu item with the title “Child 5”. Conclusion Even though many Spring users are shifting toward annotation-driven configuration, there are still things that are easier to do in XML, like creating many instances of a class with different properties. A custom XML namespace is a way to make Spring XML configuration more compact and more readable.
October 21, 2013
by Alan Hohn
· 20,308 Views
article thumbnail
Using Maven to Build with Embedded Jetty
Previous posts such as this one have shown using embedded Jetty to REST-enable a standalone Java program. Those posts were lacking an important feature for real applications: packaging into a JAR so the application will run outside of Eclipse and won’t be dependent on Maven and jetty:run. To make this happen, we will use Maven to build an executable JAR that also includes all of the Jetty and Spring dependencies we need. The goal of this work is to get to the point where we can run the example application by: Cloning the Git repository. Running mvn package. Running java -jar target/webmvc-standalone.jar When I started adding the necessary bits to the pom.xml file of my sample application, I expected a relatively straightforward solution. I ended up with a relatively straightforward solution that was completely different from what I expected. So I think it’s worth a detailed discussion of how this solution works and what Maven is doing for us. Our desire to make an executable JAR is complicated by the fact that we want our Maven project to build a WAR as a default package, so that we can use this code in a Java web container if desired. Additionally, we introduce some complexity by making a single JAR with all dependencies, because that causes files in the Spring JARs to collide. I’ll show what I did to address each of these. Build both JAR and WAR The basic idea here is that we want Maven to make both a JAR file and a WAR file during the “package” phase. Our pom.xml file specifies war as the packaging for this project, so the WAR file will be created as expected. We need to add the JAR file without disturbing this. I found a great post here that got me started. The basic idea is to add the following to pom.xml under build/plugins: org.apache.maven.plugins maven-jar-plugin 2.4 package-jar package jar This is the behavior we would get for “free” if we used jar packaging inpom.xml. The execution section ties it to the package phase so that it runs during the default build process. The jar goal tells the plugin what to make. This gets us a basic JAR with the classes in the normal place for a JAR (rather than in WEB-INF/classes as they must be in the WAR file). At the same time, we need to deal with the fact that the Maven resources plugin considers only src/main/resources to be a resources directory, while in our case we have files in src/main/webapp that also need to be included. We want to copy these resources to the target directory so the JAR plugin will pick them up. (This is an important distinction; the typical Maven question, “how do I include extra resources in my JAR?” should really be “how do I get extra resources into target so the JAR plugin will pick them up?”) We add this to the build section of pom.xml: src/main/resources src/main/webapp This causes our new webmvc.jar file to include the HTML, JavaScript, etc. required for our embedded Jetty webapp. JAR with dependencies Next, we make an additional JAR that has the correct Main-Class entry in theMANIFEST.MF file and includes the necessary dependencies so we only have to ship one file. This is done using the Maven assembly plugin. The assembly plugin does repackaging only; that’s why we had to add a JAR artifact above. Without that JAR artifact to work from, the assembly plugin repackages the WAR, and we end up with classes in WEB-INF/classes. This causes Java to complain that it can’t find our main class when we try to run the JAR. The assembly plugin comes with a jar-with-dependencies configuration that can be used simply by adding it as a descriptorRef to the relevant section of pom.xml, as shown in this StackOverflow question. However, this configuration doesn’t work in our particular case, as the Spring dependencies we need have files with overlapping names. As a result, we need to make our own assembly configuration. Fortunately, this is pretty simple. We first add this to the build/plugins section of pom.xml: org.apache.maven.plugins maven-assembly-plugin 2.4 src/assemble/distribution.xml org.anvard.webmvc.server.EmbeddedServer package single As before, we use the executions section to make sure this is run automaticaly during package. We also specify the main class for our application. Finally, we point the plugin to our assembly configuration file, which lives in src/assemble. I present the assembly configuration below, but first we need to talk about the issue with the Spring JARs that made this custom assembly necessary. Spring schemas and handlers With this sample application, we use Spring WebMVC to provide a REST API for ordinary Java classes, as discussed in this post. The Spring code we use is spread across a few different JARs. Recent versions of Spring added a “custom XML namespace” feature that allows the contents of a Spring XML configuration file to be very extensible. Spring WebMVC, and other Spring libraries, use this feature to provide custom XML tags. In order to parse the XML file with these custom tags, Spring needs to be able to match these custom namespaces to handlers. To do this, Spring expects to find files called spring.handlers andspring.schemas in the META-INF directory of any JAR providing a Spring custom namespace. Several of the Spring JARs used by this application include thosespring.handlers and spring.schemas files. Of course, each JAR only includes its own handlers and schemas. When the Maven assembly plugin uses the jar-with-dependencies configuration, only one copy of those files “wins” and makes it into the executable JAR. We really just need a single spring.handlers and spring.schemas that are the concatentation of the respective files. There is probably some Maven magic to accomplish this, but I elected to do it manually as my Bash-fu is much greater than my Maven-fu. I added two files to the src/assemble directory that have the combined contents of the various files in the Spring JARs. Maven assembly configuration The assembly file looks like this: standalone jar true META-INF/spring.handlers META-INF/spring.schemas src/assemble/spring.handlers /META-INF false src/assemble/spring.schemas /META-INF false The id will be used to name this assembly. The baseDirectory tells the assembly plugin that the pieces it assembles should go at the root of the new JAR. (Otherwise they would go into a directory using the project name, in this case “webapp”.) The next two sections are important. We want to exclude thespring.handlers and spring.schemas from the Spring JARs (a.k.a. the dependency set). Instead, we want to explicitly include them from oursrc/assemble directory, and put them into the right place. We also want the assembly plugin to unpack the dependency set JARs so we wind up with Java class files in our new JAR, rather than just JAR-files-inside-JAR-file, which would not run correctly. Notice that there is no directive telling Spring to include all dependencies from the dependency set, including transitive dependencies. This is the default so we don’t need to specify it. It’s also the default to include the unpacked files from our own artifact (webmvc.jar) into the new JAR. Conclusion A real-world application would probably pick either WAR packaging or executable JAR packaging, and be simpler. Additionally, it would be possible to use multiple Maven modules to build a JAR and embed it in the WAR. But it’s interesting to see how to implement a more complex solution that builds everything we need from a single project.
October 18, 2013
by Alan Hohn
· 23,570 Views
article thumbnail
Extracting File Metadata with C# and the .NET Framework
The Windows Explorer (shell) provides extended file property information which can be quite valuable. The challenge was how to extract this information, given that the .NET Framework has somewhat limited support for this type of extraction?
October 14, 2013
by Rob Sanders
· 64,226 Views
article thumbnail
Tutorial: How to Create a Responsive Website with AngularJS
in today’s tutorial, i’m going to show you the process of creating nearly an entire website with a new library – angularjs. however, i would like to introduce to you to angularjs first. angularjs is a magnificent framework by google for creating web applications. this framework lets you extend html’s syntax to express your application’s components clearly and succinctly, and lets you use standard html as your main template language. plus, it automatically synchronizes data from your ui with your js objects through 2-way data binding. if you’ve ever worked with jquery, the first thing to understand about angular is that this is a completely different instrument. jquery is a library, but angularjs is framework. when your code works with the library, it decides when to call a particular function or operator. in the case of the framework, you implement event handlers, and the framework decides at what moment it needs to invoke them. using this framework allows us to clearly distinguish between templates (dom), models, and functionality (in controllers). let’s come back to our template, take a look at our result: live demo download in package description this template is perfect for business sites. it consists of several static pages: projects, privacy, and about pages. each product has its own page. there is also a contact form for communication. that is all that is necessary for any small website. moreover, it is also a responsive template, thus it looks good on any device. i hope you liked the demo, so if you’re ready – let’s start making this application. please prepare a new folder for our project, and then create new folders in this directory: css – for stylesheet files images – for image files js – for javascript files (libraries, models, and controllers) pages – for internal pages stage 1. html the main layout consists of four main sections: a header with navigation, a hidden ‘contact us’ form, a main content section, and a footer. first we have to prepare a proper header: index.html as you can see, it’s an ordinary header. now – the header with the navigation: our projectsprivacy & termsaboutcontact us it's an ordinary logo, and the menu is the usual ul-li menu. the next section is more interesting – the ‘contact us’ form: contact us send message your message has been sent, thank you. finally, the last key element is the main content section: have you noticed the numerous ‘ng-’ directives? all these directives allow us to do various actions directly in the dom, for example: ng-class – the ngclass allows you to set css classes on an html element dynamically by databinding an expression that represents all classes to be added. ng-click – the ngclick allows you to specify custom behavior when element is clicked. ng-hide – the nghide directive shows and hides the given html element conditionally based on the expression provided to the nghide attribute. ng-include – fetches, compiles, and includes an external html fragment. ng-model – is a directive that tells angular to do two-way data binding. ng-show – the ngshow directive shows and hides the given html element conditionally based on the expression provided to the ngshow attribute. ng-submit – enables binding angular expressions to onsubmit events. stage 2. css in this rather large section, you can find all the styles used: css/style.css /* general settings */ html { min-height:100%; overflow-x:hidden; overflow-y:scroll; position:relative; width:100%; } body { background-color:#e6e6e6; color:#fff; font-weight:100; margin:0; min-height:100%; width:100%; } a { text-decoration:none; } a img { border:none; } h1 { font-size:3.5em; font-weight:100; } p { font-size:1.5em; } input,textarea { -webkit-appearance:none; background-color:#f7f7f7; border:none; border-radius:3px; font-size:1em; font-weight:100; } input:focus,textarea:focus { border:none; outline:2px solid #7ed7b9; } .left { float:left; } .right { float:right; } .btn { background-color:#fff; border-radius:24px; color:#595959; display:inline-block; font-size:1.4em; font-weight:400; margin:30px 0; padding:10px 30px; text-decoration:none; } .btn:hover { opacity:0.8; } .wrap { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; margin:0 auto; max-width:1420px; overflow:hidden; padding:0 50px; position:relative; width:100%; } .wrap:before { content:''; display:inline-block; height:100%; margin-right:-0.25em; vertical-align:middle; } /* header section */ header { height:110px; } header .wrap { height:100%; } header .logo { margin-top:1px; } header nav { float:right; margin-top:17px; } header nav ul { margin:1em 0; padding:0; } header nav ul li { display:block; float:left; margin-right:20px; } header nav ul li a { border-radius:24px; color:#aaa; font-size:1.4em; font-weight:400; padding:10px 27px; text-decoration:none; } header nav ul li a.active { background-color:#c33c3a; color:#fff; } header nav ul li a.active:hover { background-color:#d2413f; color:#fff; } header nav ul li a:hover,header nav ul li a.activesmall { color:#c33c3a; } /* footer section */ footer .copyright { color:#adadad; margin-bottom:50px; margin-top:50px; text-align:center; } /* other objects */ .projectobj { color:#fff; display:block; } .projectobj .name { float:left; font-size:4em; font-weight:100; position:absolute; width:42%; } .projectobj .img { float:right; margin-bottom:5%; margin-top:5%; width:30%; } .paddrow { background-color:#dadada; color:#818181; display:none; padding-bottom:40px; } .paddrow.aboutrow { background-color:#78c2d4; color:#fff !important; display:block; } .paddrow .head { font-size:4em; font-weight:100; margin:40px 0; } .paddrow .close { cursor:pointer; position:absolute; right:50px; top:80px; width:38px; } .about { color:#818181; } .about section { margin:0 0 10%; } .about .head { font-size:4em; font-weight:100; margin:3% 0; } .about .subhead { font-size:2.5em; font-weight:100; margin:0 0 3%; } .about .txt { width:60%; } .about .image { width:26%; } .about .flleft { float:left; } .about .flright { float:right; } .projecthead.product { background-color:#87b822; } .projecthead .picture { margin-bottom:6%; margin-top:6%; } .projecthead .picture.right { margin-right:-3.5%; } .projecthead .text { position:absolute; width:49%; } .projecthead .centertext { margin:0 auto; padding-bottom:24%; padding-top:6%; text-align:center; width:55%; } .image { text-align:center; } .image img { vertical-align:top; width:100%; } .contactform { width:50%; } .input { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; margin:1% 0; padding:12px 14px; width:47%; } .input.email { float:right; } button { border:none; cursor:pointer; } .textarea { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; height:200px; margin:1% 0; overflow:auto; padding:12px 14px; resize:none; width:100%; } ::-webkit-input-placeholder { color:#a7a7a7; } :-moz-placeholder { color:#a7a7a7; } ::-moz-placeholder { /* ff18+ */ color:#a7a7a7; } :-ms-input-placeholder { color:#a7a7a7; } .loader { -moz-animation:loader_rot 1.3s linear infinite; -o-animation:loader_rot 1.3s linear infinite; -webkit-animation:loader_rot 1.3s linear infinite; animation:loader_rot 1.3s linear infinite; height:80px; width:80px; } @-moz-keyframes loader_rot { from { -moz-transform:rotate(0deg); } to { -moz-transform:rotate(360deg); } } @-webkit-keyframes loader_rot { from { -webkit-transform:rotate(0deg); } to { -webkit-transform:rotate(360deg); } } @keyframes loader_rot { from { transform:rotate(0deg); } to { transform:rotate(360deg); } } .view-enter,.view-leave { -moz-transition:all .5s; -o-transition:all .5s; -webkit-transition:all .5s; transition:all .5s; } .view-enter { left:20px; opacity:0; position:absolute; top:0; } .view-enter.view-enter-active { left:0; opacity:1; } .view-leave { left:0; opacity:1; position:absolute; top:0; } .view-leave.view-leave-active { left:-20px; opacity:0; } please note that css3 transitions are used, which means that our demonstration will only work modern browsers (ff, chrome, ie10+ etc) stage 3. javascript as i mentioned before, our main controller and the model are separated. the navigation menu can be handled here, and we also can operate with the contact form. js/app.js 'use strict'; // angular.js main app initialization var app = angular.module('example359', []). config(['$routeprovider', function ($routeprovider) { $routeprovider. when('/', { templateurl: 'pages/index.html', activetab: 'projects', controller: homectrl }). when('/project/:projectid', { templateurl: function (params) { return 'pages/' + params.projectid + '.html'; }, controller: projectctrl, activetab: 'projects' }). when('/privacy', { templateurl: 'pages/privacy.html', controller: privacyctrl, activetab: 'privacy' }). when('/about', { templateurl: 'pages/about.html', controller: aboutctrl, activetab: 'about' }). otherwise({ redirectto: '/' }); }]).run(['$rootscope', '$http', '$browser', '$timeout', "$route", function ($scope, $http, $browser, $timeout, $route) { $scope.$on("$routechangesuccess", function (scope, next, current) { $scope.part = $route.current.activetab; }); // onclick event handlers $scope.showform = function () { $('.contactrow').slidetoggle(); }; $scope.closeform = function () { $('.contactrow').slideup(); }; // save the 'contact us' form $scope.save = function () { $scope.loaded = true; $scope.process = true; $http.post('sendemail.php', $scope.message).success(function () { $scope.success = true; $scope.process = false; }); }; }]); app.config(['$locationprovider', function($location) { $location.hashprefix('!'); }]); pay attention here. when we request a page, it loads an appropriate page from the ‘pages’ folder: about.html, privacy.html, index.html. depending on the selected product, it opens one of the product pages: product1.html, product2.html, product3.html or product4.html in the second half, there are functions to slide the contact form and to handle its submit process (to the sendemail.php page). next is the controller file: js/controllers.js 'use strict'; // optional controllers function homectrl($scope, $http) { } function projectctrl($scope, $http) { } function privacyctrl($scope, $http, $timeout) { } function aboutctrl($scope, $http, $timeout) { } it is empty, because we have nothing to use here at the moment. stage 4. additional pages angularjs loads pages asynchronously, thereby increasing the speed. here are templates of all additional pages used in our project: pages/about.html about us script tutorials is one of the largest web development communities. we provide high quality content (articles and tutorials) which covers all the web development technologies including html5, css3, javascript (and jquery), php and so on. our audience are web designers and web developers who work with web technologies. additional information promo 1 lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. ..... pages/privacy.html privacy & terms by accessing this web site, you are agreeing to be bound by these web site terms and conditions of use, all applicable laws and regulations, and agree that you are responsible for compliance with any applicable local laws. if you do not agree with any of these terms, you are prohibited from using or accessing this site. the materials contained in this web site are protected by applicable copyright and trade mark law. other information header 1 lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. ..... pages/footer.html copyright © 2013 script tutorials pages/index.html product #1 product #2 product #3 product #4 finally, the product pages. all of them are prototypes, so i decided to publish only one of them. pages/index.html product 1 page lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. download the app finishing touches – responsive styles all of these styles are needed to make our results look equally good on all possible mobile devices and monitors: @media (max-width: 1200px) { body { font-size:90%; } h1 { font-size:4.3em; } p { font-size:1.3em; } header { height:80px; } header .logo { margin-top:12px; width:200px; } header nav { margin-top:11px; } header nav ul li { margin-right:12px; } header nav ul li a { border-radius:23px; font-size: 1.3em; padding:10px 12px; } .wrap { padding:0 30px; } .paddrow .close { right:30px; } } @media (max-width: 900px) { .contactform { width:100%; } } @media (max-width: 768px) { body { font-size:80%; margin:0; } h1 { font-size:4em; } header { height:70px; } header .logo { margin-top:20px; width:70px; } header nav { margin-top:8px; } header nav ul li { margin-right:5px; } header nav ul li a { border-radius:20px; font-size:1.1em; padding:8px; } .wrap { padding:0 15px; } .projectobj .name { font-size:3em; } .paddrow { padding-bottom:30px; } .paddrow .head { font-size:3em; margin:30px 0; } .paddrow .close { right:20px; top:60px; width:30px; } .projecthead .picture { width:67%; } .projecthead .picture.right { margin-right:16.5%; } .projecthead .text { position:static; width:100%; } .projecthead .centertext { width:70%; } .view-enter,.view-leave { -webkit-transform:translate3d(0,0,0); transform:translate3d(0,0,0); } } @media (max-width: 480px) { body { font-size:70%; margin:0; } header { height:50px; } header .logo { display:none; } header nav { margin-top:3px; } header nav ul li { margin-right:3px; } header nav ul li a { border-radius:20px; font-size:1.3em; padding:5px 14px; } #contactbtn { display:none; } .wrap { padding:0 10px; } .paddrow { padding-bottom:20px; } .paddrow .head { margin:20px 0; } .paddrow .close { right:10px; top:45px; width:20px; } .about .image { margin:10% auto; width:60%; } .about .abicon { display:inline; } .projecthead .centertext { width:90%; } .about .txt,.input { width:100%; } .about .flleft,.about .flright,.input.email { float:none; } } live demo download in package conclusion that’s all for today. thanks for your patient attention, and if you really like what we did today, share it with all your friends in your social networks.
October 10, 2013
by Andrei Prikaznov
· 313,159 Views · 10 Likes
article thumbnail
Code Coverage of Jasmine Tests using Istanbul and Karma
for modern web application development, having dozens of unit tests is not enough anymore. the actual code coverage of those tests would reveal if the application is thoroughly stressed or not. for tests written using the famous jasmine test library, an easy way to have the coverage report is via istanbul and karma . for this example, let’s assume that we have a simple library sqrt.js which contains an alternative implementation of math.sqrt . note also how it will throw an exception instead of returning nan for an invalid input. var my = { sqrt: function(x) { if (x < 0) throw new error("sqrt can't work on negative number"); return math.exp(math.log(x)/2); } }; using jasmine placed under test/lib/jasmine-1.3.1 , we can craft a test runner that includes the following spec: describe("sqrt", function() { it("should compute the square root of 4 as 2", function() { expect(my.sqrt(4)).toequal(2); }); }); opening the spec runner in a web browser will give the expected outcome: so far so good. now let's see how the code coverage of our test setup can be measured. the first order of business is to install karma . if you are not familiar with karma, it is basically a test runner which can launch and connect to a specific set of web browsers, run your tests, and then gather the report. using node.js, what we need to do is: npm install karma karma-coverage before launching karma, we need to specify its configuration . it could be as simple as the following my.conf.js (most entries are self-explained). note that the tests are executed using phantomjs for simplicity, it is however quite trivial to add other web browsers such as chrome and firefox. module.exports = function(config) { config.set({ basepath: '', frameworks: ['jasmine'], files: [ '*.js', 'test/spec/*.js' ], browsers: ['phantomjs'], singlerun: true, reporters: ['progress', 'coverage'], preprocessors: { '*.js': ['coverage'] } }); }; running the tests, as well as performing code coverage at the same time, can be triggered via: node_modules/.bin/karma start my.conf.js which will dump the output like: info [karma]: karma v0.10.2 server started at http://localhost:9876/ info [launcher]: starting browser phantomjs info [phantomjs 1.9.2 (linux)]: connected on socket n9ndnhj0np92ntspgx-x phantomjs 1.9.2 (linux): executed 1 of 1 success (0.029 secs / 0.003 secs) as expected (from the previous manual invocation of the spec runner), the test passed just fine. however, the most particular interesting piece here is the code coverage report, it is stored (in the default location) under the subdirectory coverage . open the report in your favorite browser and there you'll find the coverage analysis report. behind the scene, karma is using istanbul , a comprehensive javascript code coverage tool (read also my previous blog post on javascript code coverage with istanbul ). istanbul parses the source file, in this example sqrt.js , using esprima and then adds some extra instrumentation which will be used to gather the execution statistics. the above report that you see is one of the possible outputs, istanbul can also generate lcov report which is suitable for many continuous integration systems (jenkins, teamcity, etc). an extensive analysis of the coverage data should also prevent any future coverage regression, check out my other post hard thresholds on javascript code coverage . one important thing about code coverage is branch coverage . if you pay attention carefully, our test above is still not exercising the situation where the input to my.sqrt is negative. there is a big "i" marking in the third-line of the code, this is istanbul telling us that the if branch is not taken at all (for the else branch, it will be an "e" marker). once this missing branch is noticed, improving the situation is as easy as adding one more test to the spec: it("should throw an exception if given a negative number", function() { expect(function(){ my.sqrt(-1); }). tothrow(new error("sqrt can't work on negative number")); }); once the test is executed again, the code coverage report looks way better and everyone is happy. if you have some difficulties following the above step-by-step instructions, take a look at a git repository i have prepared: github.com/ariya/coverage-jasmine-istanbul-karma . feel free to play with it and customize it to suit your workflow!
October 8, 2013
by Ariya Hidayat
· 49,224 Views
article thumbnail
Add REST to Standalone Java with Jetty and Spring WebMVC
I’m going to start by discussing the Spring WebMVC configuration and move on from there in future posts.
October 7, 2013
by Alan Hohn
· 36,695 Views · 1 Like
article thumbnail
Getting Started with NHibernate and ASP.NET MVC- CRUD Operations
In this post we are going to learn how we can use NHibernate in ASP.NET MVC application. What is NHibernate: ORMs(Object Relational Mapper) are quite popular this days. ORM is a mechanism to map database entities to Class entity objects without writing a code for fetching data and write some SQL queries. It automatically generates SQL Query for us and fetch data behalf on us. NHibernate is also a kind of Object Relational Mapper which is a port of popular Java ORM Hibernate. It provides a framework for mapping an domain model classes to a traditional relational databases. Its give us freedom of writing repetitive ADO.NET code as this will be act as our database layer. Let’s get started with NHibernate. How to download: There are two ways you can download this ORM. From nuget package and from the source forge site. Nuget - http://www.nuget.org/packages/NHibernate/ Source Forge-http://sourceforge.net/projects/nhibernate/ Creating a table for CRUD: I am going to use SQL Server 2012 express edition as a database. Following is a table with four fields Id, First Name, Last name, Designation. Creating ASP.NET MVC project for NHibernate: Let’s create a ASP.NET MVC project for NHibernate via click on File-> New Project –> ASP.NET MVC 4 web application. Installing NuGet package for NHibernate: I have installed nuget package from Package Manager console via following Command. It will install like following. NHibertnate configuration file: Nhibernate needs one configuration file for setting database connection and other details. You need to create a file with ‘hibernate.cfg.xml’ in model Nhibernate folder of your application with following details. NHibernate.Connection.DriverConnectionProvider NHibernate.Driver.SqlClientDriver Server=(local);database=LocalDatabase;Integrated Security=SSPI; NHibernate.Dialect.MsSql2012Dialect Here you have got different settings for NHibernate. You need to selected driver class, connection provider as per your database. If you are using other databases like Orcle or MySQL you will have different configuration. ThisNHibernate ORM can work with any databases. Creating a model class for NHibernate: Now it’s time to create model class for our CRUD operations. Following is a code for that. Property name is identical to database table columns. namespace NhibernateMVC.Models { public class Employee { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual string Designation { get; set; } } } Creating a mapping file between class and table: Now we need a xml mapping file between class and model with name “Employee.hbm.xml” like following in Nhibernate folder. Creating a class to open session for NHibernate I have created a class in models folder called NHIbernateSession and a static function it to open a session for NHibertnate. using System.Web; using NHibernate; using NHibernate.Cfg; namespace NhibernateMVC.Models { public class NHibertnateSession { public static ISession OpenSession() { var configuration = new Configuration(); var configurationPath = HttpContext.Current.Server.MapPath(@"~\Models\Nhibernate\hibernate.cfg.xml"); configuration.Configure(configurationPath); var employeeConfigurationFile = HttpContext.Current.Server.MapPath(@"~\Models\Nhibernate\Employee.hbm.xml"); configuration.AddFile(employeeConfigurationFile); ISessionFactory sessionFactory = configuration.BuildSessionFactory(); return sessionFactory.OpenSession(); } } } Listing: Now we have our open session method ready its time to write controller code to fetch data from the database. Following is a code for that. using System; using System.Web.Mvc; using NHibernate; using NHibernate.Linq; using System.Linq; using NhibernateMVC.Models; namespace NhibernateMVC.Controllers { public class EmployeeController : Controller { public ActionResult Index() { using (ISession session = NHibertnateSession.OpenSession()) { var employees = session.Query().ToList(); return View(employees); } } } } Here you can see I have get a session via OpenSession method and then I have queried database for fetching employee database. Let’s create a new for this you can create this via right lick on view on above method.We are going to create a strongly typed view for this. Our listing screen is ready once you run project it will fetch data as following. Create/Add: Now its time to write add employee code. Following is a code I have written for that. Here I have used session.save method to save new employee. First method is for returning a blank view and another method with HttpPost attribute will save the data into the database. public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Employee emplolyee) { try { using (ISession session = NHibertnateSession.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Save(emplolyee); transaction.Commit(); } } return RedirectToAction("Index"); } catch(Exception exception) { return View(); } } Now let’s create a create view strongly typed view via right clicking on view and add view. Once you run this application and click on create new it will load following screen. Edit/Update: Now let’s create a edit functionality with NHibernate and ASP.NET MVC. For that I have written two action result method once for loading edit view and another for save data. Following is a code for that. public ActionResult Edit(int id) { using (ISession session = NHibertnateSession.OpenSession()) { var employee = session.Get(id); return View(employee); } } [HttpPost] public ActionResult Edit(int id, Employee employee) { try { using (ISession session = NHibertnateSession.OpenSession()) { var employeetoUpdate = session.Get(id); employeetoUpdate.Designation = employee.Designation; employeetoUpdate.FirstName = employee.FirstName; employeetoUpdate.LastName = employee.LastName; using (ITransaction transaction = session.BeginTransaction()) { session.Save(employeetoUpdate); transaction.Commit(); } } return RedirectToAction("Index"); } catch { return View(); } } Here in first action result I have fetched existing employee via get method of NHibernate session and in second I have fetched and changed the current employee with update details. You can create view for this via right click –>add view like below. I have created a strongly typed view for edit. Once you run code it will look like following. Details: Now it’s time to create a detail view where user can see the employee detail. I have written following logic for details view. public ActionResult Details(int id) { using (ISession session = NHibertnateSession.OpenSession()) { var employee = session.Get(id); return View(employee); } } You can add view like following via right click on actionresult view. now once you run this in browser it will look like following. Delete: Now its time to write delete functionality code. Following code I have written for that. public ActionResult Delete(int id) { using (ISession session = NHibertnateSession.OpenSession()) { var employee = session.Get(id); return View(employee); } } [HttpPost] public ActionResult Delete(int id, Employee employee) { try { using (ISession session = NHibertnateSession.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { session.Delete(employee); transaction.Commit(); } } return RedirectToAction("Index"); } catch(Exception exception) { return View(); } } Here in the above first action result will have the delete confirmation view and another will perform actual delete operation with session delete method. When you run into the browser it will look like following. That’s it. It’s very easy to have crud operation with NHibernate. Stay tuned for more.
October 1, 2013
by Jalpesh Vadgama
· 47,294 Views
article thumbnail
ElasticSearch: Java API
ElasticSearch provides Java API, thus it executes all operations asynchronously by using client object.
September 30, 2013
by Hüseyin Akdoğan DZone Core CORE
· 137,562 Views · 4 Likes
article thumbnail
Injecting Spring beans into non-managed objects
Advantages coming from dependency injection can be addictive. It's a lot easier to configure application structure using injections than doing all resolutions manually. It's hard to resign from it when we have some non-managed classes that are instantiated outside of the container - for example being part of other frameworks like Vaadin UI components or JPA entities. The latter are especially important when we're using Domain Driven Design. During DDD training ran by Slawek Sobotka we were talking about options to remove "bad coupling" from aggregate factories. I'm sure you'll admit, that it's better to have generic mechanism able to "energize" objects by dependencies defined by e.g. @Inject annotation than inject all necessary dependencies into particular factory and then pass them into object by constructor, builder or simple setters. Spring framework brings us two different solutions to achieve such requirement. I'll now describe them both of them. Let's start with with simpler one. It's especially powerful when we've case such as generic repository, mentioned earlier aggregate factory, or even any other factory just ensuring that we have only few places in our code where will instantiate objects outside of the container. In this case we can make use of AutowireCapableBeanFactory class. In particular we will be interested in two methods: void autowireBean(Object existingBean) Object initializeBean(Object existingBean, String beanName) The first one just populates our bean without applying specific post processors (e.g. @PostConstruct, etc). The second one additionally applies factory callbacks like setBeanName and setBeanFactory, as well as any other post processors with @PostConstruct of course. In our code it'll look like this: public abstract class GenericFactory { @Autowired private AutowireCapableBeanFactory autowireBeanFactory; public T createBean() { // creation logic autowireBeanFactory.autowireBean(createdBean); return createdBean; } } Simple and powerful - my favorite composition :) But what can we do when we have plenty places in our code where objects get born? That's for example case of building Vaadin layouts in Spring web application. Injecting custom bean configurer objects invoking autowireBean method won't be the peak of productivity. Happily Spring developers brought us @Configurable annotation. This annotation connected with aspects will configure each annotated object even if we will create it outside of the container using new operator. Like with any other aspects we can choose between load-time-waving (LTW) compile-time-waving (CTW). The first one is easier to configure but we become (due to instrumentation) dependent from application server, which can be undesirable in some cases. To use it we need to annotate our @Configuration class by @EnableLoadTimeWeaving (or add tag if you like Flintstones and XML configuration ;)) After completing configuration just annotate class by @Configurable: @Configurable public class MyCustomButton extends Button { @Autowired private MyAwesomeService myAwesomeService; // handlers making use of injected service } The second option is a little bit more complex to setup but after this it will be a lot lighter in runtime. Because now we want to load aspects till compilation we have to integrate aspectj compiler into our build. In Maven you need to add few dependencies: org.aspectj aspectjrt 1.7.3 org.springframework spring-aspects 3.2.4.RELEASE org.springframework spring-tx 3.2.4.RELEASE javax.persistence persistence-api 1.0 provided I hope you are curious why above you can see persistence-api. That was also strange for me, when I saw "can't determine annotations of missing type javax.persistence.Entity" error during aspectj compilation. The answer can be found in SpringFramework JIRA in issue SPR-6819. This happens when you configure spring-aspects as a aspectLibrary in aspectj-maven-plugin. Issue is unresolved for over three year so better get used to it :) The last thing we need to do is to include above-mentioned plugin into our plugins section. org.codehaus.mojo aspectj-maven-plugin 1.5 1.7 1.7 1.7 true org.springframework spring-aspects compile And that's all folks :)
September 24, 2013
by Jakub Kubrynski
· 23,470 Views · 1 Like
article thumbnail
A Better Way of Using ASP.NET SignalR With Angular JS
A few days back, I blogged on using SignalR and Angular JS together and on Implementing SignalR stock ticker sample using Angular JS(Part 1 and Part 2). In those posts, I have used the traditional call-back model to call the functions defined in controller to modify data whenever an update is received from the server. One of the readers sent me feedback saying that we have a better way to use SignalR and Angular JS together. The way to go is using event methods defined on $rootscope object. This approach is based on publishing and subscribing events. As events can be published from anywhere and subscribed from anywhere, the source and destination will remain completely unaware of each other. Both of them have to depend on just one object, $rootScope. Official documentation on scope contains details on each method defined on $rootScope. We will be using the following methods for publishing and subscribing the events: $emit(name, args): Publishes an event with specified name with given arguments $on(name, listener): Subscribes to an event with specified name. Listener is a function containing logic to be executed once the event has occurred To manage SignalR’s client functionality, it is better to create a service, as services are singletons. There will be only one instance of the service in entire application. This behaviour of services makes it possible to have multiple SignalR client pages in the applications and they can be kept in sync without putting any extra amount of effort. Let’s modify the example discussed in the post titled Hooking up ASP.NET SignalR with Angular JS to use event model. Server hub, references and structure of the HTML page remains the same as past. The only components to be modified are Controller and Service. Service carries the responsibility to initialize a connection to the hub and call the SignalR’s server methods. Once a response is received from the server, we will broadcast an event from the service with data received. app.service('signalRSvc', function ($, $rootScope) { var proxy = null; var initialize = function () { //Getting the connection object connection = $.hubConnection(); //Creating proxy this.proxy = connection.createHubProxy('helloWorldHub'); //Starting connection connection.start(); //Publishing an event when server pushes a greeting message this.proxy.on('acceptGreet', function (message) { $rootScope.$emit("acceptGreet",message); }); }; var sendRequest = function () { //Invoking greetAll method defined in hub this.proxy.invoke('greetAll'); }; return { initialize: initialize, sendRequest: sendRequest }; }); To keep the things simple, I kept names of the server hub event and event rose using $emit the same. The names can be different. Let’s modify the controller to have a listener to the event raised by the service. Following is the implementation of the controller: function SignalRAngularCtrl($scope, signalRSvc, $rootScope) { $scope.text = ""; $scope.greetAll = function () { signalRSvc.sendRequest(); } updateGreetingMessage = function (text) { $scope.text = text; } signalRSvc.initialize(); //Updating greeting message after receiving a message through the event $scope.$parent.$on("acceptGreet", function (e,message) { $scope.$apply(function () { updateGreetingMessage(message) }); }); } Now open the modified page on multiple browsers and click the Greeting button randomly from all browsers. Messages printed on all browsers should be updated whenever the button is clicked. This behaviour is same as it was earlier. We just adopted a better approach to make it work. Happy coding!
September 20, 2013
by Rabi Kiran Srirangam
· 27,368 Views
article thumbnail
Solving the Detached Many-to-Many Problem with the Entity Framework
Introduction This article is part of the ongoing series I’ve been writing recently, but can be read as a standalone article. I’m going to do a better job of integrating the changes documented here into the ongoing solution I’ve been building. However, considering how much time and effort I put into solving this issue, I’ve decided to document the approach independently in case it is of use to others in the interim. The Problem Defined This issue presents itself when you are dealing with disconnected/detached Entity Framework POCO objects,. as the DbContext doesn’t track changes to entities. Specifically, trouble occurs with entities participating in a many-to-many relationship, where the EF has hidden a “join table” from the model itself. The problem with detached entities is that the data context has no way of knowing what changes have been made to an object graph, without fetching the data from the data store and doing an entity-by-entity comparison – and that assuming it’s possible to fetch the same way as it was originally. In this solution, all the entities are detached, don’t use proxy types and are designed to move between WCF service boundaries. Some Inspiration There are no out-of-the-box solutions that I’m aware of which can process POCO object graphs that are detached. I did find an interesting solution called GraphDiff which is available from github and also as a NuGet package, but it didn’t work with the latest RC version of the Entity Framework (v6). I also found a very comprehensive article on how to implement a generic repository pattern with the Entity Framework, but it was unable to handle detached many-to-many relationships. In any case, I highly recommend a read of this article, it was inspiration for some of the approach I’ve ended up taking with my own design. The Approach This morning I put together a simple data model with the relationships that I wanted to support with detached entities. I’ve attached the solution with a sample schema and test data at the bottom of this article. If you prefer to open and play with it, be sue to add the Entity Framework (v6 RC) via NuGet, I’ve omitted it for file size and licensing reasons). Here’s a logical view of the model I wanted to support: Here’s the schema view from SQL Server: Here’s the Entity Model which is generated from the above SQL schema: In the spirit of punching myself in the head, I’ve elected to have one table implement an identity specification (meaning the underlying schema allocated PK ID values) whereas the other two tables the ID must be specified. Theoretically, if I can handle the entity types in a generic fashion, then this solution can scale out to larger and more complex models. The scenarios I’m specifically looking to solve in this solution with detached object graphs are as follows: Add a relationship (many-to-many) Add a relationship (FK-based) Update a related entity (many-to-many) Update a related entity (FK-based) Remove a relationship (many-to-many) Remove a relationship (FK-based) Per the above, here’s the scenarios within the context of the above data model: Add a new Secondary entity to a Primary entity Add an Other entity to a Secondary entity Update a Secondary entity by updating a Primary entity Update an Other entity from a Secondary entity (or Primary entity) Remove (but not delete!) a Secondary entity from a Primary entity Remove (but not delete) a Other entity from a Secondary entity Establishing Test Data Just to give myself a baseline, the data model is populated (by default) with the following data. This gives us some “existing entities” to query and modify. More Work for the Consumer Although I tried my best, I couldn’t come to a design which didn’t require the consuming client to do slightly more work to enable this to work properly. Unfortunately the best place for change tracking to occur with disconnected entities is with the layer making changes – be it a business layer or something downstream. To this effect, entities will need to implement a property which reflects the state of the entity (added, modified, deleted etc.). For the object graph to be updated/managed successfully, the consumer of the entities needs to set the entity state properly. This isn’t at all as bad as it sounds, but it’s not nothing. Establishing some Scaffolding After generating the data model, the first thing to be done is ensure each entity derives from the same base class. (“EntityBase”) this is used later to establish the active state of an entity when it needs to be processed. I’ve also created an enum (“ObjectState”) which is a property of the base class and a helper function which maps ObjectState to an EF EntityState. In case this isn’t clear, here’s a class view: Constructing Data Access To ensure that the usage is consistent, I’ve defined a single Data Access class, mainly to establish the pattern for handling detached object graphs. I can’t stress enough that this is not intended as a guide to an appropriate way to structure your data access – I’ll be updating my ongoing series of articles to go into more detail – this is only to articulate a design approach to handling detached object graphs. Having said all that, here’s a look at my “DataAccessor” class, which can be used with generic data access entities (by way of generics): As with my ongoing project, the Entity Framework DbContext is instantiated by this class on construction, and implements IDisposable to ensure the DbContext is disposed properly upon construction. Here’s the constructor showing the EF configuration options I’m using: public DataAccessor() { _accessor = new SampleEntities(); _accessor.Configuration.LazyLoadingEnabled = false; _accessor.Configuration.ProxyCreationEnabled = false; } Updating an Entity We start with a basic scenario to ensure that the scaffolding has been implemented properly. The scenario is to query for a Primary entity and then change a property and update the entity in the data store. [TestMethod] public void UpdateSingleEntity() { Primary existing = null; String existingValue = String.Empty; using (DataAccessor a = new DataAccessor()) { existing = a.DataContext.Primaries.Include("Secondaries").First(); Assert.IsNotNull(existing); existingValue = existing.Title; existing.Title = "Unit " + DateTime.Now.ToString("MMdd hh:mm:ss"); } using (DataAccessor b = new DataAccessor()) { existing.State = ObjectState.Modified; b.InsertOrUpdate(existing); } using (DataAccessor c = new DataAccessor()) { existing.Title = existingValue; existing.State = ObjectState.Modified; c.InsertOrUpdate(existing); } } You’ll noticed that there is nothing particularly significant here, except that the object’s State is reset toModified between operations. Updating a Many-to-Many Relationship Now things get interesting. I’m going to query for a Primary entity, then I’ll update both a property of thePrimary entity itself, and a property of one of the entity’s relationships. [TestMethod] public void UpdateManyToMany() { Primary existing = null; Secondary other = null; String existingValue = String.Empty; String existingOtherValue = String.Empty; using (DataAccessor a = new DataAccessor()) { //Note that we include the navigation property in the query existing = a.DataContext.Primaries.Include("Secondaries").First(); Assert.IsTrue(existing.Secondaries.Count() > 1, "Should be at least 1 linked item"); } //save the original description existingValue = existing.Description; //set a new dummy value (with a date/time so we can see it working) existing.Description = "Edit " + DateTime.Now.ToString("yyyyMMdd hh:mm:ss"); existing.State = ObjectState.Modified; other = existing.Secondaries.First(); //save the original value existingOtherValue = other.AlternateDescription; //set a new value other.AlternateDescription = "Edit " + DateTime.Now.ToString("yyyyMMdd hh:mm:ss"); other.State = ObjectState.Modified; //a new data access class (new DbContext) using (DataAccessor b = new DataAccessor()) { //single method to handle inserts and updates //set a breakpoint here to see the result in the DB b.InsertOrUpdate(existing); } //return the values to the original ones existing.Description = existingValue; other.AlternateDescription = existingOtherValue; existing.State = ObjectState.Modified; other.State = ObjectState.Modified; using (DataAccessor c = new DataAccessor()) { //update the entities back to normal //set a breakpoint here to see the data before it reverts back c.InsertOrUpdate(existing); } } If we actually run this unit test and set the breakpoints accordingly, you’ll see the following in the database: Database at Breakpoint #1 / Database at Breakpoint #2 Database when Unit Test completes You’ll notice at the second breakpoint that the description of the first entities have both been updated. Examining the Insert/Update Code The function exposed by the “data access” class really just passes through to another private function which does the heavy lifting. This is mainly in case we need to reuse the logic, since it essentially processes state action on attached entities. public void InsertOrUpdate(params T[] entities) where T : EntityBase { ApplyStateChanges(entities); DataContext.SaveChanges(); } Here’s the definition of the ApplyStateChanges function, which I’ll discuss below: private void ApplyStateChanges(params T[] items) where T : EntityBase { DbSet dbSet = DataContext.Set(); foreach (T item in items) { //loads related entities into the current context dbSet.Attach(item); if (item.State == ObjectState.Added || item.State == ObjectState.Modified) { dbSet.AddOrUpdate(item); } else if (item.State == ObjectState.Deleted) { dbSet.Remove(item); } foreach (DbEntityEntry entry in DataContext.ChangeTracker.Entries() .Where(c => c.Entity.State != ObjectState.Processed && c.Entity.State != ObjectState.Unchanged)) { var y = DataContext.Entry(entry.Entity); y.State = HelperFunctions.ConvertState(entry.Entity.State); entry.Entity.State = ObjectState.Processed; } } } Notes on this Implementation What this function does is to iterate through the items to be examined, attach them to the current Data Context (which also attaches their children), act on each item accordingly (add/update/remove) and then process new entities which have been added to the Data Context’s change tracker. For each newly “discovered” entity (and ignoring entities which are unchanged or have already been examined), each entity’s DbEntityEntry is set according to the entity’s ObjectState (which is set by the calling client). Doing this allows the Entity Framework to understand what actions it needs to perform on the entities when SaveChanges() is invoked later. You’ll also note that I set the entity’s state to “Processed” when it has been examined, so we don’t act on it more than once (for performance purposes). Fun note: the AddOrUpdate extension method is something I found in theSystem.Data.Entity.Migrations namespace and it acts as an ‘Upsert’ operation, inserting or updating entities depending on whether they exist or not already. Bonus! That’s it for adding and updating, believe it or not. Corresponding Unit Test The following unit test establishes the creation of a new many-to-many entity, it is then removed (by relationship) and then finally deleted altogether from the database: [TestMethod] public void AddRemoveRelationship() { Primary existing = null; using (DataAccessor a = new DataAccessor()) { existing = a.DataContext.Primaries.Include("Secondaries") .FirstOrDefault(); Assert.IsNotNull(existing); } Secondary newEntity = new Secondary(); newEntity.State = ObjectState.Added; newEntity.AlternateTitle = "Unit"; newEntity.AlternateDescription = "Test"; newEntity.SecondaryId = 1000; existing.Secondaries.Add(newEntity); using (DataAccessor a = new DataAccessor()) { //breakpoint #1 here a.InsertOrUpdate(existing); } newEntity.State = ObjectState.Unchanged; existing.State = ObjectState.Modified; using (DataAccessor b = new DataAccessor()) { //breakpoint #2 here b.RemoveEntities(existing, x => x.Secondaries, newEntity); } using (DataAccessor c = new DataAccessor()) { //breakpoint #3 here c.Delete(newEntity); } } Test Results: Pre-Test – Breakpoint #1 / Breakpoint #2 Breakpoint #3 / Post execution (new entity deleted) SQL Profile Trace Removing a Many-to-Many Relationship Now this is where it gets tricky. I’d like to have something a little more polished, but the best I have come up with to date is a separate operation on the data provider which exposes functionality akin to “remove relationship”. The fundamental problem with how the EF POCO entities work without any modifications, is when they are detached, to remove a many-to-many relationship, the relationship to be removed is physically removed from the collection. When the object graph is sent back for processing, there’s a missing related entity, and the service or data context would have to make an assumption that the omission was on purpose, not to mention that it would have to compare against data currently in the data store. To make this easier, I’ve implemented a function called “RemoveEnttiies” which alters the relationship between the parent and the child/children. The one bug catch is that you need to specify the navigation property or collection, which might make it slightly undesirable to implement generically. In any case, I’ve provided two options – with the navigation property as a string parameter or as a LINQ expression – they both do the same thing. public void RemoveEntities(T parent, Expression> expression, params T2[] children) where T : EntityBase where T2 : EntityBase { DataContext.Set().Attach(parent); ObjectContext obj = DataContext.ToObjectContext(); foreach (T2 child in children) { DataContext.Set().Attach(child); obj.ObjectStateManager.ChangeRelationshipState(parent, child, expression, EntityState.Deleted); } DataContext.SaveChanges(); } Notes on this Implementation The “ToObjectContext” is an extension method, and is akin to (DataContext as IObjectContextAdapter).ObjectContext. This is to expose a more fundamental part of the Entity Framework’s object model. We need this level of access to get to the functionality which controls relationships. For each child to be removed (note: not deleted from the physical database), we nominate the parent object, the child, the navigation property (collection) and the nature of the relationship change (delete). Note that this will NOT WORK for Foreign Key defined relationships – more on that below. To delete entities which have active relationships, you’ll need to drop the relationship before attempting to delete or else you’ll have data integrity/referential integrity errors, unless you have accounted for cascading deletion (which I haven’t). Example execution: using (DataAccessor c = new DataAccessor()) { //c.RemoveEntities(existing, "Secondaries", s); //(or can use an expression): c.RemoveEntities(existing, x => x.Secondaries, s); } Removing FK Relationships As mentioned above, you can’t just edit the relationship to remove an FK-based relationship. Instead, you have to follow the EF practice of setting the FK entity to NULL. Here’s a Unit Test which demonstrates how this is achieved: Secondary s = ExistingEntity(); using (DataAccessor c = new DataAccessor()) { s.Other = null; s.OtherId = null; s.State = ObjectState.Modified; o.State = ObjectState.Unchanged; c.InsertOrUpdate(s); } We use the same “Insert or Update’ call – being aware that you have to set the ObjectState properties accordingly. Note: I’m in the process of testing the reverse removal – i.e. what happens if you want to remove a Secondaryentity from an Other entity’s collection. Deleting Entities This is fairly straightforward, but I’ve taken a few more precautions to ensure that the entity to be deleted is valid no the server side. public void Delete(params T[] entities) where T : EntityBase { foreach (T entity in entities) { T attachedEntity = Exists(entity); if (attachedEntity != null) { var attachedEntry = DataContext.Entry(attachedEntity); attachedEntry.State = EntityState.Deleted; } } DataContext.SaveChanges(); } To understand the above, you should take a look at the implementation of the “Exists” function which essentially checks the data store and local cache to see if there is an attached representation: protected T Exists(T entity) where T : EntityBase { var objContext = ((IObjectContextAdapter)this.DataContext) .ObjectContext; var objSet = objContext.CreateObjectSet(); var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, entity); DbSet set = DataContext.Set(); var keys = (from x in entityKey.EntityKeyValues select x.Value).ToArray(); //Remember, there can by surrogate keys, so don't assume there's //just one column/one value //If a surrogate key isn't ordered properly, the Set().Find() //method will fail, use attributes on the entity to determine the //proper order. //context.Configuration.AutoDetectChangesEnabled = false; return set.Find(keys); } This is a fairly expensive operation which is why it’s pretty much reserved for deletes and not more frequent operations. It essentially determines the target entity’s primary key and then checks whether the entity exists or not. Note: I haven’t tested this on entities with surrogate keys, but I’ll get to it at some point. If you have surrogate key tables, you can define the PK key order using attributes on the model entity, but I haven’t done this (yet). Summary This article is the culmination of about two days of heavy analysis and investigation. I’ve got a whole lot more to contribute on this topic, but for now, I felt it was worthy enough to post as-is. What you’ve got here is still incredibly rough, and I haven’t done nearly enough testing. To be honest, I was quite excited by the initial results, which is why I decided to write this post. there’s an incredibly good chance that I’ve missed something in the design and implementation, so please be aware of that. I’ll be continuing to refine this approach in my main series of articles with much cleaner implementation. In the meantime though, if any of this helps anyone out there struggling with detached entities, I hope it helps. There’s precious few articles and samples that are up to date, and very few that seem to work. This is provided without any warranty of any kind! If you find any issues please e-mail me [email protected] and I’ll attempt to refactor/debug and find ways around some of the inherent limitations. In the meantime, there are a few helpful links I’ve come across in my travels on the WWW. See below. Example Solution Files [ Files ] Note: you’ll need to add the Entity Framework v6 RC package via NuGet, I haven’t included it in the archive. Helpful Links http://blog.magnusmontin.net/2013/05/30/generic-dal-using-entity-framework/ https://github.com/refactorthis/GraphDiff http://stackoverflow.com/questions/11686225/dbset-find-method-ridiculously-slow-compared-to-singleordefault-on-id http://stackoverflow.com/questions/10381106/cannot-update-many-to-many-relationships-in-entity-framework http://stackoverflow.com/questions/8413248/how-to-save-an-updated-many-to-many-collection-on-detached-entity-framework-4-1 http://stackoverflow.com/questions/6018711/generic-way-to-check-if-entity-exists-in-entity-framework
September 18, 2013
by Rob Sanders
· 163,476 Views
article thumbnail
Introduction to ElasticSearch
Learn about ElasticSearch, an open source tool developed with Java. It is a Lucene-based, scalable, full-text search engine, and a data analysis tool.
September 17, 2013
by Hüseyin Akdoğan DZone Core CORE
· 12,113 Views · 5 Likes
article thumbnail
Exploring Apache Camel Core - Seda Component
The seda component in Apache Camel is very similar to the direct component that I’ve presented in previous blog, but in a asynchronous manner.
September 15, 2013
by Zemian Deng
· 27,249 Views
article thumbnail
Introducing the Spring YARN framework for Developing Apache Hadoop YARN Applications
Originally posted on the SpringSource blog by Janne Valkealahti We're super excited to let the cat out of the bag and release support for writing YARN based applications as part of the Spring for Apache Hadoop 2.0 M1 release. In this blog post I’ll introduce you to YARN, what you can do with it, and how Spring simplifies the development of YARN based applications. If you have been following the Hadoop community over the past year or two, you’ve probably seen a lot of discussions around YARN and the next version of Hadoop's MapReduce called MapReduce v2. YARN (Yet Another Resource Negotiator) is a component of the MapReduce project created to overcome some performance issues in Hadoop's original design. The fundamental idea of MapReduce v2 is to split the functionalities of the JobTracker, Resource Management and Job Scheduling/Monitoring, into separate daemons. The idea is to have a global Resource Manager (RM) and a per-application Application Master (AM). A generic diagram for YARN component dependencies can be found from YARN architecture. MapReduce Version 2 is an application running on top of YARN. It is also possible to make similar custom YARN based application which have nothing to do with MapReduce, it is simply running YARN application. However, writing a custom YARN based application is difficult. The YARN APIs are low-level infrastructure APIs and not developer APIs. Take a look at thedocumentation for writing a YARN application to get an idea of what is involved. Starting with the 2.0 version, Spring for Apache Hadoop introduces the Spring YARN sub-project to provide support for building Spring based YARN applications. This support for YARN steps in by trying to make development easier. “Spring handles the infrastructure so you can focus on your application” applies to writing Hadoop applications as well as other types of Java applications. Spring’s YARN support also makes it easier to test your YARN application. With Spring’s YARN support, you're going to use all familiar concepts of Spring Framework itself, including configuration and generally speaking what you can do in your application. At a high level, Spring YARN provides three different components, YarnClient, YarnAppmaster andYarnContainer which together can be called a Spring YARN Application. We provide default implementations for all components while still giving the end user an option to customize as much as he or she wants. Lets take a quick look at a very simplistic Spring YARN application which runs some custom code in a Hadoop cluster. The YarnClient is used to communicate with YARN's Resource Manager. This provides management actions like submitting new application instances, listing applications and killing running applications. When submitting applications from the YarnClient, the main concerns relate to how the Application Master is configured and launched. Both the YarnAppmaster andYarnContainer share the same common launch context config logic so you'll see a lot of similarities in YarnClient and YarnAppmaster configuration. Similar to how the YarnClient will define the launch context for the YarnAppmaster, the YarnAppmaster defines the launch context for the YarnContainer. The Launch context defines the commands to start the container, localized files, command line parameters, environment variables and resource limits(memory, cpu). The YarnContainer is a worker that does the heavy lifting of what a YARN application will actually do. The YarnAppmaster is communicating with YARN Resource Manager and starts and stops YarnContainers accordingly. You can create a Spring application that launches an ApplicationMaster by using the YARN XML namespace to define a Spring Application Context. Context configuration for YarnClient defines the launch context for YarnAppmaster. This includes resources and libraries needed by YarnAppmaster and its environment settings. An example of this is shown below. Note: Future releases will provide a Java based API for configuration, similar to what is done in Spring Security 3.2. The purpose of YarnAppmaster is to control the instance of a running application. TheYarnAppmaster is responsible for controlling the lifecycle of all its YarnContainers, the whole running application after the application is submitted, as well as itself. The example above is defining a context configuration for the YarnAppmaster. Similar to what we saw in YarnClient configuration, we define local resources for the YarnContainer and its environment. The classpath setting picks up hadoop jars as well as your own application jars in default locations, change the setting if you want to use non-default directories. Also within theYarnAppmaster we define components handling the container allocation and bootstrapping. Allocator component is interacting with YARN resource manager handling the resource scheduling. Runner component is responsible for bootstrapping of allocated containers. Above example defines a simple YarnContainer context configuration. To implement the functionality of the container, you implement the interface YarnContainer. The YarnContainer interface is similar to Java’s Runnable interface, its has a run() method, as well as two additional methods related to getting environment and command line information. Below is a simple hello world application that will be run inside of a YARN container: public class MyCustomYarnContainer implements YarnContainer { private static final Log log = LogFactory.getLog(MyCustomYarnContainer.class); @Override public void run() { log.info("Hello from MyCustomYarnContainer"); } @Override public void setEnvironment(Map environment) {} @Override public void setParameters(Properties parameters) {} } We just showed the configuration of a Spring YARN Application and the core application logic so what remains is how to bootstrap the application to run inside the Hadoop cluster. The utility class, CommandLineClientRunner provides this functionality. You can you use CommandLineClientRunner either manually from a command line or use it from your own code. # java -cp org.springframework.yarn.client.CommandLineClientRunner application-context.xml yarnClient -submit A Spring YARN Application is packaged into a jar file which then can be transferred into HDFS with the rest of the dependencies. A YarnClient can transfer all needed libraries into HDFS during the application submit process but generally speaking it is more advisable to do this manually in order to avoid unnecessary network I/O. Your application wont change until new version is created so it can be copied into HDFS prior the first application submit. You can i.e. use Hadoop's hdfs dfs -copyFromLocal command. Below you can see an example of a typical project setup. src/main/java/org/example/MyCustomYarnContainer.java src/main/resources/application-context.xml src/main/resources/appmaster-context.xml src/main/resources/container-context.xml As a wild guess, we'll make a bet that you have now figured out that you are not actually configuring YARN, instead you are configuring Spring Application Contexts for all three components, YarnClient, YarnAppmaster and YarnContainer. We have just scratched the surface of what we can do with Spring YARN. While we’re preparing more blog posts, go ahead and check existing samples in GitHub. Basically, to reflect the concepts we described in this blog post, see the multi-context example in our samples repository. Future blog posts will cover topics like Unit Testing and more advanced YARN application development.
September 11, 2013
by Pieter Humphrey
· 13,630 Views
  • Previous
  • ...
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×