Archive for the ‘Java’ Category

Posted by Tatyana at 6 February 2012

Category: Dev, Java

Tags: , , , , , , , ,

Controllers in Spring MVC are desined to be shared between requests. Each controller has a default singleton scope so if you are using controllers you neeed to be aware of that. The easiest way to make sure your controller is thread-safe is to not to have class variables. F.ex. this example from Spring MVC tutorial:

@Controller
@RequestMapping("/editPet.do")
public class EditPetForm {

    private final Clinic clinic;

    public EditPetForm(Clinic clinic) {
        this.clinic = clinic;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "petForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(
            @ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {

        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }
        else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId=" + pet.getOwner().getId();
        }
    }
}

In this example we can have a serious issue regarding thread-safety: private variable clinic. If there will be a situation where to different requests access the controller simultaniously, one of them will instanciate the controller and begin to process a form, then the other one comes inn. The result from processing of the first request will be sent to the other one, thus the requests receive fail data or nothing.

The solution to the problem may be the following:
1. Annotate Controller with @Scope(“request”) or @Scope(“session”)
2. Move private variable into one of the methods or save it in session or model.

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 12 January 2012

Category: Dev, Java

Tags: , , , , ,

Well, maybe not in theory, but in practice – definitely.

Test-drive development is a way to program where you write an automated unit test that fails first, then you write code and check that the test runs ok. Brilliant theory for an ideal world (doesn’t exist). In practice however it is very seldom that you as a programmer have a full and clear understanding of what is it you are gonna do.

Of course I’m not talking about cases where you need to calculate the result of 2+2. Sure you can write a test case here.

And here comes a hard reality where you come to the real place, f.ex. a bank that needs a new program. And here you are with a task that states smth like this “Create a form that have these and these fields and calculates that and that”. You begin with a test case? You are right! That’s what happens if you do this: you kill several days  trying to understand how you build this test case, what fields you need to fill inn to calculate the result. If you’ll try to check a more specific result then you need several extra days to find a person who maybe knows how the value must be calculated.

Because it is very seldom in the real world that programmers work together with persons who both know and can explain to the programmer how the things should be done. Simply because those persons do not exist.

So you wrote the test and now you need to write a calculation algorithm… Hmm, how the hell do we do that? We start building it and magic happens! The algorithm that can calculate the value needs all totally different input values then those you’ve written in your test case… Ouch! It happened again?

At the end you’ve used double time to write the code and update the test case in parallel plus the time you’ve killed on the test at the beginning.

So why is it so popular to talk about it and constantly try to use it? Do not know. You need to write test cases when you program difficult logic. That is the fact. But doing it FIRST? It’s just a waste of time and killing of enthusiasm. You won’t be clever and you’ll not write better code if you kill time with the test first.

What really needs to be done before you start programming is to draw a solution.

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 5 September 2011

Category: Dev, Java, Tip

To see all the sqls that your application do during execution, insert the following property in your test xml property file:

<bean id="sessionFactory"
		class="my.class.MyEntitySessionFactory">
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
		<property name="dataSource" ref="dbDataSource" />
</bean>
VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 4 September 2011

Category: Dev, Java, strips

Core: How do I make Hibernate to not to retreive all objects at the same time?
Mag: Do i lazy.
Silly: Yeah, don’t work too hard!

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 31 August 2011

Category: Dev, Java, Tip

/** @deprecated this one must be resolved differently */
@Deprecated
public void setModeChange()
{
   this.mode = Mode.CHANGE;
}
VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 28 February 2011

Category: Java, Tip

Tags: , , , ,

If an autocomplete stopped working go

Window -> Preferences -> Java -> Editor -> Content Assist -> Advanced ->  check for “Other Java Proposals”

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 17 October 2010

Category: Dev, Java

Tags: , , ,

It’s uncommon to see methods like this>

public Person findPerson() {
   if(someService) [
     return someService.getPerson();
   }
   return null;
}

There is no reason to make a Person object where there are no persons found. But doing so requires extra code in the client to handle the null value. This becomes a problem if a client is, for example, a GUI:

somePage.jsp
<%
  ...
  Person person = myService.findPerson();
%>
<table>
   <tr>
      <td>${person.name}</td>
      <td>${person.address}</td>
      <td>${person.numberOfPurchases}</td>
   </tr>
</table>

The result of such code in cases where the person cannot be found is Server error. So, there is no reason ever to return null from an object-valued method instead of returning an empty object. Especially if you deal with arrays and collections.

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 14 October 2010

Category: Dev, Java

Tags: , ,

How many times we write a program like this:

public void doSmth() {
    Salary s = calculateSalary(Person p);
    ...
}

private Salary calculateSalary(Person p) {
   return 100;
}

And so we hear from our sjef that we can’t have same salary for male and female. So we do this:

public void doSmth() {
    Salary male = calculateSalary(Person p, true);
    Salary female = calculateSalary(Person p, false);
    ...
}

private Salary calculateSalary(Person p, boolean sex) {
   if(sex) return 100;
   else return 50;
}

Yes, but what if we have more options later on? Or if we look just at the doSmth() function? What do these true/false mean?

An enum type in such cases makes your code easier to read and to write, especially if you are using an IDE that supports autocomplition. Also, it makes it easy to add more options later.

So here’s how we should do it:

public enum Sex {MALE, FEMALE}

public void doSmth() {
    Salary male = calculateSalary(Person p, Sex.MALE);
    Salary female = calculateSalary(Person p, Sex.FEMALE);
    ...
}

private Salary calculateSalary(Person p, Sex sex) {
   if(sex.equals(Sex.MALE) return 100;
   else return 50;
}
VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 4 March 2010

Category: Java

Tags: , , ,

I had some difficult time understanding all the roles regarding EJB3. Here is an easy-to-remember description of these roles that I found here.

Imagine a factory producing computers:

Bean Provider:
Chip manufacturer. On the chip, there will be a label with “Warranty void if removed” the chip has the logic and the label sets a Role. If you are not authorized to repair it, warranty voids. (i.e. you cannot access the internal chip if you are not in the role of “Warranty Repair Person”.)

Application Assembler
Mainboard assembler. It takes various chips and puts them on the mainboard. If any additional resistor or cable are required, it will put everything togheter to have something that is some kind of working unit but requires additional assembling.

EJB Server Provider
The EJB Server provider is the Computer Case manufacturer providing a case with a power supply. Is a container for the mainboard

Deployer
As every computer case is different and power voltage vary country by country, the Deployer makes sure to adapt the mainboard to the working environment. In this case adjusts the Voltage on the power supply, and connects the cables. At the same time he will define who are the person allowed to repair it (i.e. provide a list of authorized repair centers)

Persistence Provider
the persistence provider could be the network card company that provides the driver to connect to a network.

System Administrator
Is the person in charge to install the operating system and do necessary configuration changes to the OS to connect to the server, and will make sure to monitor that everything is working fine.

More about Enterprise Java Beans 3.0 and Sun Certified Business Component Developer (SCBCD) certification here.

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by Tatyana at 14 February 2010

Category: Java

Tags: ,

SCJP – Sun Certified Java Programmer
SCBDC – Sun Certified Business Component Developer

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share