alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java EE 6 example source code file (TaskManager.java)

This example Java EE 6 source code file (TaskManager.java) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Java EE 6 tags/keywords

annotation, datamodel, error, error, exception, io, listdatamodel, log, logging, long, long, persistenceaction, story, storymanager, string, string, task, task, util

The Java EE 6 TaskManager.java source code

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 *
 * Contributor(s):
 *
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package jsf2.demo.scrum.web.controller;

import jsf2.demo.scrum.model.entities.Story;
import jsf2.demo.scrum.model.entities.Task;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.validator.ValidatorException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PreDestroy;
import javax.faces.bean.CustomScoped;
import jsf2.demo.scrum.web.scope.TaskScopeResolver;

/**
 * @author Dr. Spock (spock at dev.java.net)
 */
@ManagedBean(name = "taskManager")
@CustomScoped(value="#{taskScope}")
public class TaskManager extends AbstractManager implements Serializable {

    private static final long serialVersionUID = 1L;
    private Task currentTask;
    private DataModel<Task> tasks;
    private List<Task> taskList;
    @ManagedProperty("#{storyManager}")
    private StoryManager storyManager;

    @PostConstruct
    public void construct() {
        getLogger(getClass()).log(Level.INFO, "new intance of taskManager in taskScope");
        init();
    }

    public void init() {
        Task task = new Task();
        Story currentStory = storyManager.getCurrentStory();
        task.setStory(currentStory);
        setCurrentTask(task);
        if (currentStory != null) {
            taskList = new LinkedList<Task>(currentStory.getTasks());
        } else {
            taskList = new ArrayList<Task>();
        }
        tasks = new ListDataModel<Task>(taskList);
    }

    public String create() {
        Task task = new Task();
        task.setStory(storyManager.getCurrentStory());
        setCurrentTask(task);
        return "create";
    }

    public String save() {
        if (currentTask != null) {
            try {
                Task merged = doInTransaction(new PersistenceAction<Task>() {

                    public Task execute(EntityManager em) {
                        if (currentTask.isNew()) {
                            em.persist(currentTask);
                        } else if (!em.contains(currentTask)) {
                            return em.merge(currentTask);
                        }
                        return currentTask;
                    }
                });
                if (!currentTask.equals(merged)) {
                    setCurrentTask(merged);
                    int idx = taskList.indexOf(currentTask);
                    if (idx != -1) {
                        taskList.set(idx, merged);
                    }
                }
                storyManager.getCurrentStory().addTask(merged);
                if (!taskList.contains(merged)) {
                    taskList.add(merged);
                }
            } catch (Exception e) {
                getLogger(getClass()).log(Level.SEVERE, "Error on try to save Task: " + currentTask, e);
                addMessage("Error on try to save Task", FacesMessage.SEVERITY_ERROR);
                return null;
            }
        }
        return "show";
    }

    public String edit() {
        setCurrentTask(tasks.getRowData());
        return "edit";
    }

    public String remove() {
        final Task task = tasks.getRowData();
        if (task != null) {
            try {
                doInTransaction(new PersistenceActionWithoutResult() {

                    public void execute(EntityManager em) {
                        if (em.contains(task)) {
                            em.remove(task);
                        } else {
                            em.remove(em.merge(task));
                        }
                    }
                });
                storyManager.getCurrentStory().removeTask(task);
                taskList.remove(task);
            } catch (Exception e) {
                getLogger(getClass()).log(Level.SEVERE, "Error on try to remove Task: " + currentTask, e);
                addMessage("Error on try to remove Task", FacesMessage.SEVERITY_ERROR);
                return null;
            }
        }
        return "show";
    }

    public void checkUniqueTaskName(FacesContext context, UIComponent component, Object newValue) {
        final String newName = (String) newValue;
        try {
            Long count = doInTransaction(new PersistenceAction<Long>() {

                public Long execute(EntityManager em) {
                    Query query = em.createNamedQuery((currentTask.isNew()) ? "task.new.countByNameAndStory" : "task.countByNameAndStory");
                    query.setParameter("name", newName);
                    query.setParameter("story", storyManager.getCurrentStory());
                    if (!currentTask.isNew()) {
                        query.setParameter("currentTask", (!currentTask.isNew()) ? currentTask : null);
                    }
                    return (Long) query.getSingleResult();
                }
            });
            if (count != null && count > 0) {
                throw new ValidatorException(getFacesMessageForKey("task.form.label.name.unique"));
            }
        } catch (ManagerException ex) {
            Logger.getLogger(TaskManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String cancelEdit() {
        return "show";
    }

    public Task getCurrentTask() {
        return currentTask;
    }

    public void setCurrentTask(Task currentTask) {
        this.currentTask = currentTask;
    }

    public DataModel<Task> getTasks() {
        this.tasks = new ListDataModel<Task>(storyManager.getCurrentStory().getTasks());
        return tasks;
    }

    public void setTasks(DataModel<Task> tasks) {
        this.tasks = tasks;
    }

    public Story getStory() {
        return storyManager.getCurrentStory();
    }

    public void setStory(Story story) {
        storyManager.setCurrentStory(story);
    }

    public StoryManager getStoryManager() {
        return storyManager;
    }

    public void setStoryManager(StoryManager storyManager) {
        this.storyManager = storyManager;
    }

    public String showStories() {
        endScope();
        return "/story/show";
    }

    private void endScope() {
        TaskScopeResolver.destroyScope();
    }

    @PreDestroy
    public void destroy() {
        getLogger(getClass()).log(Level.INFO, "destroy intance of taskManager in taskScope");
	currentTask = null;
	tasks = null;
	if (null != taskList) {
	    taskList.clear();
	    taskList = null;
	}
	storyManager = null;
    }

}

Other Java EE 6 examples (source code examples)

Here is a short list of links related to this Java EE 6 TaskManager.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.