Example usage for java.util Stack pop

List of usage examples for java.util Stack pop

Introduction

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

Prototype

public synchronized E pop() 

Source Link

Document

Removes the object at the top of this stack and returns that object as the value of this function.

Usage

From source file:EditorPaneTest.java

public EditorPaneFrame() {
    setTitle("EditorPaneTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    final Stack<String> urlStack = new Stack<String>();
    final JEditorPane editorPane = new JEditorPane();
    final JTextField url = new JTextField(30);

    // set up hyperlink listener

    editorPane.setEditable(false);//from w  ww. j  a  v a2  s.  c o m
    editorPane.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent event) {
            if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                try {
                    // remember URL for back button
                    urlStack.push(event.getURL().toString());
                    // show URL in text field
                    url.setText(event.getURL().toString());
                    editorPane.setPage(event.getURL());
                } catch (IOException e) {
                    editorPane.setText("Exception: " + e);
                }
            }
        }
    });

    // set up checkbox for toggling edit mode

    final JCheckBox editable = new JCheckBox();
    editable.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            editorPane.setEditable(editable.isSelected());
        }
    });

    // set up load button for loading URL

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            try {
                // remember URL for back button
                urlStack.push(url.getText());
                editorPane.setPage(url.getText());
            } catch (IOException e) {
                editorPane.setText("Exception: " + e);
            }
        }
    };

    JButton loadButton = new JButton("Load");
    loadButton.addActionListener(listener);
    url.addActionListener(listener);

    // set up back button and button action

    JButton backButton = new JButton("Back");
    backButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (urlStack.size() <= 1)
                return;
            try {
                // get URL from back button
                urlStack.pop();
                // show URL in text field
                String urlString = urlStack.peek();
                url.setText(urlString);
                editorPane.setPage(urlString);
            } catch (IOException e) {
                editorPane.setText("Exception: " + e);
            }
        }
    });

    add(new JScrollPane(editorPane), BorderLayout.CENTER);

    // put all control components in a panel

    JPanel panel = new JPanel();
    panel.add(new JLabel("URL"));
    panel.add(url);
    panel.add(loadButton);
    panel.add(backButton);
    panel.add(new JLabel("Editable"));
    panel.add(editable);

    add(panel, BorderLayout.SOUTH);
}

From source file:de.uni.bremen.monty.moco.ast.ASTBuilder.java

@Override
public ASTNode visitListComprehension(ListComprehensionContext ctx) {
    Expression target = (Expression) visit(ctx.expression());
    Position pos = position(ctx.getStart());
    Stack<ResolvableIdentifier> identifiers = new Stack<>();
    Stack<Expression> sources = new Stack<>();
    Stack<Expression> filters = new Stack<>();
    ResolvableIdentifier type = convertResolvableIdentifier(ctx.type());
    tupleDeclarationFactory.checkTupleType(type);

    for (ListGeneratorContext genCtx : ctx.listGenerator()) {
        identifiers.push(new ResolvableIdentifier(getText(genCtx.Identifier())));
        sources.push((Expression) visit(genCtx.expression()));
        if (genCtx.listFilter() != null) {
            filters.push((Expression) visit(genCtx.listFilter().expression()));
        } else {/*from   www  .ja v  a2  s.  c o  m*/
            filters.push(null);
        }
    }

    // we start with the innermost block
    Block currentBlock = new Block(position(ctx.expression().getStart()));
    currentBlocks.push(currentBlock);
    currentGeneratorReturnType.push(type);
    currentBlock.addStatement(createYieldStatement(position(ctx.expression().getStart()), target));
    currentGeneratorReturnType.pop();
    for (int i = identifiers.size(); i > 0; i--) {
        Expression filter = filters.pop();
        Expression source = sources.pop();
        source = new MemberAccess(source.getPosition(), source, new FunctionCall(source.getPosition(),
                new ResolvableIdentifier("getIterator"), new ArrayList<Expression>()));
        ResolvableIdentifier ident = identifiers.pop();
        if (filter != null) {
            Position filterPos = filter.getPosition();
            Statement ifStm = new ConditionalStatement(filterPos, filter, currentBlock, new Block(filterPos));
            currentBlocks.pop();
            currentBlock = new Block(filterPos);
            currentBlocks.push(currentBlock);
            currentBlock.addStatement(ifStm);
        }
        currentBlocks.pop();
        Block forBlock = new Block(source.getPosition()); // the block containing the for stm
        currentBlocks.push(forBlock);
        Statement forStm = (Statement) createForLoop(source.getPosition(), ident, source, currentBlock);
        currentBlock = forBlock;
        currentBlock.addStatement(forStm);
    }
    currentBlocks.pop();
    // the current block is now the outermost for loop
    ClassDeclaration generator = (ClassDeclaration) createGenerator(pos,
            TmpIdentifierFactory.getUniqueIdentifier(), type,
            // new ResolvableIdentifier("Object"),
            new ArrayList<VariableDeclaration>(), new ArrayList<VariableDeclaration>(),
            new ArrayList<Expression>(), currentBlock);
    currentBlocks.peek().addDeclaration(generator);
    // return new instance
    return new WrappedFunctionCall(pos, new FunctionCall(pos,
            ResolvableIdentifier.convert(generator.getIdentifier()), new ArrayList<Expression>()));
}

