Pages

Tampilkan postingan dengan label answers. Tampilkan semua postingan
Tampilkan postingan dengan label answers. Tampilkan semua postingan

Selasa, 25 Februari 2014

Spring and Hibernate Interview Questions and Answers AOP interceptors and deadlock retry


Before this, please refer to Hibernate Interview Questions and Answers: with annotations and Spring framework  , as the examples below are extension of this blog.


Q. How would you go about implementing a dead lock retry service using Spring and hibernate?
A.
  • Define an annotation to annotate the methods that needs deadlock retry service. E.g. DeadlockRetry.java
  • Define the interceptor that gets wired up via AOP to perform the retry functionality by invoking the annotated method. E.g. DeadlockRetryMethodInterceptor
  • Wire up the annotation and deadlock retry classes via Spring config. E.g. transactionContext.xml
  • Finally, annotate the method that needs perform the retry service. E.g. EmployeeServiceImpl --> saveEmployee (....)

Define a custom annotation class DeadlockRetry.java.

package com.myapp.deadlock;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface DeadlockRetry {

int maxTries() default 21;
int tryIntervalMillis() default 100;

}


Define the DeadlockRetryMethodInterceptor for performing retries. The above annotation will be bound to the following implementation via Spring.

package com.myapp.deadlock;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.exception.LockAcquisitionException;
import org.springframework.dao.DeadlockLoserDataAccessException;


public class DeadlockRetryMethodInterceptor implements MethodInterceptor {

private static final Logger LOGGER = LoggerFactory.getLogger(DeadlockRetryMethodInterceptor.class);

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object obj = invocation.getThis();
Method method = invocation.getMethod();
Method targetMethod = obj.getClass().getMethod(method.getName(), method.getParameterTypes());
DeadlockRetry dlRetryAnnotation = targetMethod.getAnnotation(DeadlockRetry.class);
int maxTries = dlRetryAnnotation.maxTries();
int tryIntervalMillis = dlRetryAnnotation.tryIntervalMillis();
for (int i = 0; i < maxTries; i++) {
try {
LOGGER.info("Attempting to invoke " + invocation.getMethod().getName());
Object result = invocation.proceed(); // retry
LOGGER.info("Completed invocation of " + invocation.getMethod().getName());
return result;
} catch (Throwable e) {
Throwable cause = e;

//... put the logic to identify DeadlockLoserDataAccessException or LockAcquisitionException
//...in the cause. If the execption is not due to deadlock, throw an exception

if (tryIntervalMillis > 0) {
try {
Thread.sleep(tryIntervalMillis);
} catch (InterruptedException ie) {
LOGGER.warn("Deadlock retry thread interrupted", ie);
}
}

}

//gets here only when all attempts have failed
throw new RuntimeException
("DeadlockRetryMethodInterceptor failed to successfully execute target "
+ " due to deadlock in all retry attempts",
new DeadlockLoserDataAccessException("Created by DeadlockRetryMethodInterceptor", null));
}
}


Wire up the annotation and the interceptor via Spring config transactionContext.xml. Only the snippet is shown.

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<!-- Deadlock Retry AOP -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<bean id="deadlockRetryPointcut" class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut">
<constructor-arg><null/></constructor-arg>
<constructor-arg value="com.myapp.deadlock.DeadlockRetry" />
</bean>

<bean id="deadlockRetryMethodInterceptor" class="com.myapp.deadlock.DeadlockRetryMethodInterceptor" />

<bean id="deadlockRetryPointcutAdvisor"
class="org.springframework.aop.support.DefaultPointcutAdvisor">
<constructor-arg ref="deadlockRetryPointcut" />
<constructor-arg ref="deadlockRetryMethodInterceptor" />
</bean>


Finally, annotate the method that needs to be retried in the event of dead lock issues.

package com.myapp.service;


import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
//....other imports

