How to turn Solr from stand Alone Mode to Cluster
Henry Resheto

Suppose you have existing stand-alone Solr index and you want to created a replicated version of it for load balancing and failover purposes. This blog will discuss how to add another node and create simplest replicated cluster using Master/Slave technique. In this simple scenario you do not split index into additional partitions, you simply create identical second copy of your entire index on the second host computer.

Under that simple replication scenario Master is responsible for building the index, while queries can be run against either Master or Slave. 

   

Note, that replication in Solr is done on core per core basis, therefore if you have multiple cores that you want to replicate you will need to repeat the process for each core. 
Initial Setup:

  • Host Computer Name: aspen
  • Solr version 4.8.1
  • Stand alone core name: lyrics
  • Solr install directory: /home/solr-4.8.1/
  • Core location: /home/solr-4.8.1/example/solr/lyrics 
  • Solr is running on Jetty on the default port 8983

Goal: turn lyrics core on aspen into master, add another host called willow and make lyrics core on it to be a slave.

Procedure 

Step 1. Install Solr 4.8.1 on willow.

Use the same installation directory: /home/solr-4.8.1/

Step 2.
... click to keep reading

Comments:1
Using AngularJs to develop a chrome extension - Part 1
Tony Kopetto

In this blog I'll describe how to create an chrome extension using angular JS. Chrome extensions are essentially just client side web applications, so you can write them using any JS framework, or no framework at all.  However, frameworks like AngularJS help a lot, so it makes sense to start using them. I'll be using TypeScript instead of JavaScript, you can read more about it in my previous blogs, generally, I recommend to to do this way, since TypeScript is easy to learn and it helps a lot with JavaScript development. Let's get right to it now.

Using gradle to build project.

I'll be using Gradle to build the extension, here's a sample script you'd need:

... click to keep reading

Comments:0
How to encrypt password with spring userdetailservice
Tony Kopetto

Oftentimes web applications allow users to login with a password as opposed with a facebook login (or any other OAuth provider). Here I'll describe how it can be done with spring. A typical password has to be encrypted (or hashed) so that noone can guess what it is looking at the database table. The recommended way is to make use of the BCryptPasswordEncoder spring class.

Add passwordEncoder to authentication manager

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService ())
        .passwordEncoder(new BCryptPasswordEncoder ())
        ;
    }

Declare userdetailsservice provider

    @Override
    @Bean
    protected UserDetailsService userDetailsService() {
        return new AhCloudUserDetailService ();
    }    

 Encrypt password in the service

If you are using spring, you are likely using a service bean to update your users. Use the following method to do it:

    private void encryptPassword(User user) {

        //only process if it's plain text
        if (!BCRYPT_PATTERN.matcher(user.getPassword()).matches()) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder ();
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        }
    }

 The trick is to not encrypt it twice, this line of code is a safeguard against it:

... click to keep reading

Comments:0
How to set up Tomcat for remote profiling behind firewall
Tony Kopetto

If Tomcat is running behind a firewall, visualvm will not be able to connect to it because it uses random ports to do so. So the idea is to set up Tomcat to use only well known ports for remote visualvm profiling.

Modify conf/server.xml

Add the following lines to the conf/server.xml file under the Server tag:

 <Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener"
          rmiRegistryPortPlatform="19001" rmiServerPortPlatform="19002" />

Create text files under conf

Create a new file $CATALINA_BASE/conf/jmxremote.password that contains the following:

admin letmein

and $CATALINA_BASE/conf/jmxremote.access that contains

admin readwrite

Modify or create $CATALINA_BASE/bin/setenv.sh

Add the following options:

JAVA_OPTS="-server -Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.password.file=/usr/share/tomcat7/conf/jmxremote.password -Dcom.sun.management.jmxremote.access.file=/usr/share/tomcat7/conf/jmxremote.access"

That is, presuming your tomcat is installed under /usr/share/tomcat7

copy catalina-jmx-remote.jar under $CATALINA_BASE/lib

use the following command:

wget https://archive.apache.org/dist/tomcat/tomcat-7/v7.0.39/bin/extras/catalina-jmx-remote.jar  


or download it manually.

connect VisualVM to tomcat

Use the following command to connect VisualVM to the remote Tomcat instance:

... click to keep reading

Comments:0
Tomcat 8 : load web applications in parallel
Tony Kopetto

Sometimes one may have a few web applications that take time to initialize. If that happens, it takes a while to load all the applications in tomcat. To speed it up, it's possible to load web applications in parallel. To do that, open conf/server.xml in an editor and locate the following entry:

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            >

Add a new attribute "startStopThreads" and set its value to whatever limit you need, for example 4:

... click to keep reading

Comments:0
Amazon Product API: Root departments - Update Mar 2015
Tony Kopetto

In my previous blog I'd posted a list of Amazon Root departments, or search indexes, which one can use to build a lookup or search query. Turns out, the list has changed, looks like some Browse Node ids have changed, and some new departments have been added. Here goes the updated list:

... click to keep reading

Comments:0
Amazon Product API: Root departments
Tony Kopetto

Amazpn Product API requires that a Search Index, or Root Department, is used when its Product API request is composed. If no index is used, it should be All. But beware: in this case Amazon will only return up to 50 items. If any index other than All is used, Amazon will return up 1o 100 items. Is it possible to bypass this limitation? It is, I'll blog about it. For now here's is a partial list of Amazon root categories for the US locale:

... click to keep reading

Comments:0
Spring Data Solr cannot handle long queries
Tony Kopetto

The other day I was getting unexplained errors from my solr engine. The error looked as follows:

org.springframework.data.solr.UncategorizedSolrException: Error executing query; nested exception is org.apache.solr.cli
ent.solrj.SolrServerException: Error executing query
        at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:123)
        at org.springframework.data.solr.core.SolrTemplate.executeSolrQuery(SolrTemplate.java:332)
        at org.springframework.data.solr.core.SolrTemplate.query(SolrTemplate.java:328)
        at org.springframework.data.solr.core.SolrTemplate.queryForPage(SolrTemplate.java:276)
        at org.springframework.data.solr.repository.query.AbstractSolrQuery$AbstractQueryExecution.executeFind(AbstractS
olrQuery.java:318)
        at org.springframework.data.solr.repository.query.AbstractSolrQuery$PagedExecution.execute(AbstractSolrQuery.jav
a:366)
        at org.springframework.data.solr.repository.query.AbstractSolrQuery.execute(AbstractSolrQuery.java:128)

...

Caused by: org.apache.solr.client.solrj.SolrServerException: Error executing query
        at org.apache.solr.client.solrj.request.QueryRequest.process(QueryRequest.java:98)
        at org.apache.solr.client.solrj.SolrServer.query(SolrServer.java:301)
        at org.springframework.data.solr.core.SolrTemplate$11.doInSolr(SolrTemplate.java:335)
        at org.springframework.data.solr.core.SolrTemplate$11.doInSolr(SolrTemplate.java:332)
        at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:119)
        ... 122 more
Caused by: org.apache.http.ParseException: Invalid content type:
        at org.apache.http.entity.ContentType.parse(ContentType.java:233)
        at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:443)
        at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:199)
        at org.apache.solr.client.solrj.request.QueryRequest.process(QueryRequest.java:90)
        ... 126 more

 

Not very clear. My query was reasonably long, it included about a thousand various parameters, and in the log I could see the following:

... click to keep reading

Comments:0
Oauth2, AngularJs and Downloading File
Tony Kopetto

In my previous series of blogs I'd described how an angularjs application can be secured with OAuth2. However there's still one unresolved issue. When I need to download a file, I usually use a direct link to the resource that provides file content. It would not work now, because the application is secured and I need to pass in the security token. The way I did it was using a bearer header token. But it's not working for direct links. I could, of course, pass it in as a request parameter, since spring security supports that. But I do not want to. So what are my options? Turns out, there's a way to download a file without exposing the acees token in the URL.

Change link to point to AngularJs method

Suppose you have a link to the download endpoint:

<a href="/download/fileid">Download<a/>

Change it to

