Featured FREE Whitepapers

What's New Here?

jboss-hibernate-logo

A beginner’s guide to Hibernate Types

The basic mapping concepts When learning Hibernate many like to jump to parent-child associations without mastering the object relation mapping basics. It’s very important to understand the basic mapping rules for individual Entities before starting modelling Entity associations. Hibernate types A Hibernate type is a bridge between an SQL type and a Java primitive/Object type.   These are the types Hibernate supports by default:Hibernate type (org.hibernate.type) JDBC type Java typeStringType VARCHAR StringMaterializedClob CLOB StringTextType LONGVARCHAR StringCharacterType CHAR char or CharacterBooleanType BIT boolean or BooleanNumericBooleanType INTEGER (e.g. 0 = false and 1 = true) boolean or BooleanYesNoType CHAR (e.g. ‘N’ or ‘n’ = false and ‘Y’ or ‘y’ = true) boolean or BooleanTrueFalseType CHAR (e.g. ‘F’ or ‘f’ = false and ‘T’ or ‘t’ = true) boolean or BooleanByteType TINYINT byte or ByteShortType SMALLINT short or ShortIntegerType INTEGER int or IntegerLongType BIGINT long or LongFloatType FLOAT float or FloatDoubleType DOUBLE double or DoubleBigIntegerType NUMERIC BigIntegerBigDecimalType NUMERIC BigDecimalTimestampType TIMESTAMP java.sql.Timestamp or java.util.DateTimeType TIME java.sql.TimeDateType DATE java.sql.DateCalendarType TIMESTAMP java.util.Calendar or java.util.GregorianCalendarCalendarType DATE java.util.Calendar or java.util.GregorianCalendarCurrencyType VARCHAR java.util.CurrencyLocaleType VARCHAR java.util.LocaleTimeZoneType VARCHAR java.util.TimeZoneUrlType VARCHAR java.net.URLClassType VARCHAR java.lang.ClassBlobType BLOB java.sql.BlobClobType CLOB java.sql.ClobBinaryType VARBINARY byte[] or Byte[]BinaryType BLOB byte[] or Byte[]BinaryType LONGVARBINARY byte[] or Byte[]BinaryType LONGVARBINARY byte[] or Byte[]CharArrayType VARCHAR char[] or Character[]UUIDBinaryType BINARY java.util.UUIDUUIDBinaryType CHAR or VARCHAR java.util.UUIDUUIDBinaryType PostgreSQL UUID java.util.UUIDSerializableType VARBINARY SerializableYou can always define your own custom types as we will see in a future article. Embedded (a.k.a Component) Types You can group multiple columns to a specific Java type that can be reused throughout your domain model. If the mapped Java object is always dependent on some external Entity you can choose an Embeddable type for such domain model mapping. An Embeddable object may contain both basic types and association mappings but it can never contain an @Id. The Embeddable object is persisted/removed along with its owning entity. Assuming we have the following SQL table: CREATE TABLE entity_event ( id BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1), entity_class VARCHAR(255), entity_id BIGINT, message VARCHAR(255), PRIMARY KEY (id) ); We could group the entity_class and entity_id to an Embeddable object that we’ll employ in two different owning Entities. The Embeddable object looks like this: @Embeddable public class EntityIdentifier implements Serializable {@Column(name = "entity_id", nullable = true) private Long entityId;@Column(name = "entity_class", nullable = true) private Class entityClass;public EntityIdentifier() { }public EntityIdentifier(Class entityClass, Long entityId) { this.entityClass = entityClass; this.entityId = entityId; }public Class getEntityClass() { return entityClass; }public void setEntityClass(Class entityClass) { this.entityClass = entityClass; }public Long getEntityId() { return entityId; }public void setEntityId(Long entityId) { this.entityId = entityId; } } The associated Entity table will inherit the Embeddable properties associated columns. Entity An Entity is the Java equivalent of an SQL table row. The entity must contain an @Id property mapping the associated table Primary Key. The application logic makes changes to Entities properties and notifies the Persistence Context of Entity state changes (persist, merge, remove). The persistence context will therefore translate all Entity changes to SQL statements. Assuming we have the following SQL tables: CREATE TABLE entity_attribute ( id BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1), entity_class VARCHAR(255), entity_id BIGINT, name VARCHAR(255), VALUE VARCHAR(255), PRIMARY KEY (id) ); CREATE TABLE entity_event ( id BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1), entity_class VARCHAR(255), entity_id BIGINT, message VARCHAR(255), PRIMARY KEY (id) ); We can make use of the EntityIdentifier Embeddable type since both tables contain the entity_class and entity_id columns. @Entity @Table(name = "entity_attribute") public class EntityAttribute {@Id @GeneratedValue private Long id;private String name;private String value;private EntityIdentifier entityIdentifier;public Long getId() { return id; }public String getName() { return name; }public void setName(String name) { this.name = name; }public String getValue() { return value; }public void setValue(String value) { this.value = value; }public EntityIdentifier getEntityIdentifier() { return entityIdentifier; }public void setEntityIdentifier(EntityIdentifier entityIdentifier) { this.entityIdentifier = entityIdentifier; } }@Entity @Table(name = "entity_event") public class EntityEvent {@Id @GeneratedValue private Long id;private String message;private EntityIdentifier entityIdentifier;public Long getId() { return id; }public String getMessage() { return message; }public void setMessage(String message) { this.message = message; }public EntityIdentifier getEntityIdentifier() { return entityIdentifier; }public void setEntityIdentifier(EntityIdentifier entityIdentifier) { this.entityIdentifier = entityIdentifier; } } Testing time We will create one EntityEvent and one EntityAttribute for a given Product to see how the Embeddable is being persisted along with the owning entities: @Test public void testEntityIdentifier() { doInTransaction(new TransactionCallable<Void>() { @Override public Void execute(Session session) { Product product = new Product("LCD"); session.persist(product); EntityEvent productEvent = new EntityEvent(); productEvent.setMessage(String.format("Product %s added", product.getName())); productEvent.setEntityIdentifier(new EntityIdentifier( product.getClass(), product.getId() )); session.persist(productEvent); EntityAttribute productAttribute = new EntityAttribute(); productAttribute.setName("AD_CAMPAIGN"); productAttribute.setValue("LCD_Sales"); productAttribute.setEntityIdentifier(new EntityIdentifier( product.getClass(), product.getId() )); session.persist(productAttribute); assertSame(1, session.createQuery("select ea from EntityAttribute ea where ea.entityIdentifier = :entityIdentifier") .setParameter("entityIdentifier", new EntityIdentifier(product.getClass(), product.getId())) .list().size()); return null; } }); } Query:{[ INSERT INTO product (id, name) VALUES (DEFAULT, ?) ][LCD]}Query:{[ INSERT INTO entity_event (id, entity_class, entity_id, message) VALUES (DEFAULT, ?, ?, ?) ][com.vladmihalcea.hibernate.masterclass.laboratory.entityidentifier.Product,1,Product LCD added]}Query:{[ INSERT INTO entity_attribute (id, entity_class, entity_id, name, VALUE) VALUES (DEFAULT, ?, ?, ?, ?) ][com.vladmihalcea.hibernate.masterclass.laboratory.entityidentifier.Product,1,AD_CAMPAIGN,LCD_Sales]}Query:{[ SELECT entityattr0_.id AS id1_0_, entityattr0_.entity_class AS entity_c2_0_, entityattr0_.entity_id AS entity_i3_0_, entityattr0_.name AS name4_0_, entityattr0_.VALUE AS value5_0_ FROM entity_attribute entityattr0_ WHERE entityattr0_.entity_class = ? AND entityattr0_.entity_id = ? ][com.vladmihalcea.hibernate.masterclass.laboratory.entityidentifier.Product,1]} Conclusion There are still many concepts we need to cover before getting to understand Entity associations. You should always take your time to understand the basic concepts before jumping to more advanced topics. My next post will be about Entity Identifiers and all the available generator techniques.Code available on GitHub.Reference: A beginner’s guide to Hibernate Types from our JCG partner Vlad Mihalcea at the Vlad Mihalcea’s Blog blog....
java-logo