public class EmployeeServiceImpl implements EmployeeService {

private final EmployeeTableRepository employeeRepository;
private PlatformTransactionManager transactionManager;

public EmployeeServiceImpl(EmployeeTableRepository employeeRepository, PlatformTransactionManager transactionManager) {
this.employeeRepository = employeeRepository;
this.transactionManager = transactionManager;
}


@DeadlockRetry
public Employee saveEmployee(Employeee employee) throws RepositoryException {
TransactionStatus transactionStatus =
transactionManager.getTransaction(new DefaultTransactionDefinition(
TransactionDefinition.PROPAGATION_REQUIRED));
try {
employee = this.employeeRepository.saveEmployee(employee);
} catch (Exception e) {
transactionManager.rollback(transactionStatus);
throw new RepositoryException(e);
} finally {
if (!transactionStatus.isCompleted()) {
transactionManager.commit(transactionStatus);
}
}
return employee;
}


//....other methods omitted for brevity

} 

The above example gives a real life example using a custom annotation and AOP (i.e. Aspect Oriented Programming).

Note: Also refer to Spring Interview Questions and Answers for explanation on interceptors.

Q. What are the pros and cons between Spring AOP and AspectJ AOP?
A. The Spring AOP is simpler as it is achieved via a runtime dynamic proxy class. Unlike AspectJ, it does not have to go through load time weaving or a compiler. The Spring AOP uses the proxy and decorator design patterns.

Since Spring AOP uses proxy based AOP, it can only offer method execution pointcut, whereas the AspectJ  AOP supports all pointcuts.

In some cases, the compile time weaving (e.g. AspectJ AOP) offers better performance.
Read More..

Selasa, 11 Februari 2014

Java J2EE Interview Questions and Answers Book Details



IT Book Zone Review | JavaRanch Book Review

  • 400+ popular and frequently asked Java interview questions answered clearly and concisely with lots of diagrams, examples, code snippets, comparisons and cross referencing.
  • A questions and answers approach to learning and refreshing the core Java/JEE concepts.
  • Covers 14 key areas: like Design Concepts, Design Patterns, Best Practices, Java language & JEE specification Fundamentals, Exception Handling, Performance Issues, Transaction Issues, Memory Issues, Concurrency issues, Scalability, Security, Software Development Process and Coding Tips.
  • Covers a wide range of Java/JEE related topics like Java, JEE, OOAD, Servlet, JSP, EJB, JNDI, LDAP, JDBC, JMS, JTA, XML, SQL, UML, Spring, Hibernate, Web Service, Agile Methodology, AoP, IoC, TDD, Swing, Applet, Struts, GoF design patterns, JEE design patterns, Ant, Junit, CVS etc.
  • Very handy quick reference guide and a road map where it gives a birds eye view of the core concepts relating to Java/JEE and its related technologies. Why wait for years to learn the core concepts relating to Java/JEE, when you can pro-actively learn and apply them in months?
Over 18, 000 copies sold.


Java interview questions and answers

Java Interview Questions and Answers Preview

4.5 out of 5 stars user rating at Lulu.com
4 out of 5 stars user rating at Amazon.com
Top selling Java book at Lulu.com
printed:
eBooks from Lulu.com:




Read More..

Sabtu, 01 Februari 2014

CSS Interview Questions and answers

Modern applications are web driven using HTML, CSS, and JavaScript. HTML is the building block of Web pages. CSS is the language used to make those Web pages pretty. JavaScript is used for dynamically manipulating the DOM elements and their look and feel. Understanding the basics of HTML and CSS will help you build better Web pages. CSS (Cascading Style Sheets) are vary useful and it it really worth understanding its key concepts. This blog explains the key concepts via questions and answers style.

Q. For the HTML snippet below, can you answers the questions listed below.

<div id="myAppDetails">
<form class="submit">
<fieldset>
<dl>
<dt>
<label for="portfolioCd">
<h4>Portfolio Code</h4>
</label>
</dt>
<dd>
<input id="portfolioCd" type="text">
</dd>
</dl>
<dl>
<dt>
<label for="valuationDate">
<h4>
Valuation Date <small>(dd/mm/yyyy)</small>
</h4>
</label>
</dt>
<dd>
<input id="valuationDate" type="text">
</dd>
</dl>

<div class="buttons">
<button class="btn" type="submit">
<span class="submit">Submit</span> <span class="refresh">Refresh</span>
</button>
</div>

</fieldset>
</form>

</div>



Q1. How will you write a CSS selector to hide the submit and refresh buttons?
A1. Here is the CSS

 
<style>
#myAppDetails form button .submit,
#myAppDetails form button .refresh {
display: none;
}
</style>