<a href="javascript:void(0)" data-ng-click="downloadFile ('/download/fileid')">Download<a/>

 

Implement AngularJs method to download file using a hidden IFrame

Now that we have a reference to the method that will download a file using a hidden iframe, let's implement it:

... click to keep reading

Comments:0
JQuery Validation: Customize messages for class based validations
Tony Kopetto

For one of my web applications I needed to implement a validation framework, so I ended up using the JQuery validation plugin on top of Angular. It worked out great, except that I needed to implement dynamic error messages, but it was hard to do, since I'd used class based validation, which means that the error message is hard coded when a new validator is added. Also, I needed to have different levels of messages, such as warning or errors. Below I'll show how it can be implemented with the JQuery validation framework.

Add New Class Based Validator

Let's add a new class based validator that will make sure that a user entered something into a multi value control.

... click to keep reading

Comments:0
Securing AngularJS application with OAuth2 : Part3
Tony Kopetto

In my previous blog I described the process of securing an angular web application with spring oauth. In this blog let's consider a different use case. Suppose you have a job scheduler that makes rest calls to your application. You do not really want to expose a password, but you do want to get an acces token. If that's the case we can use the client credentials oauth2 flow. The idea is simple. Spring osuth2 package exposes a 'oauth/token' endpoint, and you can make a simple call to this endpoint to ask for access token for the client credential flow. While it's not hard to implement, spring comes with a ready-to-use classes.

Spring Client Credentials Flow

Let's start off by creating a resource:

        ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();

Next, let's configure the resource:

        resource.setAccessTokenUri(baseUrl + "/oauth/token");
        resource.setClientId("client_id");
        resource.setClientSecret ("secret");
        resource.setId("restservice");
        resource.setScope(Arrays.asList("manager"));

Next let's get an access token:

        ClientCredentialsAccessTokenProvider provider = new ClientCredentialsAccessTokenProvider();
        OAuth2AccessToken accessToken = provider.obtainAccessToken(resource, new DefaultAccessTokenRequest());

And finally, make the call:

... click to keep reading

Comments:0
Securing AngularJS application with OAuth2 : Part2
Tony Kopetto

In Part1 I described how to set up oaut2 with spring security, in this blog I want to show how client side can be secured as well. We need to intercept every request that failed with reason code 401, make sure it failed because of expired access token, save it in a queue, and when the access token is refreshed, re-execute all the queued requests. Sounds like a lot? Surprisingly (or maybe not) it's not hard to do with angular. 

 

Hidden Iframe

First off, put an iframe on the index page. We'll be using it to make transparent requests to refresh the token. Do not forget to include the following code in your spring security configuration:

... click to keep reading

Comments:0
Extracting hash map values from a field in SQL Server, or sort of Split() function on steroids
Ron Duai

On occasion I am faced with necessity to parse out an array of name-value pairs, a construct commonly known as a hash map. Problem is this entire hash map might be staffed into single field in a database in, for example, following form:

'Ticker=BABA,Quantity=150,OrderType=BUY'

in this case comma is an array delimiter and equal sign separates a name from a value.      

A common task is: using T-SQL parse out the above and represent the result in the following form:

Here is the function that does exactly that:

