Thursday, June 2, 2016

init-param vs context-param

see http://javahash.com/difference-between-servlet-init-and-context-parameter/ for background. Gist:
context-param variables are global and accessible through the ServletContext. init-param variables are configured per servlet.

E.g. the org.springframework.web.servlet.DispatcherServlet can be explicitely set to use a particular application context file via init-param, i.e. setting the contextConfigLocation variable (which overrides the default <servlet-name>-context.xml)

Conversely, to register a Spring Security application context, Spring can make use of a contextConfigLocation global context-param variable which it reads via a listener: org.springframework.web.context.ContextLoaderListener -- which is also a handy way to bootstrap a Spring application on Tomcat startup. Note that the Spring Security bootstrap mechanism also relies on adding a filter: org.springframework.web.filter.DelegatingFilterProxy.


Tuesday, May 31, 2016

Select Statement Transactions and Isolation Levels

http://docs.oracle.com/javadb/10.5.3.0/devguide/cdevconcepts15366.html

Shows how isolation levels are pertinent to reads, i.e. select statement transactions overlapping update statement transactions.

Wednesday, January 27, 2016

Jettison vs Jackson CXF JSON Providers

[org.apache.cxf.jaxrs.provider.json.JSONProvider] is Jettison based and supports only JAXB annotated beans. You should use Jackson provider to process POJOs without JAXB annotations
http://cxf.apache.org/docs/jax-rs-data-bindings.html

Sunday, January 24, 2016

Gradle Tasks Example Execution

The following is a build.gradle which is what's executed when you run gradle <tasks>

task a << {  //double left angle brackets are the same as "doLast" or  more technically the "leftShift" operator
 println "in a"
}
  task b {
 println "in b"
}
  task (c, type: Copy) {
 from('c:/tmp/from/')
 into('c:/tmp/to')  
}
  c << {
 println "in c" //this ("in c") does not print below during the configuration phase for the same reason a doesn't: the print statement is in an action closure (added via leftShift op) unlike the print statements in b,d, and f whose print statements are executed as part of the configuration phase. Moreover, the "in c" is not printed in the execution phase. Why? because Gradle considers it doesn't have any work to do (hence the "UP-TO-DATE") output. If there was a file in c:/tmp/from/ then "in c" would be printed so I guess Gradle determines "didWork" property from the Copy type and ignores the leftShift appended print task here.
}
  task (d, type: Copy) {
 println "in d"
}
task e {
 doLast {
  println "in e"
 }
}
task f {
 println "in f"
 doLast {
  taskname -> println "in $taskname doLast" //note groovy (pun intended) use of lambdas.
 }
}
task g(dependsOn: c) << {
 println "c did work: " + c.getState().getDidWork();
 println "c.destinationDir: " + c.destinationDir
}
task h(dependsOn: b) << {
 println "b did work: " + b.getState().getDidWork();
}
task i(dependsOn: a) << {
 println "a did work: " + a.getState().getDidWork();
}
gradle.taskGraph.whenReady {taskGraph ->
    println "c is set to execute: " + taskGraph.hasTask(c)
}
println "the end of configuration phase"

executed:
>gradle a b c d e f g h i
in b
in d
in f
the end of configuration phase
c is set to execute: true
:a
in a
:b UP-TO-DATE
:c UP-TO-DATE
:d UP-TO-DATE
:e
in e
:f
in task ':f' doLast  // note the output from a, e, and f but none from c for reasons stated above.
:g
c did work: false
c.destinationDir: C:\tmp\to
:h
b did work: false
:i
a did work: true

BUILD SUCCESSFUL

Total time: 3.222 secs
ref: https://discuss.gradle.org/t/how-to-understand-task-creation-syntax/4478
see also: https://docs.gradle.org/current/userguide/build_lifecycle.html

Wednesday, December 16, 2015

12/16/2015

Learned
-about using joda time's DateTime to parse a UTC date.
-about using Apache Commons XMLConfiguration to drive strategy
-about one pattern for using strategies in a Java Spring Application:
in beans file add:
    <bean id="byWhichMeansStrategyFactory" class="com.awgtek.byWhichMeansStrategyFactory" factory-method="createStrategy">
<constructor-arg index="0"  ref="myXmlConfig" />
<constructor-arg index="1" type="java.lang.String">
  <value>this_means</value>
</constructor-arg>
    </bean>
   
    <bean id="MyImpl" class="com.awgtek.DoesSomethingImpl">
        <constructor-arg index="0" ref="byWhichMeansStrategyFactory" />
    </bean>
The createStrategy method would instantiate the correct strategy class basd on the "this_means" value. The injected strategy would then be used to e.g. pick a consultant either through "cheapness" defined by some parameters in the strategy or skill, etc. see http://blog.lowendahl.net/design-patterns/strategy-pattern/

-about using Guava, e.g. to import static com.google.common.base.Preconditions.checkNotNull to do checkNotNull statements where needed.

Tuesday, November 17, 2015

Camel vs Spring Integration (SI)

Camel uses producer templates to access routes.

SI uses gateways to access channels.

Saturday, September 19, 2015

Benefits of Dependency Injection

This question is often asked at interviews, and a good list of reasons to use it can be found at http://anandmanisankar.com/posts/angularjs-dependency-injection-demystified/:
  • Separate the process of creation and consumption of dependencies
  • Let the consumer worry only about how to use the dependency, and leave the process of creation of the dependency to somebody else
  • Allow concurrent/independent development of the dependency and the dependent entity, while only maintaing a known contract
  • Facilitate changing of the dependencies when needed
  • Allow injecting mock objects as dependencies for testing, by maintaining the agreed contract

