Saturday, August 24, 2013

Dependency Injection

If you have a class Employee and this employee has an Address you can have the Employee class defined as follows:
class Employee {
private Address address;

// constructor
public Employee( Address newAddress ) {
this.address = newAddress;
}

public Address getAddress() {
return this.address;
}
public void setAddress( Address newAddress ) {
this.address = newAddress;
}
}
Everything looks fine so far.
This code shows a HAS-A relationship between the employee and his address, that's fine.
Now, this HAS-A relationship created a dependency between them. The problem comes within the constructor.
Each time you want to create an Employee instance you need an Address instance:
 Address someAddress = ....
Employee oscar = new Employee( someAddress );
Working this way becomes problematic especially when you want to perform unit testing.
The main problem comes when you need to test one particular object, you need to create an instance of other object, and most likely you need to create an instance of yet other object to do that. The chain may become unmanageable.
To avoid this, you could change the constructor like this:
  public Employee(){
}
Using a no args constructor.
Then you can set the address when ever you want:
 Address someAddress = ....
Employee oscar = new Employee();
oscar.setAddress( someAddress );
Now, this may be a drag, if you have several attributes or if the objects are hard to create.
Yet, think about this, let's say, you add the Department attribute:
  class Employee {
private Address address;
private Department department;

....
If you have 300 employees, and all of them need to have the same department, and plus that same department has to be shared between some other objects ( like the company list of departments, or the roles each department have etc ) then you'll have a hard time with the visibility of the Departmentobject and to share it through all the network of objects.
What the Dependency Injection is all about it to help you to, well, "inject" these dependencies in your code. Most of the frameworks allow you to do this by specifying in an external file, what object is to be injected.
Assume a properties file for a fictitious dependency injector:
  #mock employee
employee.address = MockAddress.class
employee.department = MockDepartment.class

#production setup
employee.address = RealAddress.class
employee.department = RealDepartment.class
You'll define what to inject for a given scenario.
What the Dependency Injector framework will do is to set the correct objects for you, so you don't have to code setAddress or setDepartment. This would be done either by reflection or by code generation or other techniques.
So, the next time you need to test the Employee class you may inject mock Address andDepartments objects without having to code all the set/get for all your test. Even better, you can injectreal Address and Department objects in production code, and still have the confidence your code works as tested.
That's pretty much about it.
Still I don't think this explanation is suitable for a 5 yr old as you requested.
I hope you still find it useful.
Another explain:
I give you dependency injection for five year olds.
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.
References: Link

Monday, August 12, 2013

Insert hight light code

<pre class="brush: csharp">// Comment
public class Testing {
public Testing() {
}
 
public void Method() {
/* Another Comment
on multiple lines */
int x = 9;
}
}
</pre>


Becomes :
 // Comment
public class Testing {
public Testing() {
}

public void Method() {
/* Another Comment
on multiple lines */
int x = 9;
}
}

Sunday, August 11, 2013

Validation in hibernate objects


import java.util.Date;

import javax.persistence.AttributeOverride;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Type;
import org.hibernate.validator.AssertTrue;
import org.hibernate.validator.Min;
import org.hibernate.validator.NotNull;
import org.hibernate.validator.Valid;

import com.security.access.audit.HistoricallyAuditable;
import com.security.access.audit.NotAudited;
import com.security.access.audit.HistoricallyAuditable.AuditScope;
import com.security.facade.OrganizationContextProviderFactory;
import com.security.model.DuplicableObject;
import com.security.model.STCodeIntExtObject;
import com.security.model.StateEnum;
import com.security.model.StateEnumNotCanceledTransitionHandler;
import com.security.model.StateObject;
import com.security.model.aspect.AssociationId;
import com.security.model.aspect.AssociationObject;
import com.security.model.catalog.ProductFamily;
import com.security.model.type.MLExternalName;
import com.security.model.type.MLInternalName;
import com.security.util.helper.DateHelper;

@Entity
@AttributeOverride(name = "pk.id", column = @Column(name = "activity_id", nullable = false, insertable = false,
  updatable = false))
@HistoricallyAuditable(parentEntityRef = "season",
  validationGroup = OrganizationParameters.VALIDATION_GROUP_SEASON_PARAM, auditScope = { AuditScope.SEASON })
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Activity extends STCodeIntExtObject implements StateObject, DuplicableObject {

 private Integer seasonId;
 private Season season;

 private Integer productFamilyId;
 private ProductFamily productFamily;

 private StateEnum state = StateEnum.PREPARING;

 private ActivityTypeEnum type;

 private Date startDate = DateHelper.pastInfinite();
 private Date endDate = DateHelper.futureInfinite();
 private Date sellingStartDate = DateHelper.pastInfinite();

 private Integer maxDelayBetweenReservationAndConfirmation;
 private Integer reservationConfirmationMaxDelayBeforePerformance;

 private boolean seatOptionsAllowed = false;
 private OptionParameter optionParameter;
 private Integer optionParameterId;

 private Boolean outsideSeasonTicketAllowed;

 private Boolean unclosed = false;
 private String optionParameterInstitCode;

 private final StateEnumNotCanceledTransitionHandler transitionHandler =
   new StateEnumNotCanceledTransitionHandler(this);


 private Integer optionParamId;

 @Transient
 public Integer getOptionParamId() {
  return optionParamId;
 }

 @Transient
 public void setOptionParamId(Integer opId) {
  optionParamId = opId;
 }

 public Activity() {
 }

 public Activity(Activity original) {

 }
 
 public Activity duplicate() {
  Activity copy = new Activity();
  return copy;
 }
 
 @Temporal(TemporalType.DATE)
 @NotNull
 public Date getEndDate() {
  return endDate;
 }

 public void setEndDate(Date endDate) {
  this.endDate = endDate;
 }


 @AssertTrue
 public boolean validateEndDateEqualOrAfterStartDate() {
  return DateHelper.dateBeforeOrEqual(getStartDate(), getEndDate());
 }

 @AssertTrue
 public boolean validateStartDateVsSeason() {
  return DateHelper.dateBeforeOrEqual(getSeason().getStartDate(), getStartDate());
 }

 @AssertTrue
 public boolean validateSellingStartDateVsSeason() {
  return DateHelper.dateBeforeOrEqual(getSeason().getSellingStartDate(), getSellingStartDate());
 }

 @AssertTrue
 public boolean validateEndDateVsSeason() {
  return DateHelper.dateBeforeOrEqual(getEndDate(), getSeason().getEndDate());
 }

 @Column(name = "optionparam_instit_code")
 @NotAudited
 public String getOptionParameterInstitCode() {
  if (null == optionParameterInstitCode) {
   OptionParameter op = getOptionParameter();
   if (null != op) {
    setOptionParameterInstitCode(op.getPk().getInstitutionCode());
   }

  }
  return optionParameterInstitCode;
 }

 public void setOptionParameterInstitCode(String optionParameterInstitCode) {
  this.optionParameterInstitCode = optionParameterInstitCode;
 }

 @Column(name = "MAX_DELAY_BW_RESERVAT_CONFIRM")
 @Min(0)
 public Integer getMaxDelayBetweenReservationAndConfirmation() {
  return maxDelayBetweenReservationAndConfirmation;
 }

 public void setMaxDelayBetweenReservationAndConfirmation(Integer maxDelayBetweenReservationAndConfirmation) {
  this.maxDelayBetweenReservationAndConfirmation = maxDelayBetweenReservationAndConfirmation;
 }

 @Column(name = "RESERVAT_MAX_DELAY_B4_PERFORM")
 @Min(0)
 public Integer getReservationConfirmationMaxDelayBeforePerformance() {
  return reservationConfirmationMaxDelayBeforePerformance;
 }

 public void setReservationConfirmationMaxDelayBeforePerformance(
   Integer reservationConfirmationMaxDelayBeforePerformance) {
  this.reservationConfirmationMaxDelayBeforePerformance = reservationConfirmationMaxDelayBeforePerformance;
 }

 @NotNull
 @Type(type = "true_false")
 public boolean isSeatOptionsAllowed() {
  return seatOptionsAllowed;
 }

 public void setSeatOptionsAllowed(boolean seatOptionsAllowed) {
  this.seatOptionsAllowed = seatOptionsAllowed;
 }

 @NotNull
 @Temporal(TemporalType.DATE)
 public Date getSellingStartDate() {
  return sellingStartDate;
 }

 public void setSellingStartDate(Date sellingStartDate) {
  this.sellingStartDate = sellingStartDate;
 }

 @Temporal(TemporalType.DATE)
 @NotNull
 public Date getStartDate() {
  return startDate;
 }

 public void setStartDate(Date startDate) {
  this.startDate = startDate;
 }

 @NotNull
 @Enumerated(EnumType.STRING)
 @AccessType(value = "field")
 public StateEnum getState() {
  return state;
 }

 public void setState(StateEnum state) {
  this.state = transitionHandler.changeState(this.state, state);
 }

 @NotNull
 @Enumerated(EnumType.STRING)
 public ActivityTypeEnum getType() {
  return type;
 }

 public void setType(ActivityTypeEnum type) {
  this.type = type;
 }

 @NotNull
 @Type(type = "true_false")
 public Boolean isUnclosed() {
  return unclosed;
 }

 public void setUnclosed(Boolean unclosed) {
  this.unclosed = unclosed;
 }

 @ManyToOne(fetch = FetchType.LAZY, optional = false)
 @JoinColumns({
   @JoinColumn(name = "season_id", referencedColumnName = "season_id", insertable = false, updatable = false),
   @JoinColumn(name = "instit_code", referencedColumnName = "instit_code", insertable = false,
     updatable = false) })
 public Season getSeason() {
  return season;
 }

 @AssociationObject
 public void setSeason(Season season) {
  this.season = season;
 }

 // Parent
 @AccessType(value = "field")
 @Column(name = "season_id", updatable = false)
 @NotNull
 public Integer getSeasonId() {
  return seasonId;
 }

 @AssociationId
 public void setSeasonId(Integer seasonId) {
  this.seasonId = seasonId;
 }

 @AssociationId
 public void setProductFamilyId(Integer productFamilyId) {
  this.productFamilyId = productFamilyId;
 }

 @AccessType("field")
 @Column(name = "prodfamily_id")
 @NotNull
 public Integer getProductFamilyId() {
  return productFamilyId;
 }

 @AssociationObject
 public void setProductFamily(ProductFamily productFamily) {
  this.productFamily = productFamily;
 }

 @ManyToOne(fetch = FetchType.LAZY, optional = false)
 @JoinColumns({ @JoinColumn(name = "prodfamily_id", insertable = false, updatable = false),
   @JoinColumn(name = "instit_code", insertable = false, updatable = false) })
 public ProductFamily getProductFamily() {
  return productFamily;
 }


 @Valid
 @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
 @JoinColumns({
   @JoinColumn(name = "optionparam_id", referencedColumnName = "optionparam_id", insertable = false,
     updatable = false),
   @JoinColumn(name = "optionparam_instit_code", referencedColumnName = "instit_code", insertable = false,
     updatable = false) })
 public OptionParameter getOptionParameter() {
  return optionParameter;
 }

 @AssociationObject
 public void setOptionParameter(OptionParameter optionParameter) {
  this.optionParameter = optionParameter;
 }

 @Column(name = "optionparam_id")
 public Integer getOptionParameterId() {
  if (optionParameterId == null) {
   OptionParameter optionParameter = getOptionParameter();
   if (optionParameter != null) {
    optionParameterId = optionParameter.getPk().getId();
   }
  }
  return optionParameterId;
 }


 public void setOptionParameterId(Integer optionParameterId) {
  this.optionParameterId = optionParameterId;
 }

 @NotNull
 @Column(name = "outside_seastickt_allowed")
 @Type(type = "true_false")
 public Boolean getOutsideSeasonTicketAllowed() {
  return outsideSeasonTicketAllowed;
 }

 public void setOutsideSeasonTicketAllowed(Boolean outsideSeasonTicketAllowed) {
  this.outsideSeasonTicketAllowed = outsideSeasonTicketAllowed;
 }

 

 @Transient
 public boolean isDuplicateAllowed() {
  return true;
 }

 @Transient
 public boolean isDeleteAllowed() {
  return getState() == StateEnum.PREPARING
    && !equals(OrganizationContextProviderFactory.getOrganizationContextProvider().getCurrentActivity());
 }

 @AssertTrue
 public boolean validateSeatOptionMaxDelayRequiredWhenSeatOptionIsAllowed() {
  if (isSeatOptionsAllowed()) {
   return getOptionParameter().getMaxDelayBetweenOptionAndConfirmation() != null
     || getOptionParameter().getOptionConfirmationMaxDelayBeforePerformance() != null;
  } else {
   return true;
  }
 }

 @AssertTrue
 public boolean validateSameDecreaseQuotaAvailabilityOptionAsSeason() {
  if (isSeatOptionsAllowed() && getSeason().isSeasonTicketOptionsAllowed()
    && (getSeason().getOptionParameter() != null)) {
   return (getOptionParameter().getOptionDecreaseQuota().equals(getSeason().getOptionParameter()
     .getOptionDecreaseQuota()));
  } else {
   return true;
  }
 }
}