From source file:fsi_admin.JFsiTareas.java

public synchronized void respaldarServidor(Calendar fecha, PrintWriter out) {
    try {/*w w  w . j  a v a2 s.c o m*/
        String path = "/usr/local/forseti/log/RESP-FORSETI_ADMIN-"
                + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".log";
        FileWriter filewri = new FileWriter(path, true);
        PrintWriter pw = new PrintWriter(filewri);

        if (out != null) {
            out.println("----------------------------------------------------------------------------<br>");
            out.println("RESPALDANDO LA BASE DE DATOS PRINCIPAL: FORSETI_ADMIN Y ARCHIVOS "
                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>");
            out.println("----------------------------------------------------------------------------<br>");
            out.flush();
        }
        pw.println("----------------------------------------------------------------------------");
        pw.println("RESPALDANDO LA BASE DE DATOS PRINCIPAL: FORSETI_ADMIN Y ARCHIVOS "
                + 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;
        }

        if (tomcat.equals("NC")) {
            if (out != null) {
                out.println(
                        "PRECAUCION: La variable TOMCAT (ruta de instalacin de tomcat) no est definida... No se puede generar");
                out.flush();
            }
            pw.println(
                    "PRECAUCION: La variable TOMCAT (ruta de instalacin de tomcat) no est definida... No se puede generar");
            pw.flush();
            return;
        }

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

        String ERROR = "", RES = "";

        try {
            JAdmVariablesSet var = new JAdmVariablesSet(null);
            var.ConCat(true);
            var.m_Where = "ID_Variable = 'VERSION'";
            var.Open();
            String vers = var.getAbsRow(0).getVAlfanumerico();

            File dir = new File(respaldos, "FORSETI_ADMIN-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm"));
            dir.mkdir();
            // Primero Agrega el archivo de version para este servidor
            File version = new File(respaldos + "/" + "FORSETI_ADMIN-"
                    + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "/forseti.version");
            FileWriter fw = new FileWriter(version);
            fw.write(vers);
            fw.close();
            File diremp = new File(respaldos + "/FORSETI_ADMIN-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm"),
                    "emp");
            diremp.mkdir();

            //System.out.println(dir.getAbsolutePath());
            String CONTENT = "";
            CONTENT += "rsync -av --stats /usr/local/forseti/act " + respaldos + "/FORSETI_ADMIN-"
                    + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "\n";
            CONTENT += "rsync -av --stats /usr/local/forseti/bin " + respaldos + "/FORSETI_ADMIN-"
                    + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "\n";
            CONTENT += "rsync -av --stats /usr/local/forseti/log " + respaldos + "/FORSETI_ADMIN-"
                    + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "\n";
            CONTENT += "rsync -av --stats /usr/local/forseti/pac " + respaldos + "/FORSETI_ADMIN-"
                    + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "\n";
            CONTENT += "rsync -av --stats /usr/local/forseti/rec " + respaldos + "/FORSETI_ADMIN-"
                    + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "\n";
            CONTENT += "rsync -av --stats " + tomcat + "/webapps/ROOT.war " + respaldos + "/FORSETI_ADMIN-"
                    + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "\n";

            sc.setContent(CONTENT);
            System.out.println(CONTENT);
            RES = sc.executeCommand();
            ERROR += sc.getError();
            if (!ERROR.equals("")) {
                if (out != null) {
                    pw.println("ERROR al respaldar en RSYNC: " + ERROR + "<br>");
                    pw.flush();
                }
                pw.println("ERROR al respaldar en RSYNC: " + ERROR);
                pw.flush();
            } else {
                if (out != null) {
                    out.println("El respaldo de los archivos se genero con xito en: " + respaldos
                            + "/FORSETI_ADMIN-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + "<br>");
                    out.flush();
                }
                pw.println("El respaldo de los archivos se genero con xito en: " + respaldos
                        + "/FORSETI_ADMIN-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm"));
                pw.flush();
            }

            if (out != null) {
                out.println("FINALIZANDO RESPALDO DE ARCHIVOS FORSETI_ADMIN: "
                        + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>");
                out.flush();
            }
            pw.println("FINALIZANDO RESPALDO DE ARCHIVOS FORSETI_ADMIN: "
                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
            pw.flush();

            RES = "";
            ERROR = "";
            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") + "/FORSETI_ADMIN-"
                    + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".dump FORSETI_ADMIN";
            sc.setContent(CONTENT);
            //System.out.println(CONTENT);
            RES = sc.executeCommand();
            ERROR += sc.getError();
            //Ahora genera el Archivo Base64
            if (!ERROR.equals("")) {
                //System.out.println(ERROR);
                if (out != null) {
                    out.println("ERROR al crear el respaldo de la base de datos principal: " + ERROR + "<br>");
                    out.flush();
                }
                pw.println("ERROR al crear el respaldo de la base de datos principal: " + ERROR);
                pw.flush();
            } else {
                if (RES.equals("")) {
                    if (out != null) {
                        out.println(
                                "El respaldo de la base de datos principal se gener con xito como archivo .dump dentro de este directurio");
                        out.flush();
                    }
                    pw.println(
                            "El respaldo de la base de datos principal se gener con xito como archivo .dump dentro de este directurio");
                    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: FORSETI_ADMIN "
                        + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>");
                out.flush();
            }
            pw.println("FINALIZANDO RESPALDO DE LA BASE DE DATOS: FORSETI_ADMIN "
                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
            pw.flush();
        } catch (Throwable e) {
            if (out != null) {
                out.println("ERROR Throwable:<br>");
                e.printStackTrace(out);
                out.flush();
            }
            pw.println("ERROR Throwable:");
            e.printStackTrace(pw);
            pw.flush();
        }

        JBDSSet set = new JBDSSet(null);
        set.ConCat(true);
        set.m_OrderBy = "ID_BD ASC";
        set.Open();

        for (int i = 0; i < set.getNumRows(); i++) {
            if (!set.getAbsRow(i).getSU().equals("3")) // La base de datos esta corrupta, se debe eliminar
            {
                out.println("La siguiente base de datos esta corrupta y se debe eliminar: "
                        + set.getAbsRow(i).getNombre() + "<br>");
                out.flush();
                pw.println("La siguiente base de datos esta corrupta y se debe eliminar: "
                        + set.getAbsRow(i).getNombre());
                pw.flush();
                continue;
            } else
                respaldarEmpresa(set, i, fecha, out, pw);
        }
        if (out != null) {
            out.println(
                    "Generando el archivo zip... Esto puede tardar demasiado tiempo, hay que ser pacientes<br>");
            out.flush();
        }
        pw.println("Generando el archivo zip...");
        pw.flush();
        JZipUnZipUtil azip = new JZipUnZipUtil();
        azip.zipFolder(respaldos + "/FORSETI_ADMIN-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm"),
                respaldos + "/FORSETI_ADMIN-" + 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 + "/FORSETI_ADMIN-" + 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();
            }
        }
        if (out != null) {
            out.println("--------------- FIN DEL RESPALDO " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")
                    + " ---------------<br>");
            out.flush();
        }
        pw.println("--------------- FIN DEL RESPALDO " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")
                + " ---------------");
        pw.flush();
        pw.close();

    } catch (IOException e) {
        if (out != null) {
            out.println("OCURRIERON ERRORES DE IOException<br>");
            e.printStackTrace(out);
            out.flush();
        }
        System.out.println("OCURRIERON ERRORES DE IOException<br>");
        e.printStackTrace(System.out);

    } catch (Exception e) {
        if (out != null) {
            out.println("OCURRIERON ERRORES DE Exception<br>");
            e.printStackTrace(out);
            out.flush();
        }
        System.out.println("OCURRIERON ERRORES DE Exception<br>");
        e.printStackTrace(System.out);

    }

}

From source file:com.netcrest.pado.tools.pado.PadoShell.java

/**
 * Returns the full path. Supports '..'.
 * //from  w ww  .  j ava2  s  . c om
 * @param newPath
 *            The new path to be evaluated
 * @param relativePath
 *            The current path
 * @return Returns null if the new path is invalid.
 */
public String getFullPath(String newPath, String relativePath) {
    if (newPath == null) {
        return null;
    }
    if (newPath.startsWith("/")) {
        return newPath;
    }

    if (relativePath == null) {
        relativePath = "/";
    }

    String[] split = relativePath.split("/");
    Stack<String> pathStack = new Stack<String>();
    for (int i = 0; i < split.length; i++) {
        if (split[i].length() == 0) {
            continue;
        }
        pathStack.add(split[i]);
    }
    split = newPath.split("/");
    boolean invalidPath = false;
    for (int i = 0; i < split.length; i++) {
        if (split[i].length() == 0) {
            continue;
        }
        String dirName = split[i];
        if (dirName.equals("..")) {
            if (pathStack.size() == 0) {
                invalidPath = true;
                break;
            }
            pathStack.pop();
        } else if (dirName.equals(".")) {
            continue;
        } else {
            pathStack.add(dirName);
        }
    }

    if (invalidPath) {
        return null;
    }

    String fullPath = "";
    while (pathStack.size() > 0) {
        fullPath = "/" + pathStack.pop() + fullPath;
    }
    if (fullPath.length() == 0) {
        fullPath = "/";
    }
    return fullPath;
}

From source file:org.apache.fop.layoutmgr.BlockStackingLayoutManager.java

/** {@inheritDoc} */
@Override//  ww  w . j  a  va  2 s .com
public List getNextKnuthElements(LayoutContext context, int alignment, Stack lmStack, Position restartPosition,
        LayoutManager restartAtLM) {
    referenceIPD = context.getRefIPD();
    updateContentAreaIPDwithOverconstrainedAdjust();

    boolean isRestart = (lmStack != null);
    boolean emptyStack = (!isRestart || lmStack.isEmpty());
    List<ListElement> contentList = new LinkedList<ListElement>();
    List<ListElement> elements = new LinkedList<ListElement>();

    if (!breakBeforeServed(context, elements)) {
        // if this FO has break-before specified, and it
        // has not yet been processed, return now
        return elements;
    }

    addFirstVisibleMarks(elements, context, alignment);

    //Used to indicate a special break-after case when all content has already been generated.
    BreakElement forcedBreakAfterLast = null;

    LayoutContext childLC;
    List<ListElement> childElements;
    LayoutManager currentChildLM;
    if (isRestart) {
        if (emptyStack) {
            assert restartAtLM != null && restartAtLM.getParent() == this;
            currentChildLM = restartAtLM;
        } else {
            currentChildLM = (LayoutManager) lmStack.pop();
        }
        setCurrentChildLM(currentChildLM);
    } else {
        currentChildLM = getChildLM();
    }

    while (currentChildLM != null) {

        childLC = makeChildLayoutContext(context);

        if (!isRestart || emptyStack) {
            if (isRestart) {
                currentChildLM.reset(); // TODO won't work with forced breaks
            }

            childElements = getNextChildElements(currentChildLM, context, childLC, alignment, null, null, null);
        } else {
            // restart && non-empty LM stack
            childElements = getNextChildElements(currentChildLM, context, childLC, alignment, lmStack,
                    restartPosition, restartAtLM);
            // once encountered, irrelevant for following child LMs
            emptyStack = true;
        }

        if (contentList.isEmpty()) {
            // propagate keep-with-previous up from the first child
            context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending());
        }

        // handle non-empty child
        if (childElements != null && !childElements.isEmpty()) {
            if (!contentList.isEmpty() && !ElementListUtils.startsWithForcedBreak(childElements)) {
                // there is a block handled by prevLM before the one
                // handled by curLM, and the one handled
                // by the current LM does not begin with a break
                addInBetweenBreak(contentList, context, childLC);
            }
            if (childElements.size() == 1 && ElementListUtils.startsWithForcedBreak(childElements)) {
                // a descendant of this block has break-before
                if (currentChildLM.isFinished() && !hasNextChildLM()) {
                    // if there is no more content, make sure pending
                    // marks are cleared
                    forcedBreakAfterLast = (BreakElement) childElements.get(0);
                    context.clearPendingMarks();
                    // break without adding the child elements
                    break;
                }
                if (contentList.isEmpty()) {
                    // empty fo:block: zero-length box makes sure the IDs and/or markers
                    // are registered and borders/padding are painted.
                    elements.add(makeAuxiliaryZeroWidthBox());
                }
                // add the forced break
                contentList.addAll(childElements);
                // wrap position and return
                wrapPositionElements(contentList, elements);
                return elements;
            } else {
                // add all accumulated child elements
                contentList.addAll(childElements);
                if (ElementListUtils.endsWithForcedBreak(childElements)) {
                    // a descendant of this block has break-after
                    if (currentChildLM.isFinished() && !hasNextChildLM()) {
                        // if there is no more content, make sure any
                        // pending marks are cleared
                        forcedBreakAfterLast = (BreakElement) ListUtil.removeLast(contentList);
                        context.clearPendingMarks();
                        break;
                    }
                    //wrap positions and return
                    wrapPositionElements(contentList, elements);
                    return elements;
                }
            }
            context.updateKeepWithNextPending(childLC.getKeepWithNextPending());
        }
        currentChildLM = getChildLM();
    }

    if (contentList.isEmpty()) {
        if (forcedBreakAfterLast == null) {
            // empty fo:block: zero-length box makes sure the IDs and/or markers
            // are registered.
            elements.add(makeAuxiliaryZeroWidthBox());
        }
    } else {
        // wrap child positions
        wrapPositionElements(contentList, elements);
    }

    addLastVisibleMarks(elements, context, alignment);

    if (forcedBreakAfterLast == null) {
        addKnuthElementsForBreakAfter(elements, context);
    } else {
        forcedBreakAfterLast.clearPendingMarks();
        elements.add(forcedBreakAfterLast);
    }

    context.updateKeepWithNextPending(getKeepWithNext());
    setFinished(true);
    return elements;
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Create the MMLtext using the invert index and the cortex and corcode
 * @param cortex the plain text version/*from   w w  w.j  a v  a  2 s .  c o m*/
 * @param ccDflt the default STIL markup for that plain text
 * @param ccPages the page-breaks or null
 * @param layer the number of the layer to build
 */
void createMML(ScratchVersion cortex, ScratchVersion ccDflt, ScratchVersion ccPages, int layer) {
    String text = cortex.getLayerString(layer);
    mml = new StringBuilder();
    String stilDflt = ccDflt.getLayerString(layer);
    String stilPages = (ccPages == null) ? null : ccPages.getLayerString(layer);
    JSONObject mDflt = (JSONObject) JSONValue.parse(stilDflt);
    if (stilPages != null) {
        JSONObject mPages = (JSONObject) JSONValue.parse(stilPages);
        mDflt = mergeCorcodes(mDflt, mPages);
    }
    JSONArray ranges = (JSONArray) mDflt.get("ranges");
    Stack<EndTag> stack = new Stack<EndTag>();
    int offset = 0;
    for (int i = 0; i < ranges.size(); i++) {
        JSONObject r = (JSONObject) ranges.get(i);
        Number len = (Number) r.get("len");
        Number relOff = (Number) r.get("reloff");
        String name = (String) r.get("name");
        if (invertIndex.containsKey(name)) {
            JSONObject def = invertIndex.get(name);
            String startTag = mmlStartTag(def, offset);
            String endTag = mmlEndTag(def, len.intValue());
            int start = offset + relOff.intValue();
            // 1. insert pending end-tags and text before current range
            int pos = offset;
            while (!stack.isEmpty() && stack.peek().offset <= start) {
                // check for NLs here if obj is of type lineformat
                int tagEnd = stack.peek().offset;
                boolean isLF = isLineFormat(stack);
                for (int j = pos; j < tagEnd; j++) {
                    char c = text.charAt(j);
                    if (c != '\n') {
                        if (globals.containsKey(c))
                            mml.append(globals.get(c));
                        else
                            mml.append(c);
                    } else if (isLF && j < tagEnd - 1)
                        startPreLine(stack);
                    else
                        mml.append(c);
                }
                pos = tagEnd;
                // newlines are not permitted before tag end
                while (mml.length() > 0 && mml.charAt(mml.length() - 1) == '\n')
                    mml.setLength(mml.length() - 1);
                mml.append(stack.pop().text);
            }
            // 2. insert intervening text
            boolean inPre = isLineFormat(stack);
            int nNLs = countTerminalNLs(mml);
            for (int j = pos; j < start; j++) {
                char c = text.charAt(j);
                if (c == '\n') {
                    if (mml.length() == 0 || nNLs == 0)
                        mml.append(c);
                    if (nNLs > 0)
                        nNLs--;
                    if (inPre)
                        startPreLine(stack);
                } else {
                    mml.append(c);
                    nNLs = 0;
                }
            }
            // 3. insert new start tag
            normaliseNewlines(startTag);
            mml.append(startTag);
            stack.push(new EndTag(start + len.intValue(), endTag, def));
        } else
            System.out.println("Ignoring tag " + name);
        offset += relOff.intValue();
    }
    //empty stack
    int pos = offset;
    while (!stack.isEmpty()) {
        int tagEnd = stack.peek().offset;
        boolean inPre = isLineFormat(stack);
        for (int j = pos; j < tagEnd; j++) {
            char c = text.charAt(j);
            mml.append(c);
            if (c == '\n' && inPre && j < tagEnd - 1)
                startPreLine(stack);
        }
        pos = tagEnd;
        // newlines are not permitted before tag end
        while (mml.length() > 0 && mml.charAt(mml.length() - 1) == '\n')
            mml.setLength(mml.length() - 1);
        mml.append(stack.pop().text);
    }
}

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 . java 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:org.apache.jackrabbit.core.nodetype.NodeTypeRegistry.java

static void checkForCircularNodeAutoCreation(EffectiveNodeType childNodeENT, Stack<Name> definingParentNTs,
        EffectiveNodeTypeCache anEntCache, Map<Name, QNodeTypeDefinition> ntDefCache)
        throws InvalidNodeTypeDefException {
    // check for circularity through default node types of auto-created child nodes
    // (node type 'a' defines auto-created child node with default node type 'a')
    Name[] childNodeNTs = childNodeENT.getAllNodeTypes();
    for (Name nt : childNodeNTs) {
        int pos = definingParentNTs.lastIndexOf(nt);
        if (pos >= 0) {
            StringBuilder buf = new StringBuilder();
            for (int j = 0; j < definingParentNTs.size(); j++) {
                if (j == pos) {
                    buf.append("--> ");
                }//  www  . j a  va 2  s .c  o m
                buf.append("node type ");
                buf.append(definingParentNTs.get(j));
                buf.append(" defines auto-created child node with default ");
            }
            buf.append("--> ");
            buf.append("node type ");
            buf.append(nt);
            throw new InvalidNodeTypeDefException("circular node auto-creation detected: " + buf.toString());
        }
    }

    QNodeDefinition[] nodeDefs = childNodeENT.getAutoCreateNodeDefs();
    for (QNodeDefinition nodeDef : nodeDefs) {
        Name dnt = nodeDef.getDefaultPrimaryType();
        Name definingNT = nodeDef.getDeclaringNodeType();
        try {
            if (dnt != null) {
                // check recursively
                definingParentNTs.push(definingNT);
                checkForCircularNodeAutoCreation(getEffectiveNodeType(dnt, anEntCache, ntDefCache),
                        definingParentNTs, anEntCache, ntDefCache);
                definingParentNTs.pop();
            }
        } catch (NoSuchNodeTypeException nsnte) {
            String msg = definingNT + " defines invalid default node type for child node " + nodeDef.getName();
            log.debug(msg);
            throw new InvalidNodeTypeDefException(msg, nsnte);
        }
    }
}

From source file:org.apache.tajo.engine.planner.rewrite.ProjectionPushDownRule.java

public LogicalNode visitJoin(Context context, LogicalPlan plan, LogicalPlan.QueryBlock block, JoinNode node,
        Stack<LogicalNode> stack) throws PlanningException {
    Context newContext = new Context(context);

    String joinQualReference = null;
    if (node.hasJoinQual()) {
        for (EvalNode eachQual : AlgebraicUtil.toConjunctiveNormalFormArray(node.getJoinQual())) {
            if (eachQual instanceof BinaryEval) {
                BinaryEval binaryQual = (BinaryEval) eachQual;

                for (int i = 0; i < 2; i++) {
                    EvalNode term = binaryQual.getChild(i);
                    pushDownIfComplexTermInJoinCondition(newContext, eachQual, term);
                }//from  w ww  .  j  a v a  2  s .  co m
            }
        }

        joinQualReference = newContext.addExpr(node.getJoinQual());
        newContext.addNecessaryReferences(node.getJoinQual());
    }

    String[] referenceNames = null;
    if (node.hasTargets()) {
        referenceNames = new String[node.getTargets().length];
        int i = 0;
        for (Iterator<Target> it = getFilteredTarget(node.getTargets(), context.requiredSet); it.hasNext();) {
            Target target = it.next();
            referenceNames[i++] = newContext.addExpr(target);
        }
    }

    stack.push(node);
    LogicalNode left = visit(newContext, plan, block, node.getLeftChild(), stack);
    LogicalNode right = visit(newContext, plan, block, node.getRightChild(), stack);
    stack.pop();

    Schema merged = SchemaUtil.merge(left.getOutSchema(), right.getOutSchema());

    node.setInSchema(merged);

    if (node.hasJoinQual()) {
        Target target = context.targetListMgr.getTarget(joinQualReference);
        if (newContext.targetListMgr.isEvaluated(joinQualReference)) {
            throw new PlanningException(
                    "Join condition must be evaluated in the proper Join Node: " + joinQualReference);
        } else {
            node.setJoinQual(target.getEvalTree());
            newContext.targetListMgr.markAsEvaluated(target);
        }
    }

    LinkedHashSet<Target> projectedTargets = Sets.newLinkedHashSet();
    for (Iterator<String> it = getFilteredReferences(context.targetListMgr.getNames(), context.requiredSet); it
            .hasNext();) {
        String referenceName = it.next();
        Target target = context.targetListMgr.getTarget(referenceName);

        if (context.targetListMgr.isEvaluated(referenceName)) {
            Target fieldReference = new Target(new FieldEval(target.getNamedColumn()));
            if (LogicalPlanner.checkIfBeEvaluatedAtJoin(block, fieldReference.getEvalTree(), node,
                    stack.peek().getType() != NodeType.JOIN)) {
                projectedTargets.add(fieldReference);
            }
        } else if (LogicalPlanner.checkIfBeEvaluatedAtJoin(block, target.getEvalTree(), node,
                stack.peek().getType() != NodeType.JOIN)) {
            projectedTargets.add(target);
            context.targetListMgr.markAsEvaluated(target);
        }
    }

    node.setTargets(projectedTargets.toArray(new Target[projectedTargets.size()]));
    LogicalPlanner.verifyProjectedFields(block, node);
    return node;
}