Skip to content

Instantly share code, notes, and snippets.

@HiroNakamura
Created November 15, 2012 15:59
Show Gist options
  • Select an option

  • Save HiroNakamura/4079371 to your computer and use it in GitHub Desktop.

Select an option

Save HiroNakamura/4079371 to your computer and use it in GitHub Desktop.
Subir archivos xml, pdf, doc,zip
package org.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
//import org.siir.client.monarca.control.UnZip;
/**
*
* @author fernando
*
*/
public class UploadZipXmlPdf extends HttpServlet {
private static final long serialVersionUID = 6098745782027999297L;
private static final String DIRECTORIO = "/home/algo/";
private static final long MAXIMO = 1000000000;
private static final String TIPO = "application/zip";
private static final String TIPO2 = "application/pdf";
private static final String TIPO3 = "text/xml";
private static final String CONTENT_TYPE_UNACCEPTABLE = "{error: 'Archivo no subido. "+ "Solo archivos *.zip,*.xml y/o *.pdf pueden subirse'}";
private static final String SIZE_UNACCEPTABLE = "{error: 'Archivo no subido. El taman\u00d1o del archivo solo puede ser de "+ MAXIMO + " bytes o menos'}";
private static final String SUCCESS_MESSAGE ="{message: 'Archivo subido correctamente'}";
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
info("directorio de descarga: "+DIRECTORIO);
List items = null;
String json = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
error("error al subir archivo: ["+e+"] la causa: ["+e.getCause()+"]");
}
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
System.out.println("Nombre del fichero: "+item.getName());
info("Nombre del fichero: "+item.getName());
json = processFile(item);
}
response.setContentType("text/plain");
response.getWriter().write(json);
}
private String processFile(FileItem item) {
if (!isContentTypeAcceptable(item))
return CONTENT_TYPE_UNACCEPTABLE;
if (!isSizeAcceptable(item))
return SIZE_UNACCEPTABLE;
File uploadedFile =new File(DIRECTORIO +item.getName());
//UnZip.unzipFile(new File(DIRECTORIO +item.getName()));
String message = null;
try {
item.write(uploadedFile);
message = SUCCESS_MESSAGE;
info(">>>> "+message);
}
catch (Exception e) {
error("error al subir archivo: ["+e+"] la causa: ["+e.getCause()+"]");
}
return message;
}
private boolean isSizeAcceptable(FileItem item) {
return item.getSize() <= MAXIMO;
}
private boolean isContentTypeAcceptable(FileItem item) {
return item.getContentType().equals(TIPO)|| item.getContentType().equals(TIPO2)|| item.getContentType().equals(TIPO3);
}
public static native void error(Object obj)/*-{
console.error(obj);
}-*/;
public static native void info(Object obj)/*-{
console.log(obj);
}-*/;
}
@HiroNakamura

Copy link
Copy Markdown
Author