In the code snippet above

#myAppDetails :  refres to an element with id  myAppDetails, which is the top "DIV" element.
form :  refers to a child form element under the element with id "myAppDetails".
button : refers to a child button element under the  form element in the hierarchy.
.submit or .refresh : refers to an element with a style class, which has  the value of either "submit" or "refresh" in the hierarchy under the button element.

Finally the the "display:none" will hide the element selected.



Q2. In the above example, if you want to select more specifically the form element that has the style class submit, and a child element button with class  submit or refresh, how will you write the CSS selector to display the selected element?


A2: Here is the CSS snippet.

<style>
#myAppDetails form.submit button .submit,
#myAppDetails form.refresh button .refresh {
display: inline;
}

</style>




The above CSS is more specific than the previous one. The previous one selects any form, but this one selects only the form element with a style class of submit.

#myAppDetails : select any element with id "myAppDetails".
form.submit : select an element that has a style class "submit".
button :  a button child element under a form with class "submit"
.submit or .refresh : a child element with a class name either "submit" or "refresh" under a button element.

You can define multiple selectors with a comma.

Q3. What if the button element must immediately follow the form element?
A3.  You can use the symbol ">" to denote immediate. This is not used frequently. Here is the sample.

<style>
#myAppDetails form.submit>button .submit,
#myAppDetails form.refresh>button .refresh {
display: inline;
}

</style>


The two core concepts that are difficult to master in CSS are:

  1. CSS Specificity.
  2. CSS Floats


Q4. Why does your CSS rules dont apply to some elements?
A4. You can minimize the time it takes for hunting bugs by understanding how the browsers interpret your code and using developer tools like firebug for Firefox and Google chrome developer tool.

  • Every CSS selector has its place in the specificity hierarchy. If two selectors apply to the same element as demonstrated in the above example, the one with the higher specificity wins. For example,
"#myAppDetails  form.submit button .submit" is more specific than "#myAppDetails form button .submit" because the first one looks for specific form with class value of submit, whereas the second one applies to any form.
  • There are four distinct categories which determine the specificity level of a given selector: inline styles, IDs, classes+attributes and elements. ID selectors have a higher specificity than attribute selectors. You should always try to use IDs to increase the specificity. A class selector beats any number of element selectors. Here is an example:
 <div id="myDivId" style="font-color:blue"  class="aCSSClass" >

In CSS you will have

.aCSSClass {
     font-weight:12;
}

/** CSS comment: attribute css selector **/
[title] {
    color:blue
}

You can calculate the specificity yourself by allocating some weights, but the better approach is to use developer tools like Firebug or Chrome developer tool to calculate it for you and display the effective CSS.

Q5: When will you use a float?
A5: A float is used for laying out elements with CSS in a Web page.

Q6: Where can you apply a float?
A6: You cant float every element on a Web page. To get technical, you can only float block level elements. These are the elements that take up a block of space on the page, like ,
,
    , etc. The other elements known as inline elements like , , , etc cant be floated.


Q7: What are some of the basics you need to keep in mind regarding floats?
A7:

  • When you float an element it becomes a block box. This box can then be shifted to the left or right on the current line. The markup options are float: left, float: right or float: none.
  • You should always set a width on floated items, except if applied directly to an image, which has an implicit width. If no width is set, the results can become unpredictable.
  • The elements can only be floated to the left or right, it is not possible to make an element float in the centre. When we float an element it is shifted to the right or to the left until it reaches the edge of the containing block.
  • Elements following a floated element will wrap around the floated element. If you do not want this to occur, you can apply the “clear” property to these following elements. The four options are clear: left, clear: right, clear: both or clear: none.
  • If the container element is the HTML , the floated div will sit on the left margin of the page. If the container element is itself contained by something else, the floated div will sit on the left margin of the container.
Q8: What tips would you give to someone who is using CSS in their projects?
A8:
  • Use browser based development tools like firebug.
  • For a more professional CSS, use a library like Google bootstrap.
  • Use JavaScript frameworks like jQuery to dynamically manipulate CSS.
  • Understand the core concepts like selectors, specificity, and floats as explained above.

Here is CSS and HTML in action demonstrating float and some of the other  CSS concepts with an example.




Read More..