Listing a ZIP file contents with Stream API in Java 8

In Java 8 java.util.zip.ZipFile was equipped with a stream method that allows navigating over a ZIP file entries very easily. In this blog post I will show a bunch of examples showing how quickly we can navigate over ZIP file entries. Note: For the purpose of this blog post I downloaded one of my GitHub repositories as a ZIP file and I copied it to c:/tmp. Prior to Java 7 Reading ZIP file entries in Java prior to Java 7 is a kind of hmm… tricky? This is how one can start hating Java while looking at this code: public class Zipper { public void printEntries(PrintStream stream, String zip) { ZipFile zipFile = null; try { zipFile = new ZipFile(zip); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); stream.println(zipEntry.getName()); } } catch (IOException e) { // error while opening a ZIP file } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // do something } } } } } Java 7 With Java 7 the same can be much simpler – thanks to try-with-resources but we are still “forced” to use Enumeration in order to navigate over ZIP file entries: public class Zipper { public void printEntries(PrintStream stream, String zip) { try (ZipFile zipFile = new ZipFile(zip)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); stream.println(zipEntry.getName()); } } catch (IOException e) { // error while opening a ZIP file } } } Using Stream API The real fun starts with Java 8. As of Java 8 java.util.zip.ZipFile has a new method stream that returns an ordered stream over the ZIP file entries. This gives many opportunities while working with ZIP files in Java. Previous examples can be simply written as follows in Java 8: public class Zipper { public void printEntries(PrintStream stream, String zip) { try (ZipFile zipFile = new ZipFile(zip)) { zipFile.stream() .forEach(stream::println); } catch (IOException e) { // error while opening a ZIP file } } } With Stream API we can play with the ZipFile in many ways. See below… Filtering and sorting ZIP file contents public void printEntries(PrintStream stream, String zip) { try (ZipFile zipFile = new ZipFile(zip)) { Predicate<ZipEntry> isFile = ze -> !ze.isDirectory(); Predicate<ZipEntry> isJava = ze -> ze.getName().matches(".*java"); Comparator<ZipEntry> bySize = (ze1, ze2) -> Long.valueOf(ze2.getSize() - ze1.getSize()).intValue(); zipFile.stream() .filter(isFile.and(isJava)) .sorted(bySize) .forEach(ze -> print(stream, ze)); } catch (IOException e) { // error while opening a ZIP file } }private void print(PrintStream stream, ZipEntry zipEntry) { stream.println(zipEntry.getName() + ", size = " + zipEntry.getSize()); } While iterating over ZIP entries, I check if the entry is a file and if it matches a given name (harcoded in this example, for sake of simlicity) and then I sort it by size using a given comparator. Create files index of a ZIP file In this example I group ZIP entries by first letter of a file name to create Map<String, List<ZipEntry>> index. The expected result should look similar to the below one: a = [someFile/starting/with/an/A] u = [someFile/starting/with/an/U, someOtherFile/starting/with/an/U] Again, with Stream API it is really easy: public void printEntries(PrintStream stream, String zip) { try (ZipFile zipFile = new ZipFile(zip)) { Predicate<ZipEntry> isFile = ze -> !ze.isDirectory(); Predicate<ZipEntry> isJava = ze -> ze.getName().matches(".*java"); Comparator<ZipEntry> bySize = (ze1, ze2) -> Long.valueOf(ze2.getSize()).compareTo(Long.valueOf(ze1.getSize()));Map<String, List<ZipEntry>> result = zipFile.stream() .filter(isFile.and(isJava)) .sorted(bySize) .collect(groupingBy(this::fileIndex));result.entrySet().stream().forEach(stream::println);} catch (IOException e) { // error while opening a ZIP file } }private String fileIndex(ZipEntry zipEntry) { Path path = Paths.get(zipEntry.getName()); Path fileName = path.getFileName(); return fileName.toString().substring(0, 1).toLowerCase(); } Find a text within a ZIP file entry In the last example, I search for a @Test text occurrence in all files with java extension. This time I will utilize BufferedReader’s lines method that returns a stream of lines. public void printEntries(PrintStream stream, String zip) {try (ZipFile zipFile = new ZipFile(zip)) { Predicate<ZipEntry> isFile = ze -> !ze.isDirectory(); Predicate<ZipEntry> isJava = ze -> ze.getName().matches(".*java");List<ZipEntry> result = zipFile.stream() .filter(isFile.and(isJava)) .filter(ze -> containsText(zipFile, ze, "@Test")) .collect(Collectors.toList());result.forEach(stream::println);} catch (IOException e) { // error while opening a ZIP file } }private boolean containsText(ZipFile zipFile, ZipEntry zipEntry, String needle) { try (InputStream inputStream = zipFile.getInputStream(zipEntry); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {Optional<String> found = reader.lines() .filter(l -> l.contains(needle)) .findFirst();return found.isPresent();} catch (IOException e) { return false; } } Summary Stream API in Java 8 is kind a powerful solution that helps in solving relatively easy tasks easily. And that’s its power, in my opinion. The examples presented in this article are relatively simple and they were created for visualization purpose only. But I hope you like them and find them useful. Resourceshttp://docs.oracle.com/javase/tutorial/index.htmlReference: Listing a ZIP file contents with Stream API in Java 8 from our JCG partner Rafal Borowiec at the Codeleak.pl blog....
android-logo

15+ Useful Robotium Code Snippets for Android Test Automation

Robotium is a powerful android test automation framework. It can be used to create robust apps using unit, functional & automatic black box UI test cases. When I first looked at Robotium, it sounded almost like Selenium (for web application). Though the names are similar, they are not related. Robotium is developed by different developer group. I have tried several android testing libraries (http://www.javacodegeeks.com/2011/06/android-dependency-injection-testing.html ) and was not able to fully accomplish my app testing requirements. After few months of coding in Robotium, I realized that its a good candidate to be a part of android and jenkins continuous integration environment – http://www.javacodegeeks.com/2012/09/android-and-jenkins-continuous.html In past few weeks, I started exploring more in depth features of Robotium and started liking it. I have been a selenium (web driver) lover and had collected a handful of code snippets for web driver (Proved handy for cheating code :) ) . Therefore I decided to do the same for Robotium as well. I used it for a real app testing and collected a few commonly used code snippets that may prove helpful for other beginners including me. Below are some commonly used code snippets for testing using robotium framework. Take a Screenshot Taking snapshot of any android screen is easy using takeScreenshot method. solo.takeScreenshot() The takeScreenshot() method saves the picture in “/sdcard/Robotium-Screenshots/” folder on device. This will require write permission (android.permission.WRITE_EXTERNAL_STORAGE) in the AndroidManifest.xml of the application being tested. Check If a Button Element Exists Often its required to check if a button appears on the screen. We may want to do further action once the button is found. This can be achieved by searchButton method. solo.searchButton("My Beautiful Button", true ) Notice that button text is provided as first parameter, and second parameter indicates that method will return button object that is visible. You may want to set it false if you want to check for not visible buttons too. Running Same Test cases on Two Different Devices Testing android apps on multiple devices is a common need. Though there is nothing special required from robotium side you can use a adb command option to run it on specific device. The -s flag in adb command can be used to point to a specific device. When you want to run on two devices you can open two terminals and run the command pointing to two different devices. This will run the test cases in both devices in parallel. Lets say We want to run two different test cases on 2 connected android devices. Below command should list out both devices adb devices Command output List of devices attached SER1   device1 SER2   device2 then using the serial numbers shown in command output above we can run below command: adb -s SER1 shell am instrument -w -e class com.test.Test1 com.test/android.test.InstrumentationTestRunneradb -s SERIALOFDEVICE2 shell am instrument -w -e class com.test.Test2 com.test/android.test.InstrumentationTestRunner where com.test.Test1 com.test.Test2 Are the test classes we want to run on each device. How to Simulate a Long Press on Screen Robotium Long press can be done using clickLongOnScreen method that accept two parameters for location (x,y) on the screen. Example solo.clickLongOnScreen(10, 15);If you are not sure about x,y coordinates on device screen below picture may be useful How to Maintain the order of Robotium Test Cases If you want to execute test cases in specific order than you can use test suites. Simple example is shown below. public static final MyTest suite() { TestSuite testSt = new TestSuite(); testSt.addTest(new SampleTestCase("one")); testSt.addTest(new SampleTestCase("two"));return testSuite; } Wait for activity to finish Waiting for an activity to finish may be required in few test cases. You may want to perform test actions after an activity is finished. waitForActivity method can be used to accomplish this. solo.waitForActivity(solo.getCurrentActivity().toString()); Wait for toast to apear There is no direct method for wait for toast, however you can use a workaround by waiting for text (that is inside the toast) to appear solo.waitForText("Some text inside toast"); Wait for view to disappear There is no direct method to wait for a view to disappear, however you can use a workaround by waiting on condition for a field to become invisible. Lets say we have a text view. We can use below code snippet to wait on the textField to become invisible. TextView textField = solo.getText("My Text Value", true); solo.waitForCondition(new Condition() { @Override public boolean isSatisfied() { return textField.getVisibility() == View.INVISIBLE; } }, 1000); Notice that we have used a anonymous class implementation here. You can always create a class for the same in case you use this code snippet often. Conditional Wait – just like above example we can specify custom conditions on the wait method that proves really helpful for custom programmable wait configuration. Below is the signature of wait for condition method. It also has a timeout field that can be your upper limit on wait time for condition. solo.waitForCondition(Condition condition, int timeout); Wait for fragment Waiting for fragment is a supported method in robotium. Just need to call the waitForFragmentByTag method solo.waitForFragmentByTag("MyTag"); Above code snippet waits for a fragment matching the specified tag (MyTag). solo.waitForFragmentByTag("MyTag", 100); Above code snippet will wait for a fragment up to 100ms and continue execution. How to validate a text value in text view TextView textV = solo.getText("My Expected Value");// if textV is not null than may be we do not need next line.assertEquals("My Expected Value", textV.getText().toString()); How to Hide soft keyboard Hiding soft keyboard is a common need and robotium has a method for that too.Simple calling hideSoftKeyboard method hides the soft keyboard. solo.hideSoftKeyboard(); How to navigate back Going back to previous screen is easy with robotium. Just use the back() method. solo.goBack(); How to check sufficient memory is available on device There is a dedicated method to validate if the memory available is not considered low by android system solo.assertMemoryNotLow(); How to Clear the log file using robotium api Clearing the log file using robotium clearLog method is really helpful specially when you have long running test cases and huge log files eating device memory. solo.clearLog(); How to delete text from a editable text field You can clear the text from EditText field using below code solo.clearEditText(editText object); How overwrite update/enter text in a editable text field Below method call will overwrite the existing content of EditField solo.enterText(editText, "new value on field"); How append text in a editable text field There is no dedicated method for appending text to EditText field therefore you may need to do it by extracting old value and appending new value to it. solo.enterText(editText, editText.getText() + "new value on field"); How to set date in a date picker object We can use setDatePicker method for setting specific dates on app using robotium solo.setDatePicker(datePicker, 2014, 1, 5) Sets the date (April 1st 2014) in the specified DatePicker. Summary My application test cases were mostly focused on native android apps, therefore these code snippets are more useful for native apps. I am sure the hybrid applications may have similar feature too. Feel free to suggest more snippets and it can become a really handy resource. I hope you found this post useful, don’t forget to share or bookmark this page. If you enjoyed this, then subscribe to our newsletter to enjoy weekly updates and complimentary whitepapers! Also, check out JCG Academy for more advanced training! References: Official Website: http://code.google.com/p/robotium/ FAQs I recommend you to browse thru the FAQs pages before posting a question on any forum:http://code.google.com/p/robotium/wiki/QuestionsAndAnswers http://stackoverflow.com/questions/tagged/robotium?sort=frequent&pageSize=15Forums Official Discussion forum to ask questions related to robotium:https://groups.google.com/forum/#!forum/robotium-developers Stackoverflow is also a good place to get answers about robotium related queries – http://stackoverflow.com/questions/tagged/robotium ....
akka-logo

Handle Every Event in Your Akka Application

Event here, event there, events flying everywhere. Post about checking that every Akka event will finally find its home. Akka and reactive, event-based applications are new approach to creating software. We are using Akka pretty intensively in our current Scala-based project. Events fit our use cases especially well as we are communicating with external API which might be slow. This could damage user experience when handled using traditional synchronous approach. But luckily, our requests can be performed asynchronously so passing them to Actor seemed a good idea. When things get ouf of control But while being cool and very useful, events can still hurt project when handled by inexperienced hands. Asynchronous nature makes application flow hard to understand at first glance. And each time you add a new actor or event type to your system, probability that you will forget to handle something properly increases. Let’s look at the example class, this is an actor handling events associated with Image tags and comments: class YourActor extends Actor { override def receive = { case event: ImageTagged => doSomething() case event: OtherImageTaggedByFriend => doSomething2() case event: MostMotedUserImage => doSomething3() case event: MostCommentedFriendImageChosen => doSomething4() } } and when you add next event, let’s say MostLikedFriendImage you can easily forget to add handler case section in actor, especially if there is more than one actor listening for this type of event. DRY violating solution There is one simple solution that will allow to detect forgotten handlers. We can add case _ to each actor: class YourActor extends Actor { override def receive = { case event: ImageTagged => doSomething() case event: OtherImageTaggedByFriend => doSomething2() case event: MostMotedUserImage => doSomething3() case event: MostCommentedFriendImageChosen => doSomething4() case event: _ : logger.error("Received unknown event " + event.getClass.toString) } } And while it looks pretty ok for one or two actors, adding same code fragment to multiple actors is troublesome and violates DRY principle. But, what is most dangerous, someone in your team could forget to add it (as someone said “Every manual task that can be forgotten, will be forgotten”). So maybe we should pursue better solution? React on ANY unhandled eventLuckily, we are not stuck with our error-prone approach. When actor can not handle event that was passed to him UnhandledMessage is raised and published to ActorSystem’s EventStream. So to handle every forgotten event we could create listener and subscribe it to EventStream: class UnhandledMessageListener extends Actor {val logger = LoggerFactory.getLogger(getClass)override def receive = { case message: UnhandledMessage => logger.error(s"CRITICAL! No actors found for message ${message.getMessage}"))if (!Environment.isProduction) { // Fail fast, fail LOUD logger.error("Shutting application down") System.exit(-1) } } } And subscribing code fragment: val actorSystem = ActorSystem.create("projectActorSystem")val listener = actorSystem.actorOf(Props(new UnhandledMessageListener())) actorSystem.eventStream.subscribe(listener, classOf[UnhandledMessage]) and that’s it. Now every time there is an event that wasn’t handled by actor, we will know about it, especially when application is deployed in a non-production environment!Reference: Handle Every Event in Your Akka Application from our JCG partner Tomasz Dziurko at the Code Hard Go Pro blog....
java-logo

Code4ReferenceList Recently Used(LRU) implementation using LinkedHashMap

Recently I stumbled on one of the Java interview questions: “Implement List-Recently-Used (LRU) Cache using Java collection class?” If you have worked on a similar problem before, then it is really easy for you. Otherwise you start thinking about the best collection class to implement LRU cache. Most of the people fail to recognize that LinkedHashMap provides the support and can be used off-the-self with minimal code.   What is Least Recently Used (LRU) Cache If you know this concept, then skip to the implementation section. There are different algorithms used in Cache item eviction. The most popular one is the Least-Recently-Used. Cache always has limited memory and can contain only limited number of items. It uses an algorithm to detect and evict items which are not worthy to keep. Studies suggest that new items are mostly likely to get accessed soon as compared to older items. LRU is based on this observation. The algorithm keeps tracks of the items’ last accessed time. It evicts the items which have oldest access timestamp. LRU Cache Implementation LinkedHashMap is really helpful where you want to implement the LRU Cache. Even Sun Java framework uses this class to implement com.sun.tdk.signaturetest.util.LRUCache and sun.security.ssl.X509KeyManagerImpl.SizedMap. For the implementation, removeEldestEntry() method should be overridden. This method gets called after put() and putAll(). Based on its return value Map removes the old entry. If this method returns true, then old entry is removed. Otherwise it can stay in the Map. The default implementation of this method returns false. In this case the old entries remain in the Map and never get deleted; It just acts as general Map collection class. In most of the implementations this method returns true, if the number of entries in the map is greater than initial capacity. package code4reference.test;import java.util.LinkedHashMap; import java.util.Map;public class LRUCacheImpl extends LinkedHashMap<Integer, String> { private static final long serialVersionUID = 1L; private int capacity; public LRUCacheImpl(int capacity, float loadFactor){ super(capacity, loadFactor, true); this.capacity = capacity; } /** * removeEldestEntry() should be overridden by the user, otherwise it will not * remove the oldest object from the Map. */ @Override protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest){ return size() > this.capacity; } public static void main(String arg[]){ LRUCacheImpl lruCache = new LRUCacheImpl(4, 0.75f); lruCache.put(1, "Object1"); lruCache.put(2, "Object2"); lruCache.put(3, "Object3"); lruCache.get(1); lruCache.put(4, "Object4"); System.out.println(lruCache); lruCache.put(5, "Object5"); lruCache.get(3); lruCache.put(6, "Object6"); System.out.println(lruCache); lruCache.get(4); lruCache.put(7, "Object7"); lruCache.put(8, "Object8"); System.out.println(lruCache); } } println() method prints objects in order of their staleness. As you can see in the above code, Object1, Object2 and Object3 are inserted and object1 is accessed just before inserting the Object4 and hence Object1 is printed before the object4 in the first line of the output. When Object5 is inserted the Object2 gets evicted from the list because this object is the oldest in the list. When object3 is accessed, it gets promoted higher than object5 and when object6 is inserted Object1 is evicted. The rest output is self-explanatory, hope you will not find difficulties in understanding the output. {2=Object2, 3=Object3, 1=Object1, 4=Object4} {4=Object4, 5=Object5, 3=Object3, 6=Object6} {6=Object6, 4=Object4, 7=Object7, 8=Object8}Reference: Code4ReferenceList Recently Used(LRU) implementation using LinkedHashMap from our JCG partner Rakesh Cusat at the Code4Reference blog....
akka-logo

Reactive Queue with Akka Reactive Streams

Reactive streams is a recently announced initiative to create a standard for asynchronous stream processing with built-in back-pressure, on the JVM. The working group is formed by companies such as Typesafe, Red Hat, Oracle, Netflix, and others. One of the early, experimental implementations is based on Akka. Preview version 0.3 includes actor producers & consumers, which opens up some new integration possibilities.      To test the new technology, I implemented a very simple Reactive Message Queue. The code is at a PoC stage, lacks error handling and such, but if used properly – works! The queue is reactive, meaning that messages will be delivered to interested parties whenever there’s demand, without polling. Back-pressure is applied both when sending messages (so that senders do not overwhelm the broker), and when receiving messages (so that the broker sends only as much messages as the receivers can consume). Let’s see how it works! The queue First, the queue itself is an actor, and doesn’t know anything about (reactive) streams. The code is in the com.reactmq.queue package. The actor accepts the following actor-messages (the term “message” is overloaded here, so I’ll use plain “message” to mean the messages we send to and receive from the queue, and “actor-messages” to be the Scala class instances sent to actors):SendMessage(content) – sends a message with the specified String content. A reply (SentMessage(id)) is sent back to the sender with the id of the message ReceiveMessages(count) – signals that the sender (actor) would like to receive up to count messages. The count is cumulated with previously signalled demand. DeleteMessage(id) – unsurprisingly, deletes a messageThe queue implementation is a simplified version of what’s in ElasticMQ. After a message is received, if it is not deleted (acknowledged) within 10 seconds, it becomes available for receiving again. When an actor signals demand for messages (by sending ReceiveMessages to the queue actor), it should expect any number of ReceivedMessages(msgs) actor-messages replies, containing the received data. Going reactive To create and test our reactive queue, we need three applications:a Sender a central Broker a ReceiverWe can run any number of Senders and Receivers, but of course we should run only one Broker. The first thing that we need to do is to connect the Sender with the Broker, and the Receiver with the Broker over a network. We can do that with the Akka IO extension and the reactive TCP extension. Using a connect & bind pair, we get a stream of connections on the binding side: // sender: val connectFuture = IO(StreamTcp) ? StreamTcp.Connect(settings, sendServerAddress)   connectFuture.onSuccess { case binding: StreamTcp.OutgoingTcpConnection => logger.info("Sender: connected to broker") // per-connection logic }   // broker: val bindSendFuture = IO(StreamTcp) ? StreamTcp.Bind(settings, sendServerAddress)   bindSendFuture.onSuccess { case serverBinding: StreamTcp.TcpServerBinding => logger.info("Broker: send bound")   Flow(serverBinding.connectionStream).foreach { conn => // per-connection logic }.consume(materializer) } There’s a different address for sending and receiving messages. The sender Let’s look at the per-connection logic of the Sender first. Flow(1.second, () => { idx += 1; s"Message $idx from $senderName" }) .map { msg => logger.debug(s"Sender: sending $msg") createFrame(msg) } .toProducer(materializer) .produceTo(binding.outputStream) We are creating a tick-flow which produces a new message every second (very convenient for testing). Using the map stream transformer, we are creating a byte-frame with the message (more on that later). But that’s only a description of how our (very simple) stream should look like; it needs to be materialized using the toProducer method, which will provide concrete implementations of the stream transformation nodes. Currently there’s only one FlowMaterializer, which – again unsurprisingly – uses Akka actors under the hood, to actually create the stream and the flow. Finally, we connect the producer we have just created to the TCP binding’s outputStream, which happens to be a consumer. And we now have a reactive over-the-network stream of messages, meaning that messages will be sent only when the Broker can accept them. Otherwise back-pressure will be applied all the way up to the tick producer.The broker: sending messages On the other side of the network sits the Broker. Let’s see what happens when a message arrives. Flow(serverBinding.connectionStream).foreach { conn => logger.info(s"Broker: send client connected (${conn.remoteAddress})")   val sendToQueueConsumer = ActorConsumer[String]( system.actorOf(Props(new SendToQueueConsumer(queueActor))))   // sending messages to the queue, receiving from the client val reconcileFrames = new ReconcileFrames() Flow(conn.inputStream) .mapConcat(reconcileFrames.apply) .produceTo(materializer, sendToQueueConsumer) }.consume(materializer) First, we create a Flow from the connection’s input stream – that’s going to be the incoming stream of bytes. Next, we re-construct the String instances that were sent using our framing, and finally we direct that stream to a send-to-queue consumer. The SendToQueueConsumer is a per-connection bridge to the main queue actor. It uses the ActorConsumer trait from Akka’s Reactive Streams implementation, to automatically manage the demand that should be signalled upstream. Using that trait we can create a reactive-stream-Consumer[_], backed by an actor – so a fully customisable sink. class SendToQueueConsumer(queueActor: ActorRef) extends ActorConsumer {   private var inFlight = 0   override protected def requestStrategy = new MaxInFlightRequestStrategy(10) { override def inFlightInternally = inFlight }   override def receive = { case OnNext(msg: String) => queueActor ! SendMessage(msg) inFlight += 1   case SentMessage(_) => inFlight -= 1 } } What needs to be provided to an ActorConsumer, is a way of measuring how many stream items are currently processed. Here, we are counting the number of messages that have been sent to the queue, but for which we have not yet received an id (so they are being processed by the queue). The consumer receives new messages wrapped in the OnNext actor-message; so OnNext is sent to the actor by the stream, and SentMessage is sent in reply to a SendMessage by the queue actor. Receiving The receiving part is done in a similar way, though it requires some extra steps. First, if you take a look at the Receiver, you’ll see that we are reading bytes from the input stream, re-constructing messages from frames, and sending back the ids, hence acknowledging the message. In reality, we would run some message-processing-logic between receiving a message and sending back the id. On the Broker side, we create two streams for each connection. One is a stream of messages sent to receivers, the other is a stream of acknowledged message ids from the receivers, which are simply transformed to sending DeleteMessage actor-messages to the queue actor. Similarly to the consumer, we need a per-connection receiving bridge from the queue actor, to the stream. That’s implemented in ReceiveFromQueueProducer. Here we are extending the ActorProducer trait, which lets you fully control the process of actually creating the messages which go into the stream. In this actor, the Request actor-message is being sent by the stream, to signal demand. When there’s demand, we request messages from the queue. The queue will eventually respond with one or more ReceivedMessages actor-message (when there are any messages in the queue); as the number of messages will never exceed the signalled demand, we can safely call the ActorProducer.onNext method, which sends the given items downstream. Framing One small detail is that we need a custom framing protocol (thanks to Roland Kuhn for the clarification), as the TCP stream is just a stream of bytes, so we can get arbitrary fragments of the data, which need to be recombined later. Luckily implementing such a framing is quite simple – see the Framing class. Each frame consists of the size of the message, and the message itself. Summing up Using Reactive Streams and the Akka implementation it is very easy to create reactive applications with end-to-end back-pressure. The queue above, while missing a lot of features and proofing, won’t allow the Broker to be overloaded by the Senders, and on the other side the Receivers to be overloaded by the Broker. And all that, without the need to actually write any of the backpressure-handling code!Reference: Reactive Queue with Akka Reactive Streams from our JCG partner Adam Warski at the Blog of Adam Warski blog....
software-development-2-logo

No SRP? No TDD!

I’ve been thinking about what makes TDD fail, and there are obviously few reasons that were discussed to death (Get it? Dead? TDD? Ok, let’s move on). There’s a pattern I see when working with beginners. I’m talking about TDD beginners, because these people may have years of experience on them.  They follow the red-green steps religiously, and do minimal refactoring on the way. Usually, the refactoring looks like that:Renaming, which is very important, of course. Extracting code into private methods. Switching control flows as part of the incremental design additions. For example, adding loops, replacing if-else’s with switch-cases. Small modifications to data structures , although not many.What this gets you is a big, convoluted class that has tests, and some small internal, simple data  classes. Tests are good. But is this the magical emergent design those TDD fanatics always talk about? SOLID Ground Out of the five SOLID principles, the Single Responsibility Principle has the biggest impact on TDD. While SOLID principles are universal (I hear they are BIG on Alpha Centauri) TDD’s outside-in method separates the S from the others. The OLID principles are mostly about external interfaces.Open/Closed principle: Usually translates in OO to working against interfaces/base classes The Liskov’s Substitution principle is built into OO languages. We think about base and subclasses as similar behavior through interfaces, where it’s most powerful. Interface Segregation is about, well, interfaces. Dependency injection is about testability, and about, well, interfaces.Liskov’s Substitution principle, is a bit different from the rest, because the substitution is not just about interface, but also about behavior. Behavior means internal code. While the L principle has small internal implementation impact, SRP is mostly about it. SRP is about answering the important design question: Where Should This Code Go? Should this code be in a private method? Should it be extracted to another class? Should it be split into base and derived classes? Should it be called as a virtual method, overriding the base method? Should it be tested separately? Where should this code go? A big part of refactoring is tediously asking this question. When we do, simpler design appears. Code moves into smaller classes and components, into smaller methods , and private methods are extracted to other classes, that make more sense (and better named). The resulting code is staggeringly different than the one I described above. And that can make or break TDD implementations. TDD Is Misleading It looks like just following red-green-refactor will get you the right design. That’s a lie. If you believe it, you’ll get into the “TDD is dead” crowd. The “Emergent Design” part of TDD does not come magically from the keyboard. You and I drive the design. The best way to create the readable, understandable and maintainable design is about asking “where should this code go”. And that’s the power of SRP. If you get into TDD without understanding it, you’re most likely to fail.Reference: No SRP? No TDD! from our JCG partner Gil Zilberfeld at the Geek Out of Water blog....
android-logo

How to create android dialogs in a reusable manner

 Creating dialogs is a very common need in your app to show a dialog box to the user in order to fetch a value, be in a mobile, desktop or even a web application. Furthermore, the values can range from anything like simple OK-Cancel dialog results to a list of “check-able” values or even a date-range. I experienced the need to create an android dialog for each one of those for showing reports in a recent android app project. Whilst the java api offers maximum flexibility in creating dialog interface elements, there is no ready-made method that can be called to get, say a result for a message-dialog like this:   result = MessageBox.Show(); Other languages like C# and VB provide such methods to show modal dialog boxes that return values after waiting for a modal dialog. But unfortunately, there is no concept of “modal” in android. A thread cannot just sit idle waiting for input as the resources are too valuable for that. Instead, there is the concept of callbacks, so that instead of you waiting for the dialog to return, the method calls back a function reference you have passed it: AlertDialog.Builder builder=new AlertDialog.Builder(context); builder.setTitle("Milk supply tracker"); builder.setMessage(message); builder.setPositiveButton("Yes",listener); builder.setNegativeButton("No",listener); builder.create().show(); The listener here is the referece to a function that will be called when the Yes or No button will be clicked. This not only complicates your code, but makes it very difficult to reuse code for handling different situations like getting a selection from a range of values or getting a date/time range. To solve this problem, I created a separate java class called Dialog and added variations of ShowDialog() methods to handle each type of dialog: class Dialog { public static void ShowMessageDialog(Context context, String message) { ShowDialog(context,message,MessageBoxType.OKOnly,new String[]{},false, null,null); }   public static void ShowMessageDialog(Context context, String message, MessageBoxType type , OnClickListener listener) { ShowDialog(context,message,type,new String[]{},false, listener,null); }   public static void ShowListDialog(Context context, String message, String[] listItems, boolean isMultiChoice, OnClickListener listener) { if (isMultiChoice) ShowDialog(context, message, MessageBoxType.OkCancel , listItems, isMultiChoice, listener,null); else ShowDialog(context, message, MessageBoxType.OKOnly , listItems, isMultiChoice, null,listener); }   public static void ShowDateDialog(Context context,String message,OnDateSetListener listener) { Calendar c=Calendar.getInstance(); int y=c.get(Calendar.YEAR); int m=c.get(Calendar.MONTH); int d=c.get(Calendar.DAY_OF_MONTH);   DatePickerDialog dlg=new DatePickerDialog(context, listener, y, m, d); dlg.setTitle(message); dlg.show(); }   } As you can see, the ShowMessageDialog() accepts different parameters depending on whether a listener is required or not. ShowListDialog(), on the other hand passes an array of strings to create a dialog displaying a list of values from which a user may select. The isMultiChoice parameter tells whether a checkbox is required or not against each value in the select list. All this is actually implemented in the ShowDialog() private method, whereas the ShowDateDialog() has its own implementation. Here is the source for ShowDialog(): private static void ShowDialog(Context context, String message, MessageBoxType type , String[] listItems, boolean isMultiChoice, OnClickListener listener,OnClickListener selectedItemListener) { AlertDialog.Builder builder=new AlertDialog.Builder(context);   if (listItems.length>0 && isMultiChoice==false) { CheckedItems=new ArrayList();//won't be used in this case. builder.setTitle(message);   builder.setItems(listItems, selectedItemListener); } else if (listItems.length>0 && isMultiChoice==true) { CheckedItems=new ArrayList(); builder.setTitle(message);   builder.setMultiChoiceItems(listItems, null, new OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean checked) { if (checked) CheckedItems.add(which); else { if (CheckedItems.contains(which)) CheckedItems.remove(which); } } }); } else { builder.setTitle("Milk supply tracker"); builder.setMessage(message); }   if (listItems.length==0 || isMultiChoice) { switch(type) { case OKOnly: builder.setPositiveButton("OK",listener); break; case OkCancel: builder.setPositiveButton("OK",listener); builder.setNegativeButton("Cancel",listener); break; case YesNo: builder.setPositiveButton("Yes",listener); builder.setNegativeButton("No",listener); break; } }   builder.create().show(); } So hopefully, this class should suffice all your needs related to showing a dialog on your android app. Here is a working example of how the ShowListDialog() is actually called with checkboxes on: selItems=new String[]{"apples","oranges","grapes"}; Device.ShowListDialog(this,"Select a fruit" ,this.selItems, true, new DialogInterface.OnClickListener() {   @Override public void onClick(DialogInterface dialog, int which) { if (which==DialogInterface.BUTTON_POSITIVE) { for(int i:Device.CheckedItems) Dialog.ShowMessageDialog(ReportsActivity.this, "selected:" + selItems[i]); } } }); }Reference: How to create android dialogs in a reusable manner from our JCG partner Prahlad Yeri at the Prahlad Yeri blog....
junit-logo

Writing Clean Tests – Divide and Conquer

A good unit test should fail for only one reason. This means that a proper unit test tests only one logical concept. If we want to write clean tests, we have to identify those logical concepts, and write only one test case per logical concept. This blog post describes how we can identify the logical concepts found from our tests, and split an existing unit test into multiple unit tests.       Pretty Clean Isn’t Good Enough Let’s start by taking a look at the source code of our unit test which ensures that the registerNewUserAccount(RegistrationForm userAccountData) method of the RepositoryUserService class works as expected when a new user account is created by using a unique email address and a social sign in provider. The source code of this unit test looks as follows: import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.security.crypto.password.PasswordEncoder;import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when;@RunWith(MockitoJUnitRunner.class) public class RepositoryUserServiceTest {private static final String REGISTRATION_EMAIL_ADDRESS = "john.smith@gmail.com"; private static final String REGISTRATION_FIRST_NAME = "John"; private static final String REGISTRATION_LAST_NAME = "Smith"; private static final SocialMediaService SOCIAL_SIGN_IN_PROVIDER = SocialMediaService.TWITTER;private RepositoryUserService registrationService;@Mock private PasswordEncoder passwordEncoder;@Mock private UserRepository repository;@Before public void setUp() { registrationService = new RepositoryUserService(passwordEncoder, repository); }@Test public void registerNewUserAccount_SocialSignInAndUniqueEmail_ShouldCreateNewUserAccountAndSetSignInProvider() throws DuplicateEmailException { RegistrationForm registration = new RegistrationFormBuilder() .email(REGISTRATION_EMAIL_ADDRESS) .firstName(REGISTRATION_FIRST_NAME) .lastName(REGISTRATION_LAST_NAME) .isSocialSignInViaSignInProvider(SOCIAL_SIGN_IN_PROVIDER) .build();when(repository.findByEmail(REGISTRATION_EMAIL_ADDRESS)).thenReturn(null);when(repository.save(isA(User.class))).thenAnswer(new Answer<User>() { @Override public User answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); return (User) arguments[0]; } });User createdUserAccount = registrationService.registerNewUserAccount(registration);assertThat(createdUserAccount) .hasEmail(REGISTRATION_EMAIL_ADDRESS) .hasFirstName(REGISTRATION_FIRST_NAME) .hasLastName(REGISTRATION_LAST_NAME) .isRegisteredUser() .isRegisteredByUsingSignInProvider(SOCIAL_SIGN_IN_PROVIDER);verify(repository, times(1)).findByEmail(REGISTRATION_EMAIL_ADDRESS); verify(repository, times(1)).save(createdUserAccount); verifyNoMoreInteractions(repository); verifyZeroInteractions(passwordEncoder); } } This unit test is pretty clean. After all, our test class, test method, and the local variables created inside the test method have descriptive names. We have also replaced magic numbers with constants and created domain-specific languages for creating new objects and writing assertions. And yet, we can make this test even better. The problem of this unit test is that it can fail for more than one reason. It can fail if:Our service method doesn’t check that the email address entered to the registration form is not found from our database. The information of the persisted User object doesn’t match with the information entered to the registration form. The information of the returned User object isn’t correct. Our service method creates a password for the user by using the PasswordEncoder object.In other words, this unit test tests four different logical concepts, and this causes the following problems:If this test fails, we don’t necessarily know why it failed. This means that we have to read the source code of the unit test. The unit test is a bit long which makes it somewhat hard to read. It is hard to describe the expected behavior. This means that it is very hard to figure great names for our test methods.We can identify the logical concepts covered by a single unit test by identifying the situations when that unit test will fail. That is why we need to split this test into four unit tests. One Test, One Point of Failure Our next step is to split our unit test into four new unit tests and ensure that each of them tests a single logical concept. We can do this by writing the following unit tests:We need to ensure that our service method checks that the email address given by the user is unique. We need to verify that information of the persisted User object is correct. We need to ensure that the information of the returned User object is correct. We need to verify that our service method doesn’t create an encoded password for a user who uses social sign in provider.After we have written these unit tests, the source code of our test class looks as follows: import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.security.crypto.password.PasswordEncoder;import static net.petrikainulainen.spring.social.signinmvc.user.model.UserAssert.assertThat; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when;@RunWith(MockitoJUnitRunner.class) public class RepositoryUserServiceTest {private static final String REGISTRATION_EMAIL_ADDRESS = "john.smith@gmail.com"; private static final String REGISTRATION_FIRST_NAME = "John"; private static final String REGISTRATION_LAST_NAME = "Smith"; private static final SocialMediaService SOCIAL_SIGN_IN_PROVIDER = SocialMediaService.TWITTER;private RepositoryUserService registrationService;@Mock private PasswordEncoder passwordEncoder;@Mock private UserRepository repository;@Before public void setUp() { registrationService = new RepositoryUserService(passwordEncoder, repository); }@Test public void registerNewUserAccount_SocialSignInAndUniqueEmail_ShouldCheckThatEmailIsUnique() throws DuplicateEmailException { RegistrationForm registration = new RegistrationFormBuilder() .email(REGISTRATION_EMAIL_ADDRESS) .firstName(REGISTRATION_FIRST_NAME) .lastName(REGISTRATION_LAST_NAME) .isSocialSignInViaSignInProvider(SOCIAL_SIGN_IN_PROVIDER) .build();when(repository.findByEmail(REGISTRATION_EMAIL_ADDRESS)).thenReturn(null);registrationService.registerNewUserAccount(registration);verify(repository, times(1)).findByEmail(REGISTRATION_EMAIL_ADDRESS); }@Test public void registerNewUserAccount_SocialSignInAndUniqueEmail_ShouldSaveNewUserAccountAndSetSignInProvider() throws DuplicateEmailException { RegistrationForm registration = new RegistrationFormBuilder() .email(REGISTRATION_EMAIL_ADDRESS) .firstName(REGISTRATION_FIRST_NAME) .lastName(REGISTRATION_LAST_NAME) .isSocialSignInViaSignInProvider(SOCIAL_SIGN_IN_PROVIDER) .build();when(repository.findByEmail(REGISTRATION_EMAIL_ADDRESS)).thenReturn(null);registrationService.registerNewUserAccount(registration);ArgumentCaptor<User> userAccountArgument = ArgumentCaptor.forClass(User.class); verify(repository, times(1)).save(userAccountArgument.capture());User createdUserAccount = userAccountArgument.getValue();assertThat(createdUserAccount) .hasEmail(REGISTRATION_EMAIL_ADDRESS) .hasFirstName(REGISTRATION_FIRST_NAME) .hasLastName(REGISTRATION_LAST_NAME) .isRegisteredUser() .isRegisteredByUsingSignInProvider(SOCIAL_SIGN_IN_PROVIDER); }@Test public void registerNewUserAccount_SocialSignInAndUniqueEmail_ShouldReturnCreatedUserAccount() throws DuplicateEmailException { RegistrationForm registration = new RegistrationFormBuilder() .email(REGISTRATION_EMAIL_ADDRESS) .firstName(REGISTRATION_FIRST_NAME) .lastName(REGISTRATION_LAST_NAME) .isSocialSignInViaSignInProvider(SOCIAL_SIGN_IN_PROVIDER) .build();when(repository.findByEmail(REGISTRATION_EMAIL_ADDRESS)).thenReturn(null);when(repository.save(isA(User.class))).thenAnswer(new Answer<User>() { @Override public User answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); return (User) arguments[0]; } });User createdUserAccount = registrationService.registerNewUserAccount(registration);assertThat(createdUserAccount) .hasEmail(REGISTRATION_EMAIL_ADDRESS) .hasFirstName(REGISTRATION_FIRST_NAME) .hasLastName(REGISTRATION_LAST_NAME) .isRegisteredUser() .isRegisteredByUsingSignInProvider(SOCIAL_SIGN_IN_PROVIDER); }@Test public void registerNewUserAccount_SocialSignInAnUniqueEmail_ShouldNotCreateEncodedPasswordForUser() throws DuplicateEmailException { RegistrationForm registration = new RegistrationFormBuilder() .email(REGISTRATION_EMAIL_ADDRESS) .firstName(REGISTRATION_FIRST_NAME) .lastName(REGISTRATION_LAST_NAME) .isSocialSignInViaSignInProvider(SOCIAL_SIGN_IN_PROVIDER) .build();when(repository.findByEmail(REGISTRATION_EMAIL_ADDRESS)).thenReturn(null);registrationService.registerNewUserAccount(registration);verifyZeroInteractions(passwordEncoder); } } The obvious benefit of writing unit tests which test only one logical concept is that it easy to know why the test failed. However, this approach has two other benefits as well:It is easy to specify the expected behavior. This means that it is easier to figure out good names for our test methods. Because these unit tests are considerably shorter than the original unit test, it is easier to figure out the requirements of the tested method / component. This helps us to transform our tests into executable specifications.Let’s move on and summarize what we learned from this blog post. Summary We have now successfully splitted our unit test into four smaller unit tests which test a single logical concept. This blog post has taught us two things:We learned that we can identify the logical concepts covered by a single unit test by identifying the situations when that test will fail. We learned that writing unit tests which test only one logical concept helps us to write transform our test cases into executable specifications, which identity the requirements of the tested method / component.Reference: Writing Clean Tests – Divide and Conquer from our JCG partner Petri Kainulainen at the Petri Kainulainen blog....
android-logo

