/**
*
*/
package com.webmethods.caf.adjuntararchivosportlet;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import com.webmethods.caf.faces.data.attachments.IAttachmentItem;
import com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo;
/**
* @author Ext-costasm
*
*/
@SuppressWarnings("deprecation")
public class AdjuntarArchivosPortletDefaultviewView extends com.webmethods.caf.faces.bean.BasePageBean {
/**
* Determines if a de-serialized file is compatible with this class.
*
* Maintainers must change this value if and only if the new version
* of this class is not compatible with old versions. See Sun docs
* for
* details.
*/
private static final long serialVersionUID = 1L;
private com.webmethods.caf.adjuntararchivosportlet.AdjuntarArchivosPortlet adjuntarArchivosPortlet = null;
private com.webmethods.caf.faces.data.attachments.LocalTempAttachmentsProvider localTemporaryAttachmentsProvider = null;
private static final String[][] LOCALTEMPORARYATTACHMENTSPROVIDER_PROPERTY_BINDINGS = new String[][] {
};
private com.webmethods.caf.faces.component.attachments.view.AttachmentsListPage attachmentsListControlBean = null;
private com.webmethods.caf.adjuntararchivosportlet.AdjuntarArchivosPortletDefaultviewView adjuntarArchivosPortletDefaultviewView = null;
private java.util.ArrayList ListAttachmentsValidar = null;
private static final String[][] ListAttachmentsValidar_PROPERTY_BINDINGS = new String[][] {
};
private static final String[][] GUARDARARCHIVO_PROPERTY_BINDINGS = new String[][] {
};
private static final String[][] OBTENERARCHIVOSPATH_PROPERTY_BINDINGS = new String[][] {
};
private com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo[] archivos = null;
private static final String[][] ARCHIVOS_PROPERTY_BINDINGS = new String[][] {
};
private static final String[][] BUTTONSAVE_PROPERTY_BINDINGS = new String[][] {
};
private static final String[][] BUTTONREMOVE_PROPERTY_BINDINGS = new String[][] {
};
private static final String[][] LISTATTACHMENTSINI_PROPERTY_BINDINGS = new String[][] {
};
private java.lang.String usuarioLogueado;
private static final String[][] CARGARUSUARIOLOGUEADO_PROPERTY_BINDINGS = new String[][] {
};
private static final String[][] INITFROMEXTERNALPORTLET_PROPERTY_BINDINGS = new String[][] {
{"#{AdjuntarArchivosPortletDefaultviewView.filePath}", "#{environment[\"filePathTickets\"]}#{AdjuntarArchivosPortletDefaultviewView.ticketNumero}/"},
{"#{AdjuntarArchivosPortletDefaultviewView.obtenerArchivos}", null},
};
private static final String[][] ADJUNTARARCHIVOSPORTLETDEFAULTVIEWVIEW_PROPERTY_BINDINGS = new String[][] {
{"#{adjuntarArchivosPortletDefaultviewView.expireWithPageFlow}", "true"},
};
private com.webmethods.caf.AdjuntarArchivosMB adjuntarArchivosMB = null;
private static final String[][] INITIALIZE_PROPERTY_BINDINGS = new String[][] {
{"#{AdjuntarArchivosPortletDefaultviewView.usuarioLogueado}", "#{facesContext.externalContext.userPrincipal.name}"},
{"#{AdjuntarArchivosPortletDefaultviewView.obtenerArchivos}", null},
};
private com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo[] archivosObtenidos = null;
private static final String[][] ARCHIVOSOBTENIDOS_PROPERTY_BINDINGS = new String[][] {
};
private java.util.ArrayList listArchivosObtenidos = null;
private static final String[][] LISTARCHIVOSOBTENIDOS_PROPERTY_BINDINGS = new String[][] {
};
private java.util.ArrayList listArchivosDeUsuario = null;
private static final String[][] LISTARCHIVOSDEUSUARIO_PROPERTY_BINDINGS = new String[][] {
};
private static final String[][] ATTACHMENTSLISTCONTROLBEAN_PROPERTY_BINDINGS = new String[][] {
{"#{attachmentsListControlBean.downloadTargetWindow}", "_blank"},
{"#{attachmentsListControlBean.attachmentsProvider}", "#{AdjuntarArchivosPortletDefaultviewView.localTemporaryAttachmentsProvider}"},
{"#{attachmentsListControlBean.compositeViewNamingContainer}", "#{AdjuntarArchivosPortletDefaultviewView.attachmentsList}"},
{"#{attachmentsListControlBean.dragNDropAvailable}", "false"},
{"#{attachmentsListControlBean.maxFileSize}", "#{environment[\"maxFileSize\"]}"},
};
private com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo archivo = null;
private static final String[][] ARCHIVO_PROPERTY_BINDINGS = new String[][] {
};
private static final String[][] ADJUNTARARCHIVOSMB_PROPERTY_BINDINGS = new String[][] {
{"#{adjuntarArchivosMB.isBusqueda}", "false"},
};
/**
* Initialize page
*/
public String initialize() {
try {
//TODO Ver si viene desde portlet TASK O BUSCADOR
log("############### Initialize - ADJUNTAR ARCHIVOS ###############");
resolveDataBinding(INITIALIZE_PROPERTY_BINDINGS, null, "initialize", true, false);
return OUTCOME_OK;
} catch (Exception e) {
error(e);
log(e);
return OUTCOME_ERROR;
}
}
public String adjuntarArchivos() {
//Se ira adjuntando de a un archivo a medida que se seleccione el archivo a subir desde el disco
int index = 0;
//Attachment Provider
List attachmentList = localTemporaryAttachmentsProvider.listAttachments();
int ultimo = attachmentList.size()-1;
MesaDeAyuda_DocTypes_supportDocs_archivo[] archivos = new MesaDeAyuda_DocTypes_supportDocs_archivo[attachmentList.size()];
MesaDeAyuda_DocTypes_supportDocs_archivo archi = null;
try {
//Agrega el archivo a la lista inicial para que sirva para la siguiente validacion
InputStream inputStream = attachmentList.get(ultimo).getFileItem().getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while((len = inputStream.read(buffer)) >= 0)
out.write(buffer, 0, len);
out.close();
archi = new MesaDeAyuda_DocTypes_supportDocs_archivo();
archi.setNombre(attachmentList.get(ultimo).getFileName());
archi.setBytes(out.toByteArray());
archivos[index] = new MesaDeAyuda_DocTypes_supportDocs_archivo();
archivos[index] = archi;
index++;
} catch (IOException e) {
e.printStackTrace();
}
guardarArchivo(archivos, getAdjuntarArchivosMB().getFilePath(), getUsuarioLogueado());
//Agrego a la lista inicial de archivos de usuario, se puede hacer directamente asi porque se agrega de a un archivo
this.getListArchivosDeUsuario().add(archi);
return OUTCOME_OK;
}
public String guardarArchivo(MesaDeAyuda_DocTypes_supportDocs_archivo[] archivos, String filePath, String usuarioCreador) {
if ( archivos != null)
{
try{
File dirNroTicket = new File (filePath);
//Verifica si existe la carpeta con el numero de ticket si no la crea
if(!dirNroTicket.exists()){
dirNroTicket.mkdir();
}
log("############ GUARDAR ARCHIVO EN filePath+usuarioCreador: " + filePath+usuarioCreador);
File dirUsuario = new File (filePath+usuarioCreador+"/");
//Verifica si existe la subcarpeta para el usuario si no la crea
if(!dirUsuario.exists()){
dirUsuario.mkdir();
}
if (archivos!=null)
for ( int i = 0; i < archivos.length; i++ )
{
if (archivos[i]!=null && archivos[i].getNombre()!=null){
String nombre = archivos[i].getNombre();
byte[] arrayByteData = archivos[i].getBytes();
FileOutputStream stream = new FileOutputStream(filePath+usuarioCreador+"/"+nombre);
OutputStream output = new BufferedOutputStream(stream);
output.write(arrayByteData);
output.close();
}
}
}
catch (IOException e) {
log ("ERROR al intentar guardar archivo: "+e.getMessage());
}
}
return OUTCOME_OK;
}
public String obtenerArchivos() throws IOException {
//Si no se esta dando de alta el ticket
if (getAdjuntarArchivosMB().getTicketNumero()!=null && getAdjuntarArchivosMB().getTicketNumero()!=""){
obtenerArchivosPath(getAdjuntarArchivosMB().getFilePath());
this.archivosObtenidos = new MesaDeAyuda_DocTypes_supportDocs_archivo[getListArchivosObtenidos().size()];
if (this.archivosObtenidos!=null && this.archivosObtenidos.length > 0){
for (MesaDeAyuda_DocTypes_supportDocs_archivo archivo : this.archivosObtenidos) {
DiskFileItemFactory factory = new DiskFileItemFactory();
FileItem fi = factory.createItem(archivo.getNombre(), null, false,
archivo.getNombre());
fi.getOutputStream().write(archivo.getBytes());
fi.getOutputStream().flush();
fi.getOutputStream().close();
getLocalTemporaryAttachmentsProvider().addAttachment(fi, null);
}
this.getListArchivosObtenidos().toArray(this.archivosObtenidos);
}
}
return OUTCOME_OK;
}
public void obtenerArchivosPath(String filePath) {
File folder = new File(filePath);
String nombreCarpeta = "";
if (folder.listFiles()!=null && folder.listFiles().length>0){
int i = 0;
for (File fileEntry : folder.listFiles()) {
if (fileEntry.isFile()) {
try {
InputStream in = new FileInputStream(fileEntry);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = in.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
//Convierte el empaquetado de la fecha a Date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
MesaDeAyuda_DocTypes_supportDocs_archivo archivo = new MesaDeAyuda_DocTypes_supportDocs_archivo();
archivo.setNombre(fileEntry.getName());
archivo.setBytes(buffer.toByteArray());
this.getListArchivosObtenidos().add(archivo);
//Desarma la ruta y compara el nombre de la carpeta del usuario con el nombre de usuario logueado, usa la posicion n-1 del split. Usa la lista para validaciones
nombreCarpeta = fileEntry.getPath().split("/")[fileEntry.getPath().split("/").length-2];
if (fileEntry.getPath().split("/")[fileEntry.getPath().split("/").length-2].equals(this.getUsuarioLogueado())){
this.getListArchivosDeUsuario().add(archivo);
}
} catch (FileNotFoundException e) {
log("ERROR al obtener archivo: "+e.getMessage());
} catch (IOException e) {
log("ERROR al obtener archivo: "+e.getMessage());
}
i++;
}
else{ //SI es carpeta
obtenerArchivosPath(fileEntry.getAbsolutePath());
}
}
}
}
public com.webmethods.caf.adjuntararchivosportlet.AdjuntarArchivosPortlet getAdjuntarArchivosPortlet() {
if (adjuntarArchivosPortlet == null) {
adjuntarArchivosPortlet = (com.webmethods.caf.adjuntararchivosportlet.AdjuntarArchivosPortlet)resolveExpression("#{AdjuntarArchivosPortlet}");
}
return adjuntarArchivosPortlet;
}
public com.webmethods.caf.faces.data.attachments.LocalTempAttachmentsProvider getLocalTemporaryAttachmentsProvider() {
if (localTemporaryAttachmentsProvider == null) {
localTemporaryAttachmentsProvider = new com.webmethods.caf.faces.data.attachments.LocalTempAttachmentsProvider();
}
resolveDataBinding(LOCALTEMPORARYATTACHMENTSPROVIDER_PROPERTY_BINDINGS, localTemporaryAttachmentsProvider, "localTemporaryAttachmentsProvider", false, false);
return localTemporaryAttachmentsProvider;
}
public void setLocalTemporaryAttachmentsProvider(com.webmethods.caf.faces.data.attachments.LocalTempAttachmentsProvider localTemporaryAttachmentsProvider) {
this.localTemporaryAttachmentsProvider = localTemporaryAttachmentsProvider;
}
/**
* Getter method for the control with id='attachmentsList'
*/
public javax.faces.component.UINamingContainer getAttachmentsList() {
return (javax.faces.component.UINamingContainer)findComponentInRoot("attachmentsList");
}
public com.webmethods.caf.faces.component.attachments.view.AttachmentsListPage getAttachmentsListControlBean() {
if (attachmentsListControlBean == null) {
attachmentsListControlBean = new com.webmethods.caf.faces.component.attachments.view.AttachmentsListPage();
}
resolveDataBinding(ATTACHMENTSLISTCONTROLBEAN_PROPERTY_BINDINGS, attachmentsListControlBean, "attachmentsListControlBean", false, false);
return attachmentsListControlBean;
}
public com.webmethods.caf.adjuntararchivosportlet.AdjuntarArchivosPortletDefaultviewView getAdjuntarArchivosPortletDefaultviewView() {
if (adjuntarArchivosPortletDefaultviewView == null) {
adjuntarArchivosPortletDefaultviewView = (com.webmethods.caf.adjuntararchivosportlet.AdjuntarArchivosPortletDefaultviewView)resolveExpression("#{AdjuntarArchivosPortletDefaultviewView}");
}
resolveDataBinding(ADJUNTARARCHIVOSPORTLETDEFAULTVIEWVIEW_PROPERTY_BINDINGS, adjuntarArchivosPortletDefaultviewView, "adjuntarArchivosPortletDefaultviewView", false, false);
return adjuntarArchivosPortletDefaultviewView;
}
public java.util.ArrayList getListAttachmentsValidar() {
if (ListAttachmentsValidar == null) {
ListAttachmentsValidar = new java.util.ArrayList();
}
resolveDataBinding(ListAttachmentsValidar_PROPERTY_BINDINGS, ListAttachmentsValidar, "ListAttachmentsValidar", false, false);
return ListAttachmentsValidar;
}
public void setListAttachmentsValidar(java.util.ArrayList ListAttachmentsValidar) {
this.ListAttachmentsValidar = ListAttachmentsValidar;
}
public com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo[] getArchivos() {
if (archivos == null) {
//TODO: create/set default value here
}
resolveDataBinding(ARCHIVOS_PROPERTY_BINDINGS, archivos, "archivos", false, false);
return archivos;
}
public void setArchivos(com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo[] archivos) {
this.archivos = archivos;
}
public void buttonSave() throws Exception {
boolean adjuntar = true;
getAttachmentsListControlBean().button1_action();
List files = getLocalTemporaryAttachmentsProvider().listAttachments();
int listSize = files.size();
IAttachmentItem lastFile = null;
if (listSize>0){
lastFile = files.get(listSize-1);
int ind = lastFile.getFileName().indexOf(" [1]");
if (ind != -1){
String fileName = lastFile.getFileName().substring(0, ind);
for (int i = 0; i < listSize-1; i++) {
IAttachmentItem f = files.get(i);
if (f.getFileName().equals(fileName)){
getLocalTemporaryAttachmentsProvider().removeAttachment(lastFile.getId());
adjuntar = false;
error(FacesMessage.SEVERITY_WARN, "El archivo ya se encuentra adjunto", null);
break;
}
}
}
if (adjuntar) adjuntarArchivos();
}
}
public String buttonRemove() {
List selectedRows = getAttachmentsListControlBean().getAttachmentsTableContentProvider().getSelectedRows();
boolean eliminar = false;
for (Object objectRow : selectedRows) {
IAttachmentItem row = (IAttachmentItem) objectRow;
//Verifica si el archivo fue subido por el usuario logueado
for (MesaDeAyuda_DocTypes_supportDocs_archivo archiUsu : this.getListArchivosDeUsuario()) {
if (archiUsu.getNombre().equals(row.getFileName())){
eliminar=true;
break;
}
}
if (eliminar){
try {
String[] aEliminar = {getAdjuntarArchivosMB().getFilePath()+getUsuarioLogueado()+"/"+row.getFileName()};
eliminarArchivos(aEliminar);
getAttachmentsListControlBean().removeSelectedAttachments_action();
} catch (Exception e) {
log ("ERROR al intentar eliminar archivo: "+e.getMessage());
}
}
else{
error(FacesMessage.SEVERITY_WARN, "No se permite eliminar archivos subidos por otros usuarios.", null);
eliminar = true;
}
}
return OUTCOME_OK;
}
public void eliminarArchivos(String[] pathArchivos) throws Exception{
for (int i = 0; i < pathArchivos.length; i++) {
File archi = new File (pathArchivos[i]);
if (archi.delete()){
log("Se elimina archivo: "+pathArchivos[i]);
}else{
log("No se puede eliminar el archivo: "+pathArchivos[i]);
}
}
}
public java.lang.String getUsuarioLogueado() {
return usuarioLogueado;
}
public void setUsuarioLogueado(java.lang.String usuarioLogueado) {
this.usuarioLogueado = usuarioLogueado;
}
public String initFromExternalPortlet() {
resolveDataBinding(INITFROMEXTERNALPORTLET_PROPERTY_BINDINGS, this, "initFromExternalPortlet.this", true, false);
return OUTCOME_OK;
}
public com.webmethods.caf.AdjuntarArchivosMB getAdjuntarArchivosMB() {
if (adjuntarArchivosMB == null) {
adjuntarArchivosMB = (com.webmethods.caf.AdjuntarArchivosMB)resolveExpression("#{AdjuntarArchivosMB}");
}
resolveDataBinding(ADJUNTARARCHIVOSMB_PROPERTY_BINDINGS, adjuntarArchivosMB, "adjuntarArchivosMB", false, false);
return adjuntarArchivosMB;
}
public com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo[] getArchivosObtenidos() {
if (archivosObtenidos == null) {
//TODO: create/set default value here
}
resolveDataBinding(ARCHIVOSOBTENIDOS_PROPERTY_BINDINGS, archivosObtenidos, "archivosObtenidos", false, false);
return archivosObtenidos;
}
public void setArchivosObtenidos(com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo[] archivosObtenidos) {
this.archivosObtenidos = archivosObtenidos;
}
public java.util.ArrayList getListArchivosObtenidos() {
if (listArchivosObtenidos == null) {
listArchivosObtenidos = new java.util.ArrayList();
}
resolveDataBinding(LISTARCHIVOSOBTENIDOS_PROPERTY_BINDINGS, listArchivosObtenidos, "listArchivosObtenidos", false, false);
return listArchivosObtenidos;
}
public void setListArchivosObtenidos(java.util.ArrayList listArchivosObtenidos) {
this.listArchivosObtenidos = listArchivosObtenidos;
}
public java.util.ArrayList getListArchivosDeUsuario() {
if (listArchivosDeUsuario == null) {
listArchivosDeUsuario = new java.util.ArrayList();
}
resolveDataBinding(LISTARCHIVOSDEUSUARIO_PROPERTY_BINDINGS, listArchivosDeUsuario, "listArchivosDeUsuario", false, false);
return listArchivosDeUsuario;
}
public void setListArchivosDeUsuario(java.util.ArrayList listArchivosDeUsuario) {
this.listArchivosDeUsuario = listArchivosDeUsuario;
}
public com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo getArchivo() {
if (archivo == null) {
archivo = new com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo();
}
resolveDataBinding(ARCHIVO_PROPERTY_BINDINGS, archivo, "archivo", false, false);
return archivo;
}
public void setArchivo(com.webmethods.caf.is.document.MesaDeAyuda_DocTypes_supportDocs_archivo archivo) {
this.archivo = archivo;
}
public void setAdjuntarArchivosMB(com.webmethods.caf.AdjuntarArchivosMB adjuntarArchivosMB) {
this.adjuntarArchivosMB = adjuntarArchivosMB;
}
}