create function [dbo].[fn_ExtractHashMap]
(
 @StringToParse nvarchar(max),
 @Delimeter char(1)
)
returns @return table (name varchar(max), value varchar(max))
begin
 declare @position1 int, @position2 int, @position3 int,
  @token varchar(max), @name varchar(max), @value varchar(max)

    select @position1 = 1, @position2 = charindex(@Delimeter, @StringToParse)

    while @position1 < len(@StringToParse) + 1
 begin
        if @position2 = 0 set @position2 = len(@StringToParse) + 1
      
  set @token = substring(@StringToParse, @position1, @position2 - @position1) -- this is name=value construct
  set @position3 = charindex('=', @token) -- this is position of '=' character
  if (@position3 > 0)
  begin
   set @name = substring(@token, 1, @position3 - 1)
   set @value = substring(@token,@position3+1, len(@token))
   if (@name is not null 
... click to keep reading

Comments:0
Securing AngularJS application with OAuth2
Tony Kopetto

In this blog I'll show how to secure a AngularJs single page web application with OAuth2. To be clear, I'll be securing two layers of the application differently:

- web pages will be secured with regular spring form based security. In a one page application there would be, well, one page. 

- RESTful calls. Each and every RESTful (or Ajax, depending on how you implement it) call will be secured using OAuth2, using spring OAuth2 security extension.

Form based Security Setup

First off, let's secure our web application with regular form based security. It means that every URL will be checked by spring, and if necessary, the user will be redirected to the login page.

... click to keep reading

Comments:4
Creating Angular directive for select2 jquery plugin from scratch
Tony Kopetto

The select2 jquery plugin turns regular HTML select controls into controls with rich functionality. It requires a bit of JavaScript to initialize it, and when you have many select controls on the same page, it becomes tedious to initialize each one. What if we could do it using HTML markup as in the example below:

... click to keep reading

Comments:0
Cannot paste image into CkEditor
Tony Kopetto

I'm using the CkEditor plugin for one of my web sites. I'd noticed that when I try to paste an image into the editor, Chrome comes up with the following dialog, and refuses to paste the image in.

I could not figure out how to defeat Chrome, but I did find a way to do it in Internet Explorer. I just added my web site to the list of Trusted Sites, and it did the trick.

Now I can finally paste images in both FireFox and Internet Explorer, but still no luck with Chrome. I wonder if that's possible at all, does anyone know?

... click to keep reading

Comments:0
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/PersistenceContextType
Tony Kopetto

I have a web application, and it was working fine until I decided to run a few JUnit tests. This application used Spring, and I was getting the following error:

... click to keep reading


Products in this post
Comments:0
Spring Data and MongoDB: How to create compound Index
Tony Kopetto Sr

To index a single field is easy with Spring Data for MongoDb. For example, if I need to index the last name field in an entity called Employee, I can do the following:

public class Employee extends BaseEntity{
    
    @Indexed
    private String lastName;

But what if you need to create a unique  index on two fields? For example, you want to make sure that first name and last name are unique. For that use case we can use the CompoundIndexes spring data annotation:

... click to keep reading


Products in this post
Comments:0
AngularJs Directive for price range control
Tony Kopetto Sr

In this blog I'll describe how to create an AngularJs directive for a price range selector. It's going to be a wrapper around a jquery plugin, but it's going to use AngularJs goodies such as twi way binding. I want to use it as follows:

<range-slider 
        id="price_range"
        data-ng-model="enteredInfo.priceRange"
        data-min="0"
        data-max="20000"
        data-from="0"
        data-to="1000"
        data-prefix="$"
/>

The advantage of this approach versus using the jquery plugin directly is that there is no Javascript involved and simply by looking at the markup you know what this page is doing.

I'm going to be using TypeScript for this directive, I write more about it in my other blogs.

Basic Price Range Directive Structure

... click to keep reading

Comments:0
AngularJs vs Jquery: to use or not to use
Tony Kopetto Sr

AngularJs is an excellent client templating framework, and usually I try to use it as much as possible and limit the usage of JQuery plugins, however sometimes it is not practical. Here is one good example when I think using JQuery is more practical than using AngularJs directives.

I have a page that shows a bunch of products, and I wanted to show each products' details in a separate modal dialog. For that I found an excellent JQuery plugin, called lightbox. Usually I'd wrap it up in a AngularJs directive, and would use it as follows:

<a href="linktoproduct" tony-lightbox >

Internally the directive would just execute the lightbox method on the link.

Alternatively, I could simply use JQuery to find all the links:

... click to keep reading


Products in this post
Comments:0
Typescript Angular Directive for Flot Charts
Tony Kopetto Sr

Flot is a popular JavaScript library, or rather, a JQuery plugin, for creating charts on the client side. It means that, as opposed to creating a picture on the server side one can create dynamic charts in JavaScript. Both approaches are viable, and could be used together in one web application. In this blog I'll show how to write an angular directive that creates charts, and explain why it is a better approach than simply using JavaScript for that.

As I'd mentioned in my previous blogs, I prefer to use TypeScript to write my JavaScript code, see this blog for more information.

What I want to achieve is the following: instead of setting up my charts in JavaScript, I want to do it directly in HTML, i.e. something like this:

                      <flot-chart 
                         data-chart-data="graphData" 
                         data-chart-options="graphOptions" 
                     />

This way we can see the structure of the page when looking at HTML. Of course, chart-data and chart-options are JavaScript structures and have to be prepared somewhere, usually in an AngularJs controller. We can have other attributes as well, for example that's hwo one would set up various chart handlers:

... click to keep reading


Products in this post
Comments:0
Angular Bootstrap Toggle Directive:Part 1
Tony Kopetto Sr

In this blog I will describe how to create a directive for the bootstrap toggle plugin that can be found here. Why angular directive? angular directives allow to hide all the complexity of the underlying plugin and dramatically reduce the amount of JavaScript in your application, and it's worth the effort. In this blog I'll show the basics as well as some more advanced Angular features, such as the usage of the NgModelController Angular controller. 

Angular Directive and TypeScript

As I'd mentioned in my previous blogs, I always use TypeScript for any JavaScript code. It's an invaluable tool for every JavaScript developer. I'll develop this new directive using TypeScript. If you are new to it, do not be scared away, it's easy to learn, especially if you know any OOP language such as Java or C#.

 Here is the directive that is a wraper aroudn the jQuey plugin:

... click to keep reading


Products in this post
Comments:0
AngularJs directive for Syntax Highlighter : TypeScript
Tony Kopetto Sr

In one of my previous blogs I described how to create an AngularJs directive for the popular Syntax Highlighter JQuery plugin. In this blog I'll show how to rewrite this directive in TypeScript.

Syntax Highlighter Directive in TypeScript

Below is the SyntaxHighlighter directive written in TypeScript:

... click to keep reading

Comments:0
Angular Focus Directive
Tony Kopetto Sr

In this blog I'll show how to create a simple AngularJs directive that sets focus to the element upon which it's used. I prefer to use TypeScript for writing JavaScript code, so do not be alarmed if you do not recognize how it looks. Read my previous blogs for more AngularJs directives written in TypeScript.

AngularJs Focus Directive

Here is the directive source:

/// <reference path="../../../../../../3rdparty/d.ts/angularjs/angular.d.ts"/>

module TonyApp.Common.Directive {

    
    /////////////////////////////////////////////////////
    //Define which attributes will be created on scope
    /////////////////////////////////////////////////////
    export class FocusDirectiveScopeDefinition implements IBaseDirectiveScopeDefinition {
    };

    /////////////////////////////////////////////////////
    //Actual scope object created by angular
    /////////////////////////////////////////////////////
    export interface IFocusDirectiveScope extends IBaseDirectiveScope {
    };
    
    /////////////////////////////////////////////////////
    //return DDO object
    /////////////////////////////////////////////////////
    export class FocusDirective extends BaseDirective {

        constructor (
            $timeout:ng.ITimeoutService
        ){
            super ();
            
            this.restrict="A";
            
            this.link=function ($scope: IFocusDirectiveScope, $element:ng.IAugmentedJQuery, $attrs:any, controller:any) {
                $timeout (() => {
                    $element.focus ();                    
                });
            }
            
        }
        
        
    }

}

/////////////////////////////////////////////////////
//Let angular know about the directive
/////////////////////////////////////////////////////
var FocusDirective = angular.module('FocusDirectiveModule', [], function ($compileProvider) {
    $compileProvider.directive ('focus', function ($timeout) {
        return new TonyApp.Common.Directive.FocusDirective ($timeout);
    });
});

And that's how you could use this directive:

... click to keep reading

Comments:0
How To Simulate a Dead Lock in SQL Server 2014 Database
Ron Duai

Here is an educational exercise I did we a couple of junior SQL developers I mentor to demonstrate a concept of a dead lock.

To recap, a deadlock happens when two concurrent transactions are trying to access and lock two or more different database resources in such way that the first transaction is being locked by the second and at the same time the second transaction is being locked by the first. SQL Server detects deadlocks automatically chooses one of the inter-locked transactions, terminates it, rolls it back and reports error to the calling client.       

The easiest way to simulate a deadlock is to create two tables A and B, populate them with enough data, and then update from two transactions simultaneously. Transaction #1 would update table A first and then table B. Transaction #2 would update table B and then A.

Following script does the initial setup of this experiment.

create table CrashDummy_A
(
 RowID int not null identity,
 CurrentDate datetime not null
)
GO

create table CrashDummy_B
(
 RowID int not null identity,
 CurrentDate datetime not null
)
GO

-- Following takes about 40 seconds on PC with
-- Intel® Core™2 Quad Processor
-- Increase number of rows inserted if it happens faster 
... click to keep reading

Comments:0
Angular Directive for blocking UI during HTTP calls
Tony Kopetto Sr

Sometimes it is desirable to block certain parts of the UI when HTTP calls are made. To block the UI means to disable buttons and other clickable elements. There's a number of JQuery pluging to achieve that, however using angular it can be done in a simple and elegant manner. I'm going to develop a angular directive that allows to block any elements on any page, without using any JS code (of course the directive is written in JS, or rather Typescript, but the user of the directive does not need any JS code).

Angular Directive and Typescript

I prefer to write JS code in typescript, since it allows to catch many errors at compile time and generally allows to organize Javascript code much better. Read more about it in my other blogs. You can also find a bunch of Typescript example on my github repo.

We will be using the directiev as follows:

... click to keep reading

Comments:0
How to override angular 3rd party directive
Tony Kopetto Sr

Sometimes when you are working on a project, you may need to make use of a 3rd party angular directive. However, you may need to change it slightly. Of course, it's possible to change the source code, but it may not be desirable, because when a new version of that library comes out, it may be not so easy to apply your changes over it. In this blog I'll show a couple of tricks that can deal with this issue a bit differently.

Bootstrap Tagsinput directive

Suppose that I want to make the following tow changes to the bootstrap tagsinput directive:

  • rename it (so it's called tony-tags vs bootstrap-tagsinput)
  • change its template slightly to include a CSS file that will override its styles

Below is the new directive, it's written in TypeScript, you can read more about it in my blogs, I'm a proponent of using Typescript, and use it for all JavaScript code in my projects:

... click to keep reading

Comments:0
Amazon Product API: Part 1
Tony Kopetto Sr

Amazon has a bunch of APIs, that people can you do do different things with their infrastricture. The Amazon Product API allows to query their product database, it could be useful for example to people that want to make money with Amazon. Rather than using their tools, oen could simply write up a query and get tons of useful information. Beware of the following limitation though:

  • only 1 request per second for each account

This limitation hampers attempts to process a large number of products. In this blog, however, I want to talk about some interesting types of queries I've used.

Below is a simple Itemlookup request. It allows to get information about a particular product, identified by its ID. You can find this id on any amazon product page, it's called ASIN.

... click to keep reading


Products in this post
Comments:0
AngularJs: Directive's controller and required controllers
Tony Kopetto Sr

The other day I had to develop a AngularJs directive, which seemed simple enough, but it required using both the require attribute (i.e. I needed to use the ngModel controller) and my own directive's controller. I was pretty sure that both would be available in the post link method via the controllers attribute, but turns out it was not the case. Here is the directive (I'm writing my directives in Typescript, check out my other blogs to read more on that):

... click to keep reading

Comments:0
Install Tomcat8 with JDK 1.8 on Centos
Tony Kopetto Sr

Here is what you need to do to install Tomcat8 on Centos. Tomcat requires a JDK to run, so let's install Oracle JDK1.8.

cd /opt/
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u25-b17/jdk-8u25-linux-x64.tar.gz"
tar xzf jdk-8u25-linux-x64.tar.gz

 

These commands with download a tar archive and unarchive it.

Next, let's set up Java using the alternatives Linux command. You can read more about this package here.

cd /opt/jdk1.8.0_25/
alternatives --install /usr/bin/java java /opt/jdk1.8.0_25/bin/java 2
alternatives --config java

alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_25/bin/jar 2
alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_25/bin/javac 2
alternatives --set jar /opt/jdk1.8.0_25/bin/jar
alternatives --set javac /opt/jdk1.8.0_25/bin/javac

To make sure that Java is installed, run the following command:

# java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

Ok, looks good. Now lets download and install Tomcat8:

cd /usr/share/
wget http://www.us.apache.org/dist/tomcat/tomcat-8/v8.0.15/bin/apache-tomcat-8.0.15.tar.gz 
tar xzf apache-tomcat-8.0.15.tar.gz
mv apache-tomcat-8.0.15 tomcat8

We have created a new folder /usr/share/tomcat8. Now we can either run it manually or set up a linux service. Let's do the latter:

... click to keep reading

Comments:0
How to build grid control using AngularJs and Thymeleaf:Part5
Tony Kopetto Sr

In my previous blogs I created a fairly elaborate template based grid control that can

  • use angular or thymeleaf powered templates
  • support client side data, ajax data and no data
  • filter data
  • sort data

As I'd mentioned, given that angular templates allow to do pretty much anything with HTML markup, it makes this control quite useful. The control is template based, as opposed to the many angular or JQuery controls that are primarily JS based. But this control is missing one very important feature, which is multiple row selection. I've used this control myself, for example, to build a notifications screen. I had to deal with thousands of rows, and I had to be able to mark the messages read or unread, or remove them. 

In this blog I'll explain how to implement this functionality. Amazingly (or, for angularjs fans, not really amazingly) it is quite easy to implement. The control itself is going to provide a couple of helper methods, but the checkboxes for the selection can be provided by the template developer.

Multiple selection for grid template

The is pretty much the template which I use myself for the notification page:

... click to keep reading

Comments:0
Java Validation Framework with Spring and Drools:Part2
Tony Kopetto Sr

In my previous post I described Drools Rule engine and Drools API. In this post I'm going to build a simple Java Rule Service based on that.

Rule Manager

Rule manager is a service that, well, manages the rules. It is responsible for storing the rules in the database, building a knowledge base and establishing a new session for the rule executor. Below is the implementation of rule manager (see my previous post for the interfaces).

... click to keep reading


Products in this post
Comments:0
Java Validation Framework with Spring and Drools:Part1
Tony Kopetto Sr

For one of my projects I needed to build a validation framework, which involved a lot of dynamic data validation. Users wanted to be able to enter new rules on the fly, and magically those rules should be enforced without restarting the web server. In the past I'd done something similar using groovy, but that envolved compiling dynamic groovy scripts into classes, and generally that framework used a lot of resources. This time I want to use Drools, an excellent rule engine from Jboss and the perfect tool to impement the dynamic rules I need. Admittedly, this framework has some drawbacks, most notably lack of good documentation, but it does what it's supposed to do.

MVEL

I do not want to spend too much time on describing Drools, but it's worth mentioning that the rules can be written in a number of dialects, of which I prefer MVEL. It has a simple and conscise syntax, which is easy to pick up in a very short time. Here  is an example of a MVEL rule:

... click to keep reading


Products in this post
Comments:0
MongoDb: how to remove duplicate entries in arrays
Tony Kopetto Sr

Recently I had an interesting issue; I have a table of products, fairly small, around 50 mln records, and I store some information in arrays. Some of those arrays had corrupt data, they had some duplicates, and it was not supposed to be that way. I needed to fix it, so I looked into a few options, including writing up a small Java application. But the best way turned out to be using server side Javascript. I'm not a huge proponent of doing that, because it is considered to be slow, and it is slow - but it is also a nice way to do little fix jobs like that. Below is the snippet of code I'd used:

db.Product.find( {array : {$exists:true}, $where:'this.array.length>10'} )
.forEach(
    function (elem) {
        var newArrays =[];
        var newArraysMap ={};
        
        for (var i =0; i < elem.array.length; i ++){
        
            if (!newArraysMap [elem.array [i]]){
                newArraysMap [elem.array [i]]=elem.array [i];
                newArrays.push (elem.array [i]);
            }
        }
        elem.array = newArrays;
        db.Product.save(elem);
    }
  )

 How it works

First off, I needed to find all the bad records, because not every record was affected, thus this query:

... click to keep reading


Products in this post
Comments:0
How to build grid control using AngularJs and Thymeleaf:Part4
Tony Kopetto Sr

In my previous blog I created a fairly elaborate grid control, that is capable of quite a few tricks:

  • show data in grid format using angular templates or thymeleaf templates
  • support client side data, ajax data and no data
  • filter data
  • sort data

Given that angular templates allow to do pretty much anything with HTML markup, it makes this control very versatile. Note that this control is template based, as opposed to the many angular or JQuery controls that are primarily JS based. For example, the popular datatables control reuiqres quite a bit of code if you want to customize your grid's HTML, and that's not too convenient. Using Angular templates seems much more natural, because by simply looking at the template you can visualize how your grid is going to look.

In this blog I'll explain the rest of the control.

Directive Controller

In angular controllers are usually used to setup the scope and to define all the data structures and methods that you do not want to put on the scope. After all, the controlelr is just a JavaScript object, and you can treat it as such. It's a good question though, when to use the

... click to keep reading


Products in this post
Comments:2
How to build grid control using AngularJs and Thymeleaf:Part3
Tony Kopetto Sr

In my previous blogs I described how AngularJs and Thymeleaf can be used together to create a dynamic grid control. The idea was to use an AngularJS directive to dynamically change grid's pages using a Thymeleaf server side template. However, sometimes this is not desirable. What if I need to calculate some data in JS and feed it to the grid control? Or maybe I need to grab the client side data off the server and use a AngularJs template to present it. Looks like the control I'd built is not good enough for these 2 use cases. In this blog I'll show how to extend this control to support this functionality.

Data mode

I want my grid to be able to handle the following use cases:

  • the grid data is contained in the template, created by thymeLeaf. It means I do not need any client side data
  • The grid data is handled on the client side via AJAX calls, and the template is a simple AngularJs HTML template
  • The grid data is handled on the client side via AJAX calls, and the template is complex AngularJs HTML template, created by Thymeleaf
  • The grid data is completely handled
... click to keep reading

Comments:0
How to Create New Core in Solr
Ron Duai

This procedure explains how to create a new core in Solr 4.8.1. Suppose you have Solr installed in /home/solr-4.8.1 directory. Under /home/solr-4.8.1/example/solr/ there will directory called collection1 representing the core. In the below procedure we will clown that core to create a new one.   

Step 1. Shut down Solr.

do

# ps -ef | grep java

To find out process id of jetty process that runs Solr, suppose it is 2721.

... click to keep reading


Products in this post
Comments:0
Spring data and Solr: commit or not commit and multiple threads
Tony Kopetto Sr

In one of my previous blogs I described how Spring data can be configured to use two or more solr instalnces. Now I want to discuss an interesting issue I had. I wanted to update data in one of the cores, and I wanted to do it using Spring Data. Here is a somewhat naive approach, which I'd tried first:

Spring Data Solr Entity

Let's declare a solr entity, it's just a simple POJO annotaited with the @SolrDocument annotation:

SolrDocument(solrCoreName="product")
public class SolrProduct{
    
    @Id
    @Field
    private String id;
    
    @Field
    private String name;

}
    
 

Spring Data Solr Repository

Now we need a spring data repository. As I'd described in my previous blogs, a spring repository is an interface, although customizable, and it's used by spring data to create an implementation class. In it we get a lot of things for free, in particular, an ability to save entities.

public interface SolrProductRepository extends SolrCrudRepository<SolrProduct, String> {

}

That's it, we do not need to declare a single methods in this interface.

Spring Service

Now let's make use of the both classes, and declare a Spring Service:

... click to keep reading


Products in this post
Comments:0
Cassandra: Greater-Than Querying
Ron Duai

Let's build on the example we described in the Step 10 of one of my previous blogs:

How to install Cassandra 2.1...

Suppose you want to get a quote for Microsoft. That seems to be a straight forward thing to do.

cqlsh:stocks> select * from quotes where ticker='MSFT';

 ticker | quote
--------+-------
   MSFT | 48.68

(1 rows)

Now suppose we want to see all stocks trading above 50.00.

Let's try this:

cqlsh:stocks> select * from quotes where quote>50;
code=2200 [Invalid query] message="No indexed columns present in by-columns clause with Equal operator"

Op-s-s! Not as straight forward. Apparently Cassandra does not allow greater-than or less-that querying unless there also an equality in the where clause.  

To put long story short the solution is to add another (bogus) column to the table and define two secondary indexes: on quote column and on bogus column.

Here is the listing:

... click to keep reading


Products in this post
Comments:0
Spring MVC:@Valid not working for JSON attributes
Tony Kopetto Sr

The other day I was writing a Spring MVC controller for a restful service, and came across an interesting Spring MVC behavior. If you use both the @Valid annotation and a BindingResult argument, you may be tricked into thinking that the validation is nto working even when it is. The results are simply stored on the BindingResult parameter. If you remove this parameter, however, Spring MVC will throw an exception which will be propagated to your client. Here's a little example:

JSR303 Bean

JSR 303 is a Java specification that allows to annotate beans with validation annotations, such as @NotNull or @Size, or create your own annotations. Here is a simple POJO bean:

 public class Request {

    @NotNull(message="Name cannot be empty")
    @Size(min=0, max=255, message="Name cannot exceed 255 characters")
    private String name;
    
    @NotNull(message="Title cannot be empty")
    @Size(min=10, max=255, message="Title cannot exceed 255 characters")
    private String title;
    
    @NotNull(message="Short Description cannot be empty")
    @Size(min=25, max=1000, message="Short Description cannot exceed 1000 characters")
    private String shortDescription;

}

 Controller

Here is the controller, it's a typical RESTful controller, and this particular method is supposed to save an incoming request.

... click to keep reading


Products in this post
Comments:0
How to install Cassandra 2.1 on CentOS 6.5 and CentOS 7.0
Ron Duai

CentOS 6.5 and CentOS 7.0  are the two versions that this procedure has been tried but it should work equally well on any SentOS 6.x and 7.x.

Step 1. Install Oracle Java JDK

Out of the box Centos comes with Open JDK, but Cassandra actually requires Oracle JDK. While they say it is "recommended" to have Oracle JDK, from my experience it is absolute requirement, Cassandra will not run on Open JDK.

The following post:
How to Replace Open JDK Java with Oracle JDK on CentOS 6.x and CentOS 7.x 
describes in details the procedure.  

Step 2. Install JNA

This step is optional but recommended, it can be accomplished by running the following command:

yum install jna

Note: make sure you have an internet connection

Step 3. Create Cassandra yum file

Create the following file /etc/yum.repos.d/datastax.repo with the following content:

[datastax]
name = DataStax Repo for Apache Cassandra
baseurl = http://rpm.datastax.com/community
enabled = 1
gpgcheck = 0

 

Step 4. Install Cassandra package

This is accomplished by running these two commands

... click to keep reading

Comments:0
How to Replace Open JDK Java with Oracle JDK on CentOS 6.x and CentOS 7.x
Ron Duai

Out of the box CentOS comes with Open JDK Java, which may not be suitable for all kinds of applications.

This post will explain how to replace Open JDK with Oracle JDK. For the purposes of this example we will install Java 8, but if older version of Java is needed the procedure is similar.

In CentOS terminal window type "java -version" to find out what java is installed:

# java -version
java version "1.7.0_51"
OpenJDK Runtime Environment (rhel-2.4.5.5.el7-x86_64 u51-b31)
OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)

 Note the reference to OpenJDK

In CentOS Firefox browser go to the following URL:

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Or Google proper URL if different version of Oracle Java is needed.  

On the web page locate the following file: jdk-8u25-linux-x64.rpm

Accept Oracle's terms and conditions and proceed downloading it.

When prompted say that you want to perform installation of that package.

When installation completes type "java -version" again.

... click to keep reading


Products in this post
Comments:0
C# LINQ "In" and "Not In" Examples Using Lambda Expressions
Ron Duai

 

Suppose you have a list of objects holding info about stock tickers and stock prices. And it has all kinds of stocks in there. Suppose separately you have array of technology stocks.

You want to print:

  • Tech stocks with their prices.
  • Non tech stocks with their prices.

The first operation would be analogous to "In" cause or "Exists" clause in SQL, and the second operation would be analogous to "Not In" or "Not Exists" operation in SQL.

 

Following C# example demonstrates how to do it using LINQ fluent syntax  and lambda expressions   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqInNotInExample
{
    public class StockPrice
    {
        public String Ticker;
        public double Price;
        public StockPrice(String ticker, double price)
        {
            this.Ticker = ticker;
            this.Price = price;
        }
        public override string ToString()
        {
            return this.Ticker + ": " + this.Price;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<StockPrice> stockList = new List<StockPrice>();
            stockList.Add(new StockPrice("MSFT", 48.68));
            stockList.Add(new StockPrice("MRK", 59.34));
            stockList.Add(new StockPrice("YHOO", 48.55));
            stockList.Add(new StockPrice("ORCL", 39.94));
            stockList.Add(new StockPrice("PG", 89.13));
            stockList.Add(new StockPrice("WMT", 78.77));
            stockList.Add(new StockPrice("FB", 75.60));
            stockList.Add(new StockPrice("F", 14.17));
            stockList.Add(new StockPrice("HPQ", 
... click to keep reading


Products in this post
Comments:0
MongoDb:update field using another field
Tony Kopetto Sr

The other day I had to convert a single value field into a multi value field in MongoDb using shell, and it turned out to be not so hard to do. I'd ended up using the forEach server side method, as in the following snippet of code:

db.Table.find({singleValue:{$exists:true}})
.forEach(
    function (elem) {
      elem.singleValue = [elem.singleValue];
      db.Table.save(elem);
    }
  )

First off, I needed to find all the records that I wanted to update, so I'm using the $exists mongodb predicate:

db.Table.find({singleValue:{$exists:true}})

Then for each found element I execute Javascrit code:

... click to keep reading


Products in this post
Comments:0
AngularJS - Where is my data? - $Scope vs $parent
Tony Kopetto Sr

Angular JS is a client side templating engine, and it shines when used with templates. By that I mean creating HTML using templates and not controllers, although I've seen some people do that. It also allows to create new markup by using directives, and that's where some confusion often arises. Directives can declare isolated scopes, and sometimes, especially if you do not control the directive, you have no choice but use the $parent scope attribute to get to your data. I consider it to be quite an inconvenience, but once you learn how to access your data, it becomes no more than a nuisance.

Let's consider the following grid template. It creates a table, and it uses data provided to it as an attribute, since this template is used by a directive. It's outside the scope of this blog, but I have another blog that describes how to build such a control.

... click to keep reading

Comments:0
Spring Data and Solr: use two solr cores in one web application
Tony Kopetto Sr

In solr one can configure multiple cores, for example one core could be used to store products and another could be user to store comments information. In this blog I will show an easy way to configure spring to support multiple cores in one web application.

Spring Data Solr Java config

Spring data for solr is just like any other spring data projects, it's not different than, for example, spring data for mongodb. It allows to query solr using method names declared in interfaces, overwrite those using the @Query annotation, and generally it makes working with solr an easy thing to do. 

First off, we need to configure all the beans that we will need. Create a class called SolrConfig similar to the following:

@ComponentScan(basePackageClasses=SolrProductService.class)
@EnableSolrRepositories(multicoreSupport=true, basePackages = "com.example.repository")
public class SolrConfig {

    @Bean
    public SolrServer solrServer() {
        return new HttpSolrServer(environment.getRequiredProperty("solr.server.url"));
    }
    
    @Resource
    private Environment environment;

    @Bean(name="solrProductsTemplate")
    public SolrTemplate solrProductsTemplate() throws Exception {
        HttpSolrServer httpSolrServer = new HttpSolrServer(environment.getRequiredProperty("solr.server.url"));
        return new SolrTemplate(httpSolrServer, "product");    
    }

    @Bean(name="solrDiscussionsTemplate")
    public SolrTemplate solrDiscussionsTemplate() throws Exception {   
        HttpSolrServer httpSolrServer = new HttpSolrServer(environment.getRequiredProperty("solr.server.url"));
        return new SolrTemplate(httpSolrServer, "discussion");    
    }
    
}
... click to keep reading


Products in this post
Comments:0
Setting up Protractor tests for sample spring mvc web application: Part2
Tony Kopetto Sr

In my previous blog I described how Protractor can be used together with gradle to create an environment for UI tests. In this blog let's review some of the tests for the sample web application. I'd like to note that although my application is intentionally not of the one-page kind, it uses Angular a lot, and Protractor can be used to test it without any problems.

Basic test structure

I'm using the jasmine framework to write tests, the tests should be fairly simple and short, and if you need any shared functionality, create a number of JavaScript files, called pages. They are really just JavaScript functions. I recommend to have a class called BasePage.js, which will contain all basic functionality, and if you need more pages, they should inherit from this class. As you know, there's no Java like inheritance in JavaScript, but it can be mimiced in many ways, including prototyping inheritance, which I'll be using.

BasePage.js

 Here is the BasePage class. It has a few essential methods, which we will be using in the tests. 

... click to keep reading

Comments:0
Setting up Protractor tests for sample spring mvc web application: Part1
Tony Kopetto Sr

In my previous posts I looked into creating a sample web application written using spring mvc, Thymeleaf, AngularJs, Gradle and mongodb. This application is available on my github repository here. The M4 version which contains the code for this blog, is here. This web application is in good shape, it still is pretty minimalistic, although it has all the moving parts of a modern web application. You can pick it up from github and play around with it. This blog is concerned with setting up UI tests using Protractor.

Why Protractor?

 Protractor is a de facto end to end testing framework for Angular applications. Another framework often used for JavaScript unit tests is Karma, and I'll set it up a bit later. I will be writing protractor tests using JavaScript, and as usually, I'll write up some basic tests that are easy to understand and start using right away, without having to go through a lot of code. JavaScript tests are easy to write, but once they get to a certain size, they become much harder to understand. Just a word of caution.

Set up Protractor with Gradle

I'm using gradle to build the application, so it's

... click to keep reading

Comments:0
TypeScript : is it worth it?
Tony Kopetto Sr

I've been working with TypeScript for a little over a year, and with JavaScript for quite a bit longer. Looking back I sometimes wonder if it was worth it to learn TypeScript, after all it gets compiled into JavaScript, with all the issues, good or bad, that JavaScript has. I would say that despite all the inconveniences the time I'd spent learning the ropes was well spent. For me TypeScript has the following advantages over pure JavaScript:

  • I can use OOP concepts as opposed to functional programming only
  • At the same time, TypeScript can be mixed with Javascript. So if I want to go functional I can
  • TypeScript allows to catch most silly errors, such as incorrect parameters or typo's, before I even get to test the application

At the same time, TypeScript has to be compiled, which is not a big deal (see my blog about it). But once I got used to it, it really was not such a big deal. It does add a few seconds to the build time, and it's not as convenient to debug, but it's not as bad either.

Let's compare the two approaches. In one of my previous

... click to keep reading


Products in this post
Comments:0
Building grid control using AngularJs, Thymeleaf and TypeScript:Part2
Tony Kopetto Sr

In my previous post I described how to prepare your system for compiling typescript classes, and what changes you need to make in build.gradle to execute typescript compiler. Now let's change the existing grid directive to make use of typescript.

BaseDirective TypeScript class

Typescript supports inheritance, so I'll create a base class that defines a few properties from the DDO object (Directive Definition Object). All directives will inherit from this class. Here is the class, if you compare it to the original GridDirective.js, you will hardly recognize it, it looks nothing like a regular JavaScript function:

... click to keep reading


Products in this post
Comments:0
Building grid control using AngularJs, Thymeleaf and TypeScript:Part1
Tony Kopetto Sr

In my previous blog I described how AngularJs and Thymeleaf can be used together to build a cool grid control, which uses angularjs directive and a server-side thymeleaf template. AngularJs is a JavaScript client side framework, and I've been working with JavaScript for quite a while; I've learned that creating bad code in JavaScript is much easier than good quality code. Troubleshooting and debugging AngularJs applications can be time consuming for that very reason. What if we could write our code in strongly typed JavaScript, which would catch a lof of errors before we even get to running the application in a browser? Enter TypeScript.

TypeScript and Gradle

TypeScript is a very nice language, which makes all I mentioned above a reality. It has classes, interfaces and enums, supports inheritance and has many other cool features. Of course, it converts your source code into JavaScript, but I still prefer this approach, because my code becomes much easier to maintain. One drawback is that you need to compile your code before you can use it in the browser. I do it using gradle, since my sample web application is using it. You can download the code from my github repository

TypeScript

... click to keep reading


Products in this post
Comments:4
How to build grid control using AngularJs and Thymeleaf:Part2
Tony Kopetto Sr

Overview

In my previous blog I described how spring MVC, spring data and Thymeleaf can be used to build a page, which shows users' orders. In this blog I'm going to describe how to build a angular grid, or paginator,  directive that is capable of interacting with the server and delivering thymeleaf templates.

Why Angular and not Thymeleaf?

 It's a good question indeed. I can use Thymeleaf to produce any kind of HTML on the server side, and indeed my application is Thymeleaf based, it's not a one page application. But at the same time, it uses AngularJs to build the page out of AngularJs directives. Frankly, I do not think that one page applications are any better than web applications which use server side templating. In fact I think that the best results are achieved when both technologies are used in the same application. So my Angular control is going to interact with the server side to grab HTML, which is generated by Thymeleaf. Note that this HTML can be a Angular template, i.e. it can contain AngularJs expressions. For now I'll just use plain old HTML though. Later on I'm going to enhance this control by adding

... click to keep reading

Comments:0
github:repository not found
Tony Kopetto Sr

I prefer to work with github using the github shell, and
occasionally Eclipse. Sometimes when I try to push my
changes in, it complains that it cannot find the repository.
Turns out, it happens when somehow information about
credentials is lost. For me it happens quite often, when
I create new branches and pull the changes in, for
example. I've found a quick way to fix that, but I'm curious
if a better way exists.

Here's what I do:

dd
  • open the config file from the .git hidden folder.
    It looks like this:
[core]
    symlinks = false
    repositoryformatversion = 0
    filemode = false
    logallrefupdates = true
    bare = false
    hideDotFiles = dotGitOnly
[remote "origin"]
    url = https://github.com/tonykopetto/minimalspringmvcsample.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[branch "M1"]
    remote = origin
    merge = refs/heads/M1
[branch "M2"]
    remote = origin
    merge = refs/heads/M2

And then I add my user id and password to the URL:

... click to keep reading


Products in this post
Comments:0
C# Interview Question: What is binary tree and how to determine its depth?
Jon Pion

Answer: Binary tree is an in memory tree structure where every node can have not more than two children. It is common to refer to children of a particular node as left child or right child.   

Here are examples.

 
Binary tree with root element only Binary tree where root has two children, three grandchildren and one great grandchild The book to read more about data structures and see more problems like that and their solution

 

Node A is a root node of the tree here. Node B is a left child of node A and node C is a right child of note A. Note that node C has only only one child, so does node E, and nodes D and F have no children at all.

In C# is a simplest form a binary tree can be created with the use of the following class.

... click to keep reading


Products in this post
Comments:0
How to build grid control using AngularJs and Thymeleaf:Part1
Tony Kopetto Sr

Overview

For one of my projects I needed to find a grid control. Sounds simple, but it turned out that while there are many grid controls out there, I could not find any that would suit me. I wanted a template based control, the best plugin I could find in the angular world was the ng-grid, which was not template based. Another good alternative was the datatables control, but it was not good enough for me as well, since it was not template based and adopting it to angular was challenging (although I did do it). So in the end I decided to develop my own AngularJS control, and I'm going to describe it here. See my previous blogs for more on AngularJs, Thymeleaf and Spring Mvc. You can access the whole project on github using this link.

What is template based grid?

Most grids I looked at were designed so that I needed to describe my columns and other configuration in JavaScript. While it may work for some, I prefer to describe my tables in HTML, but I want to use angular to create a directive. Angular directives is a nice way to provide custom HTML

... click to keep reading

Comments:0
C# WPF Interview question: Resizable Sliders with MVVM
Jon Pion

Here is an interesting program what I was asked to develop during a job interview lately. The main windows consists of a bar on the top and three vertical sliders on the bottom

  1. 1) As sliders go up and down the color of the bar changes, with each slider representing R-G-B values respectively.
  2. 2) If main window resizes the height of the colored bar should remain constant but sliders should resize along with the window.
  3. 3) Implement program using MVVM design pattern  

Solution

Listing 1: MainWindow.xaml

... click to keep reading

Comments:0
Spring MVC with mongo, spring social, thymeleaf and angularjs: Part6
Tony Kopetto Sr

Over the course of my previous blogs I'd demonstrated how Spring MVC, Spring Social, Thymeleaf and MongoDb can be used all together to create a modern web application. So far my application has been pretty minimalistic on the UI part, it's time we started adding some pages. Let's start off with bootstrap, a responsive framwork, that allows your application to look good on any device, be it a desktop browser or a smartphone. Check out my previous blogs to get yourself up to speed.

Adding Bootstrap

Bootstrap is a popular JavaScript based framework, that allows to build rich web applications using plain HTML markup as opposed to JavaScript. The advantages of using Bootstrap are many, one being that your application becomes responsive and can be viewed on many devices, and another that you use the familiar HTML markup and not some JS controls to create great looking UI. To include bootstrap in your application you need the following 2 lines of code:

... click to keep reading

Comments:0
Cannot log out using spring security
Tony Kopetto Sr

The other day I was porting a spring based web app from spring 3.2.X to spring 4.1.1 and noticed an interesting glitch; the following code stopped working:

         protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin().
                loginPage("/signin")
                .permitAll()         
            .and()
            .authorizeRequests()
                .antMatchers("/dologin").permitAll()//form login
                .antMatchers("/favicon.ico","robots.txt","/resources/**","/site/**").permitAll()
                .antMatchers("/account").hasAuthority("ROLE_USER")
                .antMatchers("/search").permitAll()
                .and()
         .addFilterBefore(socialAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
         .logout()
         .deleteCookies("JSESSIONID")
         .logoutUrl("/signout")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe()
         .rememberMeServices(rememberMeServices())
         ;
        }

 Turns out, the following code 

         .logoutUrl("/signout")

has to be replaced with the following code:

... click to keep reading

Comments:1
Spring MVC with mongo, spring social, thymeleaf and angularjs: Part5
Tony Kopetto Sr

In my previous blogs I described how a spring powered web application can be configured using spring Java configuration.The application is available on github. In this blog lets take a look at thymeleaf, a powerful server side templating solution.

Template resolver

Thymeleaf has a few components, which you need to know about. One of them is the view resolver, this component is responsible for finding the templates. It is configured using the following code (see my previous blogs for more on that):

    @Bean
    public ITemplateResolver templateResolver() {
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        templateResolver.setCacheable(false);
        templateResolver.setOrder(1);
        return templateResolver;
    }

The ServletContextTemplateResolver class resolves resources as servlet context resources. It's convenient, although you may prefer other resolvers such as ClassLoaderResourceResolver, FileResourceResolver, or UrlResourceResolver. I personally prefer to use the ClassLoaderResourceResolver class, but for the purpose of this web application let's stick with  ServletContextTemplateResolver.

Controller

 In Spring MVC the class responsible for matching incoming requests with the views is called controllers. There is a ton of information about that on the internet, so I won't dwell on it, here's the controller we use in our application:

... click to keep reading


Products in this post
Comments:0
Spring MVC with mongo, spring social, thymeleaf and angularjs: Part4
Tony Kopetto Sr

In Part3 I described how spring data is used to configure MongoDb persistence layer and access multiple mongodb instances. In Part4 I'll describe how Spring Security and Spring Social are used to authenticate your visitors and secure your web application.

Spring Security

As I mentioned before I'm using Java classes and annotations to configure spring, and spring security is no exception. We will be securing a few things, including resources, requests and Java methods. Spring security configuration class was already mentioned when I described how to configure spring MVC in previous blogs:

@Configuration
@Import({PersistenceContext.class,SecurityContext.class, SocialContext.class})
@ComponentScan(basePackages = {
        "com.kopetto.sample.controller"
})
public class WebAppContext extends WebMvcConfigurationSupport

 Let's look at the SecurityContext class.

SecurityContext.java

 I'd like to mention, that this is just one of the many ways to configure spring, and it has all the necessary pieces to secure a typical web application. Some pages are accessible to all users, some accessible only to certain roles, and the same applies to Java classes. Our visitors are going to be authenticated using Facebook, and for now it's the only option I have in this application. Later on I'll add an option to authenticate using an email and password.

... click to keep reading


Products in this post
Comments:0
Spring MVC with mongo, spring social, thymeleaf and angularjs: Part3
Tony Kopetto Sr

Overview

In my previous blog I described how spring MVC can be configured using Java configuration. In this blog I'll look into configuring spring persistence layer. 

MongbDb persistence configuration

 To configure persistence layer in spring, you need two files: java configuration class and properties files, where you store properties such as database name, user and password, and other parameters that vary from environment to environment. You may also want to create a few property files, one per each environment. The Java configuration class has to create a few beans, the easiest way is to  extend the 
AbstractMongoConfiguration class as in the sample below:

... click to keep reading

Comments:0
Useful Java Utility Method that Finds the First Appearance of a Complete Word in a String
Jon Pion

Following below indexOfWord() method works pretty much like indexOf() method of String except if funds position of any of a complete word rather than any sequence of symbols. A word is something that consists of letters, precedes by any symbol that is not a letter and follows by a symbol that is not a letter. In this context "letter" means symbol between 'A' to 'Z' or 'a' to 'z'. The metod returns -1 if no matching word found.

Number of years ago I was asked this as a question during job interview, but it also came handy recently in the eCommerce project I have being worrking on. It could probably be done with reqular expressions and will end up being more compact, but I preffer procedual approach as it works faster at run time. 

public class TextUtil {

 public static int indexOfWord(String searchStr, String word)
 {
  if (word.length() == 0) return -1;
  if (searchStr.length() == 0) return -1;
  
  searchStr = searchStr.toLowerCase();
  word = word.toLowerCase();
  
  int startWith = 0;
  
  while (true)
  {
   int i = searchStr.indexOf(word, startWith);
  
   if (i < 0) return -1;
  
   boolean ok1 = true;
   boolean ok2 = true;
   
   if (i > 0 && isLetter(searchStr.charAt(i - 1))) 
... click to keep reading


Products in this post
Comments:0
Spring MVC with mongo, spring social, thymeleaf and angularjs: Part2
Tony Kopetto Sr

Overview

In my previous blog I've described the process of setting up the local development environment for a sample spring MVC web app. In this blog I'll describe how to configure this application. In my experience, configuring a spring web application could be a frustrating experience, because it can be done in many ways, and it changes from version to version. For this web app I've chosen the latest spring version which is 4.1.1 at the moment of this writing. This web app is available in github, the link is available in Part1.

Configure Web.xml

I prefer to configure spring with Java classes, fortunately starting with the Servlet 3.0 specification and latest spring it is possible to configure web.xml using a java class as well. The only thing that I could not configure using this approach was some error handlers, otherwise everything that you would usually do in web.xml to bootstrap spring, can be done in this class. Spring provides a special class WebApplicationInitializer, here's an example:

... click to keep reading

Comments:0
Spring MVC with mongo, spring social, thymeleaf and angularjs: Part1
Tony Kopetto Sr

Overview

When I just started learning spring MVC, I had been overwhelmed with the sheer amount of information about building web apps. It took some time to sift through all this info, and later on I realized that what I needed was a bare-bones web application, which I could dig into and figure out what's going on. I've seen quite a few sample applications available on the internet, but it was not exactly what I needed. In this blog I'll talk about just such an application. It is available on github and I'll be updating it as I'm progressing. It only has a few pages, but it has all the components that you need to build a modern day web application, including spring mvc, spring social, thymeleaf and angularjs, all in one app.

Project Structure

Below is a screenshot of the project in Eclipse. You can use any IDE, gradle is IDE agnostic. It's a typical maven set up, gradle works well with this code structure as well. It's also a typical spring folder structure. I'm not using any XML config files, so all the configuration classes are under the configuration folder. All controllers are under the controller folder, entities

... click to keep reading


Products in this post
Comments:0
AngularJs directive for Syntax Highlighter
Tony Kopetto Sr

Overview

The other day I needed to use the syntax highlighter for my web site. I came across a nice jQuery plugine for that, but since my site was written suing AngularJs (or rather, not the whole site, but this particular page) then I decided to create a angularJsDirective for that. 

How to use it

Here is the markup I'm using:

<div
    th:if="${! conversation.canEdit ()}"
    id="hdescription"
    data-syntax-highlighter="true"
    style="text-align: left"
    th:utext="${conversation.content == null ? 'Enter something' : conversation.content}"
>
</div>

 

This particular page is wrtten using Thymeleaf, I like this server side templating engine, and I'll blog more about it, but for now we are only interested in the

data-syntax-highlighter

attribute. As you can see, it's very easy to use, let's see how easy it is to write up a directive for that.

Directive

Every directive in angular needs a module, so let's declare one:

var commonDirectiveModule = angular.module('commonDirectiveModule', []);

 

Next we need to declare the directive:

... click to keep reading

Comments:0
How to add second physical hard disk drive to a CentOS based PC
Jon Pion

This blog describes how to add and properly mount new (empty) hard drive to a Centos based PC. I have tried this procedure with HP Minitower 8000 Elite PC and on DELL 9020SFF with CentOS 6.5 installed on it. But it will work on any PC.

So, after you physically install the hard drive into the system do the following:

1. Turn PC on, acknowledge the BIOS notification that another hard drive has been added and after OS boot run following as root:

                # fdisk -l

                to make sure there is new disk /dev/sdb.

                The first one if you did not make respective modifications during CentOS install will be /dev/sda.  

 2. Run

                # df -h /

                Take a note of a space available.

3. We assume that the new disk is either brand new and empty or whatever is on the disk can be whipped out. If you need to delete existing partition from disk /dev/sdb the easiest way to do it is using GUI tool under Applications/System Tools/Disk Utility. Launch that tool and delete partition from  /dev/sdb drive.

4. Run

... click to keep reading


Products in this post
Comments:0
AngularJS:Compile vs link
Tony Kopetto Sr

Compile or Link?

In one of my previous blogs I described how Angular's directives can be used to create nested panels. It involves changing the DOM of the outer panel directive. But it can be done in both the compile function and post link function, how do we choose which one to use, and how? It really depends on what you want to achieve, in my experience we should follow a few simple rules:

  • If I need to change the DOM in such a way that it involves adding or removing other directives, it should be done in the compile function
  • If it's not the case see if you can change it in the compile function regardless. For example, maybe you want to add some CSS styles, like borders, or embelish the DOM with some nice colors
  • If you need to initialize the scope, use the controller function
  • If you need to set up DOM event handlers, or somehow the compile method is not working out for you, use the link function.

Practically, it comes down to the directive lifecycle. The compile function will be called only once per element, and therefore, it makes sense to move

... click to keep reading


Products in this post
Comments:0
Using AngularJS to build nested panels
Tony Kopetto Sr

Nested Panels with AngularJS

In this blog I'll create a few AngularJs directives to implement nested panels. I'll demonstrate how to use the compile function to change the DOM and how Angular handles scopes, because this can be a bit tricky sometimes. I want to create a couple of new HTML elements, panel and panel-header, that will serve as a panel and its heading. These panels can be nested as well. Below is the source code you so you can see how it works right away. 

DOM Transformation

The trick here is that I want to change the DOM slightly. Given the following markup:

        <panel id="panel_4" data-style-for-panel="margin-left:20px; margin-top:10px; margin-bottom:10px;">
            <panel-header id="panel_header_4">
                <h2>Yet Another Nested Panel</h2>
            </panel-header>
            Yet Another Nested Panel Body: {{calc () * 24}}
        </panel>

 

 I want to transform it into

... click to keep reading

Comments:0
AngularJs Directives: Transclusion
Tony Kopetto Sr

What is transclusion?

When I just started learning AngularJS, I was mistified by the term transclusion, I was not sure what it was and how it was meant to be used. Since then I've learned a few things about it, I'd like to share some interesting facts.

First of all, in AngularJs world, transclusion is directly related to directives. As I'd mentioned in one of my previous blogs, Angular directives is a powerful feature that allows to extend HTML markup with your own element, attributes, or even comments. For this blog, let's develop a simple directive, that will serve as a panel.

Simple Panel Directive

We want to use the new directive in the following fashion:

  <panel header="This is a panel">
        <div>
            This is panel's body
        </div>
    </panel>

 
 Of course, you could use regular HTML markup and achieve the same result. However, if you have a lot of pages and later on decide to change the way your panels are structured, you'll end up redoing every page, which is not a good idea. Instead,

... click to keep reading


Products in this post
Comments:0
AngularJS and DataTables
Tony Kopetto Sr

AngularJS is a popular client side MVC framework, and DataTables is a popular jquery plugin, which allows to present your data in grid format. In this blog I'll show how to use them together. There are datatables directives out there, but let's take a look at a very simple standalone example. To play around with my code you just need to download one html page. The table will look as follows, nothing fancy, but just a few lines of code will produce a powerful grid control, capable of using angular expressions in its data.

Let's get started

Create a text file called test.html and put the following html structure in there:

... click to keep reading


Products in this post
Comments:0
Advantages of Normalizing Database Design
Jon Pion

Recently during a job interview I was asked a question: "What are advantages of normalizing a database design?" It wasn't a particularly hard question but the interviewer added an interesting caveat to it..

But I am getting ahead of myself; one thing at a time. So what are advantages of normalizing?

My answer went along the following lines:

  1. 1. Higher degree of data integrity since data stored in a fewer copies. For example, you heed to store customer data which consists of people names and companies. Splitting it into two separate tables would allow organize this into one-to-many structure (one company per many people) and store company name only once.  
  2.  
  3. 2. Faster updates (fewer rows to update). In the above example update of a particular company record would involve a singe row even if that company has 10 associated persons.
  4.  
  5. 2. Usually more compact storage requirements.
  6.  
  7. 3. Better concurrency control since smaller number of rows are locked during a transaction. Not only that, the rows themselves are shorter (have fewer columns), respectively big portions of data would remain unlocked. In the above example if Person table is getting updated as part of longer transaction only
... click to keep reading


Products in this post
Comments:0
Writing AngularJS Directive for CkEditor.
Tony Kopetto Sr

Overview

The other day I wanted to implement a nice WYSIWYG editor for my site. I did not really want to reinvent the wheel and implement it all by myself, so I researched a bit and came across a very nice package called CkEditor. This control is really outstanding feature-wise. This blog discusses possible ways to integrate this control in your web site. After you are done with it, check out this cool book, has tons of useful materials.

Using Inline CkEditor

What I wanted to do was to be able to edit my blog. I thought at first to have some kind of popup window and Edit button, but CkEditor comes with an inline editor. It's really easy to use it. Let's say we have a page with the following structure:

... click to keep reading


Products in this post
Comments:0

What would you like to do?

Find Posts

On our site people discuss products, events, product reviews and more. You can participate in public discussions or create private once, comment, add products and much more.

Enter Store

We have millions of products from various vendors available on our site. Choose whatever you like, discuss with friends and buy when you are ready.

New Post

Want to discuss events, products with your friends or family? Then private conversation is what you need. Or create a public conversation, for example, to review products.