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 Coding Topics

article thumbnail
Spring MVC - Flash Attributes
The latest incarnation of the Spring Framework (3.1) brought an interesting feature called Flash Attributes. It is a remedy for the problem mentioned a long time ago, in one of my posts: Spring MVC - Session Attributes handling. This problem can be described in few words: if we want to pass the attributes via redirect between two controllers, we cannot use request attributes (they will not survive the redirect), and we cannot use Spring's @SessionAttributes (because of the way Spring handles it), only an ordinary HttpSession can be used, which is not very convenient. Below you will find an example of Flash Attributes usage, before you start reviewing it, read Using flash attributes section of Spring documentation. Suppose that we have two controllers: AController and BController, first one will prepare some data and pass to the second using Flash Attributes after the form submission. On the AController we will have something like this: @RequestMapping(method = RequestMethod.POST) public String handleFormSubmission(..., final RedirectAttributes redirectAttrs) { ... redirectAttrs.addFlashAttribute("AttributeName", value); return "redirect:to_some_url_handled_by_BController"; } When the form will be submitted, attribute value will be stored as Flash Attribute named "AttributeName", and thanks to the Spring, will be passed to BController, where it can be used for example in following way: @Controller ... @SessionAttributes("AttributeName") public class SearchCriteriaHandler { ... @RequestMapping(method = RequestMethod.GET) public void handleGetRequest(@ModelAttribute("AttributeName") final SomeType value) { ... } ... } Before your handler method will be called, Spring Framework will populate the Model with the available Flash Attributes - at this point value passed from AController will become a model attribute for the BController. Note, that because we also defined this attribute as the Session Attribute, it will be automatically stored for future usage within this controller, after the GET request handling. Let me say that I was waiting for this feature for the long time, ;)
March 22, 2012
by Michal Jastak
· 53,509 Views · 2 Likes
article thumbnail
HTML5 Image Effects – Emboss
Today we continue our HTML5 canvas image filter examples. Today I would like to share with you a method of applying a Emboss effect to images. This is a pretty difficult method, but I am sure that you can repeat it. In our demo we can play with different images by adding an emboss effect to them, and we can ‘export’ our result on the image element (). Here are our demo and downloadable packages: Live Demo download in package Ok, download the example files and let's start coding ! Step 1. HTML Markup This is the markup of our demo page: index.html HTML5 Image Effects - Emboss Back to original tutorial on Script Tutorials Canvas Object Image Object Next imageApply Emboss EffectTo Image Basically – it contains just one canvas object, one image, and three ‘buttons’ (div elements). Step 2. CSS Here are our stylesheets (not so important, but anyway): css/main.css *{ margin:0; padding:0; } body { background-image:url(../images/bg.png); color:#fff; font:14px/1.3 Arial,sans-serif; } header { background-color:#212121; box-shadow: 0 -1px 2px #111111; display:block; height:70px; position:relative; width:100%; z-index:100; } header h2{ font-size:22px; font-weight:normal; left:50%; margin-left:-400px; padding:22px 0; position:absolute; width:540px; } header a.stuts,a.stuts:visited { border:none; text-decoration:none; color:#fcfcfc; font-size:14px; left:50%; line-height:31px; margin:23px 0 0 110px; position:absolute; top:0; } header .stuts span { font-size:22px; font-weight:bold; margin-left:5px; } .container { color: #000000; margin: 20px auto; overflow: hidden; position: relative; width: 1005px; } table { background-color: rgba(255, 255, 255, 0.7); } table td { border: 1px inset #888888; position: relative; text-align: center; } table td p { display: block; padding: 10px 0; } .button { cursor: pointer; height: 20px; padding: 15px 0; position: relative; text-align: center; width: 500px; -moz-user-select: none; -khtml-user-select: none; user-select: none; } Step 3. JS Finally – our JavaScript code for the Emboss effect: js/script.js // variables var canvas, ctx; var imgObj; // filter strength var strength = 0.5; // shifting matrix var matrix = [-2, -1, 0, -1, 1, 1, 0, 1, 2]; // normalize matrix function normalizeMatrix(m) { var j = 0; for (var i = 0; i < m.length; i++) { j += m[i]; } for (var i = 0; i < m.length; i++) { m[i] /= j; } return m; } // convert x-y coordinates into pixel position function convertCoordinates(x, y, w) { return x + (y * w); } // find a specified distance between two colours function findColorDiff(dif, dest, src) { return dif * dest + (1 - dif) * src; } // transform matrix function transformMatrix(img, pixels) { // create a second canvas and context to keep temp results var canvas2 = document.createElement('canvas'); var ctx2 = canvas2.getContext('2d'); ctx2.width = canvas2.width = img.width; ctx2.height = canvas2.height = img.height; // draw image ctx2.drawImage(img, 0, 0, img.width , img.height); var buffImageData = ctx2.getImageData(0, 0, canvas.width, canvas.height); var data = pixels.data; var bufferedData = buffImageData.data; // normalize matrix matrix = normalizeMatrix(matrix); var mSize = Math.sqrt(matrix.length); for (var i = 1; i < img.width - 1; i++) { for (var j = 1; j < img.height - 1; j++) { var sumR = sumG = sumB = 0; // loop through the matrix for (var h = 0; h < mSize; h++) { for (var w = 0; w < mSize; w++) { var r = convertCoordinates(i + h - 1, j + w - 1, img.width) << 2; // RGB for current pixel var currentPixel = { r: bufferedData[r], g: bufferedData[r + 1], b: bufferedData[r + 2] }; sumR += currentPixel.r * matrix[w + h * mSize]; sumG += currentPixel.g * matrix[w + h * mSize]; sumB += currentPixel.b * matrix[w + h * mSize]; } } var rf = convertCoordinates(i, j, img.width) << 2; data[rf] = findColorDiff(strength, sumR, data[rf]); data[rf + 1] = findColorDiff(strength, sumG, data[rf + 1]); data[rf + 2] = findColorDiff(strength, sumB, data[rf + 2]); } } return pixels; } // process emboss function function processEmboss() { // clear context ctx.clearRect(0, 0, canvas.width, canvas.height); // draw image ctx.drawImage(imgObj, 0, 0, imgObj.width , imgObj.height); // get image data var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); // transform image data imageData = transformMatrix(imgObj, imageData); // draw data back ctx.putImageData(imageData, 0, 0); }; $(function () { // create canvas and context objects canvas = document.getElementById('source'); ctx = canvas.getContext('2d'); // load source image imgObj = new Image(); imgObj.onload = function () { // draw image ctx.drawImage(this, 0, 0, this.width, this.height, 0, 0, canvas.width, canvas.height); } imgObj.src="images/pic1.jpg"; // different onclick handlers var iCur = 1; $('#next').click(function () { iCur++; if (iCur > 6) iCur = 1; imgObj.src="images/pic" + iCur + '.jpg'; }); $('#emboss').click(function () { processEmboss(); }); $('#toImage').click(function () { $('#img').attr('src', canvas.toDataURL('image/jpeg')); }); }); This effect requires some pretty difficult matrix transformations, so you can try to understand it, or use it as-is. Of course, our script will pass through all the pixels of the original image, and then will apply some transformations. Live Demo download in package Conclusion I hope that our demo looks fine. Today we have added a new interesting effect to our html5 application – Emboss. I will be glad to see your thanks and comments. Good luck!
March 20, 2012
by Andrei Prikaznov
· 13,181 Views
article thumbnail
PHP objects in MongoDB with Doctrine
An is equivalent to an Object-Relational Mapper, but with its targets are documents of a NoSQL database instead of table rows. No one said that a Data Mapper must always rely on a relational database as its back end. In the PHP world, probably the Doctrine ODM for MongoDB is the most successful. This followes to the opularity of Mongo, which is a transitional product between SQL and NoSQL, still based on some relational concepts like queries. Lots of features The Doctrine Mongo ODM supports mapping of objects via annotations placed in the class source code, or via external XML or YAML files. In this and in many aspects it is based on the same concepts as the Doctrine ORM: it features a Facade DocumentManager object and a Unit Of Work that batches changes to the database when objects are added to it. Moreover, two different types of relationships between objects are supported: references and embedded documents. The first is the equivalent of the classical pointer to another row which ORM always transform object references into; the second actually stores an object inside another one, like you would do with a Value Object. Thus, at least in Doctrine's case, it is easier to map objects as documents that as rows. As said before, the ODM borrows some concepts and classes from the ORM, in particular from the Doctrine\Common package which features a standard collection class. So if you have built objects mapped with the Doctrine ORM nothing changes for persisting them in MongoDB, except for the mapping metadata itself. Advantages If an ORM is sometimes a leaky abstraction, an ODM probably becomes an issue less often. It has less overhead than an ORM, since there is no schema to define and the ability to embed objects means there should be no compromises between the object model and the capabilities of the database. How many times we have renounced introducing a potential Value Object because of the difficulty in persisting it? The case for an ODM over a plain Mongo connection object is easy to make: you will still be able to use objects with proper encapsulation (like private fields and associations) and behavior (many methods) instead of extracting just a JSON package from your database. Installation A prerequisite for the ODM is the presence of the mongo extension, that can be installed via pecl. After having verified the extension is present, grab the Doctrine\Common as the 2.2.x package, and a zip of the doctrine-mongodb and doctrine-mongodb-odm projects from Github. Decompress everything into a Doctrine/ folder. After having setup autoloading for classes in Doctrine\, use this bootstrap to get a DocumentManager (the equivalent of EntityManager): use Doctrine\Common\Annotations\AnnotationReader, Doctrine\ODM\MongoDB\DocumentManager, Doctrine\MongoDB\Connection, Doctrine\ODM\MongoDB\Configuration, Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver; private function getADm() { $config = new Configuration(); $config->setProxyDir(__DIR__ . '/mongocache'); $config->setProxyNamespace('MongoProxies'); $config->setDefaultDB('test'); $config->setHydratorDir(__DIR__ . '/mongocache'); $config->setHydratorNamespace('MongoHydrators'); $reader = new AnnotationReader(); $config->setMetadataDriverImpl(new AnnotationDriver($reader, __DIR__ . '/Documents')); return DocumentManager::create(new Connection(), $config); } You will be able to call persist() and flush() on the DocumentManager, along with a set of other methods for querying like find() and getRepository(). Integration with an ORM We are researching a solution for versioning objects mapped with the Doctrine ORM. Doing this with a version column would be invasive, and also strange where multiple objects are involved (do you version just the root of an object graph? Duplicate the other ones when they change? How can you detect that?) The idea is taking a snapshot and putting it in a read only MongoDB instance, where all previous versions can be retrieved later for auditing (business reasons). This has been verified to be technically possible: the DocumentManager and EntityManager are totally separate object graphs, so they won't clash with each other. The only point of conflict is the annotations of model classes, since both use different version of @Id, and can see the other's annotation like @Entity and @Document while parsing. This can be solved by using aliases for all the annotations, using their parent namespace basename as a prefix: model = $model; } public function __toString() { return "Car #$this->document_id: $this->id, $this->model"; } } This make us able to save a copy of an ORM object into Mongo: $car = new Car('Ford'); $this->em->persist($car); $this->em->flush(); $this->dm->persist($car); $this->dm->flush(); var_dump($car->__toString()); $this->assertTrue(strlen($car->__toString()) > 20); The output produces by this test is: .string(38) "Car #4f61a8322f762f1121000000: 3, Ford" When retrieving the object, one of the two ids will be null as it is ignored by the ORM or ODM. I am not using the same field because I want to store multiple copies of a row, so it's id alone won't be unique. If you're interested, checkout my hack on Github. It contains the running example presented in this post. Remember to create the relational schema with: $ php doctrine.php orm:schema-tool:create before running the test with phpunit --bootstrap bootstrap.php DoubleMappingTest.php MongoDB won't need the schema setup, of course. There are still some use cases to test, like the behavior in the presence of proxies, but it seems that non-invasive approach of Data Mappers like Doctrine 2 is paying off: try mapping an object in multiple database with Active Records.
March 20, 2012
by Giorgio Sironi
· 22,475 Views
article thumbnail
Filtering the Stack Trace From Hell
I love stack traces. Not because I love errors, but the moment they occur, stack trace is priceless source of information. For instance in web application the stack trace shows you the complete request processing path, from HTTP socket, through filters, servlets, controllers, services, DAOs, etc. - up to the place, where an error occurred. You can read them as a good book, where every event has cause and effect. I even implemented some enhancements in the way Logback prints exceptions, see Logging exceptions root cause first. But one thing's been bothering me for a while. The infamous “stack trace from hell" symptom – stack traces containing hundreds of irrelevant, cryptic, often auto-generated methods. AOP frameworks and over-engineered libraries tend to produce insanely long execution traces. Let me show a real-life example. In a sample application I am using the following technology stack: Colours are important. According to framework/layer colour I painted a sample stack trace, caused by exception thrown somewhere deep while trying to fetch data from the database: No longer that pleasant, don't you think? Placing Spring between application and Hibernate in the first diagram was a huge oversimplification. Spring framework is a glue code that wires up and intercepts your business logic with surrounding layers. That is why application code is scattered and interleaved by dozens of lines of technical invocations (see green lines). I put as much stuff as I could into the application (Spring AOP, method-level @Secured annotations, custom aspects and interceptors, etc.) to emphasize the problem – but it is not Spring specific. EJB servers generate equally terrible stack traces (...from hell) between EJB calls. Should I care? Think about it, when you innocently call BookService.listBooks() from BookController.listBooks() do you expect to see this? at com.blogspot.nurkiewicz.BookService.listBooks() at com.blogspot.nurkiewicz.BookService$$FastClassByCGLIB$$e7645040.invoke() at net.sf.cglib.proxy.MethodProxy.invoke() at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint() at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed() at com.blogspot.nurkiewicz.LoggingAspect.logging() at sun.reflect.NativeMethodAccessorImpl.invoke0() at sun.reflect.NativeMethodAccessorImpl.invoke() at sun.reflect.DelegatingMethodAccessorImpl.invoke() at java.lang.reflect.Method.invoke() at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs() at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod() at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke() at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke() at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() at org.springframework.transaction.interceptor.TransactionInterceptor.invoke() at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke() at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed() at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept() at com.blogspot.nurkiewicz.BookService$$EnhancerByCGLIB$$7cb147e4.listBooks() at com.blogspot.nurkiewicz.web.BookController.listBooks() And have you even noticed there is custom aspect in between? That's the thing, there is so much noise in the stack traces nowadays that following the actual business logic is virtually impossible. One of the best troubleshooting tools we have is bloated with irrelevant framework-related stuff we don't need in 99% of the cases. Tools and IDEs are doing a good job of reducing the noise. Eclipse has stack trace filter patterns for Junit, IntelliJ IDEA supports console folding customization. See also: Cleaning noise out of Java stack traces, which inspired me to write this article. So why not having such possibility at the very root – in the logging framework such as Logback? I implemented a very simple enhancement in Logback. Basically you can define a set of stack trace frame patterns that are suppose to be excluded from stack traces. Typically you will use package or class names that you are not interested in seeing. This is a sample logback.xml excerpt with the new feature enabled: %d{HH:mm:ss.SSS} | %-5level | %thread | %logger{1} | %m%n%rEx{full, java.lang.reflect.Method, org.apache.catalina, org.springframework.aop, org.springframework.security, org.springframework.transaction, org.springframework.web, sun.reflect, net.sf.cglib, ByCGLIB } I am a bit extreme in filtering almost whole Spring framework + Java reflection and CGLIB classes. But it is just to give you an impression how much can you get. The very same error after applying my enhancement to Logback: Just as a reminder, green is our application. Finally in one place, finally you can really see what was your code doing when an error occurred: at com.blogspot.nurkiewicz.DefaultBookHelper.findBooks() at com.blogspot.nurkiewicz.BookService.listBooks() at com.blogspot.nurkiewicz.LoggingAspect.logging() at com.blogspot.nurkiewicz.web.BookController.listBooks() Simpler? If you like this feature, I opened a ticket LBCLASSIC-325: Filtering out selected stack trace frames. Vote and discuss. This is only a proof-of-concept, but if you like to have a look at the implementation (improvements are welcome!), it is available under my fork of Logback (around 20 lines of code).
March 20, 2012
by Tomasz Nurkiewicz
· 65,993 Views · 4 Likes
article thumbnail
Adding a .first() method to Django's QuerySet
In my last Django project, we had a set of helper functions that we used a lot. The most used was helpers.first, which takes a query set and returns the first element, or None if the query set was empty. Instead of writing this: try: object = MyModel.objects.get(key=value) except model.DoesNotExist: object = None You can write this: def first(query): try: return query.all()[0] except: return None object = helpers.first(MyModel.objects.filter(key=value)) Note, that this is not identical. The get method will ensure that there is exactly one row in the database that matches the query. The helper.first() method will silently eat all but the first matching row. As long as you're aware of that, you might choose to use the second form in some cases, primarily for style reasons. But the syntax on the helper is a little verbose, plus you're constantly including helpers.py. Here is a version that makes this available as a method on the end of your query set chain. All you have to do is have your models inherit from this AbstractModel. class FirstQuerySet(models.query.QuerySet): def first(self): try: return self[0] except: return None class ManagerWithFirstQuery(models.Manager): def get_query_set(self): return FirstQuerySet(self.model) class AbstractModel(models.Model): objects = ManagerWithFirstQuery() class Meta: abstract = True class MyModel(AbstractModel): ... Now, you can do the following. object = MyModel.objects.filter(key=value).first()
March 19, 2012
by Chase Seibert
· 12,646 Views
article thumbnail
Hadoop Basics—Creating a MapReduce Program
The Map Reduce Framework works in two main phases to process the data, which are the "map" phase and the "reduce" phase.
March 18, 2012
by Carlo Scarioni
· 212,838 Views · 4 Likes
article thumbnail
Integrating Spring Into Legacy Applications
One of the things that all Spring developers like to do is to shoehorn Spring into any application they work on - it’s one of my guilty pleasures in life: you see some code, think it’s rubbish because it contains several well known anti-patterns and then think how cool it would be if this app was a Spring app. When working with legacy code, you can’t convert it into a fully fledged Spring app over night, that takes time. What you need to do is to add Spring code a little at a time: piece by piece and there’s one good way of doing that. In the following scenario, you’re working on some legacy code and you’ve written a Spring bean called: MySpringBean and it needs to use the legacy class: LegacyAppClass The legacy class looks like this: public class LegacyAppClass { // some old code goes here public void legacyDoSomethingMethod() { System.out.println("This is so old it doesn't use a logger...."); } } ...whilst your new SpringBean looks like this: public class MySpringBean { private LegacyAppClass injectedBean; @Override public String toString() { return "The toString()"; } public LegacyAppClass getInjectedBean() { return injectedBean; } public void setInjectedBean(LegacyAppClass injectedBean) { this.injectedBean = injectedBean; } public void myDoSomethingMethod() { injectedBean.legacyDoSomethingMethod(); } } ...as you can see, the myDoSomethingMethod() method needs to call the legacy legacyDoSomethingMethod() method. Given that any legacy application will have its own way of creating various objects, and that your new Spring code will need to use those objects to get its job done, then you need a way of combining the legacy objects with your shiny new ones. This will usually involve adding the legacy objects into your Spring Context and injecting them into your objects and to do this you need Spring’s StaticApplicationContext. @Test public void loadExternalClassTest2() { LegacyAppClass myInstance = new LegacyAppClass(); GenericApplicationContext parentContext = new StaticApplicationContext(); parentContext.getBeanFactory().registerSingleton("injectedBean", myInstance); parentContext.refresh(); // seems to be required sometimes ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "SpringIntegrationExample.xml" }, parentContext); MySpringBean mySpringBean = context.getBean(MySpringBean.class); assertNotNull(mySpringBean); mySpringBean.myDoSomethingMethod(); System.out.println(mySpringBean.toString()); } In the test code above the first point to note is that I create an instance of LegacyAppClass for use by the test, but in a real world app this will have already been created somewhere in your legacy code base. The next three lines is where the magic happens... GenericApplicationContext parentContext = new StaticApplicationContext(); parentContext.getBeanFactory().registerSingleton("injectedBean", myInstance); parentContext.refresh(); // seems to be required sometimes ...in the snippet above, you can see that I’m creating a StaticApplicationContext and then pragmatically adding my legacy class instance to it. ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "SpringIntegrationExample.xml" }, parentContext); The final task, as shown above, is to then create a new Spring application context using whatever method is suitable for your project. In this case, I’ve used the proverbial ClassPathXmlApplicationContext but other types of app context work just as well. You may say that this is a simple Micky-Mouse example, but from experience it does scale very well. It’s currently being used by a couple of full scale old style JSP Front Strategy MVC applications, (covered in detail in my blog from last October called Everybody Knows About MVC), as part of an implementation of Martin Fowler’s Strangler Pattern. Finally, in the interests of completeness, below is the XML config for this example:
March 17, 2012
by Roger Hughes
· 13,749 Views
article thumbnail
Marker Interfaces in Java
Marker Interfaces in Java have special significance because of the fact that they have no methods declared in them which means that the classes implementing these interfaces don't have to override any of the methods. A few of the marker interfaces already exist in the JDK like Serializable and Cloneable. One can also create their own custom interfaces which doesn't have any method. The purpose of these interfaces is to force some kind of functionality in the classes by providing some functionality to a class if it implements the marker interface. A common question asked very frequently is about Runnable interface being marker or not. Runnable interface is not marker because Runnable interface has the public void run() method declared inside it. A very good example of marker interface is Serializable where the class implements can be used with ObjectOutputStream and ObjectInputStream classes. The Java language specification doesn't itself define the term marker interface and the term has been coined by authors, developers and designers. One common question asked is if we can create a marker interface or not and the answer is yes because of following reason: We can't create marker interface similar to Serializable or Cloneable but we can simulate the functionality by writing extra code around the custom marker interface.
March 17, 2012
by Sandeep Bhandari
· 55,655 Views · 2 Likes
article thumbnail
Intellij vs. Eclipse: Why IDEA is Better
The one major difference between IDEA and Eclipse is that IDEA "feels context", which effectively makes IDEA intelligent.
March 15, 2012
by Andrei Solntsev
· 667,561 Views · 26 Likes
article thumbnail
Display an OLE Object from a Microsoft Access Database using OLE Stripper
In database programming, it happens a lot that you need to bind a picture box to a field with type of photo or image. For example, if you want to show an Employee’s picture from Northwind.mdb database, you might want to try the following code: picEmployees.DataBindings.Add(“Image”, bsEmployees, “Photo”, true); This code works if the images are stored in the database with no OLE header or the images stored as a raw image file formats. As the pictures stored in the Northwind database in are not stored in raw image file formats and they are stored as an OLE image documents, then you have to strip off the OLE header to work with the image properly. Binding imageBinding = new Binding("Image", bsEmployees, "ImageBlob.ImageBlob", true); imageBinding.Format += new ConvertEventHandler(this.PictureFormat); private void PictureFormat(object sender, ConvertEventArgs e) { Byte[] img = (Byte[])e.Value; MemoryStream ms = new MemoryStream(); int offset = 78; ms.Write(img, offset, img.Length - offset); Bitmap bmp = new Bitmap(ms); ms.Close(); // Writes the new value back e.Value = bmp; } Fortunately, there are some overload methods in .NET Framework to take care of this mechanism, but it cannot be guaranteed whether you need to strip off the OLE object by yourself or not. For example, you can use the following technique to access the images of the Northwind.mdb that ships with Microsoft Access and they will be rendered properly. picEmployees.DataBindings.Add(“Image”, bsEmployees, “Photo”, true, DataSourceUpdateMode.Never, new Bitmap(typeof(Button), “Button.bmp”)); Unfortunately, there are some scenarios that you need a better solution. For example, the Xtreme.mdb database that ships with Crystal Reports has a photo filed that cannot be handled by the preceding methods. For these complex scenarios, you can download the OLEStripper classes from here and re-write the PictureFormat method as it is shown below: private void PictureFormat(object sender, ConvertEventArgs e) { // photoIndex is same as Employee ID int photoIndex = Convert.ToInt32(e.Value); // Read the original OLE object ReadOLE olePhoto = new ReadOLE(); string PhotoPath = olePhoto.GetOLEPhoto(photoIndex); // Strip the original OLE object StripOLE stripPhoto = new StripOLE(); string StripPhotoPath = stripPhoto.GetStripOLE(PhotoPath); FileStream PhotoStream = new FileStream(StripPhotoPath , FileMode.Open); Image EmployeePhoto = Image.FromStream(PhotoStream); e.Value = EmployeePhoto; PhotoStream.Close(); }
March 15, 2012
by Amir Ahani
· 11,139 Views
article thumbnail
Build a Simple Chat Application Using JavaFX 2
One of my favorite subjects is real-time communication. A chat component is one of the most basic forms of real-time communication. In the past, I've blogged about how to create a JavaFX 1.3 based chat application using a Comet Server. Meanwhile, we updated the internal Chat Application we are using at LodgON and it is now using JavaFX 2 and RedFX 2. The most basic JavaFX Chat Application is described at http://redfx.org/samples/chat/index.html and the required binaries can also be downloaded from that site. The example shown on the RedFX samples page is very very basic and of course not very useful in real-world cases. However, the basics about sending and receiving messages, processing them and visualizing them, are very similar. We use the exact same principles for a more complex Chat Application for focus groups that we are currently migrating from JavaFX 1.3 to JavaFX 2.1. A Chat application requires a client component and a server component. If you look at the client code that can be downloaded from the RedFX.org download section, you'll probably agree that JavaFX is the perfect candidate platform for writing chat applications. Very few lines of code are needed, and any Java developer can easily extend this application. The server component, which can be downloaded here contains a Java EE 6 Web Archive. It includes the RedFX server components, a few configuration files, and it runs out of the box on Glassfish 3.1.2 (if you enable Comet and/or Web sockets -- those are disabled by default unfortunately). A couple of weeks ago, we made the beta-release of RedFX available in a binary form. It is our intention to make available all source code that is required to run the basic samples. However, this takes time. A couple of months ago, we open-sourced the DaliCore platform, and that takes time. Making a project open-source involves much much more than putting the code in a zip and make it available online. It is my goal to make the RedFX client part of the open-source JFXtras.org project. We still have to figure out how we will deal with dependencies, and how/where we can host the RedFX server components. We will do this as fast as we can, but there are only 25 hours in a day...
March 14, 2012
by Johan Vos
· 23,770 Views
article thumbnail
All about JMS messages
JMS providers like ActiveMQ are based on the concept of passing one-directional messages between nodes and brokers asynchronously. A thorough knowledge of the type of messages that can be sent through a JMS middleware can simplify a lot your work in mapping the communication patterns to real code. The basic Message interface Some object members are shared by all messages: header fields, used to identify univocally a message and to route it to the right brokers and consumers. A dynamic map of properties which can be read programmatically by JMS brokers in order to filter or to route messages. A body, which is differentiated in the various implementations we'll see. Header fields The set of getJMS*() methods on the Message interface defines the available headers. Two of them are oriented to message identification: getJMSMessageID() contains a generated ID for identifying a message, unique at least for the current broker. All generated IDs start with the prefix 'ID:', but you can override it with the corresponding setter. getJMSCorrelationID() (and getJMSCorrelationID() as bytes) can link a message with another, usually one that has been sent previously. For example, a reply can carry the ID of the original message when put in another queue. Two to sender and recipient identification: getJMSDestination() returns a Destination object (a Topic or a Queue, or their temporary version) describing where the message was directed. getJMSReplyTo() is a Destination object where replies should be sent; it can be null of course. Three tune the delivery mechanism: getJMSDeliveryMode() can be DeliveryMode.NON_PERSISTENT or DeliveryMode.PERSISTENT; only persistent messages guarantee delivery in case of a crash of the brokers that transport it. getJMSExpiration() returns a timestamp indicating the expiration time of the message; it can be 0 on a message without a defined expiration. getJMSPriority() returns a 0-9 integer value (higher is better) defining the priority for delivery. It is only a best-effort value. While the remaining ones contain metadata: getJMSRedelivered() returns a boolean indicating if the message is being delivered again after a delivery which was not acknowledge. getJMSTimestamp() returns a long indicating the time of sending. getJMSType() defines a field for provider-specific or application-specific message types. Of these headers, only JMSCorrelationID, JMSReplyTo and JMSType have to be set when needed. The others are generated or managed by the send() and publish() methods if not specified (there are setters available for each of these headers.) Properties Generic properties with a String name can be added to messages and read with getBooleanProperty(), getStringProperty() and similar methods. The corresponding setters setBooleanProperty(), setStringProperty(), ... can be used for their addition. The reason for keeping some properties out of the content of the message (which a MapMessage can contain) is so they could be read before reaching the destination, for example in a JMS broker. The use case for this access to message properties is routing and filtering: downstream brokers and consumers may define a filter such as "I am interested only on messages on this Topic that have property X = 'value' and Y = 'value2'". Bodies All the subinterfaces of javax.jms.Message defined by the API provide different types of message bodies (while actual classes are defined by the providers and are not part of the API). Actual instantiation is then handled by the Session, which implements an Abstract Factory pattern. On the receival side, a cast is necessary for any message type (at least in the Java JMS Api), since only a generic Message is read. BytesMessage is the most basic type: it contains a sequence of uninterpreted bytes. Hence, it can in theory contain anything, but the generation and interpretation of the content is the client's job. BytesMessage m = session.createBytesMessage(); m.writeByte(65); m.writeBytes(new byte[] { 66, 68, 70 }); // on receival (cast shown only here) BytesMessage m = (BytesMessage) genericMessage; byte[] content = new byte[4]; m.readBytes(content); MapMessage defines a message containing an (unordered) set of key/value pairs, also called a map or dictionary or hash. However, the keys are String objects, while the values are primitives or Strings; since they are primitives, they shouldn't be null. MapMessage = session.createMapMessage(); m.setString('key', 'value'); // or m.setObject('key', 'value') to avoid specifying a type // on receival m.getString('key'); // or m.getObject('key') ObjectMessage wraps a generic Object for transmission. The Object should be Serializable. ObjectMessage m = session.createObjectMessage(); m.setObject(new ValueObject('field1', 42)); // on receival ValueObject vo = (ValueObject) m.getObject(); StreamMessage wraps a stream of primitive values of indefinite length. StreamMessage m = session.createStreamMessage(); m.writeBoolean(true); m.writeBoolean(false); m.writeBoolean(true); // receival System.out.println(m.readBoolean()); System.out.println(m.readBoolean()); System.out.println(m.readBoolean()); // prints true, false, true TextMessage wraps a String of any length. TextMessage m = session.createTextMessage("Contents"); // or use m.setText() afterwards // receival String text = m.getText(); Usually all messages are in a read-only phase after receival, so only getters can be called on them.
March 12, 2012
by Giorgio Sironi
· 62,007 Views · 1 Like
article thumbnail
Using Maven's -U Command Line Option
My prefered solution was to use the Maven ‘update snapshots’ command line argument.
March 11, 2012
by Roger Hughes
· 107,043 Views · 1 Like
article thumbnail
Best Practices for Variable and Method Naming
Use short enough and long enough variable names in each scope of code. Generally length may be 1 char for loop counters, 1 word for condition/loop variables, 1-2 words for methods, 2-3 words for classes, 3-4 words for globals. Use specific names for variables, for example "value", "equals", "data", ... are not valid names for any case. Use meaningful names for variables. Variable name must define the exact explanation of its content. Don't start variables with o_, obj_, m_ etc. A variable does not need tags which states it is a variable. Obey company naming standards and write variable names consistently in application: e.g. txtUserName, lblUserName, cmbSchoolType, ... Otherwise readability will reduce and find/replace tools will be unusable. Obey programming language standards and don't use lowercase/uppercase characters inconsistently: e.g. userName, UserName, USER_NAME, m_userName, username, ... use Camel Case (aka Upper Camel Case) for classes: VelocityResponseWriter use Lower Case for packages: com.company.project.ui use Mixed Case (aka Lower Camel Case) for variables: studentName use Upper Case for constants : MAX_PARAMETER_COUNT = 100 use Camel Case for enum class names and Upper Case for enum values. don't use '_' anywhere except constants and enum values (which are constants). For example for Java, Don't reuse same variable name in the same class in different contexts: e.g. in method, constructor, class. So you can provide more simplicity for understandability and maintainability. Don't use same variable for different purposes in a method, conditional etc. Create a new and different named variable instead. This is also important for maintainability and readability. Don't use non-ASCII chars in variable names. Those may run on your platform but may not on others. Don't use too long variable names (e.g. 50 chars). Long names will bring ugly and hard-to-read code, also may not run on some compilers because of character limit. Decide and use one natural language for naming, e.g. using mixed English and German names will be inconsistent and unreadable. Use meaningful names for methods. The name must specify the exact action of the method and for most cases must start with a verb. (e.g. createPasswordHash) Obey company naming standards and write method names consistently in application: e.g. getTxtUserName(), getLblUserName(), isStudentApproved(), ... Otherwise readability will reduce and find/replace tools will be unusable. Obey programming language standards and don't use lowercase/uppercase characters inconsistently: e.g. getUserName, GetUserName, getusername, ... For example for Java, use Mixed Case for method names: getStudentSchoolType use Mixed Case for method parameters: setSchoolName(String schoolName) Use meaningful names for method parameters, so it can documentate itself in case of no documentation.
March 10, 2012
by Cagdas Basaraner
· 153,989 Views · 5 Likes
article thumbnail
Resetting the Database Connection in Django
Django handles database connections transparently in almost all cases. It will start a new connection when your request starts up, and commit it at the end of the request lifetime. Other times you need to dive in further and do your own granular transaction management. But for the most part, it's fully automatic. However, sometimes your use case may require that you close the current database connection and open a new one. While this is possible in Django, it's not well documented. Why would you want to do this? I my case, I was writing an automation test framework. Some of the automation tests make database calls through the Django ORM to setup records, clean up after the test, etc. Each test is executed in the same process space, via a thread pool. We found that if one of the early tests threw an unrecoverable database error, such as an IntegrityError due to violating a unique constraint, the database connection would be aborted. Subsequent tests that tried to use the database would raise a DatabaseError: Traceback (most recent call last): File /home/user/project/app/test.py, line 73, in tearDown MyModel.objects.all() File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 444, in delete collector.collect(del_query) File /usr/local/lib/python2.6/dist-packages/django/db/models/deletion.py, line 146, in collect reverse_dependency=reverse_dependency) File /usr/local/lib/python2.6/dist-packages/django/db/models/deletion.py, line 91, in add if not objs: File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 113, in __nonzero__ iter(self).next() File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 107, in _result_iter self._fill_cache() File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 772, in _fill_cache self._result_cache.append(self._iter.next()) File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 273, in iterator for row in compiler.results_iter(): File /usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py, line 680, in results_iter for rows in self.execute_sql(MULTI): File /usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py, line 735, in execute_sql cursor.execute(sql, params) File /usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py, line 44, in execute return self.cursor.execute(query, args) DatabaseError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. It turns out that it's relatively easy to reset the database connection. We just called the following function at the start of every test. Django is smart enough to re-initialize the connection the next time it's used, assuming that it's disconnected properly. def reset_database_connection(): from django import db db.close_connection()
March 9, 2012
by Chase Seibert
· 9,213 Views
article thumbnail
REST Pagination in Spring
This is the seventh of a series of articles about setting up a secure RESTful Web Service using Spring 3.1 and Spring Security 3.1 with Java based configuration. This article will focus on the implementation of pagination in a RESTful web service. The REST with Spring series: Part 1 – Bootstrapping a web application with Spring 3.1 and Java based Configuration Part 2 – Building a RESTful Web Service with Spring 3.1 and Java based Configuration Part 3 – Securing a RESTful Web Service with Spring Security 3.1 Part 4 – RESTful Web Service Discoverability Part 5 – REST Service Discoverability with Spring Part 6 – Basic and Digest authentication for a RESTful Service with Spring Security 3.1 You can check out the entire REST with Spring Series here. Page as resource vs Page as representation The first question when designing pagination in the context of a RESTful architecture is whether to consider the page an actual resource or just a representation of resources. Treating the page itself as a resource introduces a host of problems such as no longer being able to uniquely identify resources between calls. This, coupled with the fact that outside the RESTful context, the page cannot be considered a proper entity, but a holder that is constructed when needed makes the choice straightforward: the page is part of the representation. The next question in the pagination design in the context of REST is where to include the paging information: in the URI path: /foo/page/1 the URI query: /foo?page=1 Keeping in mind that a page is not a resource, encoding the page information in the URI is no longer an option. Page information in the URI query Encoding paging information in the URI query is the standard way to solve this issue in a RESTful service. This approach does however have one downside – it cuts into the query space for actual queries: /foo?page=1&size=10 The Controller Now, for the implementation – the Spring MVC Controller for pagination is straightforward: @RequestMapping( value = "admin/foo",params = { "page", "size" },method = GET ) @ResponseBody public List< Foo > findPaginated( @RequestParam( "page" ) int page, @RequestParam( "size" ) int size, UriComponentsBuilder uriBuilder, HttpServletResponse response ){ Page< Foo > resultPage = service.findPaginated( page, size ); if( page > resultPage.getTotalPages() ){ throw new ResourceNotFoundException(); } eventPublisher.publishEvent( new PaginatedResultsRetrievedEvent< Foo > ( Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size ) ); return resultPage.getContent(); } The two query parameters are defined in the request mapping and injected into the controller method via @RequestParam; the HTTP response and the Spring UriComponentsBuilder are injected in the Controller method to be included in the event, as both will be needed to implement discoverability. Discoverability for REST pagination Withing the scope of pagination, satisfying the HATEOAS constraint of REST means enabling the client of the API to discover the next and previous pages based on the current page in the navigation. For this purpose, the Link HTTP header will be used, coupled with the official “next“, “prev“, “first” and “last” link relation types. In REST, Discoverability is a cross cutting concern, applicable not only to specific operations but to types of operations. For example, each time a Resource is created, the URI of that resource should be discoverable by the client. Since this requirement is relevant for the creation of ANY Resource, it should be dealt with separately and decoupled from the main Controller flow. With Spring, this decoupling is achieved with events, as was thoroughly discussed in the previous article focusing on Discoverability of a RESTful service. In the case of pagination, the event – PaginatedResultsRetrievedEvent – was fired in the Controller, and discoverability is achieved in a listener for this event: void addLinkHeaderOnPagedResourceRetrieval( UriComponentsBuilder uriBuilder, HttpServletResponse response, Class clazz, int page, int totalPages, int size ){ String resourceName = clazz.getSimpleName().toString().toLowerCase(); uriBuilder.path( "/admin/" + resourceName ); StringBuilder linkHeader = new StringBuilder(); if( hasNextPage( page, totalPages ) ){ String uriNextPage = constructNextPageUri( uriBuilder, page, size ); linkHeader.append( createLinkHeader( uriForNextPage, REL_NEXT ) ); } if( hasPreviousPage( page ) ){ String uriPrevPage = constructPrevPageUri( uriBuilder, page, size ); appendCommaIfNecessary( linkHeader ); linkHeader.append( createLinkHeader( uriForPrevPage, REL_PREV ) ); } if( hasFirstPage( page ) ){ String uriFirstPage = constructFirstPageUri( uriBuilder, size ); appendCommaIfNecessary( linkHeader ); linkHeader.append( createLinkHeader( uriForFirstPage, REL_FIRST ) ); } if( hasLastPage( page, totalPages ) ){ String uriLastPage = constructLastPageUri( uriBuilder, totalPages, size ); appendCommaIfNecessary( linkHeader ); linkHeader.append( createLinkHeader( uriForLastPage, REL_LAST ) ); } response.addHeader( HttpConstants.LINK_HEADER, linkHeader.toString() ); } In short, the listener logic checks if the navigation allows for a next, previous, first and last pages and, if it does, adds the relevant URIs to the Link HTTP Header. It also makes sure that the link relation type is the correct one – “next”, “prev”, “first” and “last”. This is the single responsibility of the listener (the full code here). Test Driving Pagination Both the main logic of pagination and discoverability should be extensively covered by small, focused integration tests; as in the previous article, the rest-assured library is used to consume the REST service and to verify the results. These are a few example of pagination integration tests; for a full test suite, check out the github project (link at the end of the article): @Test public void whenResourcesAreRetrievedPaged_then200IsReceived(){ Response response = givenAuth().get( paths.getFooURL() + "?page=1&size=10" ); assertThat( response.getStatusCode(), is( 200 ) ); } @Test public void whenPageOfResourcesAreRetrievedOutOfBounds_then404IsReceived(){ Response response = givenAuth().get( paths.getFooURL() + "?page=" + randomNumeric( 5 ) + "&size=10" ); assertThat( response.getStatusCode(), is( 404 ) ); } @Test public void givenResourcesExist_whenFirstPageIsRetrieved_thenPageContainsResources(){ restTemplate.createResource(); Response response = givenAuth().get( paths.getFooURL() + "?page=1&size=10" ); assertFalse( response.body().as( List.class ).isEmpty() ); } Test Driving Pagination Discoverability Testing Discoverability of Pagination is relatively straightforward, although there is a lot of ground to cover. The tests are focused on the position of the current page in navigation and the different URIs that should be discoverable from each position: @Test public void whenFirstPageOfResourcesAreRetrieved_thenSecondPageIsNext(){ Response response = givenAuth().get( paths.getFooURL()+"?page=0&size=10" ); String uriToNextPage = extractURIByRel( response.getHeader( LINK ), REL_NEXT ); assertEquals( paths.getFooURL()+"?page=1&size=10", uriToNextPage ); } @Test public void whenFirstPageOfResourcesAreRetrieved_thenNoPreviousPage(){ Response response = givenAuth().get( paths.getFooURL()+"?page=0&size=10" ); String uriToPrevPage = extractURIByRel( response.getHeader( LINK ), REL_PREV ); assertNull( uriToPrevPage ); } @Test public void whenSecondPageOfResourcesAreRetrieved_thenFirstPageIsPrevious(){ Response response = givenAuth().get( paths.getFooURL()+"?page=1&size=10" ); String uriToPrevPage = extractURIByRel( response.getHeader( LINK ), REL_PREV ); assertEquals( paths.getFooURL()+"?page=0&size=10", uriToPrevPage ); } @Test public void whenLastPageOfResourcesIsRetrieved_thenNoNextPageIsDiscoverable(){ Response first = givenAuth().get( paths.getFooURL()+"?page=0&size=10" ); String uriToLastPage = extractURIByRel( first.getHeader( LINK ), REL_LAST ); Response response = givenAuth().get( uriToLastPage ); String uriToNextPage = extractURIByRel( response.getHeader( LINK ), REL_NEXT ); assertNull( uriToNextPage ); } These are just a few examples of integration tests consuming the RESTful service. Getting All Resources On the same topic of pagination and discoverability, the choice must be made if a client is allowed to retrieve all the Resources in the system at once, or if the client MUST ask for them paginated. If the choice is made that the client cannot retrieve all Resources with a single request, and pagination is not optional but required, then several options are available for the response to a get all request. One option is to return a 404 (Not Found) and use the Link header to make the first page discoverable: Link=; rel=”first“, ; rel=”last“ Another option is to return redirect – 303 (See Other) – to the first page of the pagination. A third option is to return a 405 (Method Not Allowed) for the GET request. REST Paginag with Range HTTP headers A relatively different way of doing pagination is to work with the HTTP Range headers – Range, Content-Range, If-Range, Accept-Ranges – and HTTP status codes – 206 (Partial Content), 413 (Request Entity Too Large), 416 (Requested Range Not Satisfiable). One view on this approach is that the HTTP Range extensions were not intended for pagination, and that they should be managed by the Server, not by the Application. Implementing pagination based on the HTTP Range header extensions is nevertheless technically possible, although not nearly as common as the implementation discussed in this article. Conclusion This article covered the implementation of Pagination in a RESTful service with Spring, discussing how to implement and test Discoverability. For a full implementation of pagination, check out the github project. From the original REST Pagination in Spring of the REST with Spring series
March 9, 2012
by Eugen Paraschiv
· 67,206 Views · 4 Likes
article thumbnail
Django Settings for Production and Development: Best Practices
When you’re just starting out with Django, it can be overwhelming to see there’s no standard approach to deal with settings. However, there are a few simple best practices that work when you start needing more than the basic settings file. What’s the problem? Django stores all the settings in a project-wide settings.py file. All is fine until the moment you need different settings for different environments(such as a production environment and a development environment to start with). Of the necessity to have different settings files Your development settings should be different from your production settings. Why? you should protect sensitive things like database passwords, api secrets, private keys in a separate file the behavior of production code is not suited for development : for example you don’t want to send an email when you’re developing new features Here are a few things that may change from one environment to another: database details: database name, user name and password api keys your own private keys for encrypting data debug variables (DEBUG and TEMPLATE_DEBUG) path to different tools needed by your Django applications and any other flags needed to make your application work differently in development and in production We’re going to compare three different ways to organize your settings when having one setting file doesn’t cut it anymore. First solution: local settings This solution relies on having one settings.py file with common settings and a local_settings file where you define environment-specific settings. Let’s see: ### settings.py file ### settings that are not environment dependent try: from local_settings import * except ImportError: pass ### local_settings.py ### environment-specific settings ### example with a development environment DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER': 'django', 'PASSWORD': '1234', 'HOST': '', 'PORT': '', } Advantages: simple if you only need a development and a production environment (no staging) – the local_settings.py should stay out of source control and you need to have a separate one for development and production. Disadvantages: it limits what you can do with settings such as modify common settings in the local_settings for example. It can work for the most simple case though. Second solution: environment-based settings This is one from Ches Martin. It relies on having an environment variable pointing to the right python module. It has the advantage of being explicit, so you can name your specific settings files explicity (production file being production.py for example). [myapp]$ls settings __init__.py defaults.py dev.py staging.py production.py What happens when we do import settings? Settings is in this case a package (a package in Python being a directory with an __init__.py file inside), so when the interpreter loads the package it executes __init__.py. By default, let’s make it work in development environment. ### __init.py__ from dev import * ### default.py__ ### sensible choices for default settings ### dev.py from defaults import * DEBUG = True ### other development-specific stuff ### production.py from defaults import * DEBUG = False ### other production-specific stuff How to use it in production and staging environments? The trick is that the settings module location can be overriden by settings an environment Django variable. So we need to override that variable before starting our webserver. For example if you use Apache as your Django web server, modify your Apache configuration file with: SetEnv DJANGO_SETTINGS_MODULE myapp.settings.production Third solution: system-wide settings ### settings.py import os ENVIRONMENT_SETTING_FILE = '/etc/django.myproject.settings' ### this will load all environment file settings in here execfile(ENVIRONMENT_SETTING_FILE) ### all common settings ### ... We can see one problem of doing it this way is that we cannot modify variables defined in the common settings.py file in the environment-specific files. On the other hand, it simplifies the management of environment-specific settings files. Create a file for development, staging and production, secure it with some tight permissions, and forget about it. To conclude There are other ways to manage your settings, so you can experiment a little bit. Check the list of resources to know more about managing your settings. And drop a comment here if you want to share the way you’re doing it! Resources: Splitting up the settings file, very comprehensive resource from the official Django website Django settings, again from the official Django website Extending Django settings for the real world from Yipit Django settings at Disqus: for a more complex and modular settings configutation. Stack Overflow: How to modularize Django settings.py? How do you configure Django for simple development and deployment? Django Snippets Keep settings.py in version control safely
March 7, 2012
by Tommy Jarnac
· 44,122 Views
article thumbnail
All the mouse events in JavaScript
The HTML 5 specification is full of definitions of new events, but it gathers them in a long list only divided by the category of support: some must be supported by all elements, some by window and derivatives, and so on. Unfortunately this style mixes up many different kinds of events, like the multimedia (canplay) and keyboard-based ones (keyup). In this article, I have collected all events that can be generated with a mouse. In HTML 4 There are a few well-supported events ported by the previous version of the specification. Everyone would expect a browser to correctly fire these events: click: the simplest event. dblclick: fired on a double click on an HTML element. mousedown: fired when the button is pressed. mouseup: fired when the button is released. mouseover: fired when the cursor passes over an HTML element. mouseout: fired when the cursor leaves the displaying area of an HTML element; the inverse of mouseover. mousemove: fired everytime the cursor moves one pixel. It's very easy to hang the browser by targeting this event. In any case, window.addEventListener and element.addEventListener (where element is a reference to a DOM element) are the functions to call to setup event handlers. You could also use the on$eventName HTML attribute or property (e.g. onclick, onmouseover), but addEventListener is more flexible as it allows for many different listeners to work on the same event, without one silently replacing the other. HTML 5: dragging Most of the new mouse events (but not necessarily the most interesting ones) deal with drag and drop support: drag: fired frequently on a dragged element (which must define the *draggable* attribute.) dragstart: fired when the mouse is held down on an element and the movement starts. dragend: fired when the element is released. dragenter: fired when an element enters the displayed area of another one. dragleave: fired when an element exits the displayed area, as the inverse of dragenter. dragover: fired frequently when an element is over another. drop: fired when an element is released over another. drag, dragstart, and dragend are fired on the dragged element, while dragenter, dragleave, dragover and drop are fired on the target one. Here is a self-contained example of their usage: One of the common usages of the Drag and Drop API is the integration with the File API to allow for upload of files by dragging into the browser's window. HTML 5: the wheel The mousewheel event is fired upon the usage of the wheel over an element or the window. Here is an example that zooms in or out of an HTML element by modifying its size: The scroll event instead works at an higher-level of abstraction: it is not really a mouse-specific event, as it can be generated by the mouse but also by pressing scrolling keys. What the event models is a change in the visible section of an element, generated by a movement in the vertical or horizontal scrollbars: Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... Lorem ipsum dolor amet... HTML 5: right click The contextmenu event is fired upon a right click, that opens a contextual menu centered on the mouse pointer. Here is an example of interception: If you want to display an alternate contextual menu, you would also probably want to cancel the event; however, many browsers allow the user to override these manipulations and always show the original menu (think of websites hiding the View Source entry).
March 7, 2012
by Giorgio Sironi
· 79,719 Views
article thumbnail
Connecting to Multiple Databases Using Hibernate
In a recent project, I had a requirement of connecting to multiple databases using hibernate. As tapestry-hibernate module does not provide an out-of-box support, I thought of adding one. https://github.com/tawus/tapestry5 Now that the application is in production, I thought of writing a simple “How to”. I have cloned the latest stable(5.3.2) tapestry project at https://github.com/tawus/tapestry5 and have added multiple database support to it. Single Database It is almost fully compatible with the previous integration when using a single database except for a few things 1) HibernateConfigurer has changed public interface HibernateConfigurer { /** * Passed the configuration so as to make changes. */ void configure(Configuration configuration); /** * Factory Id for which this configurer is meant for */ Class getMarker(); /** * Entity package names * * @return */ String[] getPackageNames(); } 2) There is no HibernateEntityPackageManager, as the packages can be contributed by adding more HibernateConfigurers with the same Markers. Multiple databases For multiple database, a marker has to be used for accessing Session or HibernateSessionManager @Inject @XDB private Session session; @Inject @YDB private HibernateSessionManager sessionManager; @XDB @CommitAfter void myMethod(){ } Also you have to define a HibernateSessionManager and a Session for the secondary database in the Module class. @Scope(ScopeConstants.PERTHREAD) @Marker(DatabaseTwo.class) public static HibernateSessionManager buildHibernateSessionManagerForFinacle( HibernateSessionSource sessionSource, PerthreadManager perthreadManager) { HibernateSessionManagerImpl service = new HibernateSessionManagerImpl(sessionSource, DatabaseTwo.class); perthreadManager.addThreadCleanupListener(service); return service; } @Marker(DatabaseTwo.class) public static Session buildSessionForFinacle( @Local HibernateSessionManager sessionManager, PropertyShadowBuilder propertyShadowBuilder) { return propertyShadowBuilder.build(sessionManager, "session", Session.class); } Notice an annotation @DatabaseTwo.class. This is a Factory marker and is used to identify a service related to a particular SessionFactory. @Retention(RetentionPolicy.RUNTIME) @Target( {ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @FactoryMarker @Documented public @interface DatabaseTwo { } A typical AppModule for two databases will be public class AppModule { public static void bind(ServiceBinder binder) { binder.bind(DemoService.class, DemoServiceImpl.class); } @Contribute(HibernateSessionSource.class) public static void configureHibernateSources(OrderedConfiguration configurers) { configurers.add("databaseOne", new HibernateConfigurer() { public void configure(org.hibernate.cfg.Configuration configuration) { configuration.configure("/databaseOne.xml"); } public Class getMarker() { return DefaultFactory.class; } public String[] getPackageNames() { return new String[] {"org.example.demo.one"}; } }); configurers.add("databaseTwo", new HibernateConfigurer() { public void configure(org.hibernate.cfg.Configuration configuration) { configuration.configure("/databaseTwo.xml"); } public Class getMarker() { return DatabaseTwo.class; } public String[] getPackageNames() { return new String[] {"org.example.demo.two"}; } }); } @Contribute(SymbolProvider.class) @ApplicationDefaults public static void addSymbols(MappedConfiguration configuration) { configuration.add(HibernateSymbols.DEFAULT_CONFIGURATION, "false"); configuration.add("tapestry.app-package", "org.example.demo"); } @Scope(ScopeConstants.PERTHREAD) @Marker(DatabaseTwo.class) public static HibernateSessionManager buildHibernateSessionManagerForFinacle( HibernateSessionSource sessionSource, PerthreadManager perthreadManager) { HibernateSessionManagerImpl service = new HibernateSessionManagerImpl(sessionSource, DatabaseTwo.class); perthreadManager.addThreadCleanupListener(service); return service; } @Marker(DatabaseTwo.class) public static Session buildSessionForFinacle( @Local HibernateSessionManager sessionManager, PropertyShadowBuilder propertyShadowBuilder) { return propertyShadowBuilder.build(sessionManager, "session", Session.class); } } Injecting into Services You can inject a session in a service using the marker. As DatabaseOne is being used as the default configuration, in order to inject its Session, you have to annotate it with @DefaultFactory. For DatabaseTwo, you can use @DatabaseTwo annotation. public class DemoServiceImpl implements DemoService { private Session sessionOne; private Session sessionTwo; public DemoServiceImpl( @DefaultFactory Session sessionOne, @DatabaseTwo Session sessionTwo) { this.sessionOne = sessionOne; this.sessionTwo = sessionTwo; } @SuppressWarnings("unchecked") public List listOnes() { return sessionOne.createCriteria(EntityOne.class).list(); } @SuppressWarnings("unchecked") public List listTwos() { return sessionTwo.createCriteria(EntityTwo.class).list(); } public void save(EntityOne entityOne) { sessionOne.saveOrUpdate(entityOne); } public void save(EntityTwo entityTwo) { sessionTwo.saveOrUpdate(entityTwo); } } Using @CommitAfter You can add an advice the same way you used to. The only change is in @CommitAfter. You have to additionally annotate the method with the respective marker. public interface DemoService { List listOnes(); List listTwos(); @CommitAfter @DefaultFactory void save(EntityOne entityOne); @CommitAfter @DatabaseTwo void save(EntityTwo entityTwo); } Here is an example. From http://tawus.wordpress.com/2012/03/03/tapestry-hibernate-multiple-databases/
March 7, 2012
by Taha Siddiqi
· 100,316 Views · 3 Likes
article thumbnail
Viewing JavaFX 2 Standard Colors
The JavaFX 2 class javafx.scene.paint.Color includes several fields that are static Color members. I have taken advantage of the convenience of these publicly available static fields in many of my JavaFX 2 examples shown in this blog. There is a lengthy list of these predefined Color fields ranging (in alphabetical order) from Color.ALICEBLUE to Color.YELLOWGREEN. I have sometimes thought it would be nice to quickly see what some of the less obvious colors look like and the simple JavaFX 2 application featured in this post provides a sampling of those colors. The sample JavaFX 2 application shown here uses simple Java reflection to introspect the JavaFX Color class for its public fields that themselves of type Color. The application then iterates over those public fields, providing information about each color such as the color's field name, a sample of the color, and the red/green/blue components of that color. The final row allows the user to specify red/green/blue values to see how such a color is rendered. This is useful if the user sees a standard color that is close to what he or she wants and the user wants to try adjusting it slightly. To ensure meaningful values for displaying a color based on provided red/green/blue values, the application ensures that entered values are treated as doubles between 0.0 and 1.0 even if they are not numbers or are numbers outside of that range. The simple JavaFX 2 application showing standard Color fields is shown in the next code listing. JavaFxColorDemo.java package dustin.examples; import static java.lang.System.err; import java.lang.reflect.Field; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.shape.RectangleBuilder; import javafx.stage.Stage; /** * Simple JavaFX 2 application that prints out values of standardly available * Color fields. * * @author Dustin */ public class JavaFxColorDemo extends Application { /** Width of label for colorn name. */ private final static int COLOR_NAME_WIDTH = 150; /** Width of rectangle that displays color. */ private final static int COLOR_RECT_WIDTH = 50; /** Height of rectangle that displays color. */ private final static int COLOR_RECT_HEIGHT = 25; private final TextField redField = TextFieldBuilder.create() .text("Red Value").build(); private final TextField greenField = TextFieldBuilder.create() .text("Green Value").build(); private final TextField blueField = TextFieldBuilder.create() .text("Blue Value").build(); private final Rectangle customColorRectangle = RectangleBuilder.create() .width(COLOR_RECT_WIDTH).height(COLOR_RECT_HEIGHT) .fill(Color.WHITE).stroke(Color.BLACK).build(); /** * Build a pane containing details about the instance of Color provided. * * @param color Instance of Color about which generated Pane should describe. * @return Pane representing information on provided Color instance. */ private Pane buildColorBox(final Color color, final String colorName) { final HBox colorBox = new HBox(); final Label colorNameLabel = new Label(colorName); colorNameLabel.setMinWidth(COLOR_NAME_WIDTH); colorBox.getChildren().add(colorNameLabel); final Rectangle colorRectangle = new Rectangle(COLOR_RECT_WIDTH, COLOR_RECT_HEIGHT); colorRectangle.setFill(color); colorRectangle.setStroke(Color.BLACK); colorBox.getChildren().add(colorRectangle); final String rgbString = String.valueOf(color.getRed()) + " / " + String.valueOf(color.getGreen()) + " / " + String.valueOf(color.getBlue()) + " // " + String.valueOf(color.getOpacity()); final Label rgbLabel = new Label(rgbString); rgbLabel.setTooltip(new Tooltip("Red / Green / Blue // Opacity")); colorBox.getChildren().add(rgbLabel); return colorBox; } /** * Extracts a double between 0.0 and 1.0 inclusive from the provided String. * * @param colorString String from which a double is extracted. * @return Double between 0.0 and 1.0 inclusive based on provided String; * will be 0.0 if provided String cannot be parsed. */ private double extractValidColor(final String colorString) { double colorValue = 0.0; try { colorValue = Double.valueOf(colorString); } catch (Exception exception) { colorValue = 0.0; err.println("Treating '" + colorString + "' as " + colorValue); } finally { if (colorValue < 0) { colorValue = 0.0; err.println("Treating '" + colorString + "' as " + colorValue); } else if (colorValue > 1) { colorValue = 1.0; err.println("Treating '" + colorString + "' as " + colorValue); } } return colorValue; } /** * Build pane with ability to specify own RGB values and see color. * * @return Pane with ability to specify colors. */ private Pane buildCustomColorPane() { final HBox customBox = new HBox(); final Button button = new Button("Display Color"); button.setPrefWidth(COLOR_NAME_WIDTH); button.setOnMouseClicked(new EventHandler() { @Override public void handle(MouseEvent t) { final Color customColor = new Color(extractValidColor(redField.getText()), extractValidColor(greenField.getText()), extractValidColor(blueField.getText()), 1.0); customColorRectangle.setFill(customColor); } }); customBox.getChildren().add(button); customBox.getChildren().add(this.customColorRectangle); customBox.getChildren().add(this.redField); customBox.getChildren().add(this.greenField); customBox.getChildren().add(this.blueField); return customBox; } /** * Build the main pane indicating JavaFX 2's pre-defined Color instances. * * @return Pane containing JavaFX 2's pre-defined Color instances. */ private Pane buildColorsPane() { final VBox colorsPane = new VBox(); final Field[] fields = Color.class.getFields(); // only want public for (final Field field : fields) { if (field.getType() == Color.class) { try { final Color color = (Color) field.get(null); final String colorName = field.getName(); colorsPane.getChildren().add(buildColorBox(color, colorName)); } catch (IllegalAccessException illegalAccessEx) { err.println( "Securty Manager does not allow access of field '" + field.getName() + "'."); } } } colorsPane.getChildren().add(buildCustomColorPane()); return colorsPane; } /** * Start method overridden from parent Application class. * * @param stage Primary stage. * @throws Exception JavaFX application exception. */ @Override public void start(final Stage stage) throws Exception { final Group rootGroup = new Group(); final Scene scene = new Scene(rootGroup, 700, 725, Color.WHITE); final ScrollPane scrollPane = new ScrollPane(); scrollPane.setPrefWidth(scene.getWidth()); scrollPane.setPrefHeight(scene.getHeight()); scrollPane.setContent(buildColorsPane()); rootGroup.getChildren().add(scrollPane); stage.setScene(scene); stage.setTitle("JavaFX Standard Colors Demonstration"); stage.show(); } /** * Main function for running JavaFX application. * * @param arguments Command-line arguments; none expected. */ public static void main(final String[] arguments) { Application.launch(arguments); } } The snapshots shown next demonstrate this simple application. The first snapshot shows the application after loading. The second snapshot shows the application after scrolling down to the bottom and demonstrates use of the Tooltip and of the TextField.setPrompt(String) method. The third image shows the results of providing red/green/blue values and clicking on the button to see the corresponding color. The simple JavaFX 2 application shown in this post makes it easy to get an idea of what colors are available as standard JavaFX 2 public static Color fields. It also allows one to enter red/green/blue values that might be provided to the Color constructor to obtain an instance of Color. From http://marxsoftware.blogspot.com/2012/02/viewing-javafx-2-standard-colors.html
March 6, 2012
by Dustin Marx
· 24,604 Views · 1 Like
  • Previous
  • ...
  • 853
  • 854
  • 855
  • 856
  • 857
  • 858
  • 859
  • 860
  • 861
  • 862
  • ...
  • 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
×