Example usage for java.util Stack Stack

List of usage examples for java.util Stack Stack

Introduction

In this page you can find the example usage for java.util Stack Stack.

Prototype

public Stack() 

Source Link

Document

Creates an empty Stack.

Usage

From source file:com.taobao.tdhs.jdbc.sqlparser.ParseSQL.java

private void analyzeUpdateSetColumns(String substring) {
    if (substring == null)
        return;//from  ww w  .jav  a 2s .c o m

    /*String[] array_setColumn = substring.split(",");
      for (String setColumn : array_setColumn) {
      int addr = StringUtils.indexOfIgnoreCase(setColumn, "=");
      String column = setColumn.substring(0, addr).trim();
      String value = setColumn.substring(addr + 1).trim();
      this.updateEntries.add(new Entry<String, String>(column, value));
      }*/

    //Stack??
    Stack<String> updateColumnValueStack = new Stack<String>();
    for (int i = 0; i < substring.length(); i++) {
        updateColumnValueStack.push(substring.substring(i, i + 1));
    }

    String column = "";
    String value = "";
    while (updateColumnValueStack.isEmpty() == false) {
        column = "";
        value = "";
        //value String
        while (updateColumnValueStack.peek().equals("=") == false
                || checkRealEqual(updateColumnValueStack) == false) {
            value = updateColumnValueStack.pop() + value;
        }
        //=
        updateColumnValueStack.pop();
        //column String
        try {
            while (updateColumnValueStack.peek().equals(",") == false) {
                column = updateColumnValueStack.pop() + column;
            }
        } catch (EmptyStackException e) {
            //?
            this.updateEntries.add(new Entry<String, String>(column, value));
            break;
        }

        //,
        updateColumnValueStack.pop();
        //?
        this.updateEntries.add(new Entry<String, String>(column, value));
    }

}

From source file:com.jsmartframework.web.manager.TagHandler.java

