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

article thumbnail
Dynamically Generating Python Test Cases
Testing is crucial. While many different kinds and levels of testing exist, there’s good library support only for unit tests (the Python unittest package and its moral equivalents in other languages). However, unit testing does not cover all kinds of testing we may want to do – for example, all kinds of whole program tests and integration tests. This is where we usually end up with a custom "test runner" script. Having written my share of such custom test runners, I’ve recently gravitated towards a very convenient approach which I want to share here. In short, I’m actually using Python’s unittest, combined with the dynamic nature of the language, to run all kinds of tests. Let’s assume my tests are some sort of data files which have to be fed to a program. The output of the program is compared to some "expected results" file, or maybe is encoded in the data file itself in some way. The details of this are immaterial, but seasoned programmers usually encounter such testing rigs very frequently. It commonly comes up when the program under test is a data-transformation mechanism of some sort (compiler, encryptor, encoder, compressor, translator etc.) So you write a "test runner". A script that looks at some directory tree, finds all the "test files" there, runs each through the transformation, compares, reports, etc. I’m sure all these test runners share a lot of common infrastructure – I know that mine do. Why not employ Python’s existing "test runner" capabilities to do the same? Here’s a very short code snippet that can serve as a template to achieve this: import unittest class TestsContainer(unittest.TestCase): longMessage = True def make_test_function(description, a, b): def test(self): self.assertEqual(a, b, description) return test if __name__ == '__main__': testsmap = { 'foo': [1, 1], 'bar': [1, 2], 'baz': [5, 5]} for name, params in testsmap.iteritems(): test_func = make_test_function(name, params[0], params[1]) setattr(TestsContainer, 'test_{0}'.format(name), test_func) unittest.main() What happens here: The test class TestsContainer will contain dynamically generated test methods. make_test_function creates a test function (a method, to be precise) that compares its inputs. This is just a trivial template – it could do anything, or there can be multiple such "makers" fur multiple purposes. The loop creates test functions from the data description in testmap and attaches them to the test class. Keep in mind that this is a very basic example. I hope it’s obvious that testmap could really be test files found on disk, or whatever else. The main idea here is the dynamic test method creation. So what do we gain from this, you may ask? Quite a lot. unittest is powerful – armed to its teeth with useful tools for testing. You can now invoke tests from the command line, control verbosity, control "fast fail" behavior, easily filter which tests to run and which not to run, use all kinds of assertion methods for readability and reporting (why write your own smart list comparison assertions?). Moreover, you can build on top of any number of third-party tools for working with unittest results – HTML/XML reporting, logging, automatic CI integration, and so on. The possibilities are endless. One interesting variation on this theme is aiming the dynamic generation at a different testing "layer". unittest defines any number of "test cases" (classes), each with any number of "tests" (methods). In the code above, we generate a bunch of tests into a single test case. Here’s a sample invocation to see this in action: $ python dynamic_test_methods.py -v test_bar (__main__.TestsContainer) ... FAIL test_baz (__main__.TestsContainer) ... ok test_foo (__main__.TestsContainer) ... ok ====================================================================== FAIL: test_bar (__main__.TestsContainer) ---------------------------------------------------------------------- Traceback (most recent call last): File "dynamic_test_methods.py", line 8, in test self.assertEqual(a, b, description) AssertionError: 1 != 2 : bar ---------------------------------------------------------------------- Ran 3 tests in 0.001s FAILED (failures=1) As you can see, all data pairs in testmap are translated into distinctly named test methods within the single test case TestsContainer. Very easily, we can cut this a different way, by generating a whole test case for each data item: import unittest class DynamicClassBase(unittest.TestCase): longMessage = True def make_test_function(description, a, b): def test(self): self.assertEqual(a, b, description) return test if __name__ == '__main__': testsmap = { 'foo': [1, 1], 'bar': [1, 2], 'baz': [5, 5]} for name, params in testsmap.iteritems(): test_func = make_test_function(name, params[0], params[1]) klassname = 'Test_{0}'.format(name) globals()[klassname] = type(klassname, (DynamicClassBase,), {'test_gen_{0}'.format(name): test_func}) unittest.main() Most of the code here remains the same. The difference is in the lines within the loop: now instead of dynamically creating test methods and attaching them to the test case, we create whole test cases – one per data item, with a single test method. All test cases derive from DynamicClassBase and hence from unittest.TestCase, so they will be auto-discovered by the unittest machinery. Now an execution will look like this: $ python dynamic_test_classes.py -v test_gen_bar (__main__.Test_bar) ... FAIL test_gen_baz (__main__.Test_baz) ... ok test_gen_foo (__main__.Test_foo) ... ok ====================================================================== FAIL: test_gen_bar (__main__.Test_bar) ---------------------------------------------------------------------- Traceback (most recent call last): File "dynamic_test_classes.py", line 8, in test self.assertEqual(a, b, description) AssertionError: 1 != 2 : bar ---------------------------------------------------------------------- Ran 3 tests in 0.000s FAILED (failures=1) Why would you want to generate whole test cases dynamically rather than just single tests? It all depends on your specific needs, really. In general, test cases are better isolated and share less, than tests within one test case. Moreover, you may have a huge amount of tests and want to use tools that shard your tests for parallel execution – in this case you almost certainly need separate test cases. I’ve used this technique in a number of projects over the past couple of years and found it very useful; more than once, I replaced a whole complex test runner program with about 20-30 lines of code using this technique, and gained access to many more capabilities for free. Python’s built-in test discovery, reporting and running facilities are very powerful. Coupled with third-party tools they can be even more powerful. Leveraging all this power for any kind of testing, and not just unit testing, is possible with very little code, due to Python’s dynamism. I hope you find it useful too.
April 25, 2014
by Eli Bendersky
· 12,567 Views · 2 Likes
article thumbnail
HashMap Performance Improvements in Java 8
See how HashMap performance has been improved with new features of Java 8.
April 23, 2014
by Tomasz Nurkiewicz
· 136,697 Views · 60 Likes
article thumbnail
Update Row With Highest ID In MySQL
Recently needed to update the last inserted row of a table but didn't have anyway in knowing what the highest ID in the table was. I can easily do this by using the max() function to select the highest ID in the table. SELECT MAX(id) FROM table; Then I can use the result of this query in the UPDATE query to edit the record with the highest ID. But this is quite a easy query so I should be able to do this in one query by using a nested select query on the UPDATE. UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table) But the problem with this is that the MAX() function doesn't work inside a nested select so had to find another way of doing this. I found out that you can use an ORDER BY and a LIMIT in an UPDATE query therefore I can use a combination of these in the UPDATE query to make sure I only update the record with the highest ID, by doing a descendant order on the ID and limiting the return to only 1 record. UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;
April 23, 2014
by Paul Underwood
· 21,557 Views
article thumbnail
Java 7 vs. Java 8: Performance Benchmarking of Fork/Join
with the recent release of java 8, developers are still just beginning to asses the strengths and weaknesses of the new platform. the most pressing question is: does java 8 have the fastest jvm so far? a good way to asses the progress of java 8 is to test its ability to work with something that was new to java 7... fork/join. oleg shelajev uses the "infamous" java microbenchmark harness project (jmh) to create a benchmark test for the two most recent versions of java. but before implementing the benchmark, he takes the time to give a brief overview of fork/join and how it changes between java 7 and 8. here is a graph of the results : based on these results, oleg recommends taking a chance and upgrading to java 8, especially if you are working with mapreducing or fork/join. this is his interpretation of the data that lead him to that conclusion: one can see that the baseline results, which show the throughput of running the math directly in a single thread do not differ between the jdk 7 and 8. however, when we include the overhead of managing recursive tasks and going through a forkjoin execution then java 8 is much faster. the numbers for this simple benchmark suggest that the overhead of managing forkjoin tasks is around 35% more performant in the latest release. check out the full article ! it is very informative, has great visuals, and tackles complexity with clarity.
April 22, 2014
by Sarah Ervin
· 60,538 Views · 1 Like
article thumbnail
Java Regular Expressions to Validate Credit Cards
Visa Card ^4[0-9]{12}(?:[0-9]{3})?$^5[1-5][0-9]{14}$ Amex Card ^3[47][0-9]{13}$ Carte Blanche Card ^389[0-9]{11}$ Diners Club Card ^3(?:0[0-5]|[68][0-9])[0-9]{11}$ Discover Card ^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$ JCB Card ^(?:2131|1800|35\d{3})\d{11}$ Visa Master Card ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14})$ Insta Payment Card ^63[7-9][0-9]{13}$ Laser Card ^(6304|6706|6709|6771)[0-9]{12,15}$ Maestro Card ^(5018|5020|5038|6304|6759|6761|6763)[0-9]{8,15}$ Solo Card ^(6334|6767)[0-9]{12}|(6334|6767)[0-9]{14}|(6334|6767)[0-9]{15}$ Switch Card ^(4903|4905|4911|4936|6333|6759)[0-9]{12}|(4903|4905|4911|4936|6333|6759)[0-9]{14}|(4903|4905|4911|4936|6333|6759)[0-9]{15}|564182[0-9]{10}|564182[0-9]{12}|564182[0-9]{13}|633110[0-9]{10}|633110[0-9]{12}|633110[0-9]{13}$ Union Pay Card ^(62[0-9]{14,17})$ KoreanLocalCard ^9[0-9]{15}$ BCGlobal ^(6541|6556)[0-9]{12}$ As you can see, regular expressions are incredibly powerful and the above examples are very basic. Regular expressions are essential for all sorts of application from web scraping, form validation and pattern matching. Hopefully you will find this resource useful and would come back to refer again and again.
April 22, 2014
by Jagadeesh Motamarri
· 12,500 Views · 1 Like
article thumbnail
Java String length confusion
Facts and Terminology As you probably know, Java uses UTF-16 to represent Strings. In order to understand the confusion about String.length(), you need to be familiar with some Encoding/Unicode terms. Code Point: A unique integer value which represents a character in the code space. Code Unit: A bit sequence used to encode characters (Code Points). One or more Code Units may be required to represent a Code Point. UTF-16 Unicode Code Points are logically divided into 17 planes. The first plane, the Basic Multilingual Plane (BMP) contains the “classic” characters (from U+0000 to U+FFFF). The other planes contain the supplementary characters (from U+10000 to U+10FFFF). Characters (Code Points) from the first plane are encoded in one 16-bit Code Unit with the same value. Supplementary characters (Code Points) are encoded in two Code Units (encoding-specific, see Wiki for the explanation). Example Character: A Unicode Code Point: U+0041 UTF-16 Code Unit(s): 0041 Character: Mathematical double-struck capital A Unicode Code Point: U+1D538 UTF-16 Code Unit(s): D835 DD38 As you can see here, there are characters which are encoded in two Code Units. String.length() Let’s take a look at the Javadoc of the length() method: public int length() Returns the length of this string. The length is equal to the number of Unicode code units in the string. So if you have one supplementary character which consists of two code units, the length of that single character is two. // Mathematical double-struck capital A String str = "\uD835\uDD38"; System.out.println(str); System.out.println(str.length()); //prints 2 Which is correct according to the documentation, but maybe it’s not expected. ~Solution You need to count the code points not the code units: String str = "\uD835\uDD38"; System.out.println(str); System.out.println(str.codePointCount(0, str.length())); See: codePointCount(int beginIndex, int endIndex) References/Sources The Java Language Specification Unicode Glossary: Code Point Wiki: Code Point Unicode Glossary: Code Unit Wiki: Code Unit Wiki: Unicode Wiki: UTF-16 Supplementary Characters in the Java Platform Wiki: Unicode Planes
April 21, 2014
by Jonatan Ivanov
· 18,041 Views · 7 Likes
article thumbnail
Handy New Map Default Methods in JDK 8
The Map interface provides some handy new methods in JDK 8. Because the Map methods I cover in this post are implemented as default methods, all existing implementations of the Map interface enjoy the default behaviors defined in the default methods without any new code. The JDK 8 introduced Map methods covered in this post are getOrDefault(Object, V), putIfAbsent(K, V), remove(Object, Object), remove(Object, Object), replace(K, V), and replace(K, V, V). Example Map for Demonstrations I will be using the Map declared and initialized as shown in the following code throughout the examples in this blog post. The statesAndCapitals field is a class-level static field. I intentionally have only included a small subset of the fifty states in the United States for reading clarity and to allow easier demonstration of some of the new JDK 8 Map default methods. private final static Map statesAndCapitals; static { statesAndCapitals = new HashMap<>(); statesAndCapitals.put("Alaska", "Anchorage"); statesAndCapitals.put("California", "Sacramento"); statesAndCapitals.put("Colorado", "Denver"); statesAndCapitals.put("Florida", "Tallahassee"); statesAndCapitals.put("Nevada", "Las Vegas"); statesAndCapitals.put("New Mexico", "Sante Fe"); statesAndCapitals.put("Utah", "Salt Lake City"); statesAndCapitals.put("Wyoming", "Cheyenne"); } Map.getOrDefault(Object, V) Map's new method getOrDefault(Object, V) allows the caller to specify in a single statement to get the value of the map that corresponds to the provided key or else return a provided "default value" if no match is found for the provided key. The next code listing compares how checking for a value matching a provided key in a map or else using a default if no match is found was implemented before JDK 8 and how it can now be implemented with JDK 8. /* * Demonstrate Map.getOrDefault and compare to pre-JDK 8 approach. The JDK 8 * addition of Map.getOrDefault requires fewer lines of code than the * traditional approach and allows the returned value to be assigned to a * "final" variable. */ // pre-JDK 8 approach String capitalGeorgia = statesAndCapitals.get("Georgia"); if (capitalGeorgia == null) { capitalGeorgia = "Unknown"; } // JDK 8 approach final String capitalWisconsin = statesAndCapitals.getOrDefault("Wisconsin", "Unknown"); The Apache Commons class DefaultedMap provides functionality similar to the newMap.getOrDefault(Object, V) method. The Groovy GDK includes a similar method for Groovy,Map.get(Object, Object), but that one's behavior is a bit different because it not only returns the provided default if the "key" is not found, but also adds the key with the default value to the underlying map. Map.putIfAbsent(K, V) Map's new method putIfAbsent(K, V) has Javadoc advertising its default implementation equivalent: The default implementation is equivalent to, for this map: V v = map.get(key); if (v == null) v = map.put(key, value); return v; This is illustrated with another code sample that compares the pre-JDK 8 approach to the JDK 8 approach. /* * Demonstrate Map.putIfAbsent and compare to pre-JDK 8 approach. The JDK 8 * addition of Map.putIfAbsent requires fewer lines of code than the * traditional approach and allows the returned value to be assigned to a * "final" variable. */ // pre-JDK 8 approach String capitalMississippi = statesAndCapitals.get("Mississippi"); if (capitalMississippi == null) { capitalMississippi = statesAndCapitals.put("Mississippi", "Jackson"); } // JDK 8 approach final String capitalNewYork = statesAndCapitals.putIfAbsent("New York", "Albany"); Alternate solutions in the Java space before the addition of this putIfAbsent method are discussed in theStackOverflow thread Java map.get(key) - automatically do put(key) and return if key doesn't exist?. It's worth noting that before JDK 8, the ConcurrentMap interface (extends Map) already provided a putIfAbsent(K, V)method. Map.remove(Object, Object) Map's new remove(Object, Object) method goes beyond the long-available Map.remove(Object) method to remove a map entry only if both the provided key and provided value match an entry in the map (the previously available version only looked for a "key" match to remove). The Javadoc comment for this method explains the how the default method's implementation works in terms of equivalent pre-JDK 8 Java code: The default implementation is equivalent to, for this map: if (map.containsKey(key) && Objects.equals(map.get(key), value)) { map.remove(key); return true; } else return false; A concrete comparison of the new approach to the pre-JDK 8 approach is shown in the next code listing. /* * Demonstrate Map.remove(Object, Object) and compare to pre-JDK 8 approach. * The JDK 8 addition of Map.remove(Object, Object) requires fewer lines of * code than the traditional approach and allows the returned value to be * assigned to a "final" variable. */ // pre-JDK 8 approach boolean removed = false; if ( statesAndCapitals.containsKey("New Mexico") && Objects.equals(statesAndCapitals.get("New Mexico"), "Sante Fe")) { statesAndCapitals.remove("New Mexico", "Sante Fe"); removed = true; } // JDK 8 approach final boolean removedJdk8 = statesAndCapitals.remove("California", "Sacramento"); Map.replace(K, V) The first of the two new Map "replace" methods sets the specified value to be mapped to the specified key only if the specified key already exists with some mapped value. The Javadoc comment explains the Java equivalent of this default method implementation: The default implementation is equivalent to, for this map: if (map.containsKey(key)) { return map.put(key, value); } else return null; The comparison of this new approach to the pre-JDK 8 approach is shown next. /* * Demonstrate Map.replace(K, V) and compare to pre-JDK 8 approach. The JDK 8 * addition of replace(K, V) requires fewer lines of code than the traditional * approach and allows the returned value to be assigned to a "final" * variable. */ // pre-JDK 8 approach String replacedCapitalCity; if (statesAndCapitals.containsKey("Alaska")) { replacedCapitalCity = statesAndCapitals.put("Alaska", "Juneau"); } // JDK 8 approach final String replacedJdk8City = statesAndCapitals.replace("Alaska", "Juneau"); Map.replace(K, V, V) The second newly added Map "replace" method is more narrow in its interpretation of which existing values are replaced. While the method just covered replaces any value in a value available for the specified key in the mapping, this "replace" method that accepts an additional (third) argument will only replace the value of a mapped entry that has both a matching key and a matching value. The Javadoc comment shows the default method's implementation: The default implementation is equivalent to, for this map: if (map.containsKey(key) && Objects.equals(map.get(key), value)) { map.put(key, newValue); return true; } else return false; My comparison of this approach to the pre-JDK 8 approach is shown in the next code listing. /* * Demonstrate Map.replace(K, V, V) and compare to pre-JDK 8 approach. The * JDK 8 addition of replace(K, V, V) requires fewer lines of code than the * traditional approach and allows the returned value to be assigned to a * "final" variable. */ // pre-JDK 8 approach boolean replaced = false; if ( statesAndCapitals.containsKey("Nevada") && Objects.equals(statesAndCapitals.get("Nevada"), "Las Vegas")) { statesAndCapitals.put("Nevada", "Carson City"); replaced = true; } // JDK 8 approach final boolean replacedJdk8 = statesAndCapitals.replace("Nevada", "Las Vegas", "Carson City"); Observations and Conclusion There are several observations to make from this post. The Javadoc methods for these new JDK 8 Map methods are very useful, especially in terms of describing how the new methods behave in terms of pre-JDK 8 code. I discussed these methods' Javadoc in a more general discussion on JDK 8 Javadoc-based API documentation. As the equivalent Java code in these methods' Javadoc comments indicates, these new methods do not generally check for null before accessing map keys and values. Therefore, one can expect the same issues with nulls using these methods as one would find when using "equivalent" code as shown in the Javadoc comments. In fact, the Javadoc comments generally warn about the potential forNullPointerException and issues related to some Map implementations allowing null and some not for keys and values. The new Map methods discussed in this post are "default methods," meaning that implementations of Map "inherit" these implementations automatically. The new Map methods discussed in this post allow for cleaner and more concise code. In most of my examples, they allowed the client code to be converted from multiple state-impacting statements to a single statement that can set a local variable once and for all. The new Map methods covered in this post are not ground-breaking or earth-shattering, but they are conveniences that many Java developers previously implemented more verbose code for, wrote their own similar methods for, or used a third-party library for. JDK 8 brings these standardized methods to the Java masses without need for custom implementation or third-party frameworks. Because default methods are the implementation mechanism, even Map implementations that have been around for quite a while suddenly and automatically have access to these new methods without any code changes to the implementations.
April 21, 2014
by Dustin Marx
· 18,696 Views · 1 Like
article thumbnail
Groovy 2.3 Introduces Traits
A few days ago the second beta of Groovy 2.3 got released. One of the major new Groovy 2.3 features are traits. A trait is a reusable set of methods and fields that can be added to one or more classes. A class can be composed out of multiple traits without using multiple inheritance (and therefore avoiding the diamond problem). Basic usage The following piece of code shows a basic definition of a trait in Groovy 2.3. trait SwimmingAbility { def swim() { println "swimming.." } } A trait definition looks very similar to a class definition. This trait defines a single method swim(). We can add this trait to a class using the implements keyword: class Goldfish implements SwimmingAbility { .. } Now we are able to call the swim() methods on Goldfish objects: def goldfish = new Goldfish() goldfish.swim() So far we could have accomplished the same using inheritance. The difference is that we can add multiple traits to a single class. So let's define another trait: trait FlyingAbility { def fly() { println "flying.." } } We can now create a new class that makes use of both traits: class Duck implements SwimmingAbility, FlyingAbility { .. } Ducks can swim and fly now: def duck = new Duck() duck.swim() duck.fly() this inside traits Inside traits the this keyword represents the implementing instance. This means you can write the following: trait FlyingAbility { def fly() { println "${this.class.name} is flying.." } } In case of the Duck class from above this will print Duck is flying.. if we call duck.fly(). A more complex example Now let's look at an example that shows some more features of Groovy traits trait Trader { int availableMoney = 0 private int tradesDone = 0 def buy(Item item) { if (item.price <= availableMoney) { availableMoney -= item.price tradesDone += 1 println "${getName()} bought ${item.name}" } } def sell(Item item) { .. } abstract String getName() } Like Groovy classes traits support properties. Here the property availableMoney will become private and public getter / setter methods will be generated. These methods can be accessed on implementing classes.tradesDone is a private variable that cannot be accessed outside the Trader trait. Within this trait we defined an abstract method getName(). This method has to be implemented by classes that make use of this trait. Let's create a class that implements our Trader trait: class Merchant implements Trader { String name String getName() { return this.name } } A Merchant is now be able to buy items: def bike = new Item(name: 'big red bike', price: 750) def paul = new Merchant(name: 'paul') paul.availableMoney = 2000 paul.buy(bike) // prints "paul bought big red bike" println paul.availableMoney // 1250 Extending from traits, Overriding and conflict resolution A trait can inherit functionality from another trait using the extends keyword: trait Dealer { def getProfit() { ... } def deal() { ... } } trait CarDealer extends Dealer { def deal() { ... } } Here the CarDealer trait extends Dealer and overrides the deal() method of Dealer. Trait methods can also be overwritten in implementing classes: class OnlineCarDealer implements CarDealer { def deal() { ... } } If a class implements more than one trait it is possible to create a conflict. That's the case if two or more traits define a method with an identical signature: trait Car { def drive() { ... } } trait Bike { def drive() { ... } } class DrivingThing implements Car, Bike { ... } In such a situation the last declared trait wins (Bike in this example). Conclusion I think traits are a very useful concept and I am happy to see them in Groovy. Other than Groovy mixins traits work at compile time and can therefore be accessed from Java code. For further reading I can recommend the Groovy 2.3 Trait documentation.
April 20, 2014
by Michael Scharhag
· 24,015 Views · 2 Likes
article thumbnail
Be Careful with Java Path.endsWith(String) Usage
If you need to compare the java.io.file.Path object, be aware that Path.endsWith(String) will ONLY match another sub-element of Path object in your original path, not the path name string portion! If you want to match the string name portion, you would need to call the Path.toString() first. For example // Match all jar files. Files.walk(dir).forEach(path -> { if (path.toString().endsWith(".jar")) System.out.println(path); }); With out the "toString()" you will spend many fruitless hours wonder why your program didn't work.
April 19, 2014
by Zemian Deng
· 10,619 Views · 1 Like
article thumbnail
What's Wrong with Java 8: Currying vs Closures
There are many false ideas around about Java 8. Among these is the idea that Java 8 brings closures to Java.
April 19, 2014
by Pierre-Yves Saumont
· 136,059 Views · 31 Likes
article thumbnail
Insert Embedded or Linked OLE Object in Word Files & EUDC Fonts Support in .NET & Java Apps
What's New in this Release? Aspose development team is happy to announce the monthly release of Aspose.Words for Java &.NET 14.3.0. Aspose.Words now supports insertion of OLE objects such as another Microsoft Word document or a Microsoft Excel chart. A new public method, InsertOleObject, has been introduced in the DocumentBuilder class. This method can be used to insert an embedded or linked OLE object from a file into a Word document. Aspose.Words’ rendering engine now partially supports EUDC (End-User-Defined-Characters) fonts. Please find below the description of how EUDC fonts works on Windows. In this first implementation, Aspose.Words uses a single EUDC font. When rendering a document to fixed-page formats, this font is searched among the specified font sources by “EUDC” family name. Starting from Aspose.Words 14.3.0, Best Fit position of data labels in pie charts is partially supported. In previous versions labels with best fit position were rendered as if they had the inside end position. Currently we use a modified Open Office algorithm to set the best fit position of data labels. The list of new and improved features in this release are listed below Public API for insertion of OLE objects both linked and embedded Outline, Shadow, Reflection, Glow and Fill text effects for rendering text inside DrawingML shapes EUDC fonts rendering partially supported “PDF Logical Structure” export reworked, significantly improving memory usage Support OLE embedding of documents and files Feature Write an article about how to work with Table of contents in Aspose.Words Add tag support Support BestFit position of Pie chart's data labels. Support style:text-decoration attribute of Paragraph tag. Preserve private characters in EUDC.TTE during rendering to Pdf Support HTML table row borders in HTML import Support text outline effect. Support text fill effect. Support text shadow effect. Support text reflection effect Support text glow effect. Support text effects applied to text in Dml Shape or in SmartArt. Implement reading text effects from rPr in DML. Support inheriting styles from parent objects. Add image compression options for different image types Add a link to the online documentation in the DLLs only release Default run properties lose lang attribute value on DOCX to DOC conversions Padding for image in table is lost when rendering to Pdf Consider using "Don't vertically align cells containing floating objects" compatibility option when exporting to HTML Shape in table's cell is improperly horizontally aligned to center after export to HTML is now fixed Floating shape is now properly vertically positioned after export to HTML Warning : Unkno/wn ProgId value 'Visio.Drawing.11'. This might cause inaccessible OLE embedding Charts (DrawingML) issue fixed and now render correctly in Pdf file Aspose.Words now properly work in Jdeveloper IDE OLE object cannot be edited after re saving the document Diagram connectors are inverted/flipped after conversion from Docx to pdf WordArt letters are condensing issue is resolved Condensed character spacing is lost is fixed Relative hyperlink with Unicode is now properly saved to Pdf Add pre-built Document Explorer JAR to Java release. Aspose.Words does not take in account style set in . Table now looks correctly while converting html to doc. Hyperlinks split into multiple fragments/links in output PDF Horizontal table position is corrected. Document.UpdateFields Does not Update TOC in DOCX Content in the output html is overlapped at many places in Html Different table justify alignment for different compatibilityMode values. CSS selectors now work for , , and elements Chart Legend/Series now render correctly in output Pdf file Data labels with best fit position are rendering at correct places in Chart Offset of the hyperlink text line is off by a few pixels in output Pdf Hyperlinks split into multiple fragments/links in output PDF is fixed Document.UpdateFields is enhanced and update SUM formula field Paragraph's first line indent increases is fixed when exported to HTM Space before a paragraph following a floating element is too large after HTML to DOCX conversion is now fixd Block-level SVG image become inline after HTML to DOCX conversion Problem with vertical paragraph spacing is resolved when importing HTML using InsertHtml method Shape rotation is fixed after conversion from Doc to Pdf Text color is changed after conversion from Docx to WordML/Doc Word Table indentation is now corrected when is placed inside Arrows on the Lines gets distorted when converting to Pdf is now fixed A space character is exported to PDF output between Japanese and Numeric characters is fixed Line Shape from Header is merged with the top border of Table in Body Docx to WordML conversion issue resolved with content control Junk text is rendered in fixed page formats Positions of some DrawingML circles are now preserved during rendering A row and some content is rendering at the bottom of previous page is fixed Header table rows and images are now preserved in PDF List items issue fixed, now line up correctly after conversion from RTF to HTML Conversion from Docm to Doc creates corrupted document now fixed Hyperlink for an icon is now preserved during HTML to PDF conversion Text overlapping is fixed after conversion from Docx to Pdf Text position change is fixed after conversion from Docx to Pdf Other most recent bug fixes are also included in this release Newly added documentation pages and articles Some new tips and articles have now been added into Aspose.Words for .NET documentation that may guide you briefly how to use Aspose.Words for performing different tasks like the followings. How Aspose.Words Uses True Type Fonts How to Extract Images from a Document Overview: Aspose.Words Aspose.Words is a word processing component that enables .NET, Java & Android applications to read, write and modify Word documents without using Microsoft Word. Other useful features include document creation, content and formatting manipulation, mail merge abilities, reporting features, TOC updated/rebuilt, Embedded OOXML, Footnotes rendering and support of DOCX, DOC, WordprocessingML, HTML, XHTML, TXT and PDF formats (requires Aspose.Pdf). It supports both 32-bit and 64-bit operating systems. You can even use Aspose.Words for .NET to build applications with Mono. More about Aspose.Words Homepage Aspose.Words for .NET Homepage Java Word Library Download Aspose.Words for .NET Download Aspose.Words for Java Demos for Aspose.Words Contact Information Aspose Pty Ltd Suite 163, 79 Longueville Road Lane Cove, NSW, 2066 Australia Aspose - Your File Format Experts [email protected] Phone: 888.277.6734 Fax: 866.810.9465
April 18, 2014
by David Zondray
· 3,089 Views
article thumbnail
How to Convert C# Object Into JSON String with JSON.NET
Before some time I have written a blog post – Converting a C# object into JSON string in that post one of reader, Thomas Levesque commented that mostly people are using JSON.NET a popular high performance JSON for creating for .NET Created by James Newton- King. I agree with him if we are using .NET Framework 4.0 or higher version for earlier version still JavaScriptSerializer is good. So in this post we are going to learn How we can convert C# object into JSON string with JSON.NET framework. What is JSON.NET: JSON.NET is a very high performance framework compared to other serializer for converting C# object into JSON string. It is created by James Newton-Kind. You can find more information about this framework from following link. http://james.newtonking.com/json How to convert C# object into JSON string with JSON.NET framework: For this I am going to use old application that I have used in previous post. Following is a employee class with two properties first name and last name. public class Employee { public string FirstName { get; set; } public string LastName { get; set; } } I have created same object of “Employee” class as I have created in previous post like below. Employee employee=new Employee {FirstName = "Jalpesh", LastName = "Vadgama"}; Now it’s time to add JSON.NET Nuget package. You install Nuget package via following command. I have installed like below. Now we are done with adding NuGet package. Following is code I have written to convert C# object into JSON string. string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(employee); Console.WriteLine(jsonString); Let's run application and following is a output as expected. That’s it. It’s very easy. Hope you like it. Stay tuned for more.
April 14, 2014
by Jalpesh Vadgama
· 193,299 Views
article thumbnail
Creating Object Pool in Java
In this post, we will take a look at how we can create an object pool in Java. In recent times, JVM performance has been multiplied manifold and so object creation is no longer considered as expensive as it was done earlier. But there are few objects, for which creation of new object still seems to be slight costly as they are not considered as lightweight objects. e.g.: database connection objects, parser objects, thread creation etc. In any application we need to create multiple such objects. Since creation of such objects is costly, it’s a sure hit for the performance of any application. It would be great if we can reuse the same object again and again. Object Pools are used for this purpose. Basically, object pools can be visualized as a storage where we can store such objects so that stored objects can be used and reused dynamically. Object pools also controls the life-cycle of pooled objects. As we understood the requirement, let’s come to real stuff. Fortunately, there are various open source object pooling frameworks available, so we do not need to reinvent the wheel. In this post we will be using apache commons pool to create our own object pool. At the time of writing this post Version 2.2 is the latest, so let us use this. The basic thing we need to create is- 1. A pool to store heavyweight objects (pooled objects). 2. A simple interface, so that client can - a.) Borrow pooled object for its use. b.) Return the borrowed object after its use. Let’s start with Parser Objects. Parsers are normally designed to parse some document like xml files, html files or something else. Creating new xml parser for each xml file (having same structure) is really costly. One would really like to reuse the same (or few in concurrent environment) parser object(s) for xml parsing. In such scenario, we can put some parser objects into pool so that they can be reused as and when needed. Below is a simple parser declaration: package blog.techcypher.parser; /** * Abstract definition of Parser. * * @author abhishek * */ public interface Parser { /** * Parse the element E and set the result back into target object T. * * @param elementToBeParsed * @param result * @throws Exception */ public void parse(E elementToBeParsed, T result) throws Exception; /** * Tells whether this parser is valid or not. This will ensure the we * will never be using an invalid/corrupt parser. * * @return */ public boolean isValid(); /** * Reset parser state back to the original, so that it will be as * good as new parser. * */ public void reset(); } Let’s implement a simple XML Parser over this as below: package blog.techcypher.parser.impl; import blog.techcypher.parser.Parser; /** * Parser for parsing xml documents. * * @author abhishek * * @param * @param */ public class XmlParser implements Parser { private Exception exception; @Override public void parse(E elementToBeParsed, T result) throws Exception { try { System.out.println("[" + Thread.currentThread().getName()+ "]: Parser Instance:" + this); // Do some real parsing stuff. } catch(Exception e) { this.exception = e; e.printStackTrace(System.err); throw e; } } @Override public boolean isValid() { return this.exception == null; } @Override public void reset() { this.exception = null; } } At this point, as we have parser object we should create a pool to store these objects. Here, we will be using GenericObjectPool to store the parse objects. Apache commons pool has already build-in classes for pool implementation. GenericObjectPool can be used to store any object. Each pool can contain same kind of object and they have factory associated with them. GenericObjectPool provides a wide variety of configuration options, including the ability to cap the number of idle or active instances, to evict instances as they sit idle in the pool, etc. If you want to create multiple pools for different kind of objects (e.g. parsers, converters, device connections etc.) then you should use GenericKeyedObjectPool . package blog.techcypher.parser.pool; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import blog.techcypher.parser.Parser; /** * Pool Implementation for Parser Objects. * It is an implementation of ObjectPool. * * It can be visualized as- * +-------------------------------------------------------------+ * | ParserPool | * +-------------------------------------------------------------+ * | [Parser@1, Parser@2,...., Parser@N] | * +-------------------------------------------------------------+ * * @author abhishek * * @param * @param */ public class ParserPool extends GenericObjectPool>{ /** * Constructor. * * It uses the default configuration for pool provided by * apache-commons-pool2. * * @param factory */ public ParserPool(PooledObjectFactory> factory) { super(factory); } /** * Constructor. * * This can be used to have full control over the pool using configuration * object. * * @param factory * @param config */ public ParserPool(PooledObjectFactory> factory, GenericObjectPoolConfig config) { super(factory, config); } } As we can see, the constructor of pool requires a factory to manage lifecycle of pooled objects. So we need to create a parser factory which can create parser objects. Commons pool provide generic interface for defining a factory(PooledObjectFactory). PooledObjectFactory create and manage PooledObjects . These object wrappers maintain object pooling state, enabling PooledObjectFactory methods to have access to data such as instance creation time or time of last use. A DefaultPooledObject is provided, with natural implementations for pooling state methods. The simplest way to implement a PoolableObjectFactory is to have it extend BasePooledObjectFactory . This factory provides a makeObject() that returns wrap(create()) where create and wrap are abstract. We provide an implementation of create to create the underlying objects that we want to manage in the pool and wrap to wrap created instances in PooledObjects. So, here is our factory implementation for parser objects- package blog.techcypher.parser.pool; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import blog.techcypher.parser.Parser; import blog.techcypher.parser.impl.XmlParser; /** * Factory to create parser object(s). * * @author abhishek * * @param * @param */ public class ParserFactory extends BasePooledObjectFactory> { @Override public Parser create() throws Exception { return new XmlParser(); } @Override public PooledObject> wrap(Parser parser) { return new DefaultPooledObject>(parser); } @Override public void passivateObject(PooledObject> parser) throws Exception { parser.getObject().reset(); } @Override public boolean validateObject(PooledObject> parser) { return parser.getObject().isValid(); } } Now, at this point we have successfully created our pool to store parser objects and we have a factory as well to manage the life-cycle of parser objects. You should notice that, we have implemented couple of extra methods- 1. boolean validateObject(PooledObject obj): This is used to validate an object borrowed from the pool or returned to the pool based on configuration. By default, validation remains off. Implementing this ensures that client will always get a valid object from the pool. 2. void passivateObject(PooledObject obj): This is used while returning an object back to pool. In the implementation we can reset the object state, so that the object behaves as good as a new object on another borrow. Since, we have everything in place, let’s create a test to test this pool. Pool clients can – 1. Get object by calling pool.borrowObject() 2. Return the object back to pool by calling pool.returnObject(object) Below is our code to test Parser Pool- package blog.techcypher.parser; import static org.junit.Assert.fail; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import junit.framework.Assert; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.Before; import org.junit.Test; import blog.techcypher.parser.pool.ParserFactory; import blog.techcypher.parser.pool.ParserPool; /** * Test case to test- * 1. object creation by factory * 2. object borrow from pool. * 3. returning object back to pool. * * @author abhishek * */ public class ParserFactoryTest { private ParserPool pool; private AtomicInteger count = new AtomicInteger(0); @Before public void setUp() throws Exception { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxIdle(1); config.setMaxTotal(1); /*---------------------------------------------------------------------+ |TestOnBorrow=true --> To ensure that we get a valid object from pool | |TestOnReturn=true --> To ensure that valid object is returned to pool | +---------------------------------------------------------------------*/ config.setTestOnBorrow(true); config.setTestOnReturn(true); pool = new ParserPool(new ParserFactory(), config); } @Test public void test() { try { int limit = 10; ExecutorService es = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(limit)); for (int i=0; i parser = null; try { parser = pool.borrowObject(); count.getAndIncrement(); parser.parse(null, null); } catch (Exception e) { e.printStackTrace(System.err); } finally { if (parser != null) { pool.returnObject(parser); } } } }; es.submit(r); } es.shutdown(); try { es.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException ignored) {} System.out.println("Pool Stats:\n Created:[" + pool.getCreatedCount() + "], Borrowed:[" + pool.getBorrowedCount() + "]"); Assert.assertEquals(limit, count.get()); Assert.assertEquals(count.get(), pool.getBorrowedCount()); Assert.assertEquals(1, pool.getCreatedCount()); } catch (Exception ex) { fail("Exception:" + ex); } } } Result: [pool-1-thread-1]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-2]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-3]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-4]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-5]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-8]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-7]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-9]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-6]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 [pool-1-thread-10]: Parser Instance:blog.techcypher.parser.impl.XmlParser@fcfa52 Pool Stats: Created:[1], Borrowed:[10] You can easily see that single parser object was created and reused dynamically. Commons Pool 2 stands far better in term of performance and scalability over Commons Pool 1. Also, version 2 includes robust instance tracking and pool monitoring. Commons Pool 2 requires JDK 1.6 or above. There are lots of configuration options to control and manage the life-cycle of pooled objects. And so ends our long post… :-) Hope this article helped. Keep learning!
April 14, 2014
by Abhishek Kumar
· 101,549 Views · 9 Likes
article thumbnail
How to Migrate from MySQL to MongoDB
In the last week I was working on a key project to migrate a BI platform from MySQL to MongoDB. We chose that database due to its support and scalability.
April 14, 2014
by Moshe Kaplan
· 115,881 Views · 6 Likes
article thumbnail
How JOIN Order Can Increase Performance in SQL Queries
Introduction All developers are very much concerned about performance. If someone say that this increase performance, all the developer are running behind it. It is not a bad practice at all. Rather as per my point of view we must span all our effort related improve the performance of query. “One common question that we find that, if we change the ordering of table join in case of inner join will effect or increase performance” To understand it lets take a simple example of Inner join. There is two tables named Table-A and Table-B. We can us the Inner Join on both the table. Like this FROM [Table-A] AS a INNER JOIN [Table-B] AS b ON a.IDNO = b.IDNO OR FROM [Table-B] AS a INNER JOIN [Table-A] AS b ON a.IDNO = b.IDNO Which one is best for performance? To answer this question we all know that whenever a SQL Query is executed the MS SQL server create several query plans with different join Order and choose the best one. That means the Join order that we are writing in the query may not be executed by execution plan. May be different join order is used by the execution plan. In the above case the execution plan decide which Join order he will chose depends on best possible costing of execution. Here [Table-A] JOIN [Table-B] or [Table-B] JOIN [Table-A], MS SQL Server knows it well that both are same. To understand it Details Lets take an Example Step-1 [ Create Base Table and Insert Some Records ] -- Item Master IF OBJECT_ID(N'dbo.tbl_ITEMDTLS', N'U')IS NOT NULL BEGIN DROP TABLE [dbo].[tbl_ITEMDTLS]; END GO CREATE TABLE [dbo].[tbl_ITEMDTLS] ( ITEMCD INT NOT NULL IDENTITY PRIMARY KEY, ITEMNAME VARCHAR(50) NOT NULL ) GO -- Inserting Records INSERT INTO [dbo].[tbl_ITEMDTLS] (ITEMNAME) VALUES ('ITEM-1'),('ITEM-2'),('ITEM-3'); -- Item UOM Master IF OBJECT_ID(N'dbo.tbl_UOMDTLS', N'U')IS NOT NULL BEGIN DROP TABLE [dbo].[tbl_UOMDTLS]; END GO CREATE TABLE [dbo].[tbl_UOMDTLS] ( UOMCD INT NOT NULL IDENTITY PRIMARY KEY, UOMNAME VARCHAR(50) NOT NULL ) GO -- Inserting Records INSERT INTO [dbo].[tbl_UOMDTLS] (UOMNAME) VALUES ('KG'),('LTR'),('GRM'); GO -- Transaction Table IF OBJECT_ID(N'dbo.tbl_SBILL', N'U')IS NOT NULL BEGIN DROP TABLE [dbo].[tbl_SBILL]; END GO CREATE TABLE [dbo].[tbl_SBILL] ( TRID INT NOT NULL IDENTITY PRIMARY KEY, ITEMCD INT NOT NULL, UOMCD INT NOT NULL, QTY DECIMAL(18,3) NOT NULL, RATE DECIMAL(18,2) NOT NULL, AMOUNT AS QTY * RATE ); GO -- Foreign Key Constraint ALTER TABLE [dbo].[tbl_SBILL] ADD CONSTRAINT FK_ITEM_tbl_SBILL FOREIGN KEY(ITEMCD) REFERENCES [dbo].[tbl_ITEMDTLS](ITEMCD); GO ALTER TABLE [dbo].[tbl_SBILL] ADD CONSTRAINT FK_UOMCD_tbl_SBILL FOREIGN KEY(UOMCD) REFERENCES [dbo].[tbl_UOMDTLS](UOMCD); -- Insert Records INSERT INTO [dbo].[tbl_SBILL] (ITEMCD, UOMCD, QTY, RATE) VALUES (1, 1, 20, 2000),(2, 3, 23, 1400); Step-2 [ Now Make Some JOIN ] SELECT b.TRID, b.ITEMCD, a.ITEMNAME, b.UOMCD, c.UOMNAME, b.QTY, b.RATE, b.AMOUNT FROM [dbo].[tbl_ITEMDTLS] AS a INNER JOIN [dbo].[tbl_SBILL] AS b ON a.ITEMCD = b.ITEMCD INNER JOIN [dbo].[tbl_UOMDTLS] AS c ON b.UOMCD = c.UOMCD; Here [tbl_ITEMDETAILS] JOIN [tbl_SALES] JOIN [tbl_UOMDETAILS] If we look at the Execution Plan We find that [tbl_SALES] JOIN [tbl_ITEMDETAILS] JOIN [tbl_UOMDETAILS] Step-2 [ Now we need to Force Order Hint to maintain Join Order ] SELECT b.TRID, b.ITEMCD, a.ITEMNAME, b.UOMCD, c.UOMNAME, b.QTY, b.RATE, b.AMOUNT FROM [dbo].[tbl_ITEMDTLS] AS a INNER JOIN [dbo].[tbl_SBILL] AS b ON a.ITEMCD = b.ITEMCD INNER JOIN [dbo].[tbl_UOMDTLS] AS c ON b.UOMCD = c.UOMCD OPTION ( QUERYRULEOFF JoinCommute); For this we need the FORCE ORDER Hint. The query optimizer uses different rules to evaluate different plan and one of the rules is called JoinCommute. We can turn it off using the undocumented query hint QUERYRULEOFF. Hope you like it.
April 14, 2014
by Joydeep Das
· 26,612 Views
article thumbnail
Be a Lazy But Productive Android Developer, Part 5: Image Loading Library
Welcome to part 5 of “Be a lazy but a productive android developer” series. If you are a lazy Android developer and looking for image loading library, which could help you to load image(s) asynchronously without writing a logic for downloading and caching images then this article is for you. This series so far: Part 1: We looked at RoboGuice, a dependency injection library by which we can reduce the boiler plate code, save time and there by achieve productivity during Android app development. Part 2: We saw and explored about Genymotion, which is a rocket speed emulator and super-fast emulator as compared to native emulator. And we can use Genymotion while developing apps and can quickly test apps and there by can achieve productivity. Part 3: We understood and explored about JSON Parsing libraries (GSON and Jackson), using which we can increase app performance, we can decrease boilerplate code and there by can optimize productivity. Part 4: We talked about Card UI and explored card library, also created a basic card and simple card list demo. In this part In this part, we are going to talk about some image libraries using which we can load image(s) asynchronously, can cache images and also can download images into the local storage. Required features for loading images Almost every android app has a need to load remote images. While loading remote images, we have to take care of below things: Image loading process must be done in background (i.e. asynchronously) to avoid blocking UI main thread. Image recycling image should be done. Image should be displayed once its loaded successfully. Images should be cached in local memory for the later use. If remote image gets failed (due to network connection or bad url or any other reasons) to load then it should be managed perfectly for avoiding duplicate requests to load the same again, instead it should load if and only if net connection is available. Memory management should be done efficiently. In short, we have to write a code to manage each and every aspects of image loading but there are some awesome libraries available, using which we can load/download image asynchronously. We just have to call the load image method and success/failure callbacks. Asynchronous image loading Consider a case where we are having 50 images and 50 titles and we try to load all the images/text into the listview, it won’t display anything until all the images get downloaded. Here Asynchronous image loading process comes in picture. Asynchronous image loading is nothing but a loading process which happens in background so that it doesn’t block main UI thread and let user to play with other loaded data on the screen. Images will be getting displayed as and when it gets downloaded from background threads. Asynchronous image loading libraries Nostra’s Universal Image loader – https://github.com/nostra13/Android-Universal-Image-Loader Picasso – http://square.github.io/picasso/ UrlImageViewHelper by Koush Volley - By Android team members @ Google Novoda’s Image loader – https://github.com/novoda/ImageLoader Let’s have a look at examples using Picasso and Universal Image loader libraries. Example 1: Nostra’s Universal Image loader Step 1: Initialize ImageLoader configuration ? public class MyApplication extends Application{ @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); // Create global configuration and initialize ImageLoader with this configuration ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).build(); ImageLoader.getInstance().init(config); } } Step 2: Declare application class inside Application tag in AndroidManifest.xml file ? Step 3: Load image and display into ImageView ? ImageLoader.getInstance().displayImage(objVideo.getThumb(), holder.imgVideo); Now, Universal Image loader also provides a functionality to implement success/failure callback to check whether image loading is failed or successful. ? ImageLoader.getInstance().displayImage(photoUrl, imgView, new ImageLoadingListener() { @Override public void onLoadingStarted(String arg0, View arg1) { // TODO Auto-generated method stub findViewById(R.id.EL3002).setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String arg0, View arg1, FailReason arg2) { // TODO Auto-generated method stub findViewById(R.id.EL3002).setVisibility(View.GONE); } @Override public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) { // TODO Auto-generated method stub findViewById(R.id.EL3002).setVisibility(View.GONE); } @Override public void onLoadingCancelled(String arg0, View arg1) { // TODO Auto-generated method stub findViewById(R.id.EL3002).setVisibility(View.GONE); } }); Example 2: Picasso Image loading straight way: ? Picasso.with(context).load("http://postimg.org/image/wjidfl5pd/").into(imageView); Image re-sizing: ? Picasso.with(context) .load(imageUrl) .resize(100, 100) .centerCrop() .into(imageView) Example 3: UrlImageViewHelper library It’s an android library that sets an ImageView’s contents from a url, manages image downloading, caching, and makes your coffee too. UrlImageViewHelper will automatically download and manage all the web images and ImageViews. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically. Image loading straight way: ? UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png"); Placeholder image when image is being downloaded: ? UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png", R.drawable.loadingPlaceHolder); Cache images for a minute only: ? UrlImageViewHelper.setUrlDrawable(imgView, "http://yourwebsite.com/image.png", null, 60000); Example 4: Volley library Yes Volley is a library developed and being managed by some android team members at Google, it was announced by Ficus Kirkpatrick during the last I/O. I wrote an article about Volley library 10 months back , read it and give it a try if you haven’t used it yet. Let’s look at an example of image loading using Volley. Step 1: Take a NetworkImageView inside your xml layout. ? Step 2: Define a ImageCache class Yes you are reading title perfectly, we have to define an ImageCache class for initializing ImageLoader object. ? public class BitmapLruCache extends LruCache implements ImageLoader.ImageCache { public BitmapLruCache() { this(getDefaultLruCacheSize()); } public BitmapLruCache(int sizeInKiloBytes) { super(sizeInKiloBytes); } @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight() / 1024; } @Override public Bitmap getBitmap(String url) { return get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { put(url, bitmap); } public static int getDefaultLruCacheSize() { final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int cacheSize = maxMemory / 8; return cacheSize; } } Step 3: Create an ImageLoader object and load image Create an ImageLoader object and initialize it with ImageCache object and RequestQueue object. ? ImageLoader.ImageCache imageCache = new BitmapLruCache(); ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), imageCache); Step 4: Load an image into ImageView ? NetworkImageView imgAvatar = (NetworkImageView) findViewById(R.id.imgDemo); imageView.setImageUrl(url, imageLoader); Which library to use? Can you decide which library you would use? Let us know which and what are the reasons? Selection of the library is always depends on the requirement. Let’s look at the few fact points about each library so that you would able to compare exactly and can take decision. Picasso: It’s just a one liner code to load image using Picasso. No need to initialize ImageLoader and to prepare a singleton instance of image loader. Picasso allows you to specify exact target image size. It’s useful when you have memory pressure or performance issues, you can trade off some image quality for speed. Picasso doesn’t provide a way to prepare and store thumbnails of local images. Sometimes you need to check image loading process is in which state, loading, finished execution, failed or cancelled image loading. Surprisingly It doesn’t provide a callback functionality to check any state. “fetch()” dose not pass back anything. “get()” is for synchronously read, and “load()” is for asynchronously draw a view. Universal Image loader (UIL): It’s the most popular image loading library out there. Actually, it’s based on the Fedor Vlasov’s project which was again probably a very first complete solution and also a most voted answer (for the image loading solution) on Stackoverflow. UIL library is better in documentation and even there’s a demo example which highlights almost all the features. UIL provides an easy way to download image. UIL uses builders for customization. Almost everything can be configured. UIL doesn’t not provide a way to specify image size directly you want to load into a view. It uses some rules based on the size of the view. Indirectly you can do it by mentioning ImageSize argument in the source code and bypass the view size checking. It’s not as flexible as Picasso. Volley: It’s officially by Android dev team, Google but still it’s not documented. It’s just not an image loading library only but an asynchronous networking library Developer has to define ImageCache class their self and has to initialize ImageLoader object with RequestQueue and ImageCache objects. So now I am sure now you can be able to compare libraries. Choosing library is a bit difficult talk because it always depends on the requirement and type of projects. If the project is large then you should go for Picasso or Universal Image loader. If the project is small then you can consider to use Volley librar, because Volley isn’t an image loading library only but it tries to solve a more generic solution.). I suggest you to start with Picasso. If you want more control and customization, go for UIL. Read more: http://blog.bignerdranch.com/3177-solving-the-android-image-loading-problem-volley-vs-picasso/ http://stackoverflow.com/questions/19995007/local-image-caching-solution-for-android-square-picasso-vs-universal-image-load https://plus.google.com/103583939320326217147/posts/bfAFC5YZ3mq Hope you liked this part of “Lazy android developer: Be productive” series. Till the next part, keep exploring image loading libraries mentioned above and enjoy!
April 11, 2014
by Paresh Mayani
· 63,991 Views · 2 Likes
article thumbnail
Visualizing SQL Statements
Usually if I concentrate I am able to understand most SQL statements. There are times though such as: When a set of tables is not familiar When I did not write the SQL statement When the SQL statement is long and involves many tables and joins When I want to discuss a statement with a colleague All of the above Having a visual representation of a SQL statement can be helpful in deciphering the statement. My visualisation tool of choice for SQL is an Open Source application called Reverse Snowflake Joins (REVJ). As the name implies, this tool shines when it comes to showing you how your tables are related. I have installed the tool on my workstation but when I am on the move I use the online version of the tool. Using the tool is straight forward, simply paste your SQL statement in the text area and generate the diagram, the online version generates an SVG image. I have at times found that the tool struggles with complex CASE statements. In such cases I remove the CASE statement and just include the fields used in the case statement. Below is a sample statement to show REVJ at work. SELECT a.prod_cat_name ,b.prod_name ,c.prod_owner_name ,p.promo_id ,pt.promo_type ,sum(s.units) as total_units ,sum(s.sale_price) as total_sale_price ,sum(prev_s.units) as prev_yr_total_units FROM product_category a JOIN product b ON a.product_cat_id = b.product_cat_id LEFT OUTER JOIN product_owner c ON a.product_cat_id = c.product_cat_id JOIN sales s ON b.product_id = s.product_id JOIN sales prev_s ON s.sale_year = prev_s.sale_year-1 LEFT OUTER JOIN promotion p ON s.promo_id = p.promo_id RIGHT OUTER JOIN promo_type pt ON p.promo_type_id = pt.promo_type_id WHERE pt.promo_type IN ('Email', 'TV') AND a.prod_cat_name = 'Electronics' AND s.sale_year >=2013 GROUP BY a.prod_cat_name ,b.prod_name ,c.prod_owner_name ,p.promo_id ,pt.promo_type HAVING sum(s.units)>100 The generated image shown below. Notice how the filters applied to each table are also shown, further simplifying the task of understanding the SQL statement. For more complex examples have a look at big samples page.
April 7, 2014
by Mpumelelo Msimanga
· 18,786 Views
article thumbnail
Groovy Goodness: Converting Byte Array to Hex String
To convert a byte[] array to a String we can simply use the new String(byte[]) constructor. But if the array contains non-printable bytes we don't get a good representation. In Groovy we can use the method encodeHex() to transform a byte[] array to a hex String value. The byteelements are converted to their hexadecimal equivalents. final byte[] printable = [109, 114, 104, 97, 107, 105] // array with non-printable bytes 6, 27 (ACK, ESC) final byte[] nonprintable = [109, 114, 6, 27, 104, 97, 107, 105] assert new String(printable) == 'mrhaki' assert new String(nonprintable) != 'mr haki' // encodeHex() returns a Writable final Writable printableHex = printable.encodeHex() assert printableHex.toString() == '6d7268616b69' final nonprintableHex = nonprintable.encodeHex().toString() assert nonprintableHex == '6d72061b68616b69' // Convert back assert nonprintableHex.decodeHex() == nonprintable Code written with Groovy 2.2.1
April 6, 2014
by Hubert Klein Ikkink
· 14,465 Views · 5 Likes
article thumbnail
Compiling and Running Java Without an IDE
I’m going to start by discussing the Spring WebMVC configuration to compile and run Java without an IDE.
April 4, 2014
by Dustin Marx
· 60,563 Views · 10 Likes
article thumbnail
Common Misconceptions About Java
Java is the most widely used language in the world ([citation needed]), and everyone has an opinion about it. Due to it being mainstream, it is usually mocked, and sometimes rightly so, but sometimes the criticism just doesn’t touch reality. I’ll try to explain my favorite 5 misconceptions about Java. Java is slow – that might have been true for Java 1.0, and initially may sounds logical, since java is not compiled to binary, but to bytecode, which is in turn interpreted. However, modern versions of the JVM are very, very optimized (JVM optimizations is a topic worth not just an article, but a whole book) and this is no longer remotely true. As noted here, Java is even on-par with C++ in some cases. And it is certainly not a good idea to make a joke about Java being slow if you are a Ruby or PHP developer. Java is too verbose – here we need to split the language from the SDK and from other libraries. There is some verbosity in the JDK (e.g. java.io), which is: 1. easily overcome with de-facto standard libraries like guava 2. a good thing As for language verbosity, the only reasonable point were anonymous classes. Which are no longer an issue in Java 8 with the the functional additions. Getters and setters, Foo foo = new Foo() instead of using val – that is (possibly) boilerplate, but it’s not verbose – it doesn’t add conceptual weight to the code. It doesn’t take more time to write, read or understand. Other libraries – it is indeed pretty scary to see a class like AbstractCommonAsyncFacadeFactoryManagerImpl. But that has nothing to do with Java. It can be argued that sometimes these long names make sense, it can also be argued that they are as complex because the underlying abstraction is unnecessarily complicated, but either way, it is a design decision taken per-library, and nothing that the language or the SDK impose per-se. It is common to see overengineered stuff, but Java in no way pushes you in that direction – stuff can be done in a simple way with any language. You can certainly have AbstractCommonAsyncFacadeFactoryManagerImpl in Ruby, just there wasn’t a stupid architect that thought it’s a good idea and who uses Ruby. If “big, serious, heavy” companies were using Ruby, I bet we’d see the same. Enterprise Java frameworks are bloatware – that was certainly true back in 2002 when EJB 2 was in use (or “has been”, I’m too young to remember). And there are still some overengineered and bloated application servers that you don’t really need. The fact that people are using them is their own problem. You can have a perfectly nice, readable, easy to configure and deploy web application with a framework like Spring, Guice or even CDI; with a web framework like Spring-MVC, Play, Wicket, and even the latest JSF. Or even without any framework, if you feel like you don’t want to reuse the evolved-through-real-world-use frameworks. You can have an application using a message queue, a NoSQL and a SQL database, Amazon S3 file storage, and whatnot, without any accidental complexity. It’s true that people still like to overeingineer stuff, and add a couple of layers where they are not needed, but the fact that frameworks give you this ability doesn’t mean they make you do it. For example, here’s an application that crawls government documents, indexes them, and provides a UI for searching and subscribing. Sounds sort-of simple, and it is. It is written in Scala (in a very java way), but uses only java frameworks – spring, spring-mvc, lucene, jackson, guava. I guess you can start maintaining pretty fast, because it is straightforward. You can’t prototype quickly with Java – this is sort-of related to the previous point – it is assumed that working with Java is slow, and that’s why if you are a startup, or a weekend/hackathon project, you should use Ruby (with Rails), Python, Node JS or anything else that allows you to quickly prototype, to save & refresh, to painlessly iterate. Well, that is simply not true, and I don’t know even where it comes from. Maybe from the fact that big companies with heavy processes use Java, and so making a java app is taking more time. And Save-and-Refresh might look daunting to a beginner, but anyone who has programmed in Java (for the web) for a while, has to know a way to automate that (otherwise he’s a n00b, right?). I’ve summarized the possible approaches, and all of them are mostly OK. Another example here (which may be used as an example for the above point as well) – I made did this project for verifying secure password storage of websites within a weekend + 1 day to fix stuff in the evening. Including the security research. Spring-MVC, JSP templates, MongoDB. Again – quick and easy. You can do nothing in Java without an IDE – of course you can – you can use notepad++, vim, emacs. You will just lack refactoring, compile-on-save, call hierarchies. It would be just like programming in PHP or Python or javascript. The IDE vs Editor debate is a long one, but you can use Java without an IDE. It just doesn’t make sense to do so, because you get so much more from the IDE than from a text editor + command line tools. You may argue that I’m able to write nice and simple java applications quickly because I have a lot of experience, I know precisely which tools to use (and which not) and that I’m of some rare breed of developers with common sense. And while I’ll be flattered by that, I am no different than the good Ruby developer or the Python guru you may be. It’s just that java is too widespread to have only good developers and tools. if so many people were using other language, then probably the same amount of crappy code would’ve been generated. (And PHP is already way ahead even with less usage). I’m the last person not to laugh on jokes about Java, and it certainly isn’t the silver bullet language, but I’d be happier if people had less misconceptions either because of anecdotal evidence, or due to previous bad experience a-la “I hate Java since my previous company where the project was very bloated”. Not only because I don’t like people being biased, but because you may start your next project with a language that will not work, just because you’ve heard “Java is bad”.
April 4, 2014
by Bozhidar Bozhanov
· 22,060 Views · 1 Like
  • Previous
  • ...
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • ...
  • 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
×