Android chart tutorial: AChartEngine

In this post, I will describe how to use AchartEngine. This is a great library for Android that help you to create charts. It supports several chart types, just to name a few:line chart area chart bar chart pie chart combined chartand so on.   This library helps you in every aspects when you create a charts so you don’t need anything else to create interesting charts. Getting started If you use Android Studio you can download directly the jar containing all the classes and add it to your project. When the download is completed, you should add the library under libs folder so that I can be included automatically into your project. Now you are ready to use the lib! When you create a charts you need usually a set of data that has to be drawn in the chart, in this case to have real values and to not re-invent the wheel we can suppose we get these values using WeatherLib so that we will plot the atmospheric parameters (like temperature, and pressure..). There some basic concepts that stand behind this library and they are important so that you can use it:Dataset (The set of data you have to draw in your chart) The view (or the type of chart you want) Renderer (It controls how the view is drawn, settings some parameters you can change the way the charts looks like. There are two types of renderer: one that controls the rendering of the dataset and another one that controls how the main chart aspects look like (i.e. axis, labels and so on) Chart factory (combines the dataset and the renderers to create the charts. The chart can be created inside an Activity or the factory can return a View.)Line chart As first example, we want to create a Line chart. In this chart we will draw the temperature that is our Dataset. Considering that a line chart is an XY chart we create as first step the right series that holds the data: XYSeries series = new XYSeries("London Temperature hourly"); next we have to populate the series using the data retrieved from WeatherLib (hourly weather forecast): int hour = 0; for (HourForecast hf : nextHourForecast) { series.add(hour++, hf.weather.temperature.getTemp()); } almost done, the series contains the data. If you look carefully we represented on X-axis the hours and on Y-axis the temperature. Remembering the basic concepts described above, we have to create a series renderer: // Now we create the renderer XYSeriesRenderer renderer = new XYSeriesRenderer(); renderer.setLineWidth(2); renderer.setColor(Color.RED); // Include low and max value renderer.setDisplayBoundingPoints(true); // we add point markers renderer.setPointStyle(PointStyle.CIRCLE); renderer.setPointStrokeWidth(3); At line 3, we set the line width. One aspect you should consider when using achartengine is that the dimensions are expressed in pixel not in dp!. At line 4, we set the color and then at line 8 we set the Point Style, meaning the point contained in our series. The last step is creating the renderer that controls the full charts and add the single renderer for each series: XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); mRenderer.addSeriesRenderer(renderer); and then: // We want to avoid black border mRenderer.setMarginsColor(Color.argb(0x00, 0xff, 0x00, 0x00)); // transparent margins // Disable Pan on two axis mRenderer.setPanEnabled(false, false); mRenderer.setYAxisMax(35); mRenderer.setYAxisMin(0); mRenderer.setShowGrid(true); // we show the grid A small tip: if you create a chart, you will notice that around the chart there are black borders, if you want to remove them you have to set this margin transparent (line 2). At line 5,6 we set the Y value range. The last step is creating the View: GraphicalView chartView = ChartFactory.getLineChartView(getActivity(), dataset, mRenderer); Now we have the view the last step is adding it to our layout. Let us suppose we have a linear layout: <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/chart" android:orientation="vertical"/> We add the view to it: chartLyt.addView(chartView,0); Running the example we have at the end:Bar chart Bar chart are another type of charts that can be built using AchartEngine. In this case, we can suppose we want to plot the pressure values retrieved from WeatherLib. As we did before we have to create a data series: for (HourForecast hf : nextHourForecast) { series.add(hour++, hf.weather.currentCondition.getPressure());if (hour > 24) break; } Some steps are very similar to what explained before so we can safely jump them and create the chart: GraphicalView chartView = ChartFactory.getBarChartView(getActivity(), dataset, mRenderer, BarChart.Type.DEFAULT); As result we get:Range bar Range bar is special type of bar chart and it is interesting because it uses a different type of data series. A Range bar is a bar that has a lower and upper limit. We can use this type of chart if we want to plot the max and min temperature. RangeCategorySeries series = new RangeCategorySeries("London next days temperature"); now we add the values: for (DayForecast df : dayForecast) { series.add(df.forecastTemp.min, df.forecastTemp.max); mRenderer.addXTextLabel(hour++, sdf.format(df.timestamp)); } At line 2 we set the min and max temperature adding them to the data series. At line 3 we add a label to the X-axis values. In this case we use the day number and the month: SimpleDateFormat sdf = new SimpleDateFormat("dd,MMM"); now we add the series: XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); dataset.addSeries(series.toXYSeries()); and create the series renderer: XYSeriesRenderer renderer = new XYSeriesRenderer(); renderer.setDisplayChartValues(true); mRenderer.addSeriesRenderer(renderer); mRenderer.setYAxisMax(30.0); mRenderer.setYAxisMin(0.0); renderer.setChartValuesTextSize(12); renderer.setChartValuesFormat(new DecimalFormat("#.##")); renderer.setColor(Color.GREEN); Some aspects to notice: at line 2, we tell to the renderer we want that the values appears on the chart, while at line 6, we set the text size. Another important aspect: the value format: at line 7, we specify that we want two digits after the decimal point. Finally, we can create the graph: GraphicalView chartView = ChartFactory.getRangeBarChartView(getActivity(), dataset, mRenderer, BarChart.Type.DEFAULT); Running the example we have:Source code available soon.Reference: Android chart tutorial: AChartEngine from our JCG partner Francesco Azzola at the Surviving w/ Android blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books