VotingCompoAddEntryView.java 2.91 KB
package fi.codecrew.moya.web.cdiview.voting;

import java.io.IOException;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.validation.constraints.NotNull;

import org.primefaces.model.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.codecrew.moya.beans.VotingBeanLocal;
import fi.codecrew.moya.model.CompoEntry;
import fi.codecrew.moya.model.CompoEntryFile;
import fi.codecrew.moya.web.cdiview.GenericCDIView;

@Named
@RequestScoped
public class VotingCompoAddEntryView extends GenericCDIView {

	private static final long serialVersionUID = -93065881159476197L;

	@EJB
	VotingBeanLocal votingBean;

	@NotNull
	private String name;
	private String notes;
	private String screenMessage;

	@NotNull
	private UploadedFile uploadedFile;

	private Integer compoId;
	private String compoName;

	private static final Logger logger = LoggerFactory.getLogger(VotingCompoAddEntryView.class);

	public Integer getCompoId() {
		return compoId;
	}

	public void setCompoId(Integer compoId) {
		this.compoId = compoId;
	}

	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

	public String getScreenMessage() {
		return screenMessage;
	}

	public void setScreenMessage(String screenMessage) {
		this.screenMessage = screenMessage;
	}

	public String getNotes() {
		return notes;
	}

	public void setNotes(String notes) {
		this.notes = notes;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCompoName() {
		return compoName;
	}

	public void setCompoName(String compoName) {
		this.compoName = compoName;
	}

	public String send() {

		UploadedFile file = getUploadedFile();

		if (file == null)
		{
			super.addFaceMessage("compo.fileuploadFailed");
			return null;
		}

		byte[] contents = null;
		if (file.getContents() != null) {
			contents = file.getContents();
		} else {
			contents = new byte[(int) file.getSize()];
			try {
				file.getInputstream().read(contents);
			} catch (IOException e) {
				logger.warn("Error reading file from stream", e);
				contents = null;
			}
		}

		if (contents == null)
		{
			super.addFaceMessage("compo.fileuploadFailed");
			return null;
		}

		CompoEntry compoEntry = new CompoEntry();
		compoEntry.setTitle(name);
		compoEntry.setNotes(notes);
		compoEntry.setScreenMessage(screenMessage);
		compoEntry.setCompo(votingBean.getCompoById(compoId));
		CompoEntryFile cef = new CompoEntryFile(compoEntry);
		cef.setFileData(contents);
		cef.setFileName(uploadedFile.getFileName());
		votingBean.addEntry(compoEntry, cef);
		return null;
	}

	public void initView() {
		compoName = votingBean.getCompoById(compoId).getName();
	}
}