package org.siir.client.gui.recepcion;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.FieldSet;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.siir.client.GWTServiceXML;
import org.siir.client.GWTServiceXMLAsync;
import org.siir.client.modelo.xml.Numero;
import org.siir.client.modelo.xml.RevistaNumero;
import org.siir.client.modelo.xml.TipoCarga;
import org.siir.client.modelo.xml.TipoRepositorio;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.ExtElement;
import com.gwtext.client.core.Function;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.widgets.ToolTip;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.grid.BaseColumnConfig;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.EditorGridPanel;
import com.gwtext.client.widgets.grid.GridEditor;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.GridView;
import com.gwtext.client.widgets.grid.RowNumberingColumnConfig;
import com.gwtext.client.widgets.grid.RowParams;
import com.gwtext.client.widgets.grid.event.GridCellListenerAdapter;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.siir.client.GWTServiceDescarga;
import org.siir.client.GWTServiceDescargaAsync;
import org.siir.client.GWTServiceUtil;
import org.siir.client.GWTServiceUtilAsync;
import org.siir.client.gui.GUIMenu;
import org.siir.client.gui.xml.GUIObtenArribosByXml;
import org.siir.client.gui.xml.GUIPanelVistaPrevia;
import org.siir.client.gui.xml.GridPanelForNewArticles;
import org.siir.client.modelo.arribos.ArriboDescarga;
import org.siir.client.modelo.xml.ArticuloAModificar;
import org.siir.client.modelo.xml.ModeloRedalyc.ModeloRedalyc;
/**
*

  • @author fernando

  • */
    public class GUIUploadXmlZipOJS {
    private Panel panel;
    private FileUpload upload;
    private String claveUsuario;
    private ComboBox comboRepositorio;
    private Button botonSubirZip;
    private Button continuarButton;
    private FieldSet fieldComboRepo;
    private FieldSet fieldUploadZip;
    private FieldSet fieldInformacion;
    private Label labelInfoCargada;
    private Label labelInfoConfirmacion;
    private VerticalPanel panelInfoAuxiliar;
    private VerticalPanel panelZip;
    private HorizontalPanel horizontalPanel;
    private TipoRepositorio tipoRepositorio;
    private Long claveRepositorio;
    private String ruta = "/home/sr/S/xmls/";//ruta
    private String rutaAlDirectorioXML = "";
    private FormPanel formZip;
    private ComboBox comboBoxDeArticulos;
    private List listaDeCambios;
    private static HashMap nuevosNumeros;
    private int totalDeNumerosNuevos = 0;
    private String tituloOriginal;
    private final ExtElement maskElement = new ExtElement(GUIMenu.tabPanel.getElement());
    private Store store;

    private String claveArribo;
    private boolean onlyRead;

    private Window window;

    public GUIUploadXmlZipOJS() {
    this.onlyRead = false;
    }

    public boolean isOnlyRead() {
    return onlyRead;
    }

    public void setOnlyRead(boolean onlyRead) {
    this.onlyRead = onlyRead;
    }

    public void setWindow(Window window) {
    this.window = window;
    }

    private Window getWindow() {
    return this.window;
    }

    public void setClaveArribo(String claveArribo) {
    this.claveArribo = claveArribo;
    }

    public String getClaveArribo() {
    return this.claveArribo;
    }

    public String getClaveUsuario() {
    return claveUsuario;
    }

    public void setClaveUsuario(String claveUsuario) {
    this.claveUsuario = claveUsuario;
    }

    /**

    • crea el panel principal que contiene la informacion de todo el

    • proceso de parseo de los xml

    • @return
      */
      public Panel getGUI() {
      consoleLog("Clave Arr: " + getClaveArribo());
      panel = new Panel("XML");
      panel.setFrame(true);
      //panel.setWidth(1152);
      panel.setWidth("600");
      panel.setAutoScroll(false);

      /panel para agregar los forms/
      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(0);
      vPanel.setWidth(panel.getWidth() + "px");
      vPanel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

      /field para el combo/
      fieldComboRepo = new FieldSet();
      fieldComboRepo.setPaddings(0, 10, 10, 0);
      fieldComboRepo.setBorder(false);
      /combo de repositorios/
      HorizontalPanel comboPanel = new HorizontalPanel();
      comboPanel.setSpacing(5);
      comboPanel.add(new com.google.gwt.user.client.ui.Label("Repositorio:"));
      //comboRepositorio = new ComboBox();
      comboRepositorio = getComboRepo();
      comboPanel.add(comboRepositorio);
      fieldComboRepo.add(comboPanel);

////////////////////////////////vPanel.add(fieldComboRepo);
vPanel.setCellHorizontalAlignment(fieldComboRepo, HasAlignment.ALIGN_CENTER);

    /*field para subir el zip*/
    fieldUploadZip = new FieldSet();
    fieldUploadZip.setBorder(false);
    //fieldUploadZip.setCollapsible(true);
    fieldUploadZip.setCollapsed(true);
    fieldUploadZip.setAnimCollapse(true);
    fieldUploadZip.setPaddings(0, 10, 10, 0);
    /*form para subir el zip*/
    formZip = new FormPanel();
    formZip.setEncoding(FormPanel.ENCODING_MULTIPART);
    formZip.setMethod(FormPanel.METHOD_POST);
    /*panel para el form del zip*/
    panelZip = new VerticalPanel();
    panelZip.setSpacing(5);
    /*label para descripcion de operacion*/
    Label labelDescripcion = new Label("Solo puedes subir archivos compresos en formato zip, de lo contrario se cancelara la operación.");
    labelDescripcion.setCls("label");
    panelZip.add(labelDescripcion);
    panelZip.setCellHorizontalAlignment(labelDescripcion, HasAlignment.ALIGN_CENTER);
    /*upload del zip*/
    upload = new FileUpload();
    upload.setName("upload");
    panelZip.add(upload);
    panelZip.setCellHorizontalAlignment(upload, HasAlignment.ALIGN_CENTER);
    /*boton para subir zip*/
    botonSubirZip = new Button("Subir archivo", new ClickListener() {

        public void onClick(Widget sender) {
            //si es un archivo zip lo subimos
            try {
                String [] caracteresRaros = {"ñ","Ñ","á","Á","é","É","í","Í","ó","Ó","ú","Ú"};
                //revisamos que no contenga caracteres extraños
                boolean contieneCaracteresRaros = false;
                for(String caracter : caracteresRaros){
                    if(upload.getFilename().contains(caracter)){
                        contieneCaracteresRaros = true;
                        break;
                    }
                }
                //si contiene caracteres raros
                if(contieneCaracteresRaros){
                    MessageBox.alert("El archivo que intentas subir no debe contener '\u00f1' o acentos, corrigelo e intentalo de nuevo.");
                }else{
                    String[] campos = upload.getFilename().split("[.]");
                    String nombreArchivo = campos[0];
                    String extension = campos[campos.length - 1];
                    if (extension.equalsIgnoreCase("zip")) {
                        //inicializamos lista de cambios y de numeros nuevos
                        listaDeCambios = new ArrayList<ArticuloAModificar>();
                        nuevosNumeros = new HashMap();
                        //creamos la ruta al directorio de los xml que vamos a subir
                        //rutaAlDirectorioXML = ruta + tipoRepositorio.name() + "/" + getClaveArribo() + "/" +nombreArchivo;

                        //aqui debe apuntar al directorio de OJS, no de Scielo
                        rutaAlDirectorioXML = ruta  + "OJS/" + getClaveArribo();
                        consoleLog(rutaAlDirectorioXML);
                        formZip.submit();
                    } else {
                        MessageBox.alert("El archivo que intentas subir no esta compreso en formato zip, buelve a intentar.");
                    }
                }
            } catch (Exception ex) {
                MessageBox.alert("Error subiendo archivo ");
                ex.printStackTrace();
            }

        }
    });
    panelZip.add(botonSubirZip);
    panelZip.setCellHorizontalAlignment(botonSubirZip, HasAlignment.ALIGN_CENTER);

    /*agregamos el form al field del zip*/
    formZip.add(panelZip);
    formZip.addFormHandler(new FormHandler() {

        public void onSubmit(FormSubmitEvent event) {
            /*mascara de prueba*/
            maskElement.mask("Subiendo archivos...");

            //deshabilitamos boton de subir
            botonSubirZip.setEnabled(false);
            //deshabilitamos boton de continuar
            continuarButton.setEnabled(false);
        }

        public void onSubmitComplete(FormSubmitCompleteEvent event) {
            if (event.getResults().contains("true")) {
                //parseamos archivos
                //sendAndParseXMLFiles(rutaAlDirectorioXML, tipoRepositorio, claveRepositorio);
                guardaRegistroBajarZIP();


                /*
                /////////////////////    Inicia guara arribo descarga/////////////////////
                String rutaDescarga = "/home/siir/SIIR/xmls/"+tipoRepositorio.name()+"/" + getClaveArribo();
                consoleLog("Ruta descarga zip: " + rutaDescarga);
                ArriboDescarga arbDes = new ArriboDescarga();
                arbDes.setArriboDescargaCve(0L);
                arbDes.setRevistaNumeroArriboCve(Long.parseLong(getClaveArribo()));
                //arbDes.setNombreRepositorio(tipoRepositorio.name());
                arbDes.setNombreRepositorio(String.valueOf(claveRepositorio));
                arbDes.setRutaDescargaArribo(rutaDescarga);
                arbDes.setBanderaManualAutomatico((short)2);
                arbDes.setFechaCargaArribo(new Date());

                consoleLog("Clave del repositporio justo antes de guardar: " + claveRepositorio);

                guardarArriboDescarga(arbDes);
                /////////////////////    finaliza guarda arribodescarga() ////////////////
                 *
                 */

            } else {
                //habilitamos boton de subit
                botonSubirZip.setEnabled(true);
                maskElement.unmask();
                MessageBox.alert(event.getResults());
            }
        }
    });
    /**/
    fieldUploadZip.add(formZip);
    vPanel.add(fieldUploadZip);

    /*field de la info que se cargo*/
    fieldInformacion = new FieldSet();
    fieldInformacion.setBorder(false);
    //fieldInformacion.setCollapsible(false);
    fieldInformacion.setCollapsed(true);
    fieldInformacion.setAnimCollapse(true);
    fieldInformacion.setPaddings(0, 10, 10, 0);
    /*panel para la info*/
    VerticalPanel panelInfo = new VerticalPanel();
    panelInfo.setSpacing(3);
    /**label de informacion*/
    labelInfoCargada = new Label();
    labelInfoCargada.setCls("label");
    panelInfo.add(labelInfoCargada);
    panelInfo.setCellHorizontalAlignment(labelInfoCargada, HasAlignment.ALIGN_LEFT);
    /*panel auxiliar*/
    panelInfoAuxiliar = new VerticalPanel();
    panelInfo.add(panelInfoAuxiliar);
    panelInfo.setCellHorizontalAlignment(panelInfoAuxiliar, HasAlignment.ALIGN_CENTER);
    /*label de confirmacion*/
    FieldSet fieldConfirmacion = new FieldSet();
    fieldConfirmacion.setWidth(700);
    labelInfoConfirmacion = new Label("Confirmacion");
    fieldConfirmacion.add(labelInfoConfirmacion);

//// panelInfo.add(fieldConfirmacion);
//// panelInfo.setCellHorizontalAlignment(fieldConfirmacion, HasAlignment.ALIGN_CENTER);
/panel contenedor de los botones cancelar y continuar/
horizontalPanel = new HorizontalPanel();
horizontalPanel.setSpacing(15);
/boton para continuar/
continuarButton = new Button("Continuar");
continuarButton.addClickListener(new ClickListener() {

        public void onClick(Widget sender) {
            //llamamos al metodo de nan, le pasamos el usuario
            createAndViewRedalycObject(getClaveUsuario(), listaDeCambios, nuevosNumeros);
        }
    });
    horizontalPanel.add(continuarButton);
    /*boton para cancelar*/
    Button cancelarButton = new Button("Cancelar");
    cancelarButton.addClickListener(new ClickListener() {

        public void onClick(Widget sender) {
            //borramos archivos temporales
            deleteTemporalFiles(rutaAlDirectorioXML);
            //aqui cancelar operacion
            panel.removeAll();
            GUIMenu.tabPanel.clear();
            GUIMenu.tabPanel.setActiveTab(0);
        }
    });
    horizontalPanel.add(cancelarButton);
    panelInfo.add(horizontalPanel);
    panelInfo.setCellHorizontalAlignment(horizontalPanel, HasAlignment.ALIGN_CENTER);
    /*agregamos el field de informacion al panel*/
    fieldInformacion.add(panelInfo);
    vPanel.add(fieldInformacion);
    vPanel.setCellHorizontalAlignment(fieldInformacion, HasAlignment.ALIGN_LEFT);

    panel.add(vPanel);

    loadUploadForm();

    return panel;
}

/**
 * crea el combo de repositorios
 * @return
 */
private ComboBox getComboRepo() {
    final ComboBox cb = new ComboBox();
    getRepositorys();
    cb.setForceSelection(true);
    cb.setEditable(false);
    cb.setDisplayField("tipo");
    cb.setMode(ComboBox.LOCAL);
    cb.setTriggerAction(ComboBox.ALL);
    cb.setEmptyText("Selecciona repositorio...");
    cb.setLoadingText("Cargando repositorios...");
    cb.setTypeAhead(true);
    cb.setSelectOnFocus(true);
    cb.setWidth(350);
    cb.addListener(new ComboBoxListenerAdapter() {

        @Override
        public void onSelect(ComboBox comboBox, Record record, int index) {
            //solo para el caso sin asignar
            if (comboBox.getValue().equalsIgnoreCase("sin asignar")) {
                tipoRepositorio = TipoRepositorio.SIN_ASIGNAR;
            } else {
                TipoRepositorio[] tipos = TipoRepositorio.values();
                String renametipoRepositorio="";
                for (TipoRepositorio t : tipos) {
                       //cambiamos el nombre para que coincida con el enum
                       if(comboBox.getValue().compareTo("Scielo de entrada")==0)
                           renametipoRepositorio="Revencyt";
                       else if(comboBox.getValue().compareTo("Scielo de salida")==0)
                           renametipoRepositorio="Scielo";
                       else if(comboBox.getValue().compareTo("Doaj")==0)
                           renametipoRepositorio="Doaj";
                       else if(comboBox.getValue().compareTo("PubMed_2x_OJS")==0)
                           renametipoRepositorio="PubMed_24_OJS";
                       else if(comboBox.getValue().compareTo("PubMed_30_OJS")==0)
                           renametipoRepositorio="PubMed_30_OJS";

                    if (renametipoRepositorio.equalsIgnoreCase(t.name())) {
                        tipoRepositorio = t;
                        break;
                    }
                }
            }
            consoleLog("#Imprime clave repositorio.");
            //claveRepositorio = Long.parseLong(record.getAsString("idRepo"));
            claveRepositorio = 5L;
            consoleLog("Clave repositorio: " + claveRepositorio);
            fieldUploadZip.setCollapsed(false);
            rutaAlDirectorioXML = ruta  + "OJS/" + getClaveArribo();
            //formZip.setAction("/SIIR_09/uploadZIP?path=" + ruta + tipoRepositorio.name() + "&user=" + getClaveUsuario());
            formZip.setAction("/SIIR_09/uploadZIP?path=" + rutaAlDirectorioXML + "&user=" + getClaveUsuario());
            // falla al poner org.siir.servlet.uploapZipXmlPdf.java, no guarda en directorio
        }
    });

    return cb;
}

private void loadUploadForm() {
    fieldUploadZip.setCollapsed(false);
    rutaAlDirectorioXML = ruta  + "OJS/" + getClaveArribo();
    //formZip.setAction("/SIIR_09/uploadZIP?path=" + ruta + tipoRepositorio.name() + "&user=" + getClaveUsuario());
    formZip.setAction("/SIIR_09/uploadZIP?path=" + rutaAlDirectorioXML + "&user=" + getClaveUsuario());
}

/**
 * agrega la informacion encontrada al panel de informacion
 * @param revistasValidas
 * @param revistasExistentes
 * @param revistasNoExistentes
 */
private void addMagazinesToPanelInfo(LinkedList<RevistaNumero> revistasValidas,
        LinkedList<String> erroresRecuperables, Set<String> revistasNoExistentes, Set<String>revistasExistentesDuplicadas) {

    //si existen errores recuperables se informa
    if (erroresRecuperables.size() > 0) {
        //aqui pintar los errores
        FieldSet fieldSetInfo = new FieldSet();
        fieldSetInfo.setWidth(1092);
        fieldSetInfo.setBorder(false);

        VerticalPanel verticalPanelInfo = new VerticalPanel();
        verticalPanelInfo.setSpacing(5);

        Label labelInfo = new Label();
        labelInfo.setCls("font-xml-carga");
        String htmlError = "<b>Se encontraron los siguientes errores de marcación, intenta corregirlos e intenta de nuevo.<b><br /><br />";
        for (String error : erroresRecuperables) {
            String archivo = error.split("--")[0];
            String descripcion = error.split("--")[1];
            htmlError += "<b>Archivo:&nbsp;<font color='#DF0101'>" + archivo + "</font><br />"
                    + "Descripción:&nbsp;<font color='#DF0101'>" + descripcion + "</font></b><br /><br />";
        }
        labelInfo.setHtml(htmlError);
        fieldSetInfo.add(labelInfo);

        Button salirButton = new Button("salir");
        salirButton.addClickListener(new ClickListener() {

            public void onClick(Widget sender) {
                //borramos archivos temporales
                deleteTemporalFiles(rutaAlDirectorioXML);
                //limpiamos la pantalla
                GUIMenu.tabPanel.clear();
                GUIMenu.tabPanel.setActiveTab(0);
            }
        });
        fieldSetInfo.add(salirButton);

        horizontalPanel.clear();
        //fieldInformacion.remove(panelInfoAuxiliar);
        panelInfoAuxiliar.add(fieldSetInfo);
        panelInfoAuxiliar.setCellHorizontalAlignment(fieldSetInfo, HasAlignment.ALIGN_LEFT);
        //fieldInformacion.add(panelInfoAuxiliar);
    } else {
        //si no hay errores
        //habilitamos boton continuar
        if (revistasValidas.size() > 0) {
            continuarButton.setEnabled(true);
        }

        labelInfoCargada.setHtml("Información encontrada:<br />");

        //agregamos las revistas validas
        for (RevistaNumero revista : revistasValidas) {
            //creamos un field que va a contener a la revista
            FieldSet fieldSetInfo = new FieldSet();
            fieldSetInfo.setWidth(1092);
            fieldSetInfo.setBorder(false);
            fieldSetInfo.setStyleName("label-correct");
            //panel para ordenar los elementos que insertemos
            VerticalPanel verticalPanelInfo = new VerticalPanel();
            verticalPanelInfo.setSpacing(5);

            Label labelInfo = new Label();
            labelInfo.setCls("font-xml-carga");
            String html = "<b>ISSN:</b>&nbsp;" + revista.getIssn()
                    + "&nbsp;<b>REVISTA:</b>&nbsp;<font size='3px'><a href=' http://redalyc.uaemex.mx/src/inicio/HomRevRed.jsp?iCveEntRev="
                    + revista.getIdRevista() + "' target='blank'>" + revista.getTitulo().split("-->")[1] + "</a></font><br /><br />";
            //agregamos el label y si es necesario el grid comparable
            labelInfo.setHtml(html);
            verticalPanelInfo.add(labelInfo);
            verticalPanelInfo.setCellHorizontalAlignment(labelInfo, HasAlignment.ALIGN_CENTER);

            int indexNumero = 0;
            //agregamos los numeros a la revista
            for (Numero numero : revista.getListaDeNumeros()) {
                maskElement.mask("Cargando información de " + revista.getTitulo().split("-->")[1] + "...");

                //dependiendo el tipo de carga pintamos el nunmero
                final Label labelNumeroInfo = new Label();
                labelNumeroInfo.setCls("font-xml-carga");
                labelNumeroInfo.doOnRender(new Function() {

                    public void execute() {
                        ExtElement labelEl = new ExtElement(labelNumeroInfo.getElement());
                        ToolTip t = new ToolTip();
                        t.setHtml("<font color='#FFFFFF'><b>Puedes editar los artículos dentro"
                                + " de la tabla dando click sobre el título que consideres"
                                + " que no coincidio correctamente en Redalyc</b></font>");
                        Element[] elements = labelEl.query("img");
                        for (Element element : elements) {
                            if (element.getId().equals("img-info")) {
                                t.applyTo(element);
                                break;
                            }
                        }
                    }
                });

                String htmlNumero = getHTMLStringForNumber(numero);
                //si el tipo de carga para el numero es nada o solo articulos los comparamos
                if (numero.getTipoCarga() == TipoCarga.SOLO_ARTICULOS
                        || numero.getTipoCarga() == TipoCarga.NADA) {
                    if (numero.getListaDeArticulos().size() > 0) {
                        //aviso dependiendo el numero de articulos entrantes con
                        //los encontrados en redalyc
                        String htmlNumeroYNota = getHTMLStringForArticles(numero.getListaDeArticulosLocales().size(),
                                numero.getListaDeArticulos().size(), numero.getTipoCarga(), htmlNumero);
                        //agregamos el label y si es necesario el grid comparable
                        labelNumeroInfo.setHtml(htmlNumeroYNota);
                        verticalPanelInfo.add(labelNumeroInfo);
                        verticalPanelInfo.setCellHorizontalAlignment(labelNumeroInfo, HasAlignment.ALIGN_CENTER);
                        //cargamos los articulos para compararlos, a excepcion de los numeros que no
                        //contengan articulos locales
                        if (numero.getListaDeArticulosLocales().size() == 0) {
                            //cargamos los articulos completos
                            Label labelArticuloInfo = new Label();
                            String htmlArticuloCompleto = "<font color='#848484'><b>";
                            for (Object object : numero.getListaDeArticulos()) {
                                String tituloYCarga = (String) object;
                                String titulo = tituloYCarga.split("-->")[0];
                                htmlArticuloCompleto += titulo + "<br />";
                            }
                            htmlArticuloCompleto += "</b></font>";
                            labelArticuloInfo.setHtml(htmlArticuloCompleto);
                            verticalPanelInfo.add(labelArticuloInfo);
                            verticalPanelInfo.setCellHorizontalAlignment(labelArticuloInfo, HasAlignment.ALIGN_CENTER);
                        } else {
                            //creamos el grid para comparar
                            EditorGridPanel grid = newGridComparable(numero.getListaDeArticulos(), numero.getListaDeArticulosLocales(),
                                    revista.getIdRevista(), numero.getIdNumero());
                            //agregamos grid
                            verticalPanelInfo.add(grid);
                            verticalPanelInfo.setCellHorizontalAlignment(grid, HasAlignment.ALIGN_LEFT);
                        }
                    } else {
                        //si no contiene articulos
                    }
                } else {
                    //si el numero esta en proceso
                    if (numero.getTipoCarga() == TipoCarga.EN_PROCESO) {
                        //agregamos el label y si es necesario el grid comparable
                        labelNumeroInfo.setHtml(htmlNumero);
                        verticalPanelInfo.add(labelNumeroInfo);
                        verticalPanelInfo.setCellHorizontalAlignment(labelNumeroInfo, HasAlignment.ALIGN_CENTER);
                    } else if(numero.getTipoCarga() == TipoCarga.COMPLETA_ARTICULOS_DUPLICADOS){
                        labelNumeroInfo.setHtml(htmlNumero);
                        verticalPanelInfo.add(labelNumeroInfo);
                        verticalPanelInfo.setCellHorizontalAlignment(labelNumeroInfo, HasAlignment.ALIGN_CENTER);
                    } else {
                        //si el numero no existe
                        //continuamos normal la carga completa
                        htmlNumero += "<br />";
                        //agregamos el label
                        labelNumeroInfo.setHtml(htmlNumero);

                        verticalPanelInfo.add(labelNumeroInfo);
                        verticalPanelInfo.setCellHorizontalAlignment(labelNumeroInfo, HasAlignment.ALIGN_CENTER);

                        //agregamos el grid de los nuevos articulos
                        GridPanelForNewArticles gridForNewArticles = new GridPanelForNewArticles();
                        //creamos la ruta temporal en donde se guardaran los articulos de este numero
                        String rutaTemporalDeNumero = rutaAlDirectorioXML + "/" + revista.getIdRevista() + "numero_" + indexNumero;
                        gridForNewArticles.setArchivoTemporal(rutaTemporalDeNumero);
                        gridForNewArticles.setNumero(numero);

                        Panel panelNewArticles = gridForNewArticles.getPanelForNewArticles(numero.getListaDeArticulos());
                        verticalPanelInfo.add(panelNewArticles);
                        verticalPanelInfo.setCellHorizontalAlignment(panelNewArticles, HasAlignment.ALIGN_CENTER);

                        //contamos numeros nuevos para despues verificar
                        totalDeNumerosNuevos++;
                    }
                }
                indexNumero++;
            }
            //agregamos el field al panelInfo
            fieldSetInfo.add(verticalPanelInfo);
            panelInfoAuxiliar.add(fieldSetInfo);
            panelInfoAuxiliar.setCellHorizontalAlignment(fieldSetInfo, HasAlignment.ALIGN_CENTER);
        }

        //revistas que no existen
        for (String revistaNoExistente : revistasNoExistentes) {
            String[] campos = revistaNoExistente.split("-->");
            String issn = campos[0];
            String nombreRevista = campos[1];
            //creamos un field que va a contener a la revista
            FieldSet fieldSetInfo = new FieldSet();
            fieldSetInfo.setWidth(1092);
            fieldSetInfo.setBorder(false);
            fieldSetInfo.setStyleName("label-wrong");
            Label labelInfo = new Label();
            labelInfo.setWidth(1092);
            String html = "<b>ISSN:</b>&nbsp;" + issn
                    + "&nbsp;<b>REVISTA:</b>&nbsp;<font size='3px'>" + nombreRevista + "</font><br /><br />"
                    + "(la revista no existe)";
            labelInfo.setHtml(html);
            //agregamos el label al panel
            fieldSetInfo.add(labelInfo);
            panelInfoAuxiliar.add(fieldSetInfo);
            panelInfoAuxiliar.setCellHorizontalAlignment(fieldSetInfo, HasAlignment.ALIGN_CENTER);
        }
             //revistas que existen duplicadas
        for (String revistaDuplicada : revistasExistentesDuplicadas) {
            String[] campos = revistaDuplicada.split("-->");
            String issn = campos[0];
            String nombreRevista = campos[1];
            String revistasDuplicadas = campos[3];
            //creamos un field que va a contener a la revista
            FieldSet fieldSetInfo = new FieldSet();
            fieldSetInfo.setWidth(1092);
            fieldSetInfo.setBorder(false);
            fieldSetInfo.setStyleName("label-wrong");
            Label labelInfo = new Label();
            labelInfo.setWidth(1092);
            String html = "<b>ISSN:</b>&nbsp;" + issn
                    + "&nbsp;<b>REVISTA:</b>&nbsp;<font size='3px'>" + nombreRevista + "</font><br /><br />"
                    + "(IMPOSIBLE CARGAR ARCHIVOS DE ESTA REVISTA, EXISTEN LAS SIGUIENTES REVISTAS ASOCIADAS CON EL MISMO ISSN:&nbsp;<b>"+revistasDuplicadas+"</b>.&nbsp;CONTACTE CON EL ADMINISTRADOR DE EVALUACIÓN)";
            labelInfo.setHtml(html);
            //agregamos el label al panel
            fieldSetInfo.add(labelInfo);
            panelInfoAuxiliar.add(fieldSetInfo);
            panelInfoAuxiliar.setCellHorizontalAlignment(fieldSetInfo, HasAlignment.ALIGN_CENTER);
        }
    }
    //quitamos el field del combo
    fieldComboRepo.setCollapsed(true);
    //cerramos el field del zip
    fieldUploadZip.setCollapsed(true);
    //desplegamos el panelInfo
    fieldInformacion.setCollapsed(false);
    //quitamos la mascara
    maskElement.unmask();
}

/**
 * etiqueta para numero dependiendo su carga
 * @param numero
 * @return
 */
private String getHTMLStringForNumber(Numero numero) {
    String html = "<hr color='#848484'/><br />";
    switch (numero.getTipoCarga()) {
        case COMPLETA:
            //el numero no existe
            if (!numero.getNumero().equals("")) {
                html += "<b>número</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getNumero() + "</font>&nbsp;";
            }

            if (!numero.getVolumen().equals("")) {
                html += "<b>volumen</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getVolumen() + "</font>&nbsp;";
            }

            if (!numero.getAnioEdicion().equals("")) {
                html += "<b>a\u00f1o</b><font color='#848484' style='font-weight: bold;'>&nbsp;" + numero.getAnioEdicion() + "</font>&nbsp;";
            }

            html += "<img id='img-new' src='img/control/new.png' /><br /><b>articulos:</b>&nbsp;" + numero.getListaDeArticulos().size() + "<br />";

            return html;
        case SOLO_ARTICULOS:
            //el numero existe
            if (!numero.getNumero().equals("")) {
                html += "<b>número</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getNumero() + "</font>&nbsp;";
            }

            if (!numero.getVolumen().equals("")) {
                html += "<b>volumen</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getVolumen() + "</font>&nbsp;";
            }

            if (!numero.getAnioEdicion().equals("")) {
                html += "<b>a\u00f1o</b><font color='#848484' style='font-weight: bold;'>&nbsp;" + numero.getAnioEdicion() + "</font>&nbsp;";
            }

            html += "<img id='img-exist' src='img/control/exist.png' /><br /><b>articulos:</b>&nbsp;" + numero.getListaDeArticulos().size() + "<br />";

            return html;
        case NADA:
            //el numero y articulos existe
            if (!numero.getNumero().equals("")) {
                html += "<b>número</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getNumero() + "</font>&nbsp;";
            }

            if (!numero.getVolumen().equals("")) {
                html += "<b>volumen</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getVolumen() + "</font>&nbsp;";
            }

            if (!numero.getAnioEdicion().equals("")) {
                html += "<b>a\u00f1o</b><font color='#848484' style='font-weight: bold;'>&nbsp;" + numero.getAnioEdicion() + "</font>&nbsp;";
            }

            html += "<img id='img-exist' src='img/control/exist.png' /><br /><b>articulos:</b>&nbsp;" + numero.getListaDeArticulos().size() + "<br />"
                    + "(el numero y todos sus articulos ya existen)";

            return html;
        case EN_PROCESO:
            //el numero esta en proceso
            if (!numero.getNumero().equals("")) {
                html += "<b>número</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getNumero() + "</font>&nbsp;";
            }

            if (!numero.getVolumen().equals("")) {
                html += "<b>volumen</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getVolumen() + "</font>&nbsp;";
            }

            if (!numero.getAnioEdicion().equals("")) {
                html += "<b>a\u00f1o</b><font color='#848484' style='font-weight: bold;'>&nbsp;" + numero.getAnioEdicion() + "</font>&nbsp;";
            }

            html += "<img id='img-exist' src='img/control/exist.png' /><br />(este número no se cargara puesto que se encuentra en estado de proceso)";

            return html;
        case COMPLETA_ARTICULOS_DUPLICADOS:
            //el numero esta en proceso
            if (!numero.getNumero().equals("")) {
                html += "<b>número</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getNumero() + "</font>&nbsp;";
            }

            if (!numero.getVolumen().equals("")) {
                html += "<b>volumen</b>&nbsp;<font color='#848484' style='font-weight: bold;'>" + numero.getVolumen() + "</font>&nbsp;";
            }

            if (!numero.getAnioEdicion().equals("")) {
                html += "<b>a\u00f1o</b><font color='#848484' style='font-weight: bold;'>&nbsp;" + numero.getAnioEdicion() + "</font>&nbsp;";
            }

            html += "<br />(este número no se cargara puesto que existen articulos duplicados en su contenido:<br />"+numero.getListaDeArticulos().get(numero.getListaDeArticulos().size()-1).toString()+ "<br />&nbsp;verifique su información)";

            return html;
        default:
            break;
    }

    return html;
}

/**
 * etiqueta de aviso para la contidad y tipo de carga de los articulos
 * @param articulosLocales
 * @param articulosEntrantes
 * @param tipoCarga
 * @param html
 * @return
 */
private String getHTMLStringForArticles(int articulosLocales, int articulosEntrantes, TipoCarga tipoCarga, String html) {
    switch (tipoCarga) {
        case SOLO_ARTICULOS:
            //si no hay articulos locales
            if (articulosLocales > 0) {
                //si hay diferiencia en la cantidad de articulos
                if (articulosLocales == articulosEntrantes) {
                    html += "<br /><b>Nota:&nbsp;</b><font color='#848484'>revisa que todos los artículos de la siguiente tabla coincidan para "
                            + "que se pueda cargar su información.</font><img id='img-info' src='img/control/info.gif' />";
                    return html;
                } else {
                    html += "<br /><b>Nota:&nbsp;</b><font color='#848484'>se encontraron <b>" + articulosEntrantes + " artículos entrantes</b> y "
                            + "existen <b>" + articulosLocales + " artículos ya cargados</b> para este número, solo se cargará la información de los "
                            + "artículos contemplados en la siguiente tabla.</font><img id='img-info' src='img/control/info.gif' />";
                    return html;
                }
            } else {
                //no hay articulos locales para este numero
                return html;
            }
        case NADA:
            html += "<br /><b>Nota:&nbsp;</b><font color='#848484'>los siguientes artículos ya estan cargados para este número, si "
                    + "existe algún articulo que no coincida con otro ya cargado, editalo para poder cargar su información.</font>"
                    + "<img id='img-info' src='img/control/info.gif' />";
            return html;
        default:
            break;
    }

    return html;
}

/**
 * creal el data para llenar el grid de comparacion de articulos
 * @param listaDeArticulos
 * @return
 */
private Object[][] getArticulosAComparar(LinkedList listaDeArticulos) {
    //llenamos el grid
    Object[][] articulosAComparar = new Object[listaDeArticulos.size()][3];
    for (int i = 0; i < listaDeArticulos.size(); i++) {
        String[] campos = ((String) listaDeArticulos.get(i)).split("-->");
        String carga = campos[campos.length - 1];
        String articuloEntrante = campos[0];

        articulosAComparar[i][0] = articuloEntrante;
        articulosAComparar[i][1] = "";

        if (carga.equalsIgnoreCase("NO_EXISTE") || carga.equalsIgnoreCase("SIN_REFERENCIAS")) {
            articulosAComparar[i][2] = "";
        } else {
            String articuloLocal = campos[2];
            articulosAComparar[i][2] = articuloLocal;
        }
    }

    return articulosAComparar;
}

/**
 * crea un grid editable para comparar los articulos en redalyc con los de importacion
 * @param listaDeArticulos
 * @param listaDeArticulosLocales
 * @param idRevista
 * @param idNumero
 * @return
 */
private EditorGridPanel newGridComparable(LinkedList listaDeArticulos, List<String> listaDeArticulosLocales,
        final Long idRevista, final Long idNumero) {

    RecordDef recordDef = new RecordDef(
            new FieldDef[]{
                new StringFieldDef("articuloEntrante"),
                new StringFieldDef("space"),
                new StringFieldDef("articuloRedalyc")
            });

    //data de los articulos para llenar el grid
    final Object[][] data = getArticulosAComparar(listaDeArticulos);
    MemoryProxy proxy = new MemoryProxy(data);

    ArrayReader reader = new ArrayReader(recordDef);
    Store store = new Store(proxy, reader);
    store.load();

    final String[][] articulosLocales = new String[listaDeArticulosLocales.size() + 1][2];
    //opcion por default
    articulosLocales[0][0] = "0";
    articulosLocales[0][1] = "selecciona esta opción si no existe el artículo que buscas";
    int i = 1;
    for (String articuloYClaveLocal : listaDeArticulosLocales) {
        String clave = articuloYClaveLocal.split("-->")[0];
        String titulo = articuloYClaveLocal.split("-->")[1];
        articulosLocales[i][0] = clave;
        articulosLocales[i][1] = titulo;

        i++;
    }

    final Store cbStore = new SimpleStore(new String[]{"clave", "titulo"}, articulosLocales);
    cbStore.load();

    //combo de articulos para comparar
    comboBoxDeArticulos = new ComboBox();
    comboBoxDeArticulos.setDisplayField("titulo");
    comboBoxDeArticulos.setStore(cbStore);
    comboBoxDeArticulos.setEditable(false);
    comboBoxDeArticulos.addListener(new ComboBoxListenerAdapter() {

        @Override
        public void onSelect(ComboBox comboBox, Record record, int index) {
            addNewChangeToList(new ArticuloAModificar(Long.parseLong(record.getAsString("clave")),
                    tituloOriginal, idNumero, idRevista));
        }
    });

    //columna para los articulos entrantes
    ColumnConfig articuloEntranteColumn = new ColumnConfig("Articulo entrante", "articuloEntrante", 437, false, null, "articuloEntrante");
    //columna de espacio
    ColumnConfig spaceColumn = new ColumnConfig("", "space", 30, false);
    //columna de articulo en redalyc
    ColumnConfig articuloLocalColumn = new ColumnConfig("Articulo en Redalyc", "articuloRedalyc", 550);
    articuloLocalColumn.setEditor(new GridEditor(comboBoxDeArticulos));
    ToolTip toolTip = new ToolTip("<font color='#FFFFFF'>Click sobre el titulo que quieres editar en la columna <b>Artículo en Redlyc</b></font>.");
    toolTip.setWidth(200);
    toolTip.setDismissDelay(4000);


    BaseColumnConfig[] columns = {
        new RowNumberingColumnConfig(), articuloEntranteColumn, spaceColumn, articuloLocalColumn
    };

    ColumnModel columnModel = new ColumnModel(columns);

    final EditorGridPanel grid = new EditorGridPanel();

    grid.setStore(store);
    grid.setColumnModel(columnModel);
    grid.setWidth(1058);
    grid.setEnableColumnHide(false);
    grid.setBorder(false);
    grid.setFrame(true);
    grid.setClicksToEdit(1);

    /*customizando rows*/
    grid.setView(new GridView() {

        @Override
        public String getRowClass(Record record, int index, RowParams rowParams, Store store) {
            if (index % 2 == 0) {
                return "row-ext";
            }
            return "row-default";
        }
    });

    grid.addGridCellListener(new GridCellListenerAdapter() {

        @Override
        public void onCellClick(GridPanel grid, int rowIndex, int colindex, EventObject e) {
            Record record = grid.getStore().getRecordAt(rowIndex);
            tituloOriginal = record.getAsString("articuloEntrante");
        }
    });

    grid.getView().setAutoFill(true);
    grid.getView().setForceFit(true);

    return grid;
}

/**
 * agrega un cambio de artriculo a la lista de cambios
 * @param articulo
 */
private void addNewChangeToList(ArticuloAModificar articulo) {
    //limpiamos el registro anterior si es que lo contiene
    if (listaDeCambios.contains(articulo)) {
        for (ArticuloAModificar aam : listaDeCambios) {
            if (aam.equals(articulo)) {
                listaDeCambios.remove(aam);
                break;
            }
        }
    }
    listaDeCambios.add(articulo);
}

/**
 * agrega un numero nuevo al mapa final de nuevos numeros
 * @param numero
 * @param archivosDeNumero
 */
public static  void addNewNumberToMap(Numero numero, List archivosDeNumero) {
    nuevosNumeros.put(numero, archivosDeNumero);
}

/**
 * va por los repositorios
 */
private void getRepositorys() {
    final AsyncCallback callback = new AsyncCallback() {

        public void onFailure(Throwable caught) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        public void onSuccess(Object result) {
            String[][] repositorys = (String[][]) result;
            store = new SimpleStore(new String[]{"idRepo", "tipo"}, repositorys);
            store.load();
            comboRepositorio.setStore(store);
        }
    };
    getService().getRepositorys(callback);
}

/**
 * sube y parsea la informacion contenida en los xml
 * @param ruta
 * @param repositorio
 */
private void sendAndParseXMLFiles(String ruta, TipoRepositorio repositorio, Long claveRepositorio) {
    maskElement.mask("Parseando archivos...");

    final AsyncCallback callback = new AsyncCallback() {

        public void onFailure(Throwable caught) {
            MessageBox.alert("Error parseando xml");
            maskElement.unmask();
        }

        public void onSuccess(Object result) {
            //aqui recibimos las revistas encontradas
            maskElement.unmask();

            List<Object> listResult = (ArrayList<Object>) result;
            LinkedList<RevistaNumero> revistasValidas = (LinkedList<RevistaNumero>) listResult.get(0);
            LinkedList<String> erroresRecuperables = (LinkedList<String>) listResult.get(1);
            Set<String> revistasNoExistentes = (HashSet<String>) listResult.get(2);
            Set<String> revistasExistentesDuplicadas = (HashSet<String>) listResult.get(3);
            //agregamos las revistas encontradas al panel
            addMagazinesToPanelInfo(revistasValidas, erroresRecuperables, revistasNoExistentes, revistasExistentesDuplicadas);

        }
    };
    getService().getMagazines(ruta, repositorio, claveRepositorio,claveUsuario, callback);

}

/**
 * pasa la informacion valida a redalyc
 * @param claveUsuario
 * @param listaDeCambios
 */
private void createAndViewRedalycObject(String claveUsuario, List<ArticuloAModificar> listaDeCambios,
        HashMap nuevosNumeros) {
    final AsyncCallback callback = new AsyncCallback() {

        public void onFailure(Throwable caught) {
            MessageBox.alert("Error al crear objeto local " + caught);
        }

        public void onSuccess(Object result) {
            maskElement.mask("Generando vista previa...");

            List<ModeloRedalyc> listResult = (List<ModeloRedalyc>) result;
            GUIPanelVistaPrevia gui = new GUIPanelVistaPrevia();
            GUIMenu.tabPanel.clear();
            GUIMenu.tabPanel.add(gui.getPreviewPanel(rutaAlDirectorioXML, listResult));
            GUIMenu.tabPanel.setActiveTab(0);
        }
    };
    //si existen nuevos numeros
    if (totalDeNumerosNuevos > 0) {
        //si ya se agregaron todos los archivos
        if (totalDeNumerosNuevos == nuevosNumeros.size()) {
            maskElement.mask("Validando información...");
            getService().createRedalycObject(claveUsuario, listaDeCambios, nuevosNumeros,claveUsuario, callback);
        } else {
            MessageBox.alert("Asegurate de haber agregado y subido los archivos de cada artículo");
        }
    } else {
        //si no hay numeros nuevos
        maskElement.mask("Validando información...");
        getService().createRedalycObject(claveUsuario, listaDeCambios, nuevosNumeros,claveUsuario, callback);
    }
}

/**
 * borra los archivos que se subieron para parsear los xml
 * @param pathToDelete
 */
public static void deleteTemporalFiles(String pathToDelete) {
    final AsyncCallback callback = new AsyncCallback() {

        public void onFailure(Throwable caught) {
            MessageBox.alert("Error borrando archivos temporales");
        }

        public void onSuccess(Object result) {
            if (!(Boolean) result) {
                MessageBox.alert("No se pudo borrar archivos temporales");
            }
        }
    };
    getService().deleteTemporalXMLFiles(pathToDelete, callback);
}

private void guardarArriboDescarga(ArriboDescarga arbDes) {
    final AsyncCallback callback = new AsyncCallback() {
        public void onSuccess(Object result) {
           //setClaveRevistaCan(result.toString());
            consoleLog("Estado guardar arbDes en DB: " + result.toString());
            maskElement.unmask();
            getWindow().close();
            consoleLog("Se han subido los archivos exitosamente");
        }
        public void onFailure(Throwable caught) {
            MessageBox.alert("Error! Falló la comunicación" + caught);
        }
    };
    getServiceDescarga().guardarArriboDescarga(arbDes, callback);

}

public void guardaRegistroBajarZIP() {
    final AsyncCallback callback = new AsyncCallback() {

        public void onSuccess(Object result) {
            String rutaDescarga = (String) result;
            rutaDescarga += "/xmls/OJS/" + getClaveArribo();
            consoleLog("Ruta descarga zip guarda: " + rutaDescarga);
            ArriboDescarga arbDes = new ArriboDescarga();
            arbDes.setArriboDescargaCve(0L);
            arbDes.setRevistaNumeroArriboCve(Long.parseLong(getClaveArribo()));
            arbDes.setNombreRepositorio("5");
            //arbDes.setRutaDescargaArribo(rutaDescarga);
            consoleLog("Save next ruta on server: " + "/home/siir/SIIR/xmls/OJS/" + getClaveArribo());
            arbDes.setRutaDescargaArribo("/home/siir/SIIR/xmls/OJS/" + getClaveArribo());
            arbDes.setBanderaManualAutomatico((short)2);
            arbDes.setFechaCargaArribo(new Date());

            guardarArriboDescarga(arbDes);
            if(isOnlyRead()) {
                GUIObtenArribosByXml getArbXml = new GUIObtenArribosByXml();
                getArbXml.setClaveUsuario(String.valueOf(getClaveUsuario()));
                GUIMenu.tabPanel.clear();
                GUIMenu.tabPanel.add(getArbXml.getPanel());
                GUIMenu.tabPanel.setActiveTab(0);
            }
            MessageBox.alert("Los archivos se han subido exitosamente");
        }

        public void onFailure(Throwable caught) {
            MessageBox.alert("Error de comunicacion GUI ");
        }
    };
    getServiceRuta().obtieneDirDownloadFiles(callback);
}

public static native void consoleLog(Object o)/*-{
    console.log(o);
}-*/;

public static GWTServiceDescargaAsync getServiceDescarga() {
    GWTServiceDescargaAsync service = (GWTServiceDescargaAsync) GWT.create(GWTServiceDescarga.class);
    ServiceDefTarget endpoint = (ServiceDefTarget)service;
    String moduleRelativeURL = GWT.getModuleBaseURL() + "gwtservicedescarga";
    endpoint.setServiceEntryPoint(moduleRelativeURL);
    return service;

}

public static GWTServiceUtilAsync getServiceRuta() {
    GWTServiceUtilAsync service = (GWTServiceUtilAsync) GWT.create(GWTServiceUtil.class);
    ServiceDefTarget endpoint = (ServiceDefTarget) service;
    String moduleRelativeURL = GWT.getModuleBaseURL() + "gwtserviceutil";
    endpoint.setServiceEntryPoint(moduleRelativeURL);
    return service;
}

public static GWTServiceXMLAsync getService() {
    GWTServiceXMLAsync service = (GWTServiceXMLAsync) GWT.create(GWTServiceXML.class);
    ServiceDefTarget endpoint = (ServiceDefTarget) service;
    String moduleRelativeURL = GWT.getModuleBaseURL() + "gwtservicexml";
    endpoint.setServiceEntryPoint(moduleRelativeURL);
    return service;
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment