David J McClelland

Experiences at the Intersection of Programming & Design

Archive for the ‘Tools’ Category

Set Up Log4j (Log for Java) in Intellij IDEA

log4jLogo

Use Log4J to filter how much logging your IDE displays. Tap into logging already in code libraries you are using. And shunt output to a log file you can use for other purposes, such as CI reports, performance monitoring etc. Stop using System.out.print!

  1. In IDEA open project settings, click Libraries on Left pane, find Log4J listed in right pane. I use Maven to manage library retrieval and it was listed as Maven: log4j:log4j:signed:1.2.16
  2. Right-click Log4J and select add to modules.
  3. Click the project you will use Log4J in from the list that displays.
  4. In Project tree window find the project you added Log4J to, and open to main/resources. Create this tree if necessary. Create new file log4j.properties.
  5. Paste this in log4j.properties:
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=INFO, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Try it out:

Add this to a Java Class you want to log from:

  private final Logger logger = Logger.getLogger(<>.class);

This should prompt IDEA to ask you if you want to import Logger, which of course, you do. Also replace ClassName with the name of the class you just put your declaration in.

To test this add the following to your main function:

    logger.info("Start of setUp");

 

 

  • 2 Comments
  • Filed under: Tools
  • Selenium 2: First Test

    Background

    You have Selenium installed on your Dev PC and you want to write a simple test to see how it works. Installed meaning Selenium drivers, environmental variables, a designated test directory, properties file that Selenium reads to know how to find stuff etc. That’s not covered here, sorry maybe someday – I didn’t really set up my environment.

    Your first test

    …should be something really simple and obvious that you can run on each browser you will target in the project that requires automated testing.
    I recommend opening a browser to a well-known URL, finding a single element with a string identifier and comparing it to an expected value. Such as opening Google and comparing the window title to “foo” and asserting that the result will be false.

    I found this somewhat poorly written tutorial from IBM which uses GitHub and adapted it:

    package com.axeda.mac;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class GoogleIt
    {
      @Test
      public void test()
      {
        // Instantiate a webDriver implementation
        WebDriver webdriver = new FirefoxDriver();
        webdriver.get("https://google.com");
        Assert.assertEquals("Giggle", webdriver.getTitle());
        webdriver.quit();
      }
    }

    In intelliJ Idea you have to create a configuration that will compile and run the test and report the result back through an event log in the IDE. You can background IntelliJ and wait for a red or green icon overlay on the application in the start menu when it completes the test. If the result is a fail it will offer to display a diff between your values and what came back- nice.

    Test another browser too:

    package com.axeda.mac;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class GoogleIt
    {
      @Test
      public void test()
      {
        // Instantiate a webDriver implementation
        WebDriver webdriver = new FirefoxDriver();
        webdriver.get("https://google.com");
        Assert.assertEquals("Google", webdriver.getTitle());
        webdriver.quit();
        test2();
      }
    
      @Test
      public void test2()
      {
        WebDriver webdriver = new ChromeDriver();
        webdriver.get("https://google.com");
        Assert.assertEquals("Google", webdriver.getTitle());
        webdriver.quit();
      }
    }

    You can daisychain as many browsers as you plan to test on and watch each one load.

     

    More Background

    Since we moved off Flex and started developing HTML5 we have been building up our CI stack to include automated testing via QA, and an unhealthy amount of manual testing.

    We developers are starting to use it to build affirmative tests, as well as using Selenium grid to get concurrent testing- multiple browsers x multiple user accounts x multiple servers. More on that later.

    We are writing tests in Java and using the selenium and openqa libraries to create junit tests. This may change to another test framework in the near future.

    The IBM example I credited does not compile as written. It is missing the imports and context that would make it a good tutorial. It does have a link to a download of the project files used to create the examples, which is from Eclipse but can probably be imported into IntelliJ. I think you have to sign up on IBM Developerworks to get it.

     

     

     

  • 0 Comments
  • Filed under: Techniques, Tools
  • Getting Started with Kendo UI: Templates

    KendoUI-Figure_bigger

    What is a Template?

    more...

    Kendo UI provides a concept of encapsulated html/javascript that can have additional markup to hold repeated, variable data. There are multiple ways to declare, store and use templates. There does not appear to be documentation on the Kendo UI site specifically covering the entirety of templates, so I am going to attempt to collect some here based on examples I find and uses I develop that are reusable. If you come across this and know of a more complete or authoritative source of information please add in the comments.

    The Kendo template is not a single implementation or technique to be defined. So I will attempt to arrange a series of template implementations along a range of complexity.

    • The simplest might be an inline declaration that is part of a dataSource definition for a grid.
    • In the middle might be a template defined in a script tag that is bound to a Kendo Observable object that replaces a named div tag and includes some JavaScript
    • The most complex might be an external script file that can be used in multiple documents as a mutable form definition and makes extensive use of abstracted JavaScript.

    Kendo Template Definition Methods

    • Script I find the concept of stuffing anything you want inside script tags convenient and readable, if a bit hacky, but it is a popular technique. Kendo UI uses it so you can create a template that looks like the HTML and JavaScript that will be derived from it.
    <script id="template" type="text/x-kendo-template">
    anything html and Javascript can go here plus #template stuff inside these#
    </script>
    • JavaScript object: According to Kendo UI these are equivalent. When the template is a simple one-liner it might be better to use a JavaScript declaration inline to keep everything in one place. Using the JavaScript approach for a complex template leads to readability problems. Since a template defined via script can be converted into a JavaScript Template Object via:
    var template = kendo.template($("#template").html());

    …there is no reason to use a Javascript declaration to define a template.

    See Example...

     Template Inclusion Syntax

    Kendo lists the very limited template syntax in their documentation:

    1. Render literal values: #= #
    2. Render HTML-encoded values: #: #
    3. Execute arbitrary JavaScript code: # if(…){# … #}#

    They note that you can escape any literal “#” in JavaScript strings using “\\#” and in HTML script templates using “\#”.

    escaped vs. unescaped example:

    See Example...

    Kendo does not employ any other syntax inside templates. The design decisions around using the # delimiter for templates is refreshingly public. Kendo’s Template overview is buried here.

    Simplest Template Applications

     

    Inline JavaScript by assignment:

    In the context of a Kendo object definition, such as kendoGrid columns:

    Template: '#= kendo.toString(BirthDate,"dd MMMM yyyy") #'

    or
    Populating a list view so that data elements returned by the dataSource are displayed within the list. For example:

     template: "#:name#"
    
    

    A template can be applied to a div tag, replacing it’s contents with a mix of static template contents and variable data.

    more...

    Intermediate Template Applications

    Use a template with Javascript to process a list and spit out an unordered list that replaces a target div:

    See Example...

     
  • 1 Comment
  • Filed under: Techniques, Tools
  • Getting Started with Kendo UI: Anatomy of DataSource

    KendoUI-Figure_bigger

    Consuming services via Get vs. POST, more about Schema.

    Expand each to see a printable slide that can be used as a cheatsheet.

    Anatomy of Kendo Datasource: GET

    Simplest
    Twitter DataSource Called Out
    Transport <--> URL Crosswalk

    Kendo UI Schema

    Schema Overview

    Kendo UI POST DataSource

    DataSource POST Anatomy

     

     

  • 0 Comments
  • Filed under: Techniques, Tools
  • KnockoutJS, jQuery UI

    Quickly shifting gears to an alternative to KendoUI. Our biggest priority is to continue on with an MVVM architecture and as many controls we can customize as possible without having to build them from scratch.

    ko-logojquery

    I am surveying resources to get up and running with KO as quickly as possible. The main site has some good interactive tutorials and videos, but the standout for me so far has to be Knock Me Out. As I was completing the first tutorial on learn.knockoutjs.com I was thinking “why aren’t they presenting this on jsFiddle so I can translate this into local code and run it on my server?” That must have been what Ryan at KnockMeOut.com was thinking because he created a fiddle for each exercise.

    It’s tempting to showcase your live in-browser tutorials in your own proprietary way that hides the boring html wrapping. But it violates a fundamental learning principal: you must situate the learner in an environment where they have their bearings before you can teach them. The very first knockout tutorial will not work run locally unless you know that the Javascript must be located in the body section below the body contents. Their tutorial completely hides this from the novice learner, and leads them down a lovely garden path as a consequence.

    So why did Ryan feel the need to recreate the tutorials on jsFiddle? Why was I excited to find he had done it? because jsFiddle is a common, known environment that people know how to translate into local file implementations. I can understand what I am looking at and view the source of the frame comfortably.

    Custom jQuery Browser Scrollbar

    Find a good working Custom Scrollbar

    Rule number one is to build on a working example, if there is one. After giving up on Webkit Scrollbars, I looked for anything else that used jQuery and divs to make a complete replacement for browser scrollbars. This list claims it has 10 good ones. I tried out any that had a demo implementation, and chose the one that had the most features, documentation and recent activity and no-strings license. Then I loaded it in IE, Firefox and Chrome to see if it was truly not dependent on Webkit.

    mCSB_hScrollbarSite

    The winner: Malihu Custom Scrollbar has easing (iOS like), infinite scroll, fixed or dynamic thumb dimensions, snap-to-pixel, a gitHub, and an update a few days ago, and Creative Commans license with no stipulations. I downloaded the git and installed and ran from my test site in a matter of a minute or two.

    Previewing

    I created a new folder to run a minimal implementation to see what has to be added to the codebase to get the scrollbars.

    After making a copy of the css and arranging the files according to the main project I am going to integrate this with, I started hacking. Added a reference to the .png used for the scroll thumb. Removed a whole lot of color effects to be able to see the image. Added comments and restored most of what I hacked out. That took a couple hours of futzing around.

    mCSBscrollbarDemo

     

    Next I created a horizontal scroll thumb and got that working. To do this I added an entry to the scrollbar css copy to handle an offset of the CSS sprite for horizontal scroll thumb.

    mCSB_hScrollbarDemo

    Applying to a KendoUI component

    Getting the custom scrollbars to work with Kendo required a workout of my testing/troubleshooting techniques so I outlined them here.

    1. Spike It In: First I tried adding the custom scrollbars to a KendoUI demo twitter page by replacing the div class reference. This might worked if I had added a class to the Kendo div, but I didn’t notice that it had an ID and not a class.  The default scrollbars were not replaced. I changed the onLoad function to a named function and called it from the data change function and confirmed that it was firing after the twitter feed had loaded and displayed in the named div I was targeting.
    2. Paste It In: Next I tried adding the contents of the preview page to the twitter demo: that didn’t work right either. I could see the scrollbar but it was in the wrong place and didn’t scroll. I had added all the imports in the same places. If I had added a class to the Kendo div in step 1 it still wouldn’t have worked.
    3. Move It In: Then I moved a copy of the preview page into the twitter project and confirmed that it worked properly. This proved that all the assets were in the right places.
    4. Reverse Paste: I added the twitter demo to the copy of the preview page piece by piece: includes, divs, scripts. Finally I was able to track down the conflict to the jQuery import -commenting out the  jquery.min.js import at the bottom of the body that came from the scrollbar example and using the Kendo jquery.min.js in the head allowed both to coexist and function in a single document. Named that file scrollbarDemo.
    5. Selective Integration: Made a copy of  scrollbarDemo and named it scrollbarKendo and added the div class to the assignment operator for customScroll and it worked.

    mCSBscrollbarKendo

    One thing to note when assigning the custom scrollbar to divs: The list of div ID’s, classes and so forth can be expressions and literals, but the list must be enclosed within quotes.

    <script>
        (function($){
            $(window).load(function(){
                $(".content, #tweets").mCustomScrollbar({
                    set_width:false,
                    set_height:false,
                    horizontalScroll:false});
            });
        })(jQuery);
    </script>

     

     

  • 0 Comments
  • Filed under: Techniques, Tools
  • Webkit Browser Scrollbars

    PSD Design Source File

    If you get the design spec as a Photoshop file, just isolate the part you need on a white background and take a screenshot. I try not to use Photoshop for anything at all since version CS3 it has been very difficult to use for web work. I slice and dice in Fireworks, which somehow has been left alone by Adobe and, is therefore still awesome.

    I am building on the Kendo framework, which leverages jQuery. It has scrollbars, and they are one of the few controls Kendo left as bitmaps, but I am going to try to base64 what I come up with and stuff it in the css file – we’ll see how that goes. But before I do that I want to make sure everything works right, so I am going to try to hack onto one of the Kendo themes to get a working preview.

    Previewing

    The BlueOpal theme is nice but we don’t use it. I thought it would be good to put my scrollbar pieces in place of the Kendo ones and see what happens. When I open the .gif files they look strange – the slider-h.gif is 1×180 pixels, and slider-v.gif is 180×1. OK, this must be a way to pack extra pixels like a spritesheet to change the appearance dynamically. Maybe whatever they are doing makes the custom scrollbars work in IE (no, I checked). OK, forget this approach.

    Let’s just create a standalone project,  style the scrollbar for webkit browsers using CSS tricks and make it appear by stuffing in a lot of text in an HTML div? OK that kinda works.

    One problem: I made the track using a repeating background image – it doesn’t travel well. Let’s see if we can encode it and replace the URL reference with a base64.  Here is how to do that. I only completed the Vertical scrollbar – you can see the horizontal bar is the right color but the gradient is the wrong way and the horizontal track is missing. By the time you read this I may have fixed that too.

    Potential problem: all this trickery does not degrade well for MSIE. Should it be implemented as progressive enhancement? I loaded the fiddle in IE9 and saw Windoze scrollbars no matter what – will have to try other versions using a service. I will post some browserShots when they come back. Browsershots is way too slow, for MSIE only use NetRenderer.

    scrollbars_ie7 scrollbars_ie10

     

    MSIE 7-9 look identical, V10 has a new scrollbar. None show webkit CSS scrollbars. Firefox uses OS-like scrollbars.

  • 0 Comments
  • Filed under: Techniques, Tools
  • KendoUI-Figure_bigger

    The AutoComplete component is a nice simple one to try out all the ways of CRUD. I went over non-service methods in a previous post. But using services is usually the point, so I want to look at accessing data services via JSON, JSONp and possibly another format.  Since there is a decent tutorial on using JSONp called Bind the Grid to Remote Data on the KendoUI site I am going to use a Grid instead of AutoComplete.

    JSON

    In practice, using JSON requires co-locating your web and application servers to be secure and functional. Otherwise browsers will detect the data coming from a different URL from the page and block it because it breaks the same origin policy. I recommend that you set up a JSON service on a localhost LAMP stack, but for my purposes I am going to use JSONp.

    JSONp

    JSONp is a hacky workaround to the same origin policy that winds up getting JSON functionality. You can use it to access public API’s of popular sites like Twitter, Instagram and Google, among others, and that’s why I am going to use it. I am not going to host a JSON data source on my server- it requires too much security knowledge and upkeep.

    What is schema:{ data:”data”} about?

    Within the dataSource in that tutorial there is a schema property called data that is assigned the string value “data”. It follows a convention, but causes confusion because the significance of the name “data” is obscure. Kendo probably named the property “data” because it generically identifies where the data payload is within the JSON returned by the service. And in the service used in the example, the “data” string value is the specific name of the data property in the JSON returned by the service. But Instagram could have chosen to name it “response” like Twitter did, or any other name.

    JSON response data: is the "data" in the schema

    Finding the service name for “Data”

    I was left with the question “how are we supposed to know what the property that contains the data?” In the tutorial the writer mentioned already being very familiar with Instagram and just tells the reader to use “data”. I saw another tutorial on Twitter that covered this detail the same way. Since the API’s are public, they are documented and you could find the answer by reading the docs. I used existing REST calls on another service I am working with that could be coerced into returning JSON, which I intercepted via Charles. Generally once you are able to access a JSON data source (by registering and getting an API key usually) you can run a query and see the response in Charles, Fiddler or built-in browser developer tool to see what property (if any – not required) contains what content inside.

    Accessing Nested Objects

    The data objects within the “data” property are often an array of nested objects. This is almost certain when using a grid control. They can be traversed using dot notation so that a column can be filled with a child property, such as “user.username” in the tutorial. Chrome Developer tools does an outstanding job of outlining a JSON response in it’s preview tab. I used it to show the connection between the object layout and the field definitions in the KendoUI grid columns.

    JSON dot accessor

  • 0 Comments
  • Filed under: Techniques, Tools
  • Getting Started with KendoUI


     

    KendoUI is the pick to replace Flash at the office. We looked at several competing frameworks and Kendo seems the most polished and maintainable one out there. It is built over jQuery and seems to play nice with CSS and HTML5. It has almost all the UI controls Flex offers. Binding data to controls via MVVM declarative object instantiation. So far so good.

    Now I am starting to dig in and try to do actual things with Kendo that we are used to doing with Flex. This is turning out to not be as trivial as advertised. I tend to get lost easily when working with frameworks that are trying to make development simple. Because it isn’t.

    To start with we are moving away from using XML and replacing it with JSON. Our server application is supposed to support it. But it doesn’t really. It only supports JSON in certain ways on certain services. And then there is the complication that JSON will only work on pages hosted with the app server. I don’t run the app server on my dev box. My JSON is hosed. JSONP? Not supported.

    So I am forced to upload a package to someone else’s instance of the app server to see if anything works at all, scrape the JSON returned via Charles, make a data.json file that I can read in my local web server, and then figure out why I can’t populate a beautiful blueberry style datagrid in a single line of code.

    And within a week I am going to hear “Why isn’t this done yet? I thought this framework was a solid choice!”

  • 2 Comments
  • Filed under: Practice, Tools
  • Google Analytics from LocalHost

    If you want to integrate Google Analytics with a site, you want it all working before the site goes live. Even better: integrate it from the convenient, secure localhost server on your dev box.

    Prerequisites:

    • a gmail account
    • a Google Analytics account
    • a web server hosting at least one html page on your local PC
    Create An Account

    Your Google Analytics log-in can be associated with multiple “Accounts” which you define. I organize mine according to what server it tracks and give them the same name as the server machine name. You may decide it is best to segment by customers in order to keep data separated and name it after your customer.

    Within an account you define one or more “Properties” which define what you intend to track. If you have a customer with multiple sites or a site and a mobile app you can keep them under a single account using properties to enter distinct URLs etc. I add a property and name it for each site I develop on a given server.

    Analytics Organization

    To create a new account you have to create at least one profile which will be the default. Profiles are for filtering reports and data and are not really relevant for localhost tests except that you need to make one to see reports:

    1. Log into Google Analytics
    2. Click the Admin tab at upper Right.
    3. Click Profiles tab.
    4. Click + New Profile
    5. Enter profile name and set time zone and country
    6. Click Create Profile
    Google Analytics Property

    Google Analytics Property

    localhost
    To associate a site with a property:

    1. Click Property Settings tab
    2. Enter Property Name. I used my machine name + “” to test a page located at my localhost server’s web root.
    3. Enter Default URL: I use my site name and end with “.com” You used to be able to enter .localhost but that doesn’t work as I’m writing this.
    4. Default Profile: the profile you want the Property to be associated with. If you have more than one dev box or image, pick the one that hosts the site.
    5. I don’t think there is a way to complete a site verification, so I only bother with Webmaster Tools Settings when I move an instance of the site onto a live web server I have already verified.
    6. Click Apply
    Create A Property

    Create A Property

    Change some settings of the property to work with localhost:

      1. Click Tracking Code tab
      2. Scroll down to Website Tracking section
      3. Click Standard tab
      4. Under “1. What are you tracking?” tick Multiple top-level domains radio button
        What Are You Tracking?

        What Are You Tracking?

      5. Under “2. Paste this code on your site” copy the code from the box indicated right below and paste in a text editor
        GA-Code

        GA-Code

      6. Find the line that reads similar to this: _gaq.push([‘_setDomainName’, ‘[yourSiteName’]);
      7. Replace with this: _gaq.push([‘_setDomainName’, ‘none’]);
      8. Paste the final edited code so that it is the last script before the closing head tag in your default site page, such as index.htm.
      9. I added a button to prompt sending a call to analytics without refreshing the page using the following html: 

     

    1. Load on your browser and click the button.
    Wait for it
    Expect to see this for awhile before your clicks are registered by Google Analytics and displayed on your Overview:

    No Visitors

    No Visitors : (

    No Tracking

    No Tracking?

    Another bonus of working from your own server is that you are in control of the events that occur so the signal to noise ratio is effectively 0. My click is the one and only click today!

    visited

    visited : )

  • 0 Comments
  • Filed under: Techniques, Tools
  • Categories





    Finger Lakes, NY

    United States of America

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.