@SuppressWarnings("unchecked")
protected void pushDelegateTagParent() {
    Stack<RefAction> actionStack = (Stack<RefAction>) getMappedValue(DELEGATE_TAG_PARENT);
    if (actionStack == null) {
        actionStack = new Stack<RefAction>();
        actionStack.push(new RefAction());
        addMappedValue(DELEGATE_TAG_PARENT, actionStack);
    } else {/*  w  ww .j  av  a 2  s.co  m*/
        actionStack.push(new RefAction());
    }
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

/**
 * Recursively create a path, working down from the leaf to the root.
 * <p>//w  w  w  . ja  v a 2  s  .com
 * Borrowed from Apache Sling
 * 
 * @param path a directory path to create
 * @throws HttpException
 * @throws TransferFailedException
 * @throws AuthorizationException
 */
protected void mkdirs(String path) throws HttpException, TransferFailedException, AuthorizationException {
    // Call mkdir on all parent paths, starting at the topmost one
    final Stack<String> parents = new Stack<String>();
    while (path.length() > 0 && !resourceExists(path)) {
        parents.push(path);
        path = getParentPath(path);
    }

    while (!parents.isEmpty()) {
        mkdir(parents.pop());
    }
}

From source file:edu.uci.ics.asterix.optimizer.rules.IntroduceSecondaryIndexInsertDeleteRule.java

public static ARecordType createEnforcedType(ARecordType initialType, Index index)
        throws AsterixException, AlgebricksException {
    ARecordType enforcedType = initialType;
    for (int i = 0; i < index.getKeyFieldNames().size(); i++) {
        try {// w  w  w.  ja v  a2 s  .  c  o  m
            Stack<Pair<ARecordType, String>> nestedTypeStack = new Stack<Pair<ARecordType, String>>();
            List<String> splits = index.getKeyFieldNames().get(i);
            ARecordType nestedFieldType = enforcedType;
            boolean openRecords = false;
            String bridgeName = nestedFieldType.getTypeName();
            int j;
            //Build the stack for the enforced type
            for (j = 1; j < splits.size(); j++) {
                nestedTypeStack.push(new Pair<ARecordType, String>(nestedFieldType, splits.get(j - 1)));
                bridgeName = nestedFieldType.getTypeName();
                nestedFieldType = (ARecordType) enforcedType.getSubFieldType(splits.subList(0, j));
                if (nestedFieldType == null) {
                    openRecords = true;
                    break;
                }
            }
            if (openRecords == true) {
                //create the smallest record
                enforcedType = new ARecordType(splits.get(splits.size() - 2),
                        new String[] { splits.get(splits.size() - 1) },
                        new IAType[] { AUnionType.createNullableType(index.getKeyFieldTypes().get(i)) }, true);
                //create the open part of the nested field
                for (int k = splits.size() - 3; k > (j - 2); k--) {
                    enforcedType = new ARecordType(splits.get(k), new String[] { splits.get(k + 1) },
                            new IAType[] { AUnionType.createNullableType(enforcedType) }, true);
                }
                //Bridge the gap
                Pair<ARecordType, String> gapPair = nestedTypeStack.pop();
                ARecordType parent = gapPair.first;

                IAType[] parentFieldTypes = ArrayUtils.addAll(parent.getFieldTypes().clone(),
                        new IAType[] { AUnionType.createNullableType(enforcedType) });
                enforcedType = new ARecordType(bridgeName,
                        ArrayUtils.addAll(parent.getFieldNames(), enforcedType.getTypeName()), parentFieldTypes,
                        true);

            } else {
                //Schema is closed all the way to the field
                //enforced fields are either null or strongly typed
                enforcedType = new ARecordType(nestedFieldType.getTypeName(),
                        ArrayUtils.addAll(nestedFieldType.getFieldNames(), splits.get(splits.size() - 1)),
                        ArrayUtils.addAll(nestedFieldType.getFieldTypes(),
                                AUnionType.createNullableType(index.getKeyFieldTypes().get(i))),
                        nestedFieldType.isOpen());
            }

            //Create the enforcedtype for the nested fields in the schema, from the ground up
            if (nestedTypeStack.size() > 0) {
                while (!nestedTypeStack.isEmpty()) {
                    Pair<ARecordType, String> nestedTypePair = nestedTypeStack.pop();
                    ARecordType nestedRecType = nestedTypePair.first;
                    IAType[] nestedRecTypeFieldTypes = nestedRecType.getFieldTypes().clone();
                    nestedRecTypeFieldTypes[nestedRecType
                            .findFieldPosition(nestedTypePair.second)] = enforcedType;
                    enforcedType = new ARecordType(nestedRecType.getTypeName(), nestedRecType.getFieldNames(),
                            nestedRecTypeFieldTypes, nestedRecType.isOpen());
                }
            }

        } catch (AsterixException e) {
            throw new AlgebricksException(
                    "Cannot enforce typed fields " + StringUtils.join(index.getKeyFieldNames()), e);
        } catch (IOException e) {
            throw new AsterixException(e);
        }
    }
    return enforcedType;
}

From source file:com.quinsoft.zeidon.zeidonoperations.ZDRVROPR.java

public int BuildCSV_FromEntityAttribute(View vTgt, String cpcTgtEntity, String cpcTgtAttribute, View vSrc,
        String cpcSrcListEntityScope, String cpcSrcEAC, int lFlag) {
    Stack<ZNameItem> EntityStack = new Stack<ZNameItem>(); // tag stack (need not be unique)
    Stack<ZNameItem> AttributeStack = new Stack<ZNameItem>(); // tag stack (need not be unique)
    Stack<ZNameItem> ValueStack = new Stack<ZNameItem>(); // tag stack (need not be unique)
    Stack<ZNameItem> ContextStack = new Stack<ZNameItem>(); // tag stack (need not be unique)
    ZNameItem pEntityItem;/*from ww  w.  j a  v  a2  s.c om*/
    ZNameItem pAttribItem;
    ZNameItem pValueItem;
    ZNameItem pContextItem;
    String pchSrcListEntity;
    String pchSrcListScope;
    StringBuilder sb;
    String pch = null;
    int ulCurrLth;
    int ulMaxLth = 0;
    int k;
    int nRC;

    k = zstrchr(cpcSrcListEntityScope, '.');
    if (k > 0) {
        pchSrcListEntity = cpcSrcListEntityScope.substring(0, k);
        pchSrcListScope = cpcSrcListEntityScope.substring(k + 1);
    } else {
        pchSrcListEntity = cpcSrcListEntityScope;
        pchSrcListScope = null;
    }

    fnSetEntityAttribList(EntityStack, AttributeStack, ValueStack, ContextStack, pchSrcListEntity, cpcSrcEAC);

    if (EntityStack.size() == 0 || AttributeStack.size() == 0)
        return (-3); // entity.attribute.context parameter not well-formed

    MutableInt nLth = new MutableInt(0);
    GetAttributeLength(nLth, vTgt, cpcTgtEntity, cpcTgtAttribute);
    ulMaxLth = nLth.intValue();
    sb = new StringBuilder(ulMaxLth + 16); // extra room for adding <crlf> or <p></p>
    sb.setLength(0); // Use sb.setLength( 0 ); to clear a string buffer.

    // DisplayObjectInstance( vSrc, "", "" );
    ulCurrLth = 0;
    nRC = SetCursorFirstEntity(vSrc, pchSrcListEntity, pchSrcListScope);
    while (nRC >= zCURSOR_SET) {
        k = 0;
        if (k < AttributeStack.size()) {
            pEntityItem = EntityStack.get(k);
            pAttribItem = AttributeStack.get(k);
            pValueItem = ValueStack.get(k);
            pContextItem = ContextStack.get(k);
        } else {
            pEntityItem = null;
            pAttribItem = null;
            pValueItem = null;
            pContextItem = null;
        }

        while (pAttribItem != null) {
            if ((lFlag & 0x00000001) != 0) {
                sb.insert(ulCurrLth++, '<');
                sb.insert(ulCurrLth++, 'p');
                sb.insert(ulCurrLth++, '>');
            }

            pch = GetStringFromAttributeByContext(pch, vSrc, pEntityItem.getName(), pAttribItem.getName(),
                    pContextItem.getName(), ulMaxLth - ulCurrLth);
            ulCurrLth = zstrcpy(sb, ulCurrLth, pch);
            k++;
            if (k < AttributeStack.size()) {
                pEntityItem = EntityStack.get(k);
                pAttribItem = AttributeStack.get(k);
                pValueItem = ValueStack.get(k);
                pContextItem = ContextStack.get(k);
            } else {
                pEntityItem = null;
                pAttribItem = null;
                pValueItem = null;
                pContextItem = null;
            }

            if (pAttribItem != null) {
                sb.insert(ulCurrLth++, ',');
                sb.insert(ulCurrLth++, ' ');
            } else {
                if ((lFlag & 0x00000001) != 0) {
                    sb.insert(ulCurrLth++, '<');
                    sb.insert(ulCurrLth++, '/');
                    sb.insert(ulCurrLth++, 'p');
                    sb.insert(ulCurrLth++, '>');
                } else {
                    sb.insert(ulCurrLth++, '\r');
                    sb.insert(ulCurrLth++, '\n');
                }
            }

            if (ulCurrLth >= ulMaxLth) {
                break;
            }
        }

        if (ulCurrLth >= ulMaxLth)
            nRC = zCALL_ERROR;
        else
            nRC = SetCursorNextEntity(vSrc, pchSrcListEntity, pchSrcListScope);
    }

    SetAttributeFromString(vTgt, cpcTgtEntity, cpcTgtAttribute, sb.toString());
    return 0;
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * List the contents of directory./*from  ww w  .ja va2s  .  c om*/
 * @param directory {@link File}
 * @param includingDirectory boolean
 * @return List<String> 
 * @throws IOException in case of error
 */
public static List<String> listDirectory(File directory, boolean includingDirectory) throws IOException {

    Stack<String> stack = new Stack<String>();
    List<String> list = new ArrayList<String>();

    // If it's a file, just return itself
    if (directory.isFile()) {
        if (directory.canRead()) {
            list.add(directory.getName());
        }
    } else {

        // Traverse the directory in width-first manner, no-recursively
        String root = directory.getParent();
        stack.push(directory.getName());
        while (!stack.empty()) {
            String current = (String) stack.pop();
            File curDir = new File(root, current);
            String[] fileList = curDir.list();
            if (fileList != null) {
                for (String entry : fileList) {
                    File file = new File(curDir, entry);
                    if (file.isFile()) {
                        if (file.canRead()) {
                            list.add(current + File.separator + entry);
                        } else {
                            throw new IOException("Can't read file: " + file.getPath());
                        }
                    } else if (file.isDirectory()) {
                        if (includingDirectory) {
                            list.add(current + File.separator + entry);
                        }
                        stack.push(current + File.separator + file.getName());
                    } else {
                        throw new IOException("Unknown entry: " + file.getPath());
                    }
                }
            }
        }
    }
    return list;
}

From source file:fsi_admin.JFsiTareas.java

public synchronized void respaldarEmpresa(JBDSSet set, int ind, Calendar fecha, PrintWriter out,
        PrintWriter prntwri) {//from w  w w .ja v  a  2  s  .  c o  m
    try {
        //Primero respalda emp/NOMBRE/
        String nombre = set.getAbsRow(ind).getNombre();
        String path = "/usr/local/forseti/log/RESP-" + nombre + "-"
                + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".log";
        PrintWriter pw;
        if (prntwri == null)
            pw = new PrintWriter(new FileWriter(path, true));
        else
            pw = prntwri;

        if (out != null) {
            out.println("----------------------------------------------------------------------------<br>");
            out.println("RESPALDANDO LA BASE DE DATOS Y ARCHIVOS EMP: " + nombre.substring(6) + " "
                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>");
            out.println("----------------------------------------------------------------------------<br>");
            out.flush();
        }
        pw.println("----------------------------------------------------------------------------");
        pw.println("RESPALDANDO LA BASE DE DATOS Y ARCHIVOS EMP: " + nombre.substring(6) + " "
                + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
        pw.println("----------------------------------------------------------------------------");
        pw.flush();

        if (respaldos.equals("NC")) {
            if (out != null) {
                out.println(
                        "PRECAUCION: La variable RESPALDOS (ruta para los archivos de respaldo) no est definida... No se puede generar<br>");
                out.flush();
            }
            pw.println(
                    "PRECAUCION: La variable RESPALDOS (ruta para los archivos de respaldo) no est definida... No se puede generar");
            pw.flush();
            return;
        }

        JFsiScript sc = new JFsiScript();
        sc.setVerbose(true);

        String ERROR = "";

        try {
            File dir;
            //System.out.println(dir.getAbsolutePath());
            String CONTENT;
            JAdmVariablesSet var = new JAdmVariablesSet(null);
            var.ConCat(3);
            var.setBD(nombre);
            var.m_Where = "ID_Variable = 'VERSION'";
            var.Open();
            String vers = var.getAbsRow(0).getVAlfanumerico();

            if (prntwri == null) {
                dir = new File(respaldos, (nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm")));
                dir.mkdir();
                // Primero Agrega el archivo de version para esta empresa
                File version = new File(respaldos + "/" + nombre + "-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/forseti.version");
                FileWriter fw = new FileWriter(version);
                fw.write(vers);
                fw.close();
                CONTENT = "rsync -av --stats /usr/local/forseti/emp/" + nombre.substring(6) + " " + respaldos
                        + "/" + nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm");
            } else {
                dir = new File(respaldos + "/FORSETI_ADMIN-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm"),
                        (nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm")));
                dir.mkdir();
                // Primero Agrega el archivo de version para esta empresa
                File version = new File(respaldos + "/FORSETI_ADMIN-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/" + nombre + "-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/forseti.version");
                FileWriter fw = new FileWriter(version);
                fw.write(vers);
                fw.close();
                CONTENT = "rsync -av --stats /usr/local/forseti/emp/" + nombre.substring(6) + " " + respaldos
                        + "/FORSETI_ADMIN-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/" + nombre + "-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm");
            }
            sc.setContent(CONTENT);
            //System.out.println(CONTENT);
            String RES = sc.executeCommand();
            ERROR += sc.getError();
            if (!ERROR.equals("")) {
                if (out != null) {
                    out.println("ERROR al respaldar en RSYNC: " + ERROR + "<br>");
                    out.flush();
                }
                pw.println("ERROR al respaldar en RSYNC: " + ERROR);
                pw.flush();
            } else {
                if (out != null) {
                    out.println("El respaldo de los archivos se gener con xito en: " + respaldos + "/"
                            + nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "<br>");
                    out.flush();
                }
                pw.println("El respaldo de los archivos se gener con xito en: " + respaldos + "/" + nombre
                        + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm"));
                pw.flush();
            }
            if (out != null) {
                out.println("FINALIZANDO RESPALDO DE ARCHIVOS EMP: " + nombre.substring(6) + " "
                        + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>");
                out.println(
                        "Comenzando el respaldo de la base de datos... Esto puede tardar muchos minutos, incluso horas (dependiendo de la cantidad de informacin) hay que ser pacientes<br>");
                out.flush();
            }
            pw.println("FINALIZANDO RESPALDO DE ARCHIVOS EMP: " + nombre.substring(6) + " "
                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
            pw.flush();

            ERROR = "";
            if (prntwri == null)
                CONTENT = "PGUSER=forseti PGPASSWORD=" + JUtil.getPASS() + " pg_dump --host=" + JUtil.getADDR()
                        + " --port=" + JUtil.getPORT() + " --file=" + respaldos + "/" + nombre + "-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/" + nombre + "-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".dump --no-owner " + nombre;
            else
                CONTENT = "PGUSER=forseti PGPASSWORD=" + JUtil.getPASS() + " pg_dump --host=" + JUtil.getADDR()
                        + " --port=" + JUtil.getPORT() + " --file=" + respaldos + "/FORSETI_ADMIN-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/" + nombre + "-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/" + nombre + "-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".dump --no-owner " + nombre;

            sc.setContent(CONTENT);
            //System.out.println(CONTENT);
            RES = sc.executeCommand();
            ERROR += sc.getError();
            if (!ERROR.equals("")) {
                //System.out.println(ERROR);
                if (out != null) {
                    out.println("ERROR al crear el respaldo de la base de datos: " + ERROR + "<br>");
                    out.flush();
                }
                pw.println("ERROR al crear el respaldo de la base de datos: " + ERROR);
                pw.flush();
            } else {
                if (RES.equals("")) {
                    if (out != null) {
                        out.println(
                                "El respaldo de la base de datos se gener con xito como archivo .dump dentro de este directorio<br>");
                        out.flush();
                    }
                    pw.println(
                            "El respaldo de la base de datos se gener con xito como archivo .dump dentro de este directorio");
                    pw.flush();
                } else {
                    if (out != null) {
                        out.println("RESPUESTA PG_DUMP: " + RES + "<br>");
                        out.flush();
                    }
                    pw.println("RESPUESTA PG_DUMP: " + RES);
                    pw.flush();
                }
            }
            if (out != null) {
                out.println("FINALIZANDO RESPALDO DE LA BASE DE DATOS: " + nombre + " "
                        + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>");
                out.flush();
            }
            pw.println("FINALIZANDO RESPALDO DE LA BASE DE DATOS: " + nombre + " "
                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
            pw.flush();

            File file;
            if (prntwri == null)
                file = new File(respaldos + "/" + nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm")
                        + "/" + nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".conf");
            else
                file = new File(respaldos + "/FORSETI_ADMIN-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm")
                        + "/" + nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/" + nombre + "-"
                        + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".conf");

            String conf = "id_bd|" + set.getAbsRow(ind).getID_BD() + "\n" + "nombre|"
                    + set.getAbsRow(ind).getNombre() + "\n" + "usuario|" + set.getAbsRow(ind).getUsuario()
                    + "\n" + "password|" + set.getAbsRow(ind).getPassword() + "\n" + "fechaalta|"
                    + JUtil.obtFechaSQL(set.getAbsRow(ind).getFechaAlta()) + "\n" + "compania|"
                    + set.getAbsRow(ind).getCompania() + "\n" + "direccion|" + set.getAbsRow(ind).getDireccion()
                    + "\n" + "poblacion|" + set.getAbsRow(ind).getPoblacion() + "\n" + "cp|"
                    + set.getAbsRow(ind).getCP() + "\n" + "mail|" + set.getAbsRow(ind).getMail() + "\n" + "web|"
                    + set.getAbsRow(ind).getWeb() + "\n" + "su|" + set.getAbsRow(ind).getSU() + "\n" + "rfc|"
                    + set.getAbsRow(ind).getRFC() + "\n" + "cfd|" + set.getAbsRow(ind).getCFD() + "\n"
                    + "cfd_calle|" + set.getAbsRow(ind).getCFD_Calle() + "\n" + "cfd_noext|"
                    + set.getAbsRow(ind).getCFD_NoExt() + "\n" + "cfd_noint|"
                    + set.getAbsRow(ind).getCFD_NoInt() + "\n" + "cfd_colonia|"
                    + set.getAbsRow(ind).getCFD_Colonia() + "\n" + "cfd_localidad|"
                    + set.getAbsRow(ind).getCFD_Localidad() + "\n" + "cfd_municipio|"
                    + set.getAbsRow(ind).getCFD_Municipio() + "\n" + "cfd_estado|"
                    + set.getAbsRow(ind).getCFD_Estado() + "\n" + "cfd_pais|" + set.getAbsRow(ind).getCFD_Pais()
                    + "\n" + "cfd_cp|" + set.getAbsRow(ind).getCFD_CP() + "\n" + "cfd_regimenfiscal|"
                    + set.getAbsRow(ind).getCFD_RegimenFiscal();
            FileWriter fconf = new FileWriter(file);
            fconf.write(conf);
            fconf.close();
            if (out != null) {
                out.println(
                        "El respaldo de la configuracin se gener con xito como archivo .conf en este directorio<br>");
                out.flush();
            }
            pw.println(
                    "El respaldo de la configuracin se gener con xito como archivo .conf en este directorio");
            pw.flush();
            if (prntwri == null) {
                if (out != null) {
                    out.println("Generando el archivo zip...<br>");
                    out.flush();
                }
                pw.println("Generando el archivo zip...");
                pw.flush();
                JZipUnZipUtil azip = new JZipUnZipUtil();
                azip.zipFolder(respaldos + "/" + nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm"),
                        respaldos + "/" + nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".zip");
                if (out != null) {
                    out.println("Eliminando carpeta de respaldo<br>");
                    out.flush();
                }
                pw.println("Eliminando carpeta de respaldo...");
                pw.flush();
                //Borra los archivos del respaldo
                File dirbd = new File(
                        respaldos + "/" + nombre + "-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm"));
                File[] currList;
                Stack<File> stack = new Stack<File>();
                stack.push(dirbd);
                while (!stack.isEmpty()) {
                    if (stack.lastElement().isDirectory()) {
                        currList = stack.lastElement().listFiles();
                        if (currList.length > 0) {
                            for (File curr : currList) {
                                stack.push(curr);
                            }
                        } else {
                            stack.pop().delete();
                        }
                    } else {
                        stack.pop().delete();
                    }
                }
            }
        } catch (Throwable e) {
            if (out != null) {
                out.println("ERROR Throwable:<br>");
                e.printStackTrace(out);
                out.flush();
            }
            pw.println("ERROR Throwable:\n");
            e.printStackTrace(pw);
            pw.flush();
        }
        if (out != null) {
            out.println("----------------------------- FIN DEL RESPALDO: " + nombre
                    + " ----------------------------------<br>");
            out.flush();
        }
        pw.println("----------------------------- FIN DEL RESPALDO: " + nombre
                + " ----------------------------------");
        pw.flush();
        if (prntwri == null)
            pw.close();
    } catch (IOException e) {
        if (out != null) {
            out.println("OCURRIERON ERRORES AL ABRIR O COPIAR ARCHIVOS<br>");
            e.printStackTrace(out);
            out.flush();
        }
        e.printStackTrace(System.out);
    }

}

From source file:gdt.jgui.entity.JEntityDigestDisplay.java

private JPopupMenu getCollapsePopupMenu() {
    //System.out.println("JEntityDigestDisplay:getCollapsePopupMenu:selection="+Locator.remove(selection$, Locator.LOCATOR_ICON));
    JPopupMenu popup = new JPopupMenu();
    JMenuItem collapseItem = new JMenuItem("Collapse");
    popup.add(collapseItem);/*from   w  ww . j  a  v a  2s .  c om*/
    collapseItem.setHorizontalTextPosition(JMenuItem.RIGHT);
    collapseItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                int cnt = node.getChildCount();
                Stack<DefaultMutableTreeNode> s = new Stack<DefaultMutableTreeNode>();
                if (cnt > 0) {
                    DefaultMutableTreeNode child;
                    for (int i = 0; i < cnt; i++) {
                        child = (DefaultMutableTreeNode) node.getChildAt(i);
                        s.push(child);
                    }
                }
                while (!s.isEmpty())
                    tree.collapsePath(new TreePath(s.pop().getPath()));
            } catch (Exception ee) {
            }
        }
    });
    return popup;
}

From source file:cn.ctyun.amazonaws.services.s3.transfer.TransferManager.java

/**
 * Downloads all objects in the virtual directory designated by the
 * keyPrefix given to the destination directory given. All virtual
 * subdirectories will be downloaded recursively.
 *
 * @param bucketName/*www .  j ava  2  s  .c  o  m*/
 *            The bucket containing the virtual directory
 * @param keyPrefix
 *            The key prefix for the virtual directory, or null for the
 *            entire bucket. All subdirectories will be downloaded
 *            recursively.
 * @param destinationDirectory
 *            The directory to place downloaded files. Subdirectories will
 *            be created as necessary.
 */
public MultipleFileDownload downloadDirectory(String bucketName, String keyPrefix, File destinationDirectory) {

    if (keyPrefix == null)
        keyPrefix = "";

    List<S3ObjectSummary> objectSummaries = new LinkedList<S3ObjectSummary>();
    Stack<String> commonPrefixes = new Stack<String>();
    commonPrefixes.add(keyPrefix);
    long totalSize = 0;

    // Recurse all virtual subdirectories to get a list of object summaries.
    // This is a depth-first search.
    do {
        String prefix = commonPrefixes.pop();
        ObjectListing listObjectsResponse = null;

        do {
            if (listObjectsResponse == null) {
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName)
                        .withDelimiter(DEFAULT_DELIMITER).withPrefix(prefix);
                listObjectsResponse = s3.listObjects(listObjectsRequest);
            } else {
                listObjectsResponse = s3.listNextBatchOfObjects(listObjectsResponse);
            }

            for (S3ObjectSummary s : listObjectsResponse.getObjectSummaries()) {
                // Skip any files that are also virtual directories, since
                // we can't save both a directory and a file of the same
                // name.
                if (!s.getKey().equals(prefix)
                        && !listObjectsResponse.getCommonPrefixes().contains(s.getKey() + DEFAULT_DELIMITER)) {
                    objectSummaries.add(s);
                    totalSize += s.getSize();
                } else {
                    log.debug("Skipping download for object " + s.getKey()
                            + " since it is also a virtual directory");
                }
            }

            commonPrefixes.addAll(listObjectsResponse.getCommonPrefixes());
        } while (listObjectsResponse.isTruncated());
    } while (!commonPrefixes.isEmpty());

    TransferProgressImpl transferProgress = new TransferProgressImpl();
    transferProgress.setTotalBytesToTransfer(totalSize);
    ProgressListener listener = new TransferProgressUpdatingListener(transferProgress);

    List<DownloadImpl> downloads = new ArrayList<DownloadImpl>();

    String description = "Downloading from " + bucketName + "/" + keyPrefix;
    final MultipleFileDownloadImpl multipleFileDownload = new MultipleFileDownloadImpl(description,
            transferProgress, new ProgressListenerChain(listener), keyPrefix, bucketName, downloads);
    multipleFileDownload.setMonitor(new MultipleFileTransferMonitor(multipleFileDownload, downloads));

    final AllDownloadsQueuedLock allTransfersQueuedLock = new AllDownloadsQueuedLock();
    MultipleFileTransferStateChangeListener stateChangeListener = new MultipleFileTransferStateChangeListener(
            allTransfersQueuedLock, multipleFileDownload);

    for (S3ObjectSummary summary : objectSummaries) {
        // TODO: non-standard delimiters
        File f = new File(destinationDirectory, summary.getKey());
        File parentFile = f.getParentFile();
        if (!parentFile.exists() && !parentFile.mkdirs()) {
            throw new RuntimeException("Couldn't create parent directories for " + f.getAbsolutePath());
        }

        downloads.add((DownloadImpl) download(
                new GetObjectRequest(summary.getBucketName(), summary.getKey()).withProgressListener(listener),
                f, stateChangeListener));
    }

    if (downloads.isEmpty()) {
        multipleFileDownload.setState(TransferState.Completed);
        return multipleFileDownload;
    }

    // Notify all state changes waiting for the downloads to all be queued
    // to wake up and continue.
    synchronized (allTransfersQueuedLock) {
        allTransfersQueuedLock.allQueued = true;
        allTransfersQueuedLock.notifyAll();
    }

    return multipleFileDownload;
}