I am working on a Spring MVC project and I am getting an ArrayOutOfBound exception. If this was Java 7 then I would have no problem, but since it's Java 8 and I am new to it, I have no idea what the problem is. I have searched for about two days but have no luck. I would appreciate the help.
Now the out of bounds is caused by ProjectService
class and specifically the
public Project find(Long projectId)...
.
Now my service class is:
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import com.spring.project.model.Project;
@Service
public class ProjectService {
private List<Project> projects = new LinkedList<>();
public ProjectService(){
Project javaProject = this.createProject("Java Project", "This is a Java Project");
Project javascriptProject = this.createProject("Javascript Project", "This is a Javascript Project");
Project htmlProject = this.createProject("HTML Project", "This is an HTML project");
this.projects.addAll(Arrays.asList(new Project[]{javaProject,javascriptProject, htmlProject}));
}
public List<Project> findAll(){
return this.projects;
}
public Project find(Long projectId){
return this.projects.stream().filter(p -> {
return p.getProjectId().equals(projectId);
}).collect(Collectors.toList()).get(0);
}
private Project createProject(String title, String description){
Project project = new Project();
project.setName(title);
project.setAuthorizedFunds(new BigDecimal("100000"));
project.setAuthorizedHours(new BigDecimal("1000"));
project.setDescription(description);
project.setSponsor("NASA");
project.setYear("2016");
project.setSpecial(true);
project.setType("single");
return project;
}
}
Now my controller looks like this:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spring.project.services.ProjectService;
@Controller
@RequestMapping("/project")
public class ProjectController {
@Autowired
private ProjectService projectService;
@RequestMapping(value="/{projectId}")
public String findProject(Model model, @PathVariable("projectId") Long projectId){
model.addAttribute("project", this.projectService.find(projectId));
return "project";
}
@RequestMapping(value="/find")
public String find(Model model){
model.addAttribute("projects", this.projectService.findAll());
return "projects";
}
}