Friday, June 19, 2015

GWT - ListBox with Enum vs ValueListBox implementation example


public class EnumListBoxEditor<T extends Enum<T>> implements IsWidget, LeafValueEditor<T> {

    private ListBox listBox;    private Class<T> enumType;
    public EnumListBoxEditor(Class<T> tClass) {
        listBox = new ListBox();        this.enumType = tClass;        for(T e : enumType.getEnumConstants()) {
            listBox.addItem(e.name());        }
    }

    @Override    public Widget asWidget() {
        return listBox;    }

    @Override    public void setValue(T language) {
        listBox.setSelectedIndex(language.ordinal());    }

    @Override    public T getValue() {
        int index = listBox.getSelectedIndex();        T result = null;        for (T e : enumType.getEnumConstants()) {
            String itemName = listBox.getValue(index);            if (e.name().equals(itemName)) {
               result = e;            }
        }
        return result;    }

    public void setEnabled(boolean isEnabled){
        listBox.setEnabled(isEnabled);    }

}

Thus this approach is acceptable the best way to use ListBox with any Enum or bean that implement HasLabel interface is ValueListBox component e.g.:

@UiField(provided = true)
ValueListBox<TeamDTO> team;
 
this.team = new ValueListBox<TeamDTO>(new HasLabelRenderer<TeamDTO>(), new IdentityProvidesKey<TeamDTO>());
 
public class HasLabelRenderer<T extends HasLabel> extends AbstractRenderer<T>{

    @Override    public String render(HasLabel object) {
        return object == null ? "" : object.getLabel();    }

}
 
public class IdentityProvidesKey<T extends Identity> implements ProvidesKey<T> {
    @Override    public Object getKey(T item) {
        return item == null ? null: item.getId();    }
}

Thursday, June 18, 2015

JAVA - example of use in overrided method generic type of class that extends interface

public class HasLabelRenderer<T extends HasLabel> extends AbstractRenderer<T>{

    @Override    public String render(HasLabel object) {
        return object == null ? "" : object.getLabel();    }

}

This approach is possible due to the fact that in generics e.g. Bounded Type Parameter the type can be of the upper type it is extended. For instance, in example above the type T in HasLabelRenderer<T extends HasLabel>  can be of type HasLabel interface.

Sunday, June 7, 2015

INTERVIEW - The Art Of Hiring Great Javascript Developers

http://www.zsoltnagy.eu/the-art-of-hiring-great-javascript-developers/?utm_content=bufferb411d&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer

JavaScript - iterate or loop over JavaScript object or JSON

It is taken from here: http://stackoverflow.com/questions/684672/loop-through-javascript-object

In JavaScript, every object has a bunch of built-in key-value pairs that have meta-information. When you loop through all the key-value pairs for an object you're looping through them too. hasOwnPropery() filters these out:

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    alert(key + " -> " + p[key]);
  }
}
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)

var keys = Object.keys(p),
    len = keys.length,
    i = 0,
    prop,
    value;
while (i < len) {
    prop = keys[i];
    value = p[prop];
    i += 1;
}

KARMA + JASMINE tutorial for testing

http://www.bradoncode.com/blog/2015/02/27/karma-tutorial/

Friday, June 5, 2015

GWTBootstrap - custom email validation for TextBox

=== JAVA CODE ===

TextBox emailLookup = new TextBox();
emailLookup.addValidator(new Validator() {
            @Override
            public int getPriority() {
                return 0;
            }

            @Override
            public List<EditorError> validate(Editor editor, Object value) {
                List<EditorError> result = new ArrayList<EditorError>();
                String valueStr = value == null ? "" : value.toString();
                if (!valueStr.matches(EMAIL_REGEXP)) {
                    result.add(new BasicEditorError(emailLookup, value, "Not a valid email address"));
                } else if (isEmailReapeated(valueStr)) {
                    result.add(new BasicEditorError(emailLookup, value, "Email address is repeated"));
                }
                return result;
            }
        });

=== UI BINDER ===

<b:Row addStyleNames="{style.padding}">
    <b:Column size="XS_12">
        <b:Row>
            <b:Column size="XS_2">
                <b:FormGroup>
                    <b:TextBox ui:field="emailLookup" placeholder="Enter email" allowBlank="false"/>
                    <b:InlineHelpBlock iconType="EXCLAMATION"/>
                </b:FormGroup>
            </b:Column>

            <b:Column size="XS_1">
                <b:Button ui:field="addContact" text="Add"/>
            </b:Column>

        </b:Row>
    </b:Column>
</b:Row>

D3 Karma Jasmine testing

http://busypeoples.github.io/post/testing-d3-with-jasmine/

JavaScript Karma Jasmine - JSON parsing tests

http://stackoverflow.com/questions/20938320/loading-external-file-from-karma-jasmine-test
http://stackoverflow.com/questions/25035688/json-parse-fails-in-jasmine

ANGULAR + KARMA + JASMINE: test controller with $http, $scope

https://docs.angularjs.org/api/ngMock/service/$httpBackend

Tuesday, June 2, 2015

JAVA GWT - entity persistence approach

== IDENTITY ==
import java.io.Serializable;

public interface Identity<T extends Serializable> extends Serializable{
    T getId();
    void setId(T id);
}

JAVA Annotation - GWT impl of email validation on bean field

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.Pattern;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Replacement for the Hibernate Email constraint that is not supported by GWT.
 * <p/>
 */
@Documented
@Constraint(validatedBy = {})
@Pattern(regexp = "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@([a-z0-9!#$%&'*+/=?^_`{|}~-]+(\\" +
        ".[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])$", flags = Pattern
        .Flag.CASE_INSENSITIVE)
@ReportAsSingleViolation
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface Email {
    String message() default "{org.hibernate.validator.constraints.Email.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Defines several {@code @Email} annotations on the same element.
     */
    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        Email[] value();
    }
}

JAVA Annotation for phone number validation of bean field

==== USE OF ANNOTATION ON BEAN FIELD ====
   @Phone
    public String getPhone() {
        return phone;
    }

==== PHONE NUMBER VALIDATION CLASS ===
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.Pattern;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Created by baraole on 27/05/2015.
 */
@Documented
@Constraint(validatedBy = {})
@Pattern(regexp = "\\+?[0-9()]+")
@ReportAsSingleViolation
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface Phone {
    String message() default "not a well-formed phone number";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Defines several {@code @Phone} annotations on the same element.
     */
    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        Phone[] value();
    }
}

JS frameworks comparision

http://habrahabr.ru/post/259311/

MongoDB - шпаргалка

http://habrahabr.ru/post/259219/

AngularJS - Combating AngularJS executing controller twice

AngularJS docs - ngController
Note that you can also attach controllers to the DOM by declaring it in a route definition via the $route service. A common mistake is to declare the controller again using ng-controller in the template itself. This will cause the controller to be attached and executed twice.

http://stackoverflow.com/questions/15535336/combating-angularjs-executing-controller-twice