Saturday, September 12, 2015

Use of "Requires New" Transaction in Chunk Processing

One place to use @Transaction "requires new" is on the onXXXError listener methods (or on methods called from them) that fire on error events during chunk processing in Spring Batch because the current transaction might be rolled back (depending on any no-rollback-exceptions set):

With annotation based transaction handling you can put the annotation @Transactional(propagation=Propagation.REQUIRES_NEW) on the method to achieve this.
https://blog.codecentric.de/en/2012/03/transactions-in-spring-batch-part-2-restart-cursor-based-reading-and-listeners/

Tuesday, August 4, 2015

Configuring Drools Rules Precedence

See how: http://blog.athico.com/2014/04/exercise-1-public-training-san.html

Sunday, August 2, 2015

On LazyInitializationException - Example

Example given here: http://grails.github.io/grails-doc/2.3.11/guide/services.html

Review how it's possible to get this exception if a Hibernate session is closed via transaction rollback but the exception carries a pointer to the non-greedy loaded object. In the catch clause if the object's children are accessed a LazyInitializationException is thrown because the object is detached and it's lazy-loaded children are uninitialized.

Thursday, March 5, 2015

Useful Custom Exceptions

One useful custom exception to cite as an example of "when would you use a custom exception" interview question is the ObjectNotFoundException triggered when accessing an invalid proxy gotten from the session.load() method. Custom exceptions are useful to for conditional logic that is strongly typed and semantically precise and, moreover, more natural then parsing and identifying error codes or String value properties of more generic exception types.

Friday, February 27, 2015

Hibernate's inverse=true on sets, and cascade=all

review this example: http://www.mkyong.com/hibernate/inverse-true-example-and-explanation/

upshot: makes more sense to do inverse=true -- results in fewer SQL statements.

But what if you just want a many-to-one relationship? e.g. a Rectangle that has a instance variable of type Point and Point can be a property of multiple Rectangles. Furthermore, you only need this to be unidirectional. No need to navigate from Point to Rectangles. (Note: a rectangle's location be defined by a single point.) In this case inverse="true" won't help because it can only be applied to a collection not a property. So what if you want to persist the Rectangle with one Hibernate save statement, and not have to first save the point, then save the rectangle to avoid a referential integrity error. The trick was mentioned in passing here: using cascade="all" on the many-to-one element in the unidirectional relationship's only side, in this case Rectangle, or if using annotations @ManyToOne(cascade=CascadeType.ALL) -- with cascade set to all, " if we perform an insert on the child row, Hibernate will automatically create the parent row based on where the child row is pointing." THAT saves a line of code, which can be a HUGE benefit especially if this is a polymorphic Hibernate util, otherwise, you would have to do something like either cast the entity to see if it's a Rectangle and has a point or in which case persist the Point or create a "performPreSave(session)" which is called on all entities where a Rectangle could override and persist its Point. Hacky! So...use cascade="all"...

Update. Rather than cascade="all" to achieve this single-save-cascade effect, should use "save-update" because you don't want to cascade a delete probably ever, if it's a many-to-one, since there could be other shapes like polygon relating to that point and possibly even other rectangles. In fact, cascade delete would probably only ever make sense in a one-to-one, and only ever in a one-to-many if the many-side table (the table holding the foreign key to the one-side table) did not contain foreign key references / relations to other entities. Answer here referencing Hibernate docs agrees with this.

This save-update effect would be useful to the afore-mentioned unidirectional relationship for the purposes of adding the related records upon saving the primary record, in this case the rectangle.

Saturday, December 27, 2014

Observable: Reason for setChanged()

This is useful because it separates the part where you say that the Observable has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged().
- jbx http://stackoverflow.com/questions/13744450/interview-when-do-we-use-observer-and-observable

 ...setChanged is used like a flag I think. This is to avoid unnecessary updating
- James Poulson http://stackoverflow.com/questions/7271044/observable-in-java

But note possible race condition in Java's implementation of Observable where a second call to notifyObservers may not be completed and thus second parameter (if one is provided) is not sent. See answer by mab at http://stackoverflow.com/questions/4446718/why-observable-snapshot-observer-vector/11122611#11122611.

Saturday, December 13, 2014

How to specify JAXB root element

With no metadata specified we need to supply JAXB with a root element name (and namespace).
http://blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-xstream.html
@XmlRootElement
public class Customer {
...

Friday, October 10, 2014

Iteration Syntaxes

http://www.javaworld.com/article/2461744/java-language/java-language-iterating-over-collections-in-java-8.html

Do each syntax on demand.

Sunday, October 5, 2014

Uses of targetNamespace

Example:
http://www.liquid-technologies.com/Tutorials/XmlSchemas/XsdTutorial_04.aspx

Ex. how to define in JAXB @XmlSchema annotation:
http://stackoverflow.com/questions/16584555/understanding-jaxb-xmlrootelement-annotation

Monday, September 29, 2014

Java wait() releases synchronization lock

Threads calling wait() release the synchronization lock on the current instance, i.e. the method with synchronized keyword is allowed to be entered by other threads.
http://tutorials.jenkov.com/java-concurrency/starvation-and-fairness.html

Saturday, May 10, 2014

HTTP POST vs PUSH

It's not as simple as Update vs Create.

According to the HTTP 1.1 specification, GET, HEAD, PUT and DELETE are idempotent, while POST is not.

http://jcalcote.wordpress.com/2008/10/16/put-or-post-the-rest-of-the-story/ Author states that there is no direct mapping between the HTTP and CRUD verb spaces and that a "higher level logic" should be added to complete the transformation.