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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Latest Articles - DZone

article thumbnail
Parking Lot - Simplistic Design C#
Parking Lot Design Implementation in C#. public class ParkingLot { List _parkingSpots; public ParkingLot() { _parkingSpots = new List(); // 10 parking spots; 2 free; 6 Regular Paid; 2 Handicapped Free //2 free for (int i = 0; i p.IsFree == true && p.IsAvailable); } public ParkingSpot FindPaidSpot() { return this._parkingSpots.Find(p => p.IsFree == false && p.IsAvailable); } public int GetAvailableSpotsCount() { return this._parkingSpots.Count(p => p.IsAvailable); } public int GetTotalSpots() { return this._parkingSpots.Count; } } public class ParkingSpot { public bool IsAvailable { get; set; } public bool IsFree { get; set; } public IVehicle ParkedVehicle { get; set; } public ParkingMeter Meter { get; set; } public void Park(IVehicle vehicle) { if (this.ParkedVehicle == null) { this.ParkedVehicle = vehicle; this.IsAvailable = false; } else { throw new Exception("Parking Spot is Taken. Cannot Park here!"); } } public ParkingSpot() { this.IsAvailable = true; this.IsFree = true; } public ParkingSpot(bool isFree) { this.IsAvailable = true; this.IsFree = isFree; if (!this.IsFree) { this.Meter = new ParkingMeter(); } } } public class HandicappedParkingSpot : ParkingSpot { } public class ParkingMeter { public DateTime EndTime { get; set; } public int MinutesRemaining { get { if (DateTime.Now >= EndTime) return 0; else return (EndTime - DateTime.Now).Minutes; } } public int ParkingIntervalMins { get { return 1; } } public void Pay(int quarters) { EndTime = DateTime.Now.AddMinutes(quarters * ParkingIntervalMins); } } public interface IVehicle { string Make { get; set; } string Model { get; set; } void Drive(); } public class Car : IVehicle { public string Make { get; set; } public string Model { get; set; } public void Drive() { } public void Park() { } } public class Truck : IVehicle { public string Make { get; set; } public string Model { get; set; } public void Drive() { } public void Park() { } }
June 11, 2012
by Aniruddha Deshpande
· 17,952 Views
article thumbnail
NetBeans IDE 7.2 Introduces TestNG
One of the advantages of code generation is the ability to see how a specific language feature or framework is used. As I discussed in the post NetBeans 7.2 beta: Faster and More Helpful, NetBeans 7.2 beta provides TestNG integration. I did not elaborate further in that post other than a single reference to that feature because I wanted to devote this post to the subject. I use this post to demonstrate how NetBeans 7.2 can be used to help a developer new to TestNG start using this alternative (to JUnit) test framework. NetBeans 7.2's New File wizard makes it easier to create an empty TestNG test case. This is demonstrated in the following screen snapshots that are kicked off by using New File | Unit Tests (note that "New File" is available under the "File" drop-down menu or by right-clicking in the Projects window). Running the TestNG test case creation as shown above leads to the following generated test code. TestNGDemo.java (Generated by NetBeans 7.2) package dustin.examples; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.Assert; /** * * @author Dustin */ public class TestNGDemo { public TestNGDemo() { } @BeforeClass public void setUpClass() { } @AfterClass public void tearDownClass() { } @BeforeMethod public void setUp() { } @AfterMethod public void tearDown() { } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // // @Test // public void hello() {} } The test generated by NetBeans 7.2 includes comments indicate how test methods are added and annotated (similar to modern versions of JUnit). The generated code also shows some annotations for overall test case set up and tear down and for per-test set up and tear down (annotations are similar to JUnit's). NetBeans identifies import statements that are not yet used at this point (import org.testng.annotations.Test; and import org.testng.Assert;), but are likely to be used and so have been included in the generated code. I can add a test method easily to this generated test case. The following code snippet is a test method using TestNG. testIntegerArithmeticMultiplyIntegers() @Test public void testIntegerArithmeticMultiplyIntegers() { final IntegerArithmetic instance = new IntegerArithmetic(); final int[] integers = {4, 5, 6}; final int expectedProduct = 2 * 3 * 4 * 5 * 6; final int product = instance.multiplyIntegers(2, 3, integers); assertEquals(product, expectedProduct); } This, of course, looks very similar to the JUnit equivalent I used against the same IntegerArithmetic class that I used for testing illustrations in the posts Improving On assertEquals with JUnit and Hamcrest and JUnit's Built-in Hamcrest Core Matcher Support. The following screen snapshot shows the output in NetBeans 7.2 beta from right-clicking on the test case class and selecting "Run File" (Shift+F6). The text output of the TestNG run provided in the NetBeans 7.2 beta is reproduced next. [TestNG] Running: Command line suite [VerboseTestNG] RUNNING: Suite: "Command line test" containing "1" Tests (config: null) [VerboseTestNG] INVOKING CONFIGURATION: "Command line test" - @BeforeClass dustin.examples.TestNGDemo.setUpClass() [VerboseTestNG] PASSED CONFIGURATION: "Command line test" - @BeforeClass dustin.examples.TestNGDemo.setUpClass() finished in 33 ms [VerboseTestNG] INVOKING CONFIGURATION: "Command line test" - @BeforeMethod dustin.examples.TestNGDemo.setUp() [VerboseTestNG] PASSED CONFIGURATION: "Command line test" - @BeforeMethod dustin.examples.TestNGDemo.setUp() finished in 2 ms [VerboseTestNG] INVOKING: "Command line test" - dustin.examples.TestNGDemo.testIntegerArithmeticMultiplyIntegers() [VerboseTestNG] PASSED: "Command line test" - dustin.examples.TestNGDemo.testIntegerArithmeticMultiplyIntegers() finished in 12 ms [VerboseTestNG] INVOKING CONFIGURATION: "Command line test" - @AfterMethod dustin.examples.TestNGDemo.tearDown() [VerboseTestNG] PASSED CONFIGURATION: "Command line test" - @AfterMethod dustin.examples.TestNGDemo.tearDown() finished in 1 ms [VerboseTestNG] INVOKING CONFIGURATION: "Command line test" - @AfterClass dustin.examples.TestNGDemo.tearDownClass() [VerboseTestNG] PASSED CONFIGURATION: "Command line test" - @AfterClass dustin.examples.TestNGDemo.tearDownClass() finished in 1 ms [VerboseTestNG] [VerboseTestNG] =============================================== [VerboseTestNG] Command line test [VerboseTestNG] Tests run: 1, Failures: 0, Skips: 0 [VerboseTestNG] =============================================== =============================================== Command line suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== Deleting directory C:\Users\Dustin\AppData\Local\Temp\dustin.examples.TestNGDemo test: BUILD SUCCESSFUL (total time: 2 seconds) The above example shows how easy it is to start using TestNG, especially if one is moving to TestNG from JUnit and is using NetBeans 7.2 beta. Of course, there is much more to TestNG than this, but learning a new framework is typically most difficult at the very beginning and NetBeans 7.2 gets one off to a fast start.
June 11, 2012
by Dustin Marx
· 21,753 Views · 1 Like
article thumbnail
How To Analyze Thread Dumps: IBM VM
This article is part 4 of our Thread Dump analysis series which will provide you with an overview of what is a JVM Thread Dump for the IBM VM and the different Threads and data points that you will find. As you will see and learn, the IBM VM Thread Dump format is different but provides even more out-of-the-box troubleshooting data. At this point, you should know how Threads interact with the Java EE container and what a Thread Dump is. Before we go any further in the deep dive analysis patterns, you also need to understand the IBM VM Thread Dump format since this is the typical Thread Dump data to expect when using IBM WAS on IBM VM. IBM VM Thread Dump breakdown overview In order for you to better understand, find below a diagram showing you a visual breakdown of an IBM 1.6 VM Thread Dump and its common data points found: As you can, there are extra runtime data that you will not find from a HotSpot VM Thread Dump. Please keep in mind that you may not need to review all these data points but you still need to understand what data is available depending of your problem case. The rest of the article will cover each Thread Dump portion in more detail. # Thread Dump generation event The first portion provides you with detail on how this Thread Dump was generated. IBM Thread Dump can be generated as a result of a “signal 3” or “user” e.g. kill -3 or automatically as a result of severe JVM conditions such as an OutOfMemoryError. 0SECTION TITLE subcomponent dump routine NULL =============================== 1TISIGINFO Dump Event "user" (00004000) received 1TIDATETIME Date: 2012/03/12 at 20:52:13 1TIFILENAME Javacore filename: /apps/wl11g/domains/app/javacore.20120312.205205.1949928.0004.txt 1TIREQFLAGS Request Flags: 0x81 (exclusive+preempt) 1TIPREPSTATE Prep State: 0x4 (exclusive_vm_access) 0SECTION TITLE subcomponent dump routine NULL =============================== 1TISIGINFO OUTOFMEMORY received 1TIDATETIME Date: 2012/06/01 at 09:52:12 1TIFILENAME Javacore filename: /usr/WebSphere/AppServer/javacore311328.1338524532.txt # HW and OS environment detail The next section provides you with some detail on the current hardware and OS that this IBM VM is running from: 0SECTION GPINFO subcomponent dump routine NULL ================================ 2XHOSLEVEL OS Level : AIX 5.3 2XHCPUS Processors - 3XHCPUARCH Architecture : ppc64 3XHNUMCPUS How Many : 6 3XHNUMASUP NUMA is either not supported or has been disabled by user # JRE detail and Java start-up arguments This section is very useful as it provides you with a full view on your JRE major version and patch level along with all JVM start-up arguments. 0SECTION ENVINFO subcomponent dump routine NULL ================================= 1CIJAVAVERSION JRE 1.6.0 IBM J9 2.4 AIX ppc64-64 build jvmap6460sr9-20101124_69295 1CIVMVERSION VM build 20101124_069295 1CIJITVERSION JIT enabled, AOT enabled - r9_20101028_17488ifx2 1CIGCVERSION GC - 20101027_AA 1CIRUNNINGAS Running as a standalone JVM ………………………………………………………………………………………… # User and environment variables This section provides you with a listing of current user and environment variables such as File Descriptor limit. 1CIUSERLIMITS User Limits (in bytes except for NOFILE and NPROC) NULL ------------------------------------------------------------------------ NULL type soft limit hard limit 2CIUSERLIMIT RLIMIT_AS unlimited unlimited 2CIUSERLIMIT RLIMIT_CORE 1073741312 unlimited 2CIUSERLIMIT RLIMIT_CPU unlimited unlimited 2CIUSERLIMIT RLIMIT_DATA unlimited unlimited 2CIUSERLIMIT RLIMIT_FSIZE unlimited unlimited 2CIUSERLIMIT RLIMIT_NOFILE 4096 4096 2CIUSERLIMIT RLIMIT_RSS 33554432 unlimited 2CIUSERLIMIT RLIMIT_STACK 33554432 4294967296 # Java Heap detail and GC history Similar to HotSpot VM 1.6+, IBM VM Thread Dump also contains information on the Java Heap capacity and utilization along with memory segments allocated for each memory space of the Java process. Please keep in mind that deeper Java Heap analysis will require you to analyze the Heap Dump binary snapshot as per below tutorial. http://javaeesupportpatterns.blogspot.com/2011/02/ibm-sdk-heap-dump-httpsession-footprint.htm Finally, a history of the garbage collection process is also present. 0SECTION MEMINFO subcomponent dump routine NULL ================================= 1STHEAPFREE Bytes of Heap Space Free: 51104BC8 1STHEAPALLOC Bytes of Heap Space Allocated: 80000000 1STSEGTYPE Internal Memory ………………………………………………………………………………………… 1STSEGTYPE Object Memory ………………………………………………………………………………………… 1STSEGTYPE Class Memory ………………………………………………………………………………………… 1STSEGTYPE JIT Code Cache ………………………………………………………………………………………… 1STSEGTYPE JIT Data Cache ………………………………………………………………………………………… STGCHTYPE GC History 3STHSTTYPE 00:52:07:523048405 GMT j9mm.51 - SystemGC end: newspace=466136480/483183616 oldspace=899251600/1610612736 loa=80530432/80530432 3STHSTTYPE 00:52:07:523046694 GMT j9mm.139 - Reference count end: weak=40149 soft=87504 phantom=33 threshold=17 maxThreshold=32 3STHSTTYPE 00:52:07:522164027 GMT j9mm.91 - GlobalGC end: workstackoverflow=0 overflowcount=0 weakrefs=40149 soft=87504 threshold=17 phantom=33 finalizers=4947 newspace=466136480/483183616 oldspace=899251600/1610612736 loa=80530432/80530432 3STHSTTYPE 00:52:07:522152764 GMT j9mm.90 - GlobalGC collect complete # Java and JVM object monitor lock and deadlock detail This Thread Dump portion is very important. Quite often Thread problems involve Threads waiting between each other due to locks on particular Object monitors e.g. Thread B waiting to acquire a lock on Object monitor held by Thread A. Deadlock conditions can also be triggered from time to time; especially for non-Thread safe implementations. The IBM VM Thread Dump provides a separate section where you can analyze lock(s) held by each Thread including waiting chain(s) e.g. Many Threads waiting to acquire the same Object monitor lock. 0SECTION LOCKS subcomponent dump routine NULL =============================== NULL 1LKPOOLINFO Monitor pool info: 2LKPOOLTOTAL Current total number of monitors: 1034 NULL 1LKMONPOOLDUMP Monitor Pool Dump (flat & inflated object-monitors): 2LKMONINUSE sys_mon_t:0x0000000115B53060 infl_mon_t: 0x0000000115B530A0: 3LKMONOBJECT java/util/Timer$TimerImpl@0x0700000000C92AA0/0x0700000000C92AB8: 3LKNOTIFYQ Waiting to be notified: 3LKWAITNOTIFY "Thread-7" (0x0000000114CAB400) ………………………………………………………………………… ## Threads waiting chain 2LKMONINUSE sys_mon_t:0x000000012462FE00 infl_mon_t: 0x000000012462FE40: 3LKMONOBJECT com/inc/server/app/Request@0x07000000142ADF30/0x07000000142ADF48: owner "Thread-30" (0x000000012537F300), entry count 1 3LKNOTIFYQ Waiting to be notified: 3LKWAITNOTIFY "Thread-26" (0x0000000125221F00) 3LKWAITNOTIFY "Thread-27" (0x0000000125252000) 3LKWAITNOTIFY "Thread-28" (0x000000012527B800) 3LKWAITNOTIFY "Thread-29" (0x00000001252DDA00) 3LKWAITNOTIFY "Thread-31" (0x0000000125386200) 3LKWAITNOTIFY "Thread-32" (0x0000000125423600) 3LKWAITNOTIFY "Thread-33" (0x000000012548C500) 3LKWAITNOTIFY "Thread-34" (0x00000001255D6000) 3LKWAITNOTIFY "Thread-35" (0x00000001255F7900) ………………………………………………………………………… # Java EE middleware, third party & custom application Threads Similar to the HotSpot VM Thread Dump format, this portion is the core of the Thread Dump and where you will typically spend most of your analysis time. The number of Threads found will depend on your middleware software that you use, third party libraries (that might have its own Threads) and your application (if creating any custom Thread, which is generally not a best practice). The following Thread in the example below is in BLOCK state which typically means it is waiting to acquire a lock on an Object monitor. You will need to search in the earlier section and determine which Thread is holding the lock so you can pinpoint the root cause. 3XMTHREADINFO "[STUCK] ExecuteThread: '162' for queue: 'weblogic.kernel.Default (self-tuning)'" J9VMThread:0x000000013ACF0800, j9thread_t:0x000000013AC88B20, java/lang/Thread:0x070000001F945798, state:B, prio=1 3XMTHREADINFO1 (native thread ID:0x1AD0F3, native priority:0x1, native policy:UNKNOWN) 3XMTHREADINFO3 Java callstack: 4XESTACKTRACE at org/springframework/jms/connection/SingleConnectionFactory.createConnection(SingleConnectionFactory.java:207(Compiled Code)) 4XESTACKTRACE at org/springframework/jms/connection/SingleConnectionFactory.createQueueConnection(SingleConnectionFactory.java:222(Compiled Code)) 4XESTACKTRACE at org/springframework/jms/core/JmsTemplate102.createConnection(JmsTemplate102.java:169(Compiled Code)) 4XESTACKTRACE at org/springframework/jms/core/JmsTemplate.execute(JmsTemplate.java:418(Compiled Code)) 4XESTACKTRACE at org/springframework/jms/core/JmsTemplate.send(JmsTemplate.java:475(Compiled Code)) 4XESTACKTRACE at org/springframework/jms/core/JmsTemplate.send(JmsTemplate.java:467(Compiled Code)) ………………………………………………………………………………………………………… # JVM class loader summary Finally, the last section of the IBM VM Thread Dump provides you with a detailed class loader summary. This is very crucial data when dealing with Class Loader related issues and leaks. You will find the number and type of loaded Classes for each active Class loader in the running JVM. I suggest that you review the following case study for a complete tutorial on how to pinpoint root cause for this type of issues when using IBM VM. http://javaeesupportpatterns.blogspot.com/2011/04/class-loader-memory-leak-debugging.html 0SECTION CLASSES subcomponent dump routine NULL ================================= 1CLTEXTCLLOS Classloader summaries 1CLTEXTCLLSS 12345678: 1=primordial,2=extension,3=shareable,4=middleware,5=system,6=trusted,7=application,8=delegating 2CLTEXTCLLOADER p---st-- Loader *System*(0x0700000000878898) 3CLNMBRLOADEDLIB Number of loaded libraries 6 3CLNMBRLOADEDCL Number of loaded classes 3721 2CLTEXTCLLOADER -x--st-- Loader sun/misc/Launcher$ExtClassLoader(0x0700000000AE8F40), Parent *none*(0x0000000000000000) 3CLNMBRLOADEDLIB Number of loaded libraries 0 3CLNMBRLOADEDCL Number of loaded classes 91 2CLTEXTCLLOADER -----ta- Loader sun/misc/Launcher$AppClassLoader(0x07000000008786D0), Parent sun/misc/Launcher$ExtClassLoader(0x0700000000AE8F40) 3CLNMBRLOADEDLIB Number of loaded libraries 3 3CLNMBRLOADEDCL Number of loaded classes 15178 …………………………………………………………………………………………… I hope this article has helped to understand the basic view of an IBM VM Thread Dump. The next article (part 5) will provide you with a tutorial on how to analyze a JVM Thread Dump via a step by step tutorial and technique I have used over the last 10 years. Please feel free to post any comment and question.
June 11, 2012
by Pierre - Hugues Charbonneau
· 18,775 Views · 1 Like
article thumbnail
C++ and Metro: Basic Application
Visual Studio 11 Consumer Preview enables creating Metro styled applications using C++ which is great news for any native developer. Let’s create a simple Metro application. Start up Visual Studio and create new project using the Visual C++>Windows Metro Style>Blank Application template. “Hello world” Open the BlankPage.xaml file and start poking around with XAML. For those who haven’t used it yet, it is similar to HTML development. Scroll the code down until you find the Grid element and insert a TextBlock inside it, the final result should be: The Margin property offsets the element from the default top left corner for 12 pixels from the left and 20 pixels from the top. I have used the style that comes native with all Metro applications and it is primarily used to increase the size of the text. If you want, you can set size via the FontSize attribute. If you run the application now, you should get a black screen with the familiar “Hello world” text in the upper left corner. You define how the UI will look like in the BlankPage.xaml file, but the logic is placed in the regular BlankPage.xaml.h and BlankPage.xaml.cpp which are placed as child items for the BlankPage.xaml file in Solution Explorer. This is a regular C++ class but something looks different. The code does not look native at all with all those strange hats around the code and ref new syntax. Although these are reminiscent of the C++/CLI syntax, these extensions are called C++/CX, which is short for Component extensions. Pure C++ is not used for developing Metro applications and using the pure WinRT would be cumbersome since everything in Metro world is actually a COM object. C++/CX extensions are supposed to cut the burden for C++ programmer with this nonstandard extension. It litters the code with AddRef and Release calls and essentially all hat pointers are nothing more than shared_ptr variant. C++ to XAML You can “name” the previously added TextBlock XAML element by adding the x:Name="txtHello" attribute and value. By doing this, you can refer to it from the code behind files using the following code (add it to the BlankPage::OnNavigatedTo method): txtHello->Text = "Hello world!!!"; Run application and you should see different text like on the image below. Although not very exciting and super-simple, think about how it is done in Win32, MFC or WTL, this is clearly easier. In the next post we will look at how to handle simple events.
June 10, 2012
by Toni Petrina
· 6,789 Views
article thumbnail
Using lxml.objectify to Parse XML With Python
A couple years ago I started a series of articles on XML parsing. I covered lxml’s etree and Python builtin minidom XML parsing library. For whatever reason I didn’t notice lxml’s objectify sub-package, but I saw it recently and decided to check it out. In my mind, the objectify module seems to be even more “Pythonic” than etree is. Let’s take some time and go over my old XML examples using objectify and see how it’s different! Let’s Get This Party Started! If you haven’t already, go out and download lxml or you won’t be able to follow along very well. Once you have it, we can continue. We’ll be using the following piece of XML for our parsing pleasure: 1181251680 040000008200E000 1181572063 1800 Bring pizza home 1234360800 1800 Check MS Office website for updates 604f4792-eb89-478b-a14f-dd34d3cc6c21-1234360800 dismissed Now we need to write some code that can parse and modify the XML. Let’s take a look at this little demo that shows a bunch of the neat abilities that objectify provides. from lxml import etree, objectify #---------------------------------------------------------------------- def parseXML(xmlFile): """""" with open(xmlFile) as f: xml = f.read() root = objectify.fromstring(xml) # returns attributes in element node as dict attrib = root.attrib # how to extract element data begin = root.appointment.begin uid = root.appointment.uid # loop over elements and print their tags and text for e in root.appointment.iterchildren(): print "%s => %s" % (e.tag, e.text) # how to change an element's text root.appointment.begin = "something else" print root.appointment.begin # how to add a new element root.appointment.new_element = "new data" # print the xml obj_xml = etree.tostring(root, pretty_print=True) print obj_xml # remove the py:pytype stuff #objectify.deannotate(root) etree.cleanup_namespaces(root) obj_xml = etree.tostring(root, pretty_print=True) print obj_xml # save your xml with open("new.xml", "w") as f: f.write(obj_xml) #---------------------------------------------------------------------- if __name__ == "__main__": f = r'path\to\sample.xml' parseXML(f) The code is pretty well commented, but we’ll spend a little time going over it anyway. First we pass it our sample XML file and objectify it. If you want to get access to a tag’s attributes, use the attrib property. It will return a dictionary of the attribute’s of the tag. To get to sub-tag elements, you just use dot notation. As you can see, to get to the begin tag’s value, we can just do something like this: begin = root.appointment.begin If you need to iterate over the children elements, you can use iterchildren. You may have to use a nested for loop structure to get everything. Changing an element’s value is as simple as just assigning it a new value. And if you need to create a new element, just add a period and the name of the new element (see below): root.appointment.new_element = "new data" When we add or change items using objectify, it will add some annotations to the XML, such as xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str". You may not want that included, so you'll have to call the following method to remove that stuff: [python] etree.cleanup_namespaces(root) You can also use “objectify.deannotate(root)” to do some deannotation chores, but I wasn’t able to get it to work for this example. To save the new XML, you actually seem to need lxml’s etree module to convert it to a string so you can save it. At this point, you should be able to parse most XML documents and edit them effectively with lxml’s objectify. I thought it was very intuitive and easy to pick up. Hopefully you will find it useful in your endeavors as well.
June 10, 2012
by Mike Driscoll
· 17,153 Views
article thumbnail
Polymorphism and Inheritance are Independent of Each Other
flexible programs focus on polymorphism and not inheritance . some languages focus on static type checking ( c++ , java , c# ) which links the concepts and reduces polymorphic opportunities . languages that separate the concepts can allow you to focus on polymorphism and create more robust code. javascript, python, ruby, and vb.net do not have typed variables and defer type checking to runtime. is the value of static type checking worth giving up the power of pure polymorphism at runtime? inheritance and polymorphism are independent but related entities – it is possible to have one without the other. if we use a language that requires variables to have a specific type ( c++ , c# , java ) then we might believe that these concepts are linked. if you only use languages that do not require variables to be declared with a specific type, i.e. var in javascript , def in python , def in ruby , dim in vb.net then you probably have no idea what i'm squawking about! :-) i believe that the benefits of pure polymorphism outweigh the value of static type checking. now that we have fast processors, sophisticated debuggers, and runtime exception constructs the value of type checking at compile time is minimal. some struggle with polymorphism , so let's define it: polymorphism is the ability to send a message to an object without knowing what its type is. polymorphism is the reason why we can drive each others cars and why we have no trouble using different light switches . a car is polymorphic because you can send commonly understood messages to any car ( start (), accelerate (), turnleft (), turnright (), etc) without knowing who built the car. a light switch is polymorphic because you can send the message turnon () and turnoff () to any light switch without knowing who manufactured it. polymorphism is literally what makes our economy work. it allows us to build functionally equivalent products that can have radically different implementations. this is the basis for price and quality differences in products, i.e. toasters, blenders, etc. polymorphism through inheritance the uml diagram above shows how polymorphism is stated in languages like c++ , java , and c# . the method (a.k.a operation) start () is declared to be abstract (in uml), which defers the implementation of the method to the subclasses in your target language. the method for start () is declared in class car and specifies only the method signature and not an implementation (technically polymorphism requires that no code exists for method start () in class car ). the code for method start () is then implemented separately in the volkswagenbeetle and sportscar subclasses. polymorphism implies that start () is implemented using different attributes in the subclasses, otherwise the start () method could simply been implemented in the super class car . even though most of us no longer code in c++ , it is instructive to see why a strong link between inheritance and polymorphism kills flexibility. // c++ polymorphism through inheritance class car { // declare signature as pure virtual function public virtual boolean start() = 0; } class volkswagenbeetle : car { public boolean start() { // implementation code } } class sportscar : car { public boolean start() { // implementation code } } // invocation of polymorphism car cars[] = { new volkswagenbeetle(), new sportscar() }; for( i = 0; i < 2; i++) cars[i].start(); the cars array is of type car and can only hold objects that derive from car ( volkswagenbeetle and sportscar ) and polymorphism works as expected. however, suppose i had the following additional class in my c++ program: // c++ lack of polymorphism with no inheritance class jalopy { public boolean start() { … } } // jalopy does not inherit from car, the following is illegal car cars[] = { new volkswagenbeetle(),new jalopy() }; for( i = 0; i < 2; i++) cars[i].start(); at compile time this will generate an error because the jalopy type is not derived from car . even though they both implement the start () method with an identical signature, the compiler will stop me because there is a static type error. strong type checking imposed at compile time means that all polymorphism has to come through inheritance. this leads to problems with deep inheritance hierarchies and multiple inheritance where there are all kinds of problems with unexpected side effects. even moderately complex programs become very hard to understand and maintain in c++ . historical note: c++ was dominant until the mid 1990s simply because it was an object oriented solution that was not interpreted. this meant that on the slow cpus of the time it had decent performance. we used c++ because we could not get comparable performance with any of the interpreted object-oriented languages of the time, i.e. smalltalk. weakening the link the negative effects of the tight link between inheritance and polymorphism lead both java and c# to introduce the concept of interface to pry apart the ideas of inheritance and polymorphism but keep strong type checking at compile time. first it is possible to implement the above c++ example exactly using inheritance as shown by the c# below: // c# polymorphism using inheritance class car { public virtual boolean start(); // declare signature } class volkswagenbeetle : car { public override boolean start() { // implementation code } } class sportscar : car { public override boolean start() { // implementation code } } // invocation of polymorphism car cars[] = { new volkswagenbeetle(), new sportscar() }; for( i = 0; i < 2; i++) cars[i].start(); in addition, through the use of the interface concept we can write the classes in java as follows: // java polymorphism using interface interface car { public boolean start(); } class volkswagenbeetle implements car { public boolean start() { // implementation code } } class sportscar implements car { public boolean start() { // implementation code } } by using an interface , the implementations of the volkswagenbeetle and sportscar can be completely independent as long as they continue to satisfy the car interface. in this manner, we can now get our jalopy class to be polymorphic with the other two classes simply by: class jalopy implements car { … } polymorphism without inheritance there are languages where you have polymorphism without using inheritance . some examples are javascript, python, ruby, vb.net, and small talk. in each of these languages it is possible to write car.start () without knowing anything about the object car and its method. # python polymorphism class volkswagenbeetle(car): def start(): # code to start volkswagen class sportscar(car): def start(): # code to start sportscar # invocation of polymorphism cars = [ volkswagenbeetle(), sportscar() ] for car in cars: car.start() the ability to get pure polymorphism stems from these languages only have a single variable type prior to runtime i.e. var in javascript, def in python, def in ruby, dim in vb.net. with only one variable type there can not be type error prior to runtime. historical note: it was only during the time frame when java and c# were introduced that cpu power was sufficient for interpreted languages to give sufficient performance at run time. the transition from having polymorphism and inheritance tightly coupled to being more loosely coupled depended on run time interpreters being able to execute practical applications with decent performance. there is no such thing as a free lunch you can end up with strange behaviors when you make method calls to objects that don’t implement a method when type checking is deferred to runtime, i.e. sending start () to an object with no start() method. when type checking is deferred to runtime you want an object to respond “ i have no idea how to start () ” if you send the start () method to it by accident. some purely polymorphic languages generally have a way of detecting missing methods: in visual basic you can get the notimplementedexception in ruby you either implement the method _ missing() method or catch a nomethoderror exception in smalltalk you get the # doesnotunderstand exception some languages don’t have exceptions but there are clunky work arounds: in python you have to use the getattr () call to see if an attribute exists for a name and then use callable() to figure out if it can be called. for the car example above it would look like: startcar = getattr(obj, "start", none) if callable(startcar): startcar () javascript ( ecmascript ) will only raise an exception for a missing method in firefox/spidermonkey. even if you have a well defined exception mechanism (i.e. try catch), when you defer type checking to runtime it becomes harder to prove that your programs work correctly. untyped variables at development time allow a developer to create collections of heterogeneous objects (i.e. sets, bags, vectors, maps, arrays). when you iterate over these heterogeneous collections there is always the possibility that a method will be called on an object that is not implemented. even if you get an exception when this happens, it can take a long time for subtle problems to be found. conclusion the concepts of polymorphism and inheritance are linked only if your language requires static type checking ( c++ , java , c# , etc). any language with only a generic type for variable declaration has full separation of polymorphism and inheritance ( javascript , python , ruby , vb.net ), whether they are compiled to byte code or are directly interpreted. the original compiled languages ( c++ , etc) performed static type checking because of performance issues. performing type checking at compile time created a strong link between inheritance and polymorphism. needing deep class inheritance structures and multiple inheritance lead to runtime side effects and code that was hard to understand. languages like c# and java used the notion of an interface to preserve type checking at compile time to weaken the link between inheritance and polymorphism. in addition, these languages compile to a byte code that is interpreted at runtime to give a balance been static type checking and runtime performance. languages like ruby , python , javascript , visual basic , and smalltalk take advantage of powerful cpus to use interpreters to defer type checking to run time (whether the source code is compiled to byte code or purely interpreted). by deferring type checking we break the link between inheritance and polymorphism, however, this power comes with the difficulty of proving that a subtle runtime problem won't emerge. the one caveat to pure polymorphism is that we may develop subtle bugs that can be difficult to track down and fix. pure polymorphism is only worth seeking if the language that you are using can reliably throw an exception when a method is not implemented. effective programmers are seeking polymorphism and not strong>inheritance. the benefits of pure polymorphism outweigh any advantage that compile time type checking provides, especially when we have access to very sophisticated debuggers and support for runtime exception handling. in general, i believe that the benefits of pure polymorphism outweigh the value of static type checking.
June 8, 2012
by Dalip Mahal
· 36,470 Views
article thumbnail
How to: File Sharing Application in C#
This is a sequel to my blog post on "A Client Server File Sharing Application in C#" I have received several emails asking for the application to be made into a whole package instead of having it as a separate client and server applications. In order to save time and not to send the solution as email to people again, I have decided to make it a blog post and make the whole package available. The application is written in C# and it will allow files to be sent from one computer to another on the network. It attempts to compile what both the client and server applications in my previous post- A Client Server File Sharing Application in C# do into a single project. To gain a full understanding of the workings, I recommend you read the following- The full listing of the source code is below. using System;; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FileSharingApp { public partial class Form1 : Form { private static string shortFileName = ""; private static string fileName = ""; public delegate void FileRecievedEventHandler(object source, string fileName); public event FileRecievedEventHandler NewFileRecieved; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.NewFileRecieved+=new FileRecievedEventHandler (Form1_NewFileRecieved); } private void Form1_NewFileRecieved(object sender, string fileName) { this.BeginInvoke( new Action( delegate() { MessageBox.Show("New File Recieved\n"+fileName); System.Diagnostics.Process.Start("explorer", @"c:\"); })); } private void btnListen_Click(object sender, EventArgs e) { int port = int.Parse(txtHost.Text); Task.Factory.StartNew(() => HandleIncomingFile(port)); MessageBox.Show("Listening on port"+port); } public void HandleIncomingFile(int port) { try { TcpListener tcpListener = new TcpListener(port); tcpListener.Start(); while (true) { Socket handlerSocket = tcpListener.AcceptSocket(); if (handlerSocket.Connected) { string fileName = string.Empty; NetworkStream networkStream = new NetworkStream (handlerSocket); int thisRead = 0; int blockSize = 1024; Byte[] dataByte = new Byte[blockSize]; lock (this) { string folderPath = @"c:\"; handlerSocket.Receive(dataByte); int fileNameLen = BitConverter.ToInt32(dataByte, 0); fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen); Stream fileStream = File.OpenWrite(folderPath + fileName); fileStream.Write(dataByte, 4+fileNameLen,( 1024-(4+fileNameLen))); while (true) { thisRead = networkStream.Read(dataByte, 0, blockSize); fileStream.Write(dataByte, 0,thisRead); if (thisRead == 0) break; } fileStream.Close(); } if (NewFileRecieved != null) { NewFileRecieved(this, fileName); } handlerSocket = null; } } } catch { } } private void btnBrowse_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "File Sharing Client"; dlg.ShowDialog(); txtFile.Text = dlg.FileName; fileName = dlg.FileName; shortFileName = dlg.SafeFileName; } private void btnSend_Click(object sender, EventArgs e) { string ipAddress = txtIPAddress.Text; int port = int.Parse(txtPort.Text); string fileName = txtFile.Text; Task.Factory.StartNew(() => SendFile(ipAddress,port, fileName,shortFileName)); MessageBox.Show("File Sent"); } public void SendFile(string remoteHostIP, int remoteHostPort , string longFileName, string shortFileName) { try { if(!string.IsNullOrEmpty(remoteHostIP)) { byte[] fileNameByte = Encoding.ASCII.GetBytes (shortFileName); byte[] fileData = File.ReadAllBytes(longFileName); byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length]; byte[] fileNameLen = BitConverter.GetBytes( fileNameByte.Length); fileNameLen.CopyTo(clientData, 0); fileNameByte.CopyTo(clientData,4); fileData.CopyTo(clientData, 4 + fileNameByte.Length); TcpClient clientSocket = new TcpClient(remoteHostIP, remoteHostPort); NetworkStream networkStream = clientSocket.GetStream(); networkStream.Write(clientData, 0, clientData.GetLength (0)); networkStream.Close(); } } catch { } } } } The Complete source code of the application is available for download Here
June 7, 2012
by Ayobami Adewole
· 24,511 Views
article thumbnail
Killing IntelliJ Launched Processes
I often use IntelliJ to run applications, and on occasion things go wrong. For example, a thread that wont terminate can cause a running application to become unstoppable via the IntelliJ UI. Usually when this happens I end up running ps aux | grep java and following up with a kill -9 for each process that looks like it might be the one I'm looking for. On good days there's only a few processes; however, things are more complicated when I have several to look through. Last week I noticed that the command used to launch the process printed in the Console window, and, more importantly, the idea.launcher.port is part of that command: e.g. idea.launcher.port=7538. Assuming the port is unique, or even almost unique it's much easier to ps aux | grep for than java.
June 7, 2012
by Jay Fields
· 16,679 Views · 3 Likes
article thumbnail
Infographics: Cloud Computing and History
infographic: clouds computing and history i have prepared three new infographics for you;aall of them related with cloud computing. these infographics will tell you about history of cloud computing, its definition, and who needs this cloud. i think that this will be interesting for you. information graphics (known as infographics) are one of the best ways to transfer some information into a reader’s mind. it can be something new, or other useful information gathered in one place. nowadays many people don’t have enough time to read a lot of text on multiple screens. infographics makes the information intuitive and understandable. that’s why we would like to share the best relevant infographics from all over the web. original source: cloud computing by the small business authority original source: a complete history of cloud computing original source: hosting decisions, from the chalkboard
June 6, 2012
by Andrei Prikaznov
· 12,166 Views
article thumbnail
How to Get the JPQL/SQL String From a CriteriaQuery in JPA ?
I.T. is full of complex things that should (and sometimes could) be simple. Getting the JQPL/SQL String representation for a JPA 2.0 CriteriaQuery is one of them. By now you all know the JPA 2.0 Criteria API : a type safe way to write a JQPL query. This API is clever in the way that you don’t use Strings to build your query, but is quite verbose… and sometimes you get lost in dozens of lines of Java code, just to write a simple query. You get lost in your CriteriaQuery, you don’t know why your query doesn’t work, and you would love to debug it. But how do you debug it ? Well, one way would be by just displaying the JPQL and/or SQL representation. Simple, isn’t it ? Yes, but JPA 2.0 javax.persistence.Query doesn’t have an API to do this. You then need to rely on the implementation… meaning, the code is different if you use EclipseLink, Hibernate or OpenJPA. The CriteriaQuery we want to debug Let’s say you have a simple Book entity and you want to retrieve all the books sorted by their id. Something like SELECT b FROM Book b ORDER BY b.id DESC. How would you write this with the CriteriaQuery ? Well, something like these 5 lines of Java code : CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery q = cb.createQuery(Book.class); Root b = q.from(Book.class); q.select(b).orderBy(cb.desc(b.get("id"))); TypedQuery findAllBooks = em.createQuery(q); So imagine when you have more complex ones. Sometimes, you just get lost, it gets buggy and you would appreciate to have the JPQL and/or SQL String representation to find out what’s happening. You could then even unit test it. Getting the JPQL/SQL String Representations for a Criteria Query So let’s use an API to get the JPQL/SQL String representations of a CriteriaQuery (to be more precise, the TypedQuery created from a CriteriaQuery). The bad news is that there is no standard JPA 2.0 API to do this. You need to use the implementation API hoping the implementation allows it (thank god that’s (nearly) the case for the 3 main JPA ORM frameworks). The good news is that the Query interface (and therefore TypedQuery) has an unwrap method. This method returns the provider’s query API implementation. Let’s see how you can use it with EclipseLink, Hibernate and OpenJPA. EclipseLink EclipseLink‘s Query representation is the org.eclipse.persistence.jpa.JpaQuery interface and the org.eclipse.persistence.internal.jpa.EJBQueryImpl implementation. This interface gives you the wrapped native query (org.eclipse.persistence.queries.DatabaseQuery) with two very handy methods : getJPQLString() and getSQLString(). Unfortunatelly the getJPQLString() method will not translate a CriteriaQuery into JPQL, it only works for queries originally written in JPQL (dynamic or named query). The getSQLString() method relies on the query being “prepared”, meaning you have to run the query once before getting the SQL String representation. findAllBooks.unwrap(JpaQuery.class).getDatabaseQuery().getJPQLString(); // doesn't work for CriteriaQuery findAllBooks.unwrap(JpaQuery.class).getDatabaseQuery().getSQLString(); Hibernate Hibernate‘s Query representation is org.hibernate.Query. This interface has several implementations and the very useful method that returns the SQL query string : getQueryString(). I couldn’t find a method that returns the JPQL representation, if I’ve missed something, please let me know. findAllBooks.unwrap(org.hibernate.Query.class).getQueryString() OpenJPA OpenJPA‘s Query representation is org.apache.openjpa.persistence.QueryImpl and also has a getQueryString() method that returns the SQL (not the JPQL). It delegates the call to the internal org.apache.openjpa.kernel.Query interface. I couldn’t find a method that returns the JPQL representation, if I’ve missed something, please let me know. findAllBooks.unwrap(org.apache.openjpa.persistence.QueryImpl.class).getQueryString() Unit testing Once you get your SQL String, why not unit test it ? Hey, but I don’t want to test my ORM, why would I do that ? Well, it happens that I’ve discovered a but in the new releases of OpenJPA by unit testing a query… so, there is a use case for that. Anyway, this is how you could do it : assertEquals("SELECT b FROM Book b ORDER BY b.id DESC", findAllBooksCriteriaQuery.unwrap(org.apache.openjpa.persistence.QueryImpl.class).getQueryString()); Conclusion As you can see, it’s not that simple to get a String representation for a TypedQuery. Here is a digest of the three main ORMs : ORM Framework Query implementation How to get the JPQL String How to get the SPQL String EclipseLink JpaQuery getDatabaseQuery().getJPQLString()* getDatabaseQuery().getSQLString()** Hibernate Query N/A getQueryString() OpenJPA QueryImpl getQueryString() N/A (*) Only possible on a dynamic or named query. Not possible on a CriteriaQuery (**) You need to execute the query first, if not, the value is null To illustrate all that I’ve written simple test cases using EclipseLink, Hibernate and OpenJPA that you can download from GitHub. Give it a try and let me know. And what about having an API in JPA 2.1 ? For a developers’ point of view it would be great to have two methods in the javax.persistence.Query (and therefore javax.persistence.TypedQuery) interface that would be able to easily return the JPQL and SQL String representations, e.g : Query.getJPQLString() and Query.getSQLString(). Hey, that would be the perfect time to have it in JPA 2.1 that will be shipped in less than a year. Now, as an implementer, this might be tricky to do, I would love to ear your point of view on this. Anyway, I’m going to post an email to the JPA 2.1 Expert Group… just in case we can have this in the next version of JPA ;o) References http://efreedom.com/Question/1-6412774/Get-SQL-String-JPQLQuery http://old.nabble.com/Cannot-get-the-JPQL—SQL-String-of-a-CriteriaQuery-td33882629.html http://paddyweblog.blogspot.fr/2010/04/some-examples-of-criteria-api-jpa-20.html http://www.altuure.com/2010/09/23/jpa-criteria-api-by-samples-part-i/ http://www.altuure.com/2010/09/23/jpa-criteria-api-by-samples-%E2%80%93-part-ii/ http://www.jumpingbean.co.za/blogs/jpa2-criteria-api http://wiki.eclipse.org/EclipseLink/FAQ/JPA#How_to_get_the_SQL_for_a_Query.3F
June 5, 2012
by Antonio Goncalves
· 61,276 Views · 1 Like
article thumbnail
Get TeamCity Artifacts Using HTTP, Ant, Gradle and Maven
In how many ways can you retrieve TeamCity artifacts? I say plenty to choose from! If you’re in a world of Java build tools then you can use plain HTTP request, Ant + Ivy, Gradle and Maven to download and use binaries produced by TeamCity build configurations. How? Read on. Build Configuration “id” Before you retrieve artifacts of any build configuration you need to know its "id" which can be seen in a browser when corresponding configuration is browsed. Let’s take IntelliJ IDEA Community Edition project hosted at teamcity.jetbrains.com as an example. Its “Community Dist” build configuration provides a number of artifacts which we’re going to play with. And as can be seen on the screenshot below, its "id" is "bt343". HTTP Anonymous HTTP access is probably the easiest way to fetch TeamCity artifacts, the URL to do so is: http://server/guestAuth/repository/download/// Fot this request to work 3 parameters need to be specified: btN Build configuration "id", as mentioned above. buildNumber Build number or one of predefined constants: "lastSuccessful", "lastPinned", or "lastFinished". For example, you can download periodic IDEA builds from last successful TeamCity execution. artifactName Name of artifact like "ideaIC-118.SNAPSHOT.win.zip". Can also take a form of "artifactName!archivePath" for reading archive’s content, like IDEA’s build file. You can get a list of all artifacts produced in a certain build by requesting a special "teamcity-ivy.xml" artifact generated by TeamCity. Ant + Ivy All artifacts published to TeamCity are accompanied by "teamcity-ivy.xml" Ivy descriptor, effectively making TeamCity an Ivy repository. The code below downloads "core/annotations.jar" from IDEA distribution to "download/ivy" directory: "ivyconf.xml" "ivy.xml" "build.xml" Gradle Identically to Ivy example above it is fairly easy to retrieve TeamCity artifacts with Gradle due to its built-in Ivy support. In addition to downloading the same jar file to "download/gradle" directory with a custom Gradle task let’s use it as "compile" dependency for our Java class, importing IDEA’s @NotNull annotation: "Test.java" import org.jetbrains.annotations.NotNull; public class Test { private final String data; public Test ( @NotNull String data ){ this.data = data; } } "build.gradle" apply plugin: 'java' repositories { ivy { ivyPattern 'http://teamcity.jetbrains.com/guestAuth/repository/download/[module]/[revision]/teamcity-ivy.xml' artifactPattern 'http://teamcity.jetbrains.com/guestAuth/repository/download/[module]/[revision]/[artifact](.[ext])' } } dependencies { compile ( 'org:bt343:lastSuccessful' ){ artifact { name = 'core/annotations' type = 'jar' } } } task copyJar( type: Copy ) { from configurations.compile into "${ project.projectDir }/download/gradle" } Maven The best way to use Maven with TeamCity is by setting up an Artifactory repository manager and its TeamCity plugin. This way artifacts produced by your builds are nicely deployed to Artifactory and can be served from there as from any other remote Maven repository. However, you can still use TeamCity artifacts in Maven without any additional setups. "ivy-maven-plugin" bridges two worlds allowing you to plug Ivy resolvers into Maven’s runtime environment, download dependencies required and add them to corresponding "compile" or "test" scopes. Let’s compile the same Java source from the Gradle example but using Maven this time. "pom.xml" 4.0.0 com.test maven jar 0.1-SNAPSHOT [${project.groupId}:${project.artifactId}:${project.version}] Ivy Maven plugin example com.github.goldin ivy-maven-plugin 0.2.5 get-ivy-artifacts ivy initialize ${project.basedir}/ivyconf.xml ${project.basedir}/ivy.xml ${project.basedir}/download/maven compile When this plugin runs it resolves IDEA annotations artifact using the same "ivyconf.xml" and "ivy.xml" files we’ve seen previously, copies it to "download/maven" directory and adds to "compile" scope so our Java sources can compile. GitHub Project All examples demonstrated are available in my GitHub project. Feel free to clone and run it: git clone git://github.com/evgeny-goldin/teamcity-download-examples.git cd teamcity-download-examples chmod +x run.sh dist/ant/bin/ant gradlew dist/maven/bin/mvn ./run.sh Resources The links below can provide you with more details: TeamCity – Patterns For Accessing Build Artifacts TeamCity – Accessing Server by HTTP TeamCity – Configuring Artifact Dependencies Using Ant Build Script Gradle – Ivy repositories "ivy-maven-plugin" That’s it, you’ve seen it – TeamCity artifacts are perfectly accessible using either of 4 ways: direct HTTP access, Ant + Ivy, Gradle or Maven. Which one do you use? Let me know!
June 5, 2012
by Evgeny Goldin
· 11,455 Views
article thumbnail
Issues With Position Fixed & Scrolling on iOS
with the release of ios 5, fixed positioned layout is said to be supported in mobilesafari. the word supported needs to be taken with a pinch of salt, because there’s all kinds of issues which i intend to show you in the following post. note that i have filed bugs for a number of these during the beta of ios 5 – but god knows how the radar apple thing works, so i don’t know the issue numbers. update: i’ve added “scrolling == unusable position:fixed element” based on corey duston pointing out more bugs with position fixed. position:fixed, who cares? i might have argued that fixed positioned doesn’t matter or isn’t really required in a good app. however, there’s an increasing number of ios apps i’ve noticed that are actually just a collection of webviews (mini-mobilesafaris) with fixed position toolbars as seen in apple’s own appstore app, the native facebook app and instagram below: appstore via @devongovett , facebook via @9eggs issues i’ve created a number of example pages that you can view for yourself, which are used in the following videos. juddering if you add position : fixed in any normal way as you might on a “desktop” site, you’ll see some degree of juddering as the page scrolls. note that this is the simulator running, but i’ve also captured the real iphone (using reflection) showing the same behaviour. the page used was: jsbin.com/3/ixewok/6/ ( edit ) no updated values on scroll the sharp eyed viewer might have spotted some values changing in the video. i’m monitoring the window . scrolltop and window . pageyoffset (and another value which we’ll look at later). you’ll notice that the values don’t change until the scroll has finished. this is a problem if you want to monitor the page position to simulate effects like the bumping and shunting of category headings like you might see in the address book app. position drift if the page is zoomed at all, which you can get in ios when the user rotates from portrait to landscape, as the user scrolls in any scale beyond 1 (i.e. zoomed), the position fixed element drifts upwards (i’ve seen this drift entirely out of view before in other sites): the page used was: jsbin.com/3/ixewok/6/ ( edit ) focus jumping if there’s a focusable element inside the position fixed element, i.e. an input element, this can cause the entire fixed element to jump out of place. this will only happen if the user has scrolled any amount (but if you’re using position : fixed you’re expecting exactly that kind of usage). the page used was: jsbin.com/3/ixewok/8/ ( edit ) scrolling == unusable position:fixed element corey dutson pointed out there’s another issue with position fixed. although his example show scrolling using javascript, the core problem is: if the page moves programatically (i.e. the user didn’t cause the scroll) the elements inside the fix element are unavailable. from the screencast i’ve recorded you can see using iwebinspector that although mobilesafari has painted the fixed element in place, it’s actually not there – the actual element remains in place until you touch and move the page again. the page used was: jsbin.com/3/ixewok/13/ ( edit ) i don’t have a fix for this yet, and i suspect it’s a core painting issue inside of mobilesafari – but i will keep playing to see if there’s something that can be done. fixing juddering with ios 5, mobilesafari also came with - webkit - overflow - scrolling : touch . this is actually intended for inline blocks of content to the page (i mean inline with respect to the document). if i change the css in my previous example, and set the height of my html , body and content block to 100%, then apply the scrolling touch property to the content, the juddering goes away. however, that alone does not fix the juddering. the trick would seem to be: make sure your fixed position element is not on a “moving canvas”. this example has the fixed element over a scrolling element, but not inside of it. so when i tried to apply this technique to the body element, the juddering was still visible, as the fixed element was inside the scrolling element. i also captured this on the real device too. the page used was: jsbin.com/3/ixewok/10/ ( edit ) getting scroll position to update again, those keen eyes might have spotted values are moving again. note that as i’ve changed the css the body is no longer scrolling, so the 0 values on the left and right are window . scrolltop and window . pageyoffset respectively. since the window isn’t scrolling, the content block is in an overflow, the values won’t change. however, the content . scrollx value is changing – but it doesn’t by default. firstly, you have to attach any touch event handler to get this value to update as the user is scrolling (or actually touching), so in javascript i can add: content.ontouchstart = function () {}; the touch event will work with start, end and move, and just needs a value set (note that i didn’t test just setting it to true – that might work too!). however, it’s still not perfect. you’ll see from the video above, that it only updated whilst i’m touching . as soon as i let go during a swipe to scroll, the momentum makes the page continue to scroll, but the value doesn’t update. i’ve yet to work out if it’s even possible to capture this value. ::sigh:: to conclude / tl;dr don’t use position : fixed inside a scrolling element, it’s juddery and looks rubbish (i’ve seen much worse than the juddering shown in the videos). do make use of - webkit - overflow - scrolling : touch and if you want the scroll values, make sure you attach a touch handler to that scrolling element. at the same time: make this work in other mobile browsers too – don’t just cater to apple. it’s a huge headache that apple have half arsed-ed-ly fixed the position : fixed issue and done in a typically microsoft proprietory way.
June 5, 2012
by $$anonymous$$
· 35,749 Views
article thumbnail
Sort Linked List in Ascending Order - C#
Sort Linked List in Ascending Order - C# Efficiency: O(n^2) Inspired by Selection Sort algorithm /// /// This method sorts elements in linked list and returns a new sorted linked list /// /// head node of unsorted linked list /// number of elements in unsorted linked list /// head node of new sorted linked list public static Node SortLinkedList(Node head, int count) { // Basic Algorithm Steps //1. Find Min Node //2. Remove Min Node and attach it to new Sorted linked list //3. Repeat "count" number of times Node _current = head; Node _previous = _current; Node _min = _current; Node _minPrevious = _min; Node _sortedListHead = null; Node _sortedListTail = _sortedListHead; for (int i = 0; i < count; i++) { _current = head; _min = _current; _minPrevious = _min; //Find min Node while (_current != null) { if (_current.Data < _min.Data) { _min = _current; _minPrevious = _previous; } _previous = _current; _current = _current.Next; } // Remove min Node if (_min == head) { head = head.Next; } else if (_min.Next == null) //if tail is min node { _minPrevious.Next = null; } else { _minPrevious.Next = _minPrevious.Next.Next; } //Attach min Node to the new sorted linked list if (_sortedListHead != null) { _sortedListTail.Next = _min; _sortedListTail = _sortedListTail.Next; } else { _sortedListHead = _min; _sortedListTail = _sortedListHead; } } return _sortedListHead; }
June 4, 2012
by Aniruddha Deshpande
· 22,215 Views
article thumbnail
Database unit testing with DBUnit, Spring and TestNG
I really like Spring, so I tend to use its features to the fullest. However, in some dark corners of its philosophy, I tend to disagree with some of its assumptions. One such assumption is the way database testing should work. In this article, I will explain how to configure your projects to make Spring Test and DBUnit play nice together in a multi-developers environment. Context My basic need is to be able to test some complex queries: before integration tests, I've to validate those queries get me the right results. These are not unit tests per se but let's assilimate them as such. In order to achieve this, I use since a while a framework named DBUnit. Although not maintained since late 2010, I haven't found yet a replacement (be my guest for proposals). I also have some constraints: I want to use TestNG for all my test classes, so that new developers wouldn't think about which test framework to use I want to be able to use Spring Test, so that I can inject my test dependencies directly into the test class I want to be able to see for myself the database state at the end of any of my test, so that if something goes wrong, I can execute my own queries to discover why I want every developer to have its own isolated database instance/schema Considering the last point, our organization let us benefit from a single Oracle schema per developer for those "unit-tests". Basic set up Spring provides the AbstractTestNGSpringContextTests class out-of-the-box. In turn, this means we can apply TestNG annotations as well as @Autowired on children classes. It also means we have access to the underlying applicationContext, but I prefer not to (and don't need to in any case). The structure of such a test would look like this: @ContextConfiguration(location = "classpath:persistence-beans.xml") public class MyDaoTest extends AbstractTestNGSpringContextTests { @Autowired private MyDao myDao; @Test public void whenXYZThenTUV() { ... } } Readers familiar with Spring and TestNG shouldn't be surprised here. Bringing in DBunit DbUnit is a JUnit extension targeted at database-driven projects that, among other things, puts your database into a known state between test runs. [...] DbUnit has the ability to export and import your database data to and from XML datasets. Since version 2.0, DbUnit can also work with very large datasets when used in streaming mode. DbUnit can also help you to verify that your database data match an expected set of values. DBunit being a JUnit extension, it's expected to extend the provided parent class org.dbunit.DBTestCase. In my context, I have to redefine some setup and teardown operation to use Spring inheritance hierarchy. Luckily, DBUnit developers thought about that and offer relevant documentation. Among the different strategies available, my tastes tend toward the CLEAN_INSERT and NONE operations respectively on setup and teardown. This way, I can check the database state directly if my test fails. This updates my test class like so: @ContextConfiguration(locations = {"classpath:persistence-beans.xml", "classpath:test-beans.xml"}) public class MyDaoTest extends AbstractTestNGSpringContextTests { @Autowired private MyDao myDao; @Autowired private IDatabaseTester databaseTester; @BeforeMethod protected void setUp() throws Exception { // Get the XML and set it on the databaseTester // Optional: get the DTD and set it on the databaseTester databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT); databaseTester.setTearDownOperation(DatabaseOperation.NONE); databaseTester.onSetup(); } @Test public void whenXYZThenTUV() { ... } } Per-user configuration with Spring Of course, we need to have a specific Spring configuration file to inject the databaseTester. As an example, here is one: However, there's more than meets the eye. Notice the databaseTester has to be fed a datasource. Since a requirement is to have a database per developer, there are basically two options: either use a in-memory database or use the same database as in production and provide one such database schema per developer. I tend toward the latter solution (when possible) since it tends to decrease differences between the testing environment and the production environment. Thus, in order for each developer to use its own schema, I use Spring's ability to replace Java system properties at runtime: each developer is characterized by a different user.name. Then, I configure a PlaceholderConfigurer that looks for {user.name}.database.properties file, that will look like so: db.username=myusername1 db.password=mypassword1 db.schema=myschema1 This let me achieve my goal of each developer using its own instance of Oracle. If you want to use this strategy, do not forget to provide a specific database.properties for the Continuous Integration server. Huh oh? Finally, the whole testing chain is configured up to the database tier. Yet, when the previous test is run, everything is fine (or not), but when checking the database, it looks untouched. Strangely enough, if you did load some XML dataset and assert it during the test, it does behaves accordingly: this bears all symptoms of a transaction issue. In fact, when you closely look at Spring's documentation, everything becomes clear. Spring's vision is that the database should be left untouched by running tests, in complete contradiction to DBUnit's. It's achieved by simply rollbacking all changes at the end of the test by default. In order to change this behavior, the only thing to do is annotate the test class with @TransactionConfiguration(defaultRollback=false). Note this doesn't prevent us from specifying specific methods that shouldn't affect the database state on a case-by-case basis with the @Rollback annotation. The test class becomes: @ContextConfiguration(locations = {classpath:persistence-beans.xml", "classpath:test-beans.xml"}) @TransactionConfiguration(defaultRollback=false) public class MyDaoTest extends AbstractTestNGSpringContextTests { @Autowired private MyDao myDao; @Autowired private IDatabaseTester databaseTester; @BeforeMethod protected void setUp() throws Exception { // Get the XML and set it on the databaseTester // Optional: get the DTD and set it on the databaseTester databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT); databaseTester.setTearDownOperation(DatabaseOperation.NONE); databaseTester.onSetup(); } @Test public void whenXYZThenTUV() { ... } } Conclusion Though Spring and DBUnit views on database testing are opposed, Spring's configuration versatility let us make it fit our needs (and benefits from DI). Of course, other improvements are possible: pushing up common code in a parent test class, etc. To go further: Spring Test documentation DBUnit site Database data verification Database testing best practices Generating DTD from your database schema
June 4, 2012
by Nicolas Fränkel
· 59,899 Views
article thumbnail
Dynamic Property Management in Spring
Dynamic and static properties are really interesting. Learn about managing dynamic property in Spring.
June 4, 2012
by Eren Avsarogullari
· 104,892 Views
article thumbnail
Spring Integration - Robust Splitter Aggregator
A Robust Splitter Aggregator Design Strategy - Messaging Gateway Adapter Pattern What do we mean by robust? In the context of this article, robustness refers to an ability to manage exception conditions within a flow without immediately returning to the caller. In some processing scenarios n of m responses is good enough to proceed to conclusion. Example processing scenarios that typically have these tendencies are: Quotations for finance, insurance and booking systems. Fan-out publishing systems. Why do we need Robust Splitter Aggregator Designs? First and foremost an introduction to a typical Splitter Aggregator pattern maybe necessary. The Splitter is an EIP pattern that describes a mechanism for breaking composite messages into parts in order that they can be processed individually. A Router is an EIP pattern that describes routing messages into channels - aiming them at specific messaging endpoints. The Aggregator is an EIP pattern that collates and stores a set of messages that belong to a group, and releases them when that group is complete. Together, those three EIP constructs form a powerful mechanism for dividing processing into distinct units of work. Spring Integration (SI) uses the same pattern terminology as EIP and so readers of that methodology will be quite comfortable with Spring Integration Framework constructs. The SI Framework allows significant customisations of all three of those constructs and furthermore, by simply using asynchronous channels as you would in any other multi-threaded configuration, allows those units of work to be executed in parallel. An interesting challenge working with SI Splitter Aggregator designs is building appropriately robust flows that operate predictably in a number of invocation scenarios. A simple splitter aggregator design can be used in many circumstances and operate without heavy customisation of the SI constructs. However, some service requirements demand a more robust processing strategy and therefore more complex configuration. The following sections describe and show what a Simple Splitter Aggregator design actually looks like, the type of processing your design must be able to deal with and then goes on to suggest candidate solutions for more robust processing. A Simple Splitter Aggregator Design The following Splitter Aggregator design shows a simple flow that receives document request messages into messaging gateway, splits the message into two processing routes and then aggregates the response. Note that the diagram has been built from EIP constructs in OmniGraffle rather than being an Integration Graph view from within STS; the channels are missing from the diagram for the sake of brevity. SI Constructs in detail: Messaging Gateways - there are three messaging gateways. A number of configurations are available for gateway specifications but significantly can return business objects, exceptions and nulls (following a timeout). The gateway to the far left is the service gateway for which we are defining the flow. The other two gateways, between the Router and Aggregator, are external systems that will be providing responses to business questions that our flow generates. The Splitter - a single splitter exists and is responsible for consuming the document message and producing a collection of messages for onward processing. The Java signature for the, most often, custom Splitter specifies a single object argument and a collection for return. The Recipient List Router - a single router exists, any appropriate router can be used, chose the one that closely matches your requirements - you can easily route by expression or payload type. The primary purpose of the router is route a collection of messages supplied by the splitter. This is a pretty typical Splitter Aggregator configuration. Aggregator - a single construct that is responsible for collecting messages together in a group in order that further processing can take place on the gateway responses. Although the Aggregator can be configured with attributes and bean definitions to provide alternative grouping and release strategies, most often the default aggregation strategy suffices. Interesting Aspects of Splitter Aggregator Operation Gateway - the inbound gateway, the one on the far left, may or may not have an error handling bean reference defined on it. If it does then that bean will have an opportunity to handle an exceptions thrown within the flow to the right of that gateway. If not, any exception will be thrown straight out of the gateway. Gateway - an optional default-reply-timeout can be set on each of the gateways, there are significant implications for setting this value, ensure that they're well understood. An expired timeout will result in a null being returned from the gateway. This is the very same condition that can lead to a thread getting parked if an upstream gateway also has no default-reply-timeout set. Splitter Input Channel - this can be a simple direct channel or a direct channel with a dispatcher defined on it. If the channel has a dispatcher specified the flow downstream of this point will be asynchronous, multi-threaded. This also changes the upstream gateway semantics as it usually means that an otherwise impotent default-reply-timeout becomes active. Splitter - the splitter must return a single object. The single object returned by the splitter is a collection, a java.util.List. The SI framework will take each member of that list and feed it into the output-channel of the Splitter - as with this example, usually straight into a router. The contract for Splitter List returns is as its use in Java - it may contain zero, one or more elements. If the splitter returns an empty list it's unlikely that the router will have any work to do and so the flow invocation will be complete. However, if the List contains one item, the SI framework will extract that item from the list and push it into the router, if this gets routed successfully, the flow will continue. Router - the router will simply route messages into one of two gateways in this example. Gateways - the two gateways that are used between the Splitter and Aggregator are interesting. In this example I have used the generic gateway EIP pattern to represent a message sub-system but not defined it explicitly - we could use an HTTP outbound gateway, another SI flow or any other external system. Of course, for each of those sub-systems, a number of responses is possible. Depending on the protocol and external system, the message request may fail to send, the response fail to arrive, a long running process invoked, a network error or timeout or a general processing exception. Aggregator - the single aggregator will wait for a number of responses depending on what's been created by the Splitter. In the case where the splitter return list is empty the Aggregator will not get invoked. In the case where the Splitter return list has one entry, the aggregator will be waiting for one gateway response to complete the group. In the case where the Splitter list has n entries the Aggregator will be waiting for n entries to complete the group. Custom correlation strategies, release strategies and message stores can be injected amongst a set of rich configuration aspects. Interesting Aspects of Simple Splitter Aggregator Operation The primary deciding factor for establishing whether this type of simple gateway is adequate for requirements is to understand what happens in the event of failure. If any exception occurring in your SI flow results in the flow invocation being abandoned and that suits your requirements, there's no need to read any further. If, however, you need to continue processing following failure in one of the gateways the remainder of this article may be of more interest. Exceptions, from any source, generated between the splitter and aggregator, will result in an empty or partial group being discarded by the Aggregator. The exception will propagate back to the closest upstream gateway for either handling by a custom bean or re-throwing by the gateway. Note that a custom release strategy on the Aggregator is difficult to use and especially so alongside timeouts but would not help in this case as the exception will propagate back to the leftmost gateway before the aggregator is invoked. It's also possible to configure exception handlers on the innermost gateways, the exception message could be caught but how do you route messages from a custom exception handler into the aggregator to complete the group, inject the aggregator channel definition into the custom exception handler? This is a poor approach and would involve unpacking an exception message payload, copying the original message headers into a new SI message and then adding the original payload - only four or five lines of code, but dirty it is. Following exception generation, exception messages (without modification) cannot be routed into an Aggregator to complete the group. The original message, the one that contains the correlation and sequence ids for the group and group position are buried inside the SI messages exception payload. If processing needs to continue following exception generation, it should be clear that in order to continue processing, the following must take place: the aggregation group needs to be completed, any exceptions must be caught and handled before getting back to the closet upstream gateway, the correlation and sequence identifiers that allow group completion in the aggregator are buried within the exception message payload and will require extraction and setting on the message that's bound for the aggregator A More Robust Solution - Messaging Gateway Adapter Pattern Dealing with exceptions and null returns from gateways naturally leads to a design that implements a wrapper around the messaging gateway. This affords a level of control that would otherwise be very difficult to establish. This adapter technique allows all returns from messaging gateways to be caught and processed as the messaging gateway is injected into the Service Activator and called directly from that. The messaging gateway no longer responds to the aggregator directly, it responds to a custom Java code Spring bean configured in the Service Activator namespace definition. As expected, processing that does not undergo exception will continue as normal. Those flows that experience exception conditions or unexpected or missing responses from messaging gateways need to process messages in such as way that message groups bound for aggregation can be completed. If the Service Activator were to allow the exception to be propagated outside of it's backing bean, the group would not complete. The same applies not just for exceptions but any return object that does not carry the prerequisite group correlation id and sequence headers - this is where the adaptation is applied. Exception messages or null responses from messaging gateways are caught and handled as shown in the following example code: import com.l8mdv.sample.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.integration.Message; import org.springframework.integration.MessageHeaders; import org.springframework.integration.support.MessageBuilder; import org.springframework.util.Assert; public class AvsServiceImpl implements AvsService { private static final Logger logger = LoggerFactory.getLogger(AvsServiceImpl.class); public static final String MISSING_MANDATORY_ARG = "Mandatory argument is missing."; private AvsGateway avsGateway; public AvsServiceImpl(final AvsGateway avsGateway) { this.avsGateway = avsGateway; } public Message service(Message message) { Assert.notNull(message, MISSING_MANDATORY_ARG); Assert.notNull(message.getPayload(), MISSING_MANDATORY_ARG); MessageHeaders requestMessageHeaders = message.getHeaders(); Message responseMessage = null; try { logger.debug("Entering AVS Gateway"); responseMessage = avsGateway.send(message); if (responseMessage == null) responseMessage = buildNewResponse(requestMessageHeaders, AvsResponseType.NULL_RESULT); logger.debug("Exited AVS Gateway"); return responseMessage; } catch (Exception e) { return buildNewResponse(responseMessage, requestMessageHeaders, AvsResponseType.EXCEPTION_RESULT, e); } } private Message buildNewResponse(MessageHeaders requestMessageHeaders, AvsResponseType avsResponseType) { Assert.notNull(requestMessageHeaders, MISSING_MANDATORY_ARG); Assert.notNull(avsResponseType, MISSING_MANDATORY_ARG); AvsResponse avsResponse = new AvsResponse(); avsResponse.setError(avsResponseType); return MessageBuilder.withPayload(avsResponse) .copyHeadersIfAbsent(requestMessageHeaders).build(); } private Message buildNewResponse(Message responseMessage, MessageHeaders requestMessageHeaders, AvsResponseType avsResponseType, Exception e) { Assert.notNull(responseMessage, MISSING_MANDATORY_ARG); Assert.notNull(responseMessage.getPayload(), MISSING_MANDATORY_ARG); Assert.notNull(requestMessageHeaders, MISSING_MANDATORY_ARG); Assert.notNull(avsResponseType, MISSING_MANDATORY_ARG); Assert.notNull(e, MISSING_MANDATORY_ARG); AvsResponse avsResponse = new AvsResponse(); avsResponse.setError(avsResponseType, responseMessage.getPayload(), e); return MessageBuilder.withPayload(avsResponse) .copyHeadersIfAbsent(requestMessageHeaders).build(); } } Notice the last line of the catch clause of the exception handling block. This line of code copies the correlation and sequence headers into the response message, this is mandatory if the aggregation group is going to be allowed to complete and will always be necessary following an exception as shown here. Consequences of using this technique There's no doubt that introducing a Messaging Gateway Adapter into SI config makes the configuration more complex to read and follow. The key factor here is that there is no longer a linear progression through the configuration file. This because the Service Activator must forward reference a Gateway or a Gateway defined before it's adapting Service Activator - in both cases the result is the same. Resources Note:- The design for the software that drove creation of this meta-pattern was based on a requirement that a number of external risk assessment services would be accessed by a single, central Risk Assessment Service. In order to satisfy clients of the service, invocation had to take place in parallel and continue despite failure in any one of those external services. This requirement lead to the design of the Messaging Gateway Adapter Pattern for the project. Spring Integration Reference Manual The solution approach for this problem was discussed directly with Mark Fisher (SpringSource) in the context of building Risk Assessment flows for a large US financial institution. Although the configuration and code is protected by NDA and copyright, it's acceptable to express the design intention and similar code in this article.
June 3, 2012
by Matt Vickery
· 23,571 Views
article thumbnail
The Passive-Aggressive Programmer (again)
I'm not even interested in psychology. But. This kind of thing seems to come up once in a great while. You're asked (or "forced") to work with someone who—essentially—fails to cooperate. They don't actively disagree or actively suggest something better. They passively fail to agree. In fact, they probably disagree. They may actually have an idea of their own. But they prefer to passively "fail to agree." I have little patience to begin with. And I had noted my personal inability to cope in The Passive-Aggressive Programmer or Why Nothing Gets Done. Recently, I received this. "I thought I was going crazy and started doubting myself when dealing with a PAP co-worker. I went out on the internet searching for help and ran into your blog and its helped me realize that I'm not crazy. The example conversations you posted are almost every day occurrences here at my job when dealing with my co-worker. From outside of the department it was oh those two just butt-heads because I never knew how to communicate or point out that really I'm a targeted victim of a PAP rather than a butting heads issue. No matter what approach I took with the PAP I was doomed and still not quite sure where to go from here. Would you happen to offer any advice on how to actually deal with PAP? It's driven me to a point where I'm looking for new employment because my employer won't deal with it." I really have no useful advice. There's no way to "force" them to agree with anything specific. In some cases, there's no easy to even determine what they might agree with. Your employer will only "deal with" problems that cause them real pain. If you're butting heads, but still getting things done, then there's no real pain. You're successful, even if you're unhappy. If you want to be both happy and successful, you need to stop doing things that make you unhappy. If you can't agree with a co-worker, you can butt heads (which makes you unhappy) or you can ignore them (which may make you happy.) Ignoring them completely may mean that things will stop getting done. You may appear less successful. If you stop being successful, then your employer will start to feel some pain. When you employer feels pain, they will take action to relieve the pain. You might want to try to provide clear, complete documentation of your colleague's ideas, whatever they are. If you write down the Passive-Aggressive Programmer's "suggestions", then you might be able to demonstrate what's causing the pain. Since a properly passive programmer never actually agrees with anything, it's tricky to pin them down to anything specific. You might be able to make it clear that they're the roadblock that needs to be removed.
June 2, 2012
by Steven Lott
· 12,814 Views
article thumbnail
Why You Should Write a Blog Post Today
Blogging was quite a trend a few years ago, but with the rise of Facebook & Twitter, it’s fallen out of favor with some. Well, I’m here to tell you that you should open your own blog today, and if you own a blog but haven’t posted in a while … you should come back to it and post some more. There are several reasons for maintaining a blog, some of which I’m sure are relevant to you: Reason 1 – A technical memento to your future self I found out today how to do something cool. In a year, I won’t remember how to do it … but I might remember it enough to know what to look for. Once I’ve blogged about something, if I Google for it in the future I often find my own blog post, and save myself a considerable amount of time. There are other venues for such mementos-to-self, but none as indexable and expressive as a blog post. Facebook content is poorly searchable … I searched for something I posted 2 days ago on Facebook and failed to find it except going over my stream/timeline. Twitter is very limiting … I guess it might be good for something, but not for keeping concrete knowledge about how to solve a problem, except that knowledge is just a link. You could post a Stack Overflow or Quora question, and answer it, but that feels kind of akward. Actually, Quora has Boards which are rather similar to blogs for this purpose. Reason 2 – Why not share the love? An immediate followup to Reason#1 – if you worked hard and found out something, why not share it and save some time for other people who might run into the same problem? It’s just being a good citizen, and it doesn’t cost you more effort to share it rather than keep it in a private knowledge base e.g. Evernote / Google Docs. If you’ve ever Googled and found a blog post that solved your problem – now is your time to give something back. Reason 3 – Professional Resume Your blog tells the world about you. Whenever I interview for a job, the first thing on my resume is my blog. It shows that I am passionate about my profession. Even if your blog is just a collection of links, it shows what kind of technology stack you’re using or interested in, what your beliefs are, and what makes you tick. I’ll give a candidate with a personal blog a big +1 over a candidate without a blog any time. It takes courage to go out there and say “Even though I’m not worthy, I’m still out here, doing, writing, and sharing. I’m not the best software engineer / biologist / whatever in the world … but I’m trying my best, and I want to share it with you”. Reason 4 - Alzheimer This is an extension of reason 1. Reason 1 was about forgetting technical stuff … but as the years pass, you don’t just forget technical stuff, you forget who you were. Your life isn’t lived by a single personality, but is rather experienced by an endless series (or continuum) of personalities, each slightly different than the ones before it. I hardly remember what things we like twenty years ago … but I do know that 5 years ago, I felt the immense joy of leaving the army, didn’t like Google for a day, and had loads of fun playing Portal. I recently started maintaining, in addition to this blog and social media accounts, a personal record of how each day worked out for me. My setup is simple – I setup a Google Calendar event to send me a daily reminder at 7 PM each day. I forward this reminder to Evernote, and prefix it with a number between 1 and 5 of “how much I enjoyed this day”, plus a one liner of key events that happened. I have a grand plan to one day go over these notes, chart out my happiness graph, and note any specific events … but for the time being I’m recording. A blog can serve to record part of your history – the part you’re willing to be public about, of course. I picture my kids, ten or twenty years from now, reading through my blog (yeah right, all hundreds of entries , to learn who their father was back on 2012, when we didn’t have hovercrafts and teleportation. Maybe it will happen, maybe it won’t, but I know that I would have been happy if my parents had kept such a diary. Reason 5 – Helping semi-distant friends keep in touch I have 267 friends on Facebook … guess with how many I actually keep in touch in real life? I guess maybe ten-fifteen max, and the real number is probably more close to five. But, thanks to Facebook, I get to not lose my other friends completely. Even though I don’t spend enough time with them, I get occasional glimpses of their lives. The problem with social networks is you can’t possibly keep up with everything … I even miss cool posts like this one because they’re swallowed up in a huge stream of noise. A part of the fix is blogging. When you have a blog, I’ll follow it with my trusty Google Reader, and it won’t get swallowed up, because I do read or glance everything in my reader stream. So please, if you’re a friend of mine, do me a personal favor and blog – I want to keep in touch with you! Summary Please, don’t give me bullshit like “You don’t have anything worth writing about” or “You’re not a good enough writer”. Perfect is the enemy of good … just start by writing something, it’s better by any definition than not writing anything. If you care about it, work on your writing and save up interesting bits to write later (I was saving the idea for this post for a couple of months now, until I got the time and energy to write it). Stuff happens in your life, both personal & professional. Save up the good parts, and write … your future self + children will thank you later.
May 31, 2012
by Ron Gross
· 13,063 Views · 1 Like
article thumbnail
Eclipse Working Sets Explained
eclipse comes with a large set of different views: they allow the developer to represent the information in various forms and with different angles. most of these views are navigation oriented: a perfect example for this is the projects view or the outline view . but over time i add more projects, more resources to my project, and at a certain time things get overwhelming. i have a lot of projects, and i do not want to switch between workspace too often. yes, i can open and close projects, but this gets cumbersome too. thankfully, there is a solution in eclipse: working sets . working sets allow me to group elements for display in views. with that, i can do operations on a set of elements in that working set. especially as i’m using many projects the same time, working sets are a big help to focus on the right set of things at a time. i can define a set of things i want to look at, work with, or whatever: it allows me to get be productive in the universe of my environment. building/compiling a working set a nice feature of using working sets is to build a set of projects. instead of selecting a set of projects and then to compile them together, i use a working set. i use the menu project > build working set > select working set… to create or change working sets: menu to select working set if i have no working set defined, then this will show the following dialog where i can press new… to create a new one: creating new working set to create a working set of c/c++ projects, i select c/c++ and press next : new c c++ working set next i give a name and select the project(s) which shall be in my working set, and press finish : defining working set to build my set of projects, i can select the working set and press ok : selected working set search in a working set it is possible to limit the search to a working set. for this i can choose a working set as scope in the search dialogs: search in a working set managing working sets to manage working sets, i press ctrl+3 (see quick access ) and choose manage working sets… : ctrl+3 with manage working sets… note: i can add extra tool-bars and menus for working sets too (this is explained later). then i can manage my working sets: manage working set configuration project view filtering with working sets i can filter the projects shown in the project view based on working sets. for this i select the small triangle and select/define a working set or choose one from the most recently used sets: working sets for project view with this i can easily filter and focus on a subset of projects: project view with applied working set really cool tip: i’m using working sets as well to avoid too many workspaces. instead of having projects spread over different workspaces, i can keep them in one workspace and use working sets instead. there is an added benefit of using working sets: having too many projects open at the same time in eclipse can slow down the ide: using working sets allows me just to switch quickly between the set of projects i’m working on. but it does not stop at filtering by projects: you can filter even things inside the project structure. i simply deselect things i don’t want to see and can focus on what is important for me: filtering project files export and import of working sets note: import and export of working sets is not part of the standard codewarrior eclipse distribution. you get the import/export feature installed with the mqx plugins (www.freescale.com/mqx) or with the anyedit plugins (http://andrei.gmxhome.de/anyedit/index.html). to export a working set, i use the menu file > export > other > export working set : export working sets with mqx plugins note: the anyedit plugins come as well with an import/expert working set wizard. the file format is different, and the mqx plugin allows drag&drop of the file into eclipse. this gives the following dialog where i can specify the file name and the root of projects: export working set dialog this will store the settings in an xml file. importing the working set is done with file > import > other > import working set . tip: i’m using *.wsd extension for working sets. that way i can simply drag&drop the file into eclipse to import it. other kinds of working sets working sets do not stop at projects and files: select working set type i can create working sets of breakpoints or analysis/trace points. or i can create working sets of any resource files or tasks. the possibilities are nearly endless and depend as well on the extra plugins installed. window working sets and now back to the really cool part. one question remains: what are window working sets? window working sets the thing is that every view and dialog has its own working set setting. in my example below i use a working set ‘coldfire’ for the projects view, but my search dialog has a ‘kinetis’ working set configured: two different working sets sometimes i want this, but not always. what i need is a ‘global’ working set. and here the window working sets comes to rescue me. for this i’m going to add some menus and toolbars to make it really easy… for this i choose the menu window > customize perspecti ve. in the command groups i enable ‘window working set’. additionally it is a good idea to enable ‘working set manipulation’ as well: window working set commands the same way i can enable the toolbar and menu visibility. this gives me added tool-bars to switch between working sets and to add/remove things from a working set quickly: working set toolbars in a similar way, it gives me menu access as well: working sets menu and here is the trick: using ‘ window working set ‘ really means ‘ using the global workbench working set ‘. to select the global workbench working set, i use the toolbar icon to switch between window (or workbench) working sets: selecting global window or workbench working set in the individual views i choose to use the window working sets instead a selection of working sets: selected global window or workbench working set now my working set settings are shared and common for all views: if i switch the working set, it will switch for all views where i have set it to ‘window working set’: window working set applied to multiple views that way my working set is the same across views, and switching between different project settings is done with a simple mouse click. summary working sets are an extremely powerful feature to get focus on a subset of things inside eclipse, based on my workflow. as with many great eclipse features, i need to know about it until you really appreciate the power of it. who knows how many other hidden treasures are buried in eclipse i hope this article helps to save you a few mouse clicks. happy work-setting but over time i add more projects, more resources to my project, and at a certain time things get overwhelming. i have a lot of projects, and i do not want to switch between workspace too often.
May 31, 2012
by Erich Styger
· 69,213 Views
article thumbnail
Two Way Communication in JMS
Today I will debunk quite a popular myth about one way only communication in JMS. There is no classic request-response equivalent of course (just like there is in AMQP), but a message may convey a reply to header containing a reference to a temporary queue. This way we can achieve two way communication in JMS. Below I give you a simple JUnit test which illustrates the idea. Example In the following example I use a temporary queue and set it as JMS reply to header. The temporary queue exists as long as its creator's session is active. The code is pretty simple and self commenting. In testA I create a message and a temporary queue which I expect to recieve a response from the consumer. Comsumer in testB consumes the message, retrieves the reply to destination and sends a text message to it. testC consumes the message from temporary queue. Once the session is closed, temporary queue is disposed and removed. public class AppTest { private static Connection connection; private static Session session; private static Destination destination; private static Destination replyToDestination; @BeforeClass public static void setup() throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory( "tcp://localhost:62626"); connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(true, Session.SESSION_TRANSACTED); destination = session.createQueue("Java.ActiveMQ.Test.Queue"); replyToDestination = session.createTemporaryQueue(); } @AfterClass public static void cleanup() throws JMSException { session.close(); connection.stop(); connection.close(); } @Test public void testA() throws JMSException { MessageProducer producer = session.createProducer(destination); Person person = new Person(); person.setFirstName("Lukasz"); person.setLastName("Budnik"); Message message = session.createObjectMessage(person); message.setJMSReplyTo(replyToDestination); producer.send(message); session.commit(); } @Test public void testB() throws JMSException, InterruptedException { Person person = null; MessageConsumer consumer = session.createConsumer(destination); Message message; while ((message = consumer.receive(2000l)) != null) { if (message instanceof ObjectMessage) { ObjectMessage objectMessage = (ObjectMessage) message; Object object = objectMessage.getObject(); if (object instanceof Person) { person = (Person) object; Assert.assertEquals("Lukasz", person.getFirstName()); Assert.assertEquals("Budnik", person.getLastName()); Destination replyToDestination = message.getJMSReplyTo(); MessageProducer replyToMessageProducer = session.createProducer(replyToDestination); Message replyMessage = session.createTextMessage("OK"); replyToMessageProducer.send(replyMessage); session.commit(); } } } if (person == null) { Assert.fail("Person is null"); } } @Test public void testC() throws JMSException, InterruptedException { String text = null; MessageConsumer consumer = session.createConsumer(replyToDestination); Message message; while ((message = consumer.receive(2000l)) != null) { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; text = textMessage.getText(); Assert.assertEquals("OK", text); session.commit(); } } if (text == null) { Assert.fail("Text is null"); } } } Summary Simple, isn't it? This mechanism is used heavily in Apache Camel and WS frameworks which use transacted JMS under the hood for WS-RM implementations. Using those frameworks, temporary queues and reply to headers are being taken care of transparently so I may even not know that you use them :) cheers, Łukasz
May 29, 2012
by Łukasz Budnik
· 26,674 Views · 1 Like
  • Previous
  • ...
  • 1581
  • 1582
  • 1583
  • 1584
  • 1585
  • 1586
  • 1587
  • 1588
  • 1589
  • 1590
  • ...
  • 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
×