Example usage for java.util LinkedList getFirst

List of usage examples for java.util LinkedList getFirst

Introduction

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

Prototype

public E getFirst() 

Source Link

Document

Returns the first element in this list.

Usage

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private void getLineSpans(SpanManager sm, LinkedList<Span> lineSpans) {
    sm.manageList(lineSpans);//  ww w .  j a  v  a  2s  .  co  m

    int start = 0;
    int end;

    while ((end = sm.indexOf(lineSeparator, start)) != -1) {
        lineSpans.add(new Span(start, end).trimTrail(sm));
        start = end + lineSeparator.length();
    }
    lineSpans.add(new Span(start, sm.length()).trimTrail(sm));

    while (!lineSpans.isEmpty() && lineSpans.getFirst().length() == 0) {
        lineSpans.removeFirst();
    }
    while (!lineSpans.isEmpty() && lineSpans.getLast().length() == 0) {
        lineSpans.removeLast();
    }
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private Table buildTable(SpanManager sm, ContentElementParsingParameters cepp, LinkedList<Span> lineSpans) {

    Table result = new Table();
    int col = -1;
    int row = 0;//from w  w  w .  jav a 2 s.  c om
    int subTables = 0;
    LinkedList<Span> tableDataSpans = new LinkedList<Span>();
    sm.manageList(tableDataSpans);

    if (calculateSrcSpans) {
        result.setSrcSpan(new SrcSpan(sm.getSrcPos(lineSpans.getFirst().getStart()), -1));
    }

    lineSpans.removeFirst();

    while (!lineSpans.isEmpty()) {
        Span s = lineSpans.removeFirst();

        int pos = s.nonWSCharPos(sm);
        char c0 = s.charAt(pos, sm);
        char c1 = s.charAt(pos + 1, sm);

        if (subTables == 0 && (c0 == '!' || c0 == '|')) {
            if (!tableDataSpans.isEmpty()) {
                lineSpans.addFirst(s);

                SrcSpan ei = null;
                if (calculateSrcSpans) {
                    ei = new SrcSpan(sm.getSrcPos(tableDataSpans.getFirst().getStart() - 1) + 1, -1);
                }

                TableElement te = new TableElement(parseSections(sm, cepp, tableDataSpans), row, col);
                te.setSrcSpan(ei);
                result.addTableElement(te);
                lineSpans.removeFirst();
            }

            col++;
            if (c1 == '-') {
                row++;
                col = -1;
                continue;
            } else if (c0 == '|' && c1 == '}') {
                sm.removeManagedList(tableDataSpans);

                if (calculateSrcSpans) {
                    result.getSrcSpan().setEnd(sm.getSrcPos(s.getEnd()));
                }

                return result;
            } else if (c0 == '|' && c1 == '+') {
                result.setTitleElement(
                        parseContentElement(sm, cepp, new Span(s.getStart() + pos + 2, s.getEnd()).trim(sm)));
                continue;
            } else {
                int multipleCols;
                if ((multipleCols = sm.indexOf("||", s.getStart() + pos + 1, s.getEnd())) != -1) {
                    lineSpans.addFirst(new Span(multipleCols + 1, s.getEnd()));
                    s.setEnd(multipleCols);
                }

                int optionTagPos = sm.indexOf("|", s.getStart() + pos + 1, s.getEnd());

                if (optionTagPos != -1) {
                    s.setStart(optionTagPos + 1).trim(sm);
                } else {
                    s.adjustStart(pos + 1).trim(sm);
                }
            }
        } else if (c0 == '|' && c1 == '}') {
            subTables--;
        } else if (c0 == '{' && c1 == '|') {
            subTables++;
        }

        tableDataSpans.addLast(s);
    }

    if (tableDataSpans.size() != 0) {

        SrcSpan ei = null;
        if (calculateSrcSpans) {
            ei = new SrcSpan(sm.getSrcPos(tableDataSpans.getFirst().getStart() - 1) + 1, -1);
        }

        TableElement te = new TableElement(parseSections(sm, cepp, tableDataSpans), row, col);
        te.setSrcSpan(ei);

        result.addTableElement(te);
    }

    sm.removeManagedList(tableDataSpans);

    if (calculateSrcSpans) {
        result.getSrcSpan().setEnd(-1);
    }

    return result;
}

From source file:hr.fer.spocc.regex.AbstractRegularExpression.java

protected RegularExpression<T> createParseTree(List<RegularExpressionElement> elements) {

    //      System.out.println(">>> Parsing regexp: "+elements);

    /**/*w  ww . j a  v  a2  s.  c  o m*/
     * Stack which contains parts of regular expression 
     * which are not yet used
     * by the operator. In addition, <code>null</code> values
     * can be pushed onto this stack to indicate that 
     * the symbols to the right are grouped by the parenthesis.
     * 
     */
    LinkedList<RegularExpression<T>> symbolStack = new LinkedList<RegularExpression<T>>();

    /**
     * Operator stack
     */
    LinkedList<RegularExpressionOperator> opStack = new LinkedList<RegularExpressionOperator>();

    boolean sentinelParentheses = false;

    //      if (this.elements.get(0).getElementType() 
    //            != RegularExpressionElementType.LEFT_PARENTHESIS
    //         || this.elements.get(elements.size()-1).getElementType()
    //         != RegularExpressionElementType.RIGHT_PARENTHESIS) {
    sentinelParentheses = true;
    symbolStack.push(null);
    opStack.push(null);
    //      }

    int ind = -1;

    Iterator<RegularExpressionElement> iter = elements.iterator();
    while (iter.hasNext() || sentinelParentheses) {
        ++ind;
        RegularExpressionElement e;
        if (iter.hasNext()) {
            e = iter.next();
        } else { // osiguraj dodatnu iteraciju za umjetnu zadnju )
            e = RegularExpressionElements.RIGHT_PARENTHESIS;
            sentinelParentheses = false;
        }

        switch (e.getElementType()) {
        case SYMBOL:
            symbolStack.push(createTrivial(elements.subList(ind, ind + 1)));
            break;
        default:
            RegularExpressionOperator curOp = (e.getElementType() == RegularExpressionElementType.OPERATOR
                    ? (RegularExpressionOperator) e
                    : null);

            int priority = (curOp != null ? curOp.getPriority() : -1);

            if (e.getElementType() != RegularExpressionElementType.LEFT_PARENTHESIS) {

                //               System.out.println("Pre-while symbolStack: "+symbolStack);

                while (!opStack.isEmpty() && opStack.getFirst() != null
                        && opStack.getFirst().getPriority() >= priority && symbolStack.getFirst() != null) {

                    RegularExpressionOperator op = opStack.pop();
                    int arity = op.getArity();
                    int elementCount = 0;

                    //                  System.out.println("POP: "+op);

                    @SuppressWarnings("unchecked")
                    RegularExpression<T>[] operands = new RegularExpression[arity];
                    for (int i = arity - 1; i >= 0; --i) {
                        if (symbolStack.isEmpty()) {
                            throw new IllegalArgumentException("Missing ( after");
                        } else if (symbolStack.getFirst() == null) {
                            throw new IllegalArgumentException("Missing operand #" + (arity - i)
                                    + " for the operator " + op + " before index " + ind);
                        }
                        operands[i] = symbolStack.pop();
                        elementCount += operands[i].size();
                    }

                    RegularExpression<T> regex = createComposite(elements.subList(ind - elementCount - 1, ind),
                            op, operands);

                    //                  System.err.println(regex);
                    //                  System.err.println(regex.getSubexpression(0));

                    symbolStack.push(regex);

                    //                  System.out.println("Group: "+
                    //                        ArrayToStringUtils.toString(operands, "\n"));
                    //                  System.out.println("End group");
                    //                  System.out.println("Evaluated [" + (ind-elementCount-1)
                    //                        + ", " + ind + "): "+regex);
                    //                  System.out.println("Symbol stack: "+symbolStack);
                    //                  System.out.println("Op stack: "+opStack);
                    //                  System.out.println("---");

                }
            }

            if (curOp != null) {
                opStack.push(curOp);
            } else {
                switch (e.getElementType()) {
                case LEFT_PARENTHESIS:
                    symbolStack.push(null);
                    opStack.push(null);
                    break;
                default: // ako je )
                    Validate.isTrue(symbolStack.size() >= 2,
                            "Exactly one expression is expected " + "inside parentheses before index " + ind);

                    // pop left bracket (null) from the operator stack
                    Object nullValue = opStack.pop();
                    Validate.isTrue(nullValue == null);

                    // pop left bracket (null) from the symbol stack
                    RegularExpression<T> regex = symbolStack.pop();
                    nullValue = symbolStack.pop();

                    // check if left bracket was removed indeed
                    //                  Validate.isTrue(nullValue == null, 
                    //                        "Expected ( at index " + (ind-regex.size()-1));

                    // expand the expression if parentheses are not sentinel
                    if (sentinelParentheses) { // XXX neki drugi flag bolje
                        //                     System.out.print("Expand [" 
                        //                           + (ind - regex.size() - 1) + ", "
                        //                           + (ind + 1) + "]: ");
                        //                     System.out.println("[regex size = "+regex.size()
                        //                           + "]");
                        regex = createExpanded(regex, elements.subList(ind - regex.size() - 1, ind + 1));

                        //                     System.out.println(" -> "+regex);
                    }

                    // and put back the expression inside parentheses
                    symbolStack.push(regex);
                }
            }

        } // end of switch

        //         System.out.println("----- " + ind + " ----");
        //         System.out.println("Symbol stack: "+symbolStack);
        //         System.out.println("Op stack: "+opStack);
    }

    //Validate.isTrue(symbolStack.size() == 1);
    //Validate.isTrue(opStack.isEmpty());

    return symbolStack.pop();
}

From source file:org.hyperic.hq.measurement.server.session.AvailabilityManagerImpl.java

private PageList<HighLowMetricValue> getPageList(List<AvailabilityDataRLE> availInfo, long begin, long end,
        long interval, boolean prependUnknowns) {
    PageList<HighLowMetricValue> rtn = new PageList<HighLowMetricValue>();
    for (Iterator<AvailabilityDataRLE> it = availInfo.iterator(); it.hasNext();) {
        AvailabilityDataRLE rle = it.next();
        long availStartime = rle.getStartime();
        long availEndtime = rle.getEndtime();
        //skip measurements that are before first time slot
        if (availEndtime < begin) {
            continue;
        }/*from  w w w .j a v  a 2 s . c  o m*/
        LinkedList<AvailabilityDataRLE> queue = new LinkedList<AvailabilityDataRLE>();
        queue.add(rle);
        int i = 0;
        for (long curr = begin; curr <= end; curr += interval) {
            long next = curr + interval;
            next = (next > end) ? end : next;
            long endtime = ((AvailabilityDataRLE) queue.getFirst()).getEndtime();
            //while next time slot is after measurement time range
            while (next > endtime) {
                // it should not be the case that there are no more
                // avails in the array, but we need to handle it
                if (it.hasNext()) {
                    AvailabilityDataRLE tmp = (AvailabilityDataRLE) it.next();
                    queue.addFirst(tmp);
                    endtime = tmp.getEndtime();
                } else {
                    endtime = availEndtime;
                    int measId = rle.getMeasurement().getId().intValue();
                    String msg = "Measurement, " + measId + ", for interval " + begin + " - " + end
                            + " did not return a value for range " + curr + " - " + (curr + interval);
                    log.warn(msg);
                }
            }
            endtime = availEndtime;
            while (curr > endtime) {
                queue.removeLast();
                // this should not happen unless the above !it.hasNext()
                // else condition is true
                if (queue.size() == 0) {
                    rle = new AvailabilityDataRLE(rle.getMeasurement(), rle.getEndtime(), next, AVAIL_UNKNOWN);
                    queue.addLast(rle);
                }
                rle = (AvailabilityDataRLE) queue.getLast();
                availStartime = rle.getStartime();
                availEndtime = rle.getEndtime();
                endtime = availEndtime;
            }
            HighLowMetricValue val;
            if (curr >= availStartime) {
                val = getMetricValue(queue, curr);
            } else if (prependUnknowns) {
                val = new HighLowMetricValue(AVAIL_UNKNOWN, curr);
                val.incrementCount();
            } else {
                i++;
                continue;
            }
            if (rtn.size() <= i) {
                rtn.add(round(val));
            } else {
                updateMetricValue(val, (HighLowMetricValue) rtn.get(i));
            }
            i++;
        }
    }
    if (rtn.size() == 0) {
        rtn.addAll(getDefaultHistoricalAvail(end));
    }
    return rtn;
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private Paragraph buildParagraph(SpanManager sm, ContentElementParsingParameters cepp,
        LinkedList<Span> lineSpans, lineType paragraphType) {

    LinkedList<Span> paragraphSpans = new LinkedList<Span>();
    Paragraph result = new Paragraph();
    Span s = lineSpans.removeFirst();//from  ww  w  .  j  av a  2s. c  o m
    paragraphSpans.add(s);

    switch (paragraphType) {
    case PARAGRAPH:
        result.setType(Paragraph.type.NORMAL);
        while (!lineSpans.isEmpty()) {
            if (paragraphType != getLineType(sm, lineSpans.getFirst())) {
                break;
            }
            paragraphSpans.add(lineSpans.removeFirst());
        }
        break;

    case PARAGRAPH_BOXED:
        result.setType(Paragraph.type.BOXED);
        while (!lineSpans.isEmpty()) {
            lineType lt = getLineType(sm, lineSpans.getFirst());
            if (paragraphType != lt && lineType.EMPTYLINE != lt) {
                break;
            }
            paragraphSpans.add(lineSpans.removeFirst());
        }
        break;

    case PARAGRAPH_INDENTED:
        result.setType(Paragraph.type.INDENTED);
        s.trim(sm.setCharAt(s.getStart(), ' '));
        break;

    default:
        return null;
    }

    parseContentElement(sm, cepp, paragraphSpans, result);

    return result;
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * This method determines whether the global presence server needs to be started
 * // w  w  w  .  ja v a  2  s.  c o  m
 */
private boolean configPresenceServer() {
    presenceServerEnabled = SystemSettings.getBooleanSetting("Presence Server");
    if (presenceServerEnabled) {
        Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
        String psName = platform.getProperty(SettingConstants.PRESENCE_SERVER_FSM);
        if (presenceServerFile == null) {
            presenceServerFile = psName;
        } else if (presenceServerFile.equals(psName)) {
            return true;
        } else {
            if (stacks != null)
                stacks.shutdownPresenceServer();
            presenceServerFile = psName;
        }
        if (presenceServerFile != null) {
            File ps = new File(presenceServerFile);
            if (ps != null && ps.exists() && ps.canRead() && ps.isFile()) {
                TSParser tsp = new TSParser(false);
                try {
                    logger.info(PC2LogCategory.Parser, subCat,
                            "Parsing document " + presenceServerFile + " for PresenceServer processing.");
                    TSDocument psDoc = tsp.parse(presenceServerFile);
                    LinkedList<FSM> fsms = psDoc.getFsms();
                    if (fsms.size() == 1) {
                        FSM f = fsms.getFirst();
                        if (f.getModel() instanceof PresenceModel) {
                            PresenceModel model = (PresenceModel) f.getModel();
                            // Initialize the settings that can be overwritten from
                            // within the document 
                            setExtensions(fsms);
                            PresenceServer server = PresenceServer.getInstance(f, model.getElements());
                            if (server != null) {
                                Stacks.setPresenceServer(server);
                                server.init();
                                return true;
                            }
                        }

                    }
                } catch (PC2XMLException pe) {
                    String err = "\n** Parsing error in file \n    " + pe.getFileName() + " at line "
                            + pe.getLineNumber();
                    if (pe.getSystemId() != null) {
                        err += ", uri " + pe.getSystemId();
                    }
                    if (pe.getPublicId() != null) {
                        err += ", public " + pe.getPublicId();
                    }
                    err += "\n";

                    logger.fatal(PC2LogCategory.Parser, subCat, err, pe);
                } catch (SAXParseException spe) {
                    String err = "\n** Parsing error in file \n    " + presenceServerFile + " at line "
                            + spe.getLineNumber();
                    if (spe.getSystemId() != null) {
                        err += ", uri " + spe.getSystemId();
                    }
                    if (spe.getPublicId() != null) {
                        err += ", public " + spe.getPublicId();
                    }
                    err += "\n";

                    logger.fatal(PC2LogCategory.Parser, subCat, err, spe);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                //               if (ps == null) {
                //                  logger.fatal(PC2LogCategory.Parser, subCat,
                //                        "The platform configuration file doesn't appear to have a " 
                //                        + "value for the \"Presence Server FSM\" setting.");
                //               }
                if (!ps.exists()) {
                    logger.fatal(PC2LogCategory.Parser, subCat, "The \"Presence Server FSM\" setting=[" + ps
                            + "] doesn't appear to define a valid path or file name.");
                }
                if (!ps.canRead()) {
                    logger.fatal(PC2LogCategory.Parser, subCat,
                            "The \"Presence Server FSM\" setting=[" + ps + "] can not be read by the system.");
                }
                if (!ps.isFile()) {
                    logger.fatal(PC2LogCategory.Parser, subCat, "The \"Presence Server FSM\" setting=[" + ps
                            + "] doesn't appear to define a file.");
                }
            }
        }
    }
    return false;
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.parser.TreePatternParserVisitorImplementation.java

/**
 * build the XAM representation in memory by gathering the nodes and the
 * edges return the in-memory tree representation of the XAM
 */// ww w. j ava2s  .  c o  m
public Object visit(ASTTreePatternSpec node, Object data) {
    defaultNamespace = new String("");
    NavigationTreePattern p = new NavigationTreePattern();
    LinkedList<NavigationTreePatternNode> nodes = new LinkedList<NavigationTreePatternNode>();
    boolean fromRoot = false;

    try {
        for (int i = 0; i < node.jjtGetNumChildren(); i++) {
            Object child = node.jjtGetChild(i);

            if (child instanceof ASTNSPEC) {
                //add all xam nodes to the in-memory tree structure x
                nodes = (LinkedList<NavigationTreePatternNode>) visit(((ASTNSPEC) child), data, nodes);
            } else if (child instanceof ASTROOT) {
                // the first node is the root
                fromRoot = true;
            } else if (child instanceof ASTDefaultNamespace) {
                ASTDefaultNamespace defaultNamespaceNode = (ASTDefaultNamespace) child;
                ASTContent defaultNamespace = (ASTContent) defaultNamespaceNode.jjtGetChild(0);
                this.defaultNamespace = removeQuotes(defaultNamespace.getInfo());
            } else if (child instanceof ASTOrdered) {
                // the first node is the root
                p.setOrdered(true);
            } else if (child instanceof ASTEdgeSpec) {
                //add all xam edges to the in-memory tree structure x
                nodes = (LinkedList<NavigationTreePatternNode>) visit(((ASTEdgeSpec) child), data, nodes);
            } else
                return null;//todo: maybe throw an exception instead
        }
    } catch (Exception e) {
        logger.error("Exception: ", e);
    }
    NavigationTreePatternNode theRoot = new NavigationTreePatternNode("", "", -1, startNamespaceDelimiter,
            endNamespaceDelimiter);
    theRoot.addEdge(nodes.getFirst(), fromRoot, false, false);
    p.setRoot(theRoot);

    //add the PatternNodes with the Patterns to which they belong to the HashMap patternMap
    Iterator<NavigationTreePatternNode> iterPatNode = nodes.iterator();
    while (iterPatNode.hasNext()) {
        patternMap.put(iterPatNode.next().getNodeCode(), p);
    }

    return p;
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private DefinitionList buildDefinitionList(SpanManager sm, ContentElementParsingParameters cepp,
        LinkedList<Span> lineSpans) {
    List<ContentElement> content = new ArrayList<ContentElement>();

    Span s = lineSpans.removeFirst();//from  w  w w .  j  a v  a  2 s.  c  om

    int temp = sm.indexOf(":", s);
    if (temp == -1) {
        content.add(parseContentElement(sm, cepp, new Span(s.getStart() + 1, s.getEnd())));
    } else {
        content.add(parseContentElement(sm, cepp, new Span(temp + 1, s.getEnd())));
        content.add(0, parseContentElement(sm, cepp, new Span(s.getStart() + 1, temp)));
    }

    while (!lineSpans.isEmpty()) {
        Span ns = lineSpans.getFirst();
        if (sm.charAt(ns.getStart()) != ':') {
            break;
        }
        lineSpans.removeFirst();
        content.add(parseContentElement(sm, cepp, new Span(ns.getStart() + 1, ns.getEnd())));
    }

    DefinitionList result = new DefinitionList(content);

    if (calculateSrcSpans) {
        result.setSrcSpan(
                new SrcSpan(sm.getSrcPos(s.getStart()), content.get(content.size() - 1).getSrcSpan().getEnd()));
    }

    return result;
}

From source file:repast.simphony.relogo.ide.wizards.NetlogoImportWizard.java

private void exportRelogoTemplates(IFolder srcFolder, IFolder srcGenFolder, IFolder rsFolder,
        IFolder styleFolder) throws IOException {
    loadStringTemplates();//from  ww  w .j a  v  a  2s . c o m
    String packageName = pageOne.getPackageName();
    // first write the static Java and Groovy classes
    // two static java classes in the style package
    IFolder folder = createFolderResource(srcFolder, STYLE_PACKAGE_NAME);
    for (int i = 0; i < RELOGO_STYLE_TEMPLATES.length; i++) {
        String templateName = "/templates/" + RELOGO_STYLE_TEMPLATES[i] + ".java.txt";
        String instantiationName = RELOGO_STYLE_TEMPLATES[i] + ".java";
        InputStream stream = loadClassTemplate(templateName, packageName, "");
        createFileResource(folder, instantiationName, stream);
    }
    // a single static groovy class in the context package
    folder = createFolderResource(srcFolder, CONTEXT_PACKAGE_NAME);
    for (int i = 0; i < RELOGO_CONTEXT_TEMPLATES.length; i++) {
        String templateName = "/templates/" + RELOGO_CONTEXT_TEMPLATES[i] + ".groovy.txt";
        String instantiationName = RELOGO_CONTEXT_TEMPLATES[i] + ".groovy";
        InputStream stream = loadClassTemplate(templateName, packageName, "");
        createFileResource(folder, instantiationName, stream);
    }
    // a single static groovy class in the factories package
    IFolder factoriesFolder = createFolderResource(srcFolder, FACTORIES_PACKAGE_NAME);
    for (int i = 0; i < RELOGO_FACTORIES_TEMPLATES.length; i++) {
        String templateName = "/templates/" + RELOGO_FACTORIES_TEMPLATES[i] + ".java.txt";
        String instantiationName = RELOGO_FACTORIES_TEMPLATES[i] + ".java";
        InputStream stream = loadClassTemplate(templateName, packageName, "");
        createFileResource(factoriesFolder, instantiationName, stream);
    }

    String[] instances = { "reLogoTurtle", "reLogoPatch", "reLogoLink", "reLogoObserver" };
    String[] fileNames = { "ReLogoTurtle.java", "ReLogoPatch.java", "ReLogoLink.java", "ReLogoObserver.java" };
    for (int i = 0; i < instances.length; i++) {
        StringTemplate rlTemplate = reLogoOTPLTemplateGroup.getInstanceOf(instances[i]);

        rlTemplate.setAttribute("packageName", packageName);
        createFileResource(srcGenFolder, fileNames[i],
                new ByteArrayInputStream(rlTemplate.toString().getBytes("UTF-8")));
    }

    /*
     * for (int i = 0; i < RELOGO_FACTORIES_TEMPLATES.length; i++) { String
     * templateName = "/templates/" + RELOGO_FACTORIES_TEMPLATES[i] +
     * ".groovy.txt"; String instantiationName = RELOGO_FACTORIES_TEMPLATES[i] +
     * ".groovy"; InputStream stream = loadClassTemplate(templateName,
     * packageName, ""); createFileResource(factoriesFolder, instantiationName,
     * stream); }
     */
    LinkedList<RelogoClass> allClasses = pageOne.getGeneratedClasses();
    IFolder relogoSourceFolder = createFolderResource(srcFolder, "relogo");
    // output the Model class, adding in all global variables
    /*
     * { RelogoClass modelClass = null; for (RelogoClass relogoClass :
     * allClasses) { if (relogoClass != null && relogoClass.getGenericCategory()
     * == RelogoClass.RELOGO_CLASS_MODEL) { modelClass = relogoClass; } } if
     * (modelClass != null) { String templateName = "/templates/" +
     * RELOGO_CUSTOM_MODEL_TEMPLATE + ".java.txt"; String instantiationName =
     * RELOGO_CUSTOM_MODEL_TEMPLATE + ".java"; InputStream stream =
     * loadClassTemplate(templateName, packageName, modelClass.getJavaCode());
     * createFileResource(srcFolder, instantiationName, stream); } else {
     * System.err.println("No global class generated!"); } }
     */
    // output the Plot class, adding in all plots and series.
    // Template code implies one Plot class to support all plots.
    /*
     * { StringTemplate plotTpl = plotTemplateGroup.getInstanceOf("plot");
     * NLPlot[] plots = pageOne.getPlots(); // do these two for each plot, axis,
     * and series String plots_and_pens = ""; for (int plotId = 0; plotId <
     * plots.length; plotId++) { if (plots_and_pens.length() == 0) {
     * plots_and_pens = plots[plotId].getTitle()+":["; } else { plots_and_pens =
     * plots_and_pens + ",\n" + plots[plotId].getTitle()+":["; } String pens =
     * ""; for (NLPen pen : plots[plotId].getPens()) { StringTemplate seriesTpl
     * = plotTemplateGroup.getInstanceOf("series");
     * seriesTpl.setAttribute("plot", plots[plotId].getTitle());
     * seriesTpl.setAttribute("axis", plots[plotId].getYTitle());
     * seriesTpl.setAttribute("series", pen.getLabel());
     * seriesTpl.setAttribute("series_label", pen.getLabel());
     * plotTpl.setAttribute("series", seriesTpl.toString()); if
     * (pens.length()==0) { pens = "\"" + pen.getLabel() + "\""; } else { pens =
     * pens + ",\"" + pen.getLabel() + "\""; } } plots_and_pens += pens+"]"; }
     * plotTpl.setAttribute("package", packageName);
     * plotTpl.setAttribute("plots_and_pens", plots_and_pens);
     * plotTpl.setAttribute("dollar", "$"); // we need this unless we code a
     * custom TokenLexer for StringTemplate String instantiationName =
     * RELOGO_CUSTOM_PLOT_TEMPLATE + ".groovy"; createFileResource(srcFolder,
     * instantiationName, new StringInputStream(plotTpl.toString())); }
     */
    // Build the template for built-ins dependent upon user breeds.
    // StringTemplate utilityTpl =
    // utilityTemplateGroup.getInstanceOf("user_utility_body");
    // utilityTpl.setAttribute("package", packageName);
    // finally output the dynamic Groovy classes and insert the new code
    // from the Netlogo model
    {
        // UserTurtle
        StringBuffer bodyCode = new StringBuffer();
        StringBuffer turtlesOwnCode = new StringBuffer();
        for (RelogoClass relogoClass : allClasses) {
            if (relogoClass != null && relogoClass.getGenericCategory() == RelogoClass.RELOGO_CLASS_TURTLE) {
                String breedPlural = relogoClass.getBreed().getPluralName();
                String breedSingular = relogoClass.getBreed().getSingularName();

                // Collect the turtle attributes into a @TurtlesOwn
                // statement, turtlesOwnCode
                if (breedPlural.equals("turtles")) {
                    // Generate:
                    // @TurtlesOwn
                    // def attribute1, attribute2
                    if (hasAttributesToGenerate(relogoClass)) {
                        turtlesOwnCode.append("def ");
                        int attributeCounter = 0;
                        for (Attribute attr : relogoClass.attributes()) {
                            if (attr.generate) {
                                String name = attr.toString();
                                if (attributeCounter != 0) {
                                    turtlesOwnCode.append(", ");
                                }
                                turtlesOwnCode.append(name);
                                attributeCounter++;
                            }
                        }
                        turtlesOwnCode.append("\n");
                    }
                }
                if (!breedPlural.equals("turtles")) {

                    /**
                     * class Worker extends UserTurtle{
                     * 
                     * def destination, cargo
                     */

                    if (breedPlural != null) {
                        StringTemplate ctTemplate = userOTPLTemplateGroup.getInstanceOf("customTurtle");
                        ctTemplate.setAttribute("packageName", packageName);

                        String breedName = WizardUtilities.getJavaName(breedSingular);
                        String className = Character.toString(breedName.charAt(0)).toUpperCase()
                                + breedName.substring(1);
                        if (!WizardUtilities.getJavaName(breedPlural)
                                .equals(WizardUtilities.getJavaName(breedSingular) + "s")) {
                            ctTemplate.setAttribute("pluralAnnotation",
                                    "@Plural('" + WizardUtilities.getJavaName(breedPlural) + "')");
                        }
                        ctTemplate.setAttribute("turtleClassName", className);

                        if (hasAttributesToGenerate(relogoClass)) {
                            StringBuffer sb = new StringBuffer();
                            sb.append("def ");
                            int attributeCounter = 0;
                            for (Attribute attr : relogoClass.attributes()) {
                                if (attr.generate) {
                                    String name = attr.toString();
                                    if (attributeCounter != 0) {
                                        sb.append(", ");
                                    }
                                    sb.append(name);
                                    attributeCounter++;
                                }
                            }
                            ctTemplate.setAttribute("turtleVars", sb.toString());
                        }
                        createFileResource(relogoSourceFolder, className + ".groovy",
                                new ByteArrayInputStream(ctTemplate.toString().getBytes("UTF-8")));
                    }
                }
                // This should probably remain the same, and go to the
                // UserTurtle class
                bodyCode.append(relogoClass.getGroovyCode());
            }
        }
        // Accumulated information above

        StringTemplate utTemplate = userOTPLTemplateGroup.getInstanceOf("userTurtle");

        utTemplate.setAttribute("packageName", packageName);
        if (turtlesOwnCode.length() != 0) {
            utTemplate.setAttribute("turtleVars", turtlesOwnCode.toString());
        }
        utTemplate.setAttribute("bodyCode", bodyCode);
        createFileResource(relogoSourceFolder, "UserTurtle.groovy",
                new ByteArrayInputStream(utTemplate.toString().getBytes("UTF-8")));

    }
    {
        // UserPatch
        StringBuffer patchesOwnCode = new StringBuffer();
        StringBuffer bodyCode = new StringBuffer();
        StringTemplate upTemplate = userOTPLTemplateGroup.getInstanceOf("userPatch");
        upTemplate.setAttribute("packageName", packageName);
        for (RelogoClass relogoClass : allClasses) {
            if (relogoClass != null && relogoClass.getGenericCategory() == RelogoClass.RELOGO_CLASS_PATCH) {
                // @PatchesOwn
                if (hasAttributesToGenerate(relogoClass)) {
                    patchesOwnCode.append("@Diffusible\ndef ");
                    int attributeCounter = 0;
                    for (Attribute attr : relogoClass.attributes()) {
                        if (attr.generate) {
                            String name = attr.toString();
                            if (attributeCounter != 0) {
                                patchesOwnCode.append(", ");
                            }
                            patchesOwnCode.append(name);
                            attributeCounter++;
                        }
                    }
                    upTemplate.setAttribute("patchVars", patchesOwnCode.toString());

                }
                bodyCode.append(relogoClass.getGroovyCode());
            }
        }
        upTemplate.setAttribute("bodyCode", bodyCode.toString());
        createFileResource(relogoSourceFolder, "UserPatch.groovy",
                new ByteArrayInputStream(upTemplate.toString().getBytes("UTF-8")));
    }
    {
        // UserLink
        StringTemplate ulTemplate = userOTPLTemplateGroup.getInstanceOf("userLink");
        ulTemplate.setAttribute("packageName", packageName);
        StringBuffer linksOwnCode = new StringBuffer();
        StringBuffer bodyCode = new StringBuffer();
        StringBuffer projections = new StringBuffer();

        String[] displayStrings = { "netStylesEntry", "editedNetStylesEntry",
                "repastSimphonyScoreProjectionData", "projectionDescriptorsEntry" };
        StringTemplate displayTemplate = new StringTemplate();
        StringBuffer netStylesEntryBuffer = new StringBuffer();
        StringBuffer editedNetStylesEntryBuffer = new StringBuffer();
        StringBuffer repastSimphonyScoreProjectionDataBuffer = new StringBuffer();
        StringBuffer projectionDescriptorsEntryBuffer = new StringBuffer();
        ArrayList<StringBuffer> bufferList = new ArrayList<StringBuffer>(4);
        bufferList.add(0, netStylesEntryBuffer);
        bufferList.add(1, editedNetStylesEntryBuffer);
        bufferList.add(2, repastSimphonyScoreProjectionDataBuffer);
        bufferList.add(3, projectionDescriptorsEntryBuffer);
        // StringTemplate editedNetStylesEntryTemplate =
        // displayTemplateGroup.getInstanceOf("editedNetStylesEntry");
        // StringTemplate repastSimphonyScoreProjectionDataTemplate =
        // displayTemplateGroup.getInstanceOf("repastSimphonyScoreProjectionData");
        // StringTemplate projectionDescriptorsEntryTemplate =
        // displayTemplateGroup.getInstanceOf("projectionDescriptorsEntry");
        int linkBreedCounter = 0;
        for (RelogoClass relogoClass : allClasses) {
            if (relogoClass != null && relogoClass.getGenericCategory() == RelogoClass.RELOGO_CLASS_LINK) {

                if (relogoClass.getBreed() != null) {
                    String breedPlural = relogoClass.getBreed().getPluralName();
                    String breedSingular = relogoClass.getBreed().getSingularName();
                    boolean linkBreedDirected = relogoClass.getBreed().isLinkBreedDirected();
                    // Collect the link attributes into @LinksOwn field
                    // declarations
                    if (breedPlural.equals("links")) {
                        if (hasAttributesToGenerate(relogoClass)) {
                            linksOwnCode.append("def ");
                            int attributeCounter = 0;
                            for (Attribute attr : relogoClass.attributes()) {
                                if (attr.generate) {
                                    // TODO : Change to preserve
                                    // capitalization
                                    String name = attr.toString();
                                    if (attributeCounter != 0) {
                                        linksOwnCode.append(", ");
                                    }
                                    linksOwnCode.append(name);
                                    attributeCounter++;
                                }
                            }
                            // linkVars to utTemplate
                            ulTemplate.setAttribute("linkVars", linksOwnCode.toString());
                        }
                    }
                    if (!breedPlural.equals("links")) {
                        StringTemplate clTemplate = userOTPLTemplateGroup.getInstanceOf("customLink");
                        clTemplate.setAttribute("packageName", packageName);
                        String breedName = WizardUtilities.getJavaName(breedSingular);
                        String className = Character.toString(breedName.charAt(0)).toUpperCase()
                                + breedName.substring(1);
                        clTemplate.setAttribute("linkClassName", className);

                        if (breedPlural != null) {
                            projections.append("<projection id=\"" + className + "\" type=\"network\" />\n");
                            for (int i = 0; i < 4; i++) {
                                displayTemplate = displayTemplateGroup.getInstanceOf(displayStrings[i]);
                                displayTemplate.setAttribute("networkName", className);
                                if (i == 0) {
                                    displayTemplate.setAttribute("packageName", packageName);
                                }
                                if (i == 3) {
                                    displayTemplate.setAttribute("number", 5 + linkBreedCounter);
                                    linkBreedCounter++;
                                }
                                bufferList.get(i).append(displayTemplate.toString() + "\n");
                            }
                            // exportAdditionalNetworkStyleFile(camelCase(
                            // breedPlural, false), styleFolder);

                            // Create the @LinkBreed statement and append to
                            // allLinkBreedCode

                            if (!linkBreedDirected) {
                                clTemplate.setAttribute("directedAnnotation", "@Undirected");
                            } else {
                                clTemplate.setAttribute("directedAnnotation", "@Directed");
                            }
                            if (!WizardUtilities.getJavaName(breedPlural)
                                    .equals(WizardUtilities.getJavaName(breedSingular) + "s")) {
                                clTemplate.setAttribute("pluralAnnotation",
                                        "@Plural('" + WizardUtilities.getJavaName(breedPlural) + "')");
                            }

                        }

                        // Collect the breed's attributes into a
                        // @LinksOwn('breedPlural') statement and append to
                        // allBreedsOwnCode
                        if (hasAttributesToGenerate(relogoClass)) {
                            StringBuffer breedsOwnCode = new StringBuffer();
                            breedsOwnCode.append("def ");
                            int attributeCounter = 0;
                            for (Attribute attr : relogoClass.attributes()) {
                                if (attr.generate) {
                                    String name = attr.toString();
                                    if (attributeCounter != 0) {
                                        breedsOwnCode.append(", ");
                                    }
                                    breedsOwnCode.append(name);
                                    attributeCounter++;
                                }
                            }
                            clTemplate.setAttribute("linkVars", breedsOwnCode.toString());
                        }
                        createFileResource(relogoSourceFolder, className + ".groovy",
                                new ByteArrayInputStream(clTemplate.toString().getBytes("UTF-8")));
                    }
                    bodyCode.append(relogoClass.getGroovyCode());
                }
            }
        }
        // Create UserLink.groovy
        ulTemplate.setAttribute("bodyCode", bodyCode.toString());
        createFileResource(relogoSourceFolder, "UserLink.groovy",
                new ByteArrayInputStream(ulTemplate.toString().getBytes("UTF-8")));

        StringTemplate context_file = contextTemplateGroup.getInstanceOf("context_file");
        context_file.setAttribute("modelName", pageOne.getProjectName());
        context_file.setAttribute("additionalProjections", projections.toString());
        createFileResource(rsFolder, "context.xml",
                new ByteArrayInputStream(context_file.toString().getBytes("UTF-8")));

        StringTemplate display_file = displayTemplateGroup.getInstanceOf("display_file");
        // display_file(packageName,additionalNetStyles,additionalEditedNetStylesEntries,additionalRepastSimphonyScoreProjectionDatas,additionalProjectionDescriptorsEntries)
        display_file.setAttribute("packageName", packageName);
        display_file.setAttribute("additionalNetStyles", bufferList.get(0).toString());
        display_file.setAttribute("additionalEditedNetStylesEntries", bufferList.get(1).toString());
        display_file.setAttribute("additionalRepastSimphonyScoreProjectionDatas", bufferList.get(2).toString());
        display_file.setAttribute("additionalProjectionDescriptorsEntries", bufferList.get(3).toString());
        String displayFileName = "repast.simphony.action.display_relogoDefault.xml";
        createFileResource(rsFolder, displayFileName,
                new ByteArrayInputStream(display_file.toString().getBytes("UTF-8")));

    }
    {
        // UserObserver
        String templateName = "userObserver";
        String instantiationName = "UserObserver.groovy";
        String upccInstantiationName = RELOGO_CUSTOM_UGPF + ".groovy";
        StringTemplate ugpfTemplate = ugpfTemplateGroup.getInstanceOf("ugpf");
        ugpfTemplate.setAttribute("packageName", packageName);
        StringBuffer bodyCode = new StringBuffer();
        StringBuffer globalsCode = new StringBuffer();
        List<ProcedureDefinition> observerMethods = new ArrayList<ProcedureDefinition>();
        for (RelogoClass relogoClass : allClasses) {
            if (relogoClass != null && relogoClass.getGenericCategory() == RelogoClass.RELOGO_CLASS_OBSERVER) {
                // adding the non-button methods to UserObserver
                bodyCode.append(relogoClass.getGroovyCode());
                // getting all methods defined in the observer context
                Iterable<ProcedureDefinition> iter = relogoClass.methods();
                for (ProcedureDefinition proc : iter) {
                    observerMethods.add(proc);
                }
            }
            // Collect the global attributes into addGlobal('attribute')
            // statement,
            // globalsCode
            if (relogoClass != null && relogoClass.getClassName() == "*global*") {

                if (hasAttributesToGenerate(relogoClass)) {
                    for (Attribute attr : relogoClass.attributes()) {
                        if (attr.generate) {
                            String name = attr.toString();
                            globalsCode.append("addGlobal('" + name + "')\n");
                        }
                    }
                }
            }
        }
        if (globalsCode.length() != 0) {
            ugpfTemplate.setAttribute("globals", globalsCode.toString());
        }
        /**
         * Use the information gathered by the NetlogoSimulation scan method to
         * generate the appropriate UPCC code, using the UPCC.stg group string
         * template file.
         * 
         */
        List<ProcedureDefinition> observerNonButtonMethods = new ArrayList<ProcedureDefinition>();
        List<ProcedureDefinition> observerButtonMethods = new ArrayList<ProcedureDefinition>();
        List<ProcedureDefinition> observerToggleButtonMethods = new ArrayList<ProcedureDefinition>();
        for (ProcedureDefinition procDef : observerMethods) {
            if (procDef.getName().startsWith("button_method_")) {
                observerButtonMethods.add(procDef);
            } else if (procDef.getName().startsWith("toggle_button_method_")) {
                observerToggleButtonMethods.add(procDef);
            } else {
                observerNonButtonMethods.add(procDef);
            }
        }
        // split this into toggle and button methods
        StringBuffer ugpfComponents = new StringBuffer();

        // button methods
        StringTemplate buttonTemplate = ugpfTemplateGroup.getInstanceOf("button");
        buttonTemplate.setAttribute("observerName", "default_observer");
        for (ProcedureDefinition procDef : observerButtonMethods) {

            boolean generateButtonUsingExistingMethod = false;
            String buttonMethodName = procDef.getName();
            LinkedList ll = procDef.getCode().getContents();
            if (ll.size() == 1) {
                Object o = ll.getFirst();
                if (o instanceof ProcedureInvocation) {
                    String buttonInnerMethodName = ((ProcedureInvocation) o).getProfile().getJavaName();
                    for (ProcedureDefinition obsProcDef : observerNonButtonMethods) {
                        String observerMethodName = obsProcDef.getProfile().getJavaName();
                        if (observerMethodName.equals(buttonInnerMethodName)
                                && obsProcDef.getProfile().getSize() == 1) {
                            generateButtonUsingExistingMethod = true;
                            buttonMethodName = observerMethodName;
                            break;
                        }
                    }
                }
            }

            if (generateButtonUsingExistingMethod) {
                // create button with existing method name as argument
                buttonTemplate.setAttribute("methodName", buttonMethodName);
            } else {
                // create button with button method name as argument
                buttonMethodName = buttonMethodName.substring(14);
                procDef.setName(buttonMethodName);
                buttonTemplate.setAttribute("methodName", buttonMethodName);
                // add button method to UserObserver bodyCode
                bodyCode.append(procDef);
                bodyCode.append("\n\n");
                // bodyCode.append(buttonTemplate.toString());
            }
            /**
             * if (allBreedsOwnCode.length()!=0){ allBreedsOwnCode.append("\n"); }
             */
            if (ugpfComponents.length() != 0) {
                ugpfComponents.append("\n");
            }
            ugpfComponents.append(buttonTemplate.toString());
            buttonTemplate.removeAttribute("methodName");
        }

        // toggle button methods
        StringTemplate toggleButtonTemplate = ugpfTemplateGroup.getInstanceOf("toggleButton");
        toggleButtonTemplate.setAttribute("observerName", "default_observer");
        for (ProcedureDefinition procDef : observerToggleButtonMethods) {
            boolean generateButtonUsingExistingMethod = false;
            String buttonMethodName = procDef.getName();
            LinkedList ll = procDef.getCode().getContents();
            if (ll.size() == 1) {
                Object o = ll.getFirst();
                if (o instanceof ProcedureInvocation) {
                    String buttonInnerMethodName = ((ProcedureInvocation) o).getProfile().getJavaName();
                    for (ProcedureDefinition obsProcDef : observerNonButtonMethods) {
                        String observerMethodName = obsProcDef.getProfile().getJavaName();
                        if (observerMethodName.equals(buttonInnerMethodName)) {
                            generateButtonUsingExistingMethod = true;
                            buttonMethodName = observerMethodName;
                            break;
                        }
                    }
                }
            }

            if (generateButtonUsingExistingMethod) {
                // create button with existing method name as argument
                toggleButtonTemplate.setAttribute("methodName", buttonMethodName);
            } else {
                buttonMethodName = buttonMethodName.substring(21);
                procDef.setName(buttonMethodName);
                // create button with button method name as argument
                toggleButtonTemplate.setAttribute("methodName", buttonMethodName);
                // add button method to UserObserver bodyCode
                bodyCode.append(procDef);
                bodyCode.append("\n\n");
                // bodyCode.append(buttonTemplate.toString());
            }
            /**
             * if (allBreedsOwnCode.length()!=0){ allBreedsOwnCode.append("\n"); }
             */
            if (ugpfComponents.length() != 0) {
                ugpfComponents.append("\n");
            }
            ugpfComponents.append(toggleButtonTemplate.toString());
            toggleButtonTemplate.removeAttribute("methodName");
        }

        StringTemplate uoTemplate = userOTPLTemplateGroup.getInstanceOf("userObserver");
        uoTemplate.setAttribute("packageName", packageName);
        uoTemplate.setAttribute("bodyCode", bodyCode.toString());
        createFileResource(relogoSourceFolder, "UserObserver.groovy",
                new ByteArrayInputStream(uoTemplate.toString().getBytes("UTF-8")));

        // at this point the UserObserver is completed.

        List<NLControl> nlControls = pageOne.getNetlogoSimulation().getNLControls();
        for (NLControl ctl : nlControls) {
            if (ctl instanceof NLMonitor) {
                StringTemplate monitorTemplate = ugpfTemplateGroup.getInstanceOf("monitor");
                String var = ((NLMonitor) ctl).getVariable();
                String label = ((NLMonitor) ctl).getLabel();
                if (label != null && label.length() > 0) {
                    label = getJavaName(label);
                } else {
                    label = getJavaName(var);
                }
                label = "monitor_reporter_" + label;
                // observerName,reporterName,interval
                monitorTemplate.setAttribute("observerName", "default_observer");
                monitorTemplate.setAttribute("reporterName", label);
                monitorTemplate.setAttribute("interval", 5.0);
                if (ugpfComponents.length() != 0) {
                    ugpfComponents.append("\n");
                }
                ugpfComponents.append(monitorTemplate.toString());
            } else if (ctl instanceof NLChooser) {
                StringTemplate chooserTemplate = ugpfTemplateGroup.getInstanceOf("chooser");
                // variableName and list
                String var = ((NLChooser) ctl).getVariable().trim();
                int index = ((NLChooser) ctl).getInitialValue();
                List list = ((NLChooser) ctl).getChoices();
                chooserTemplate.setAttribute("variableName", camelCase(var, false));
                chooserTemplate.setAttribute("list", list);
                chooserTemplate.setAttribute("index", index);
                if (ugpfComponents.length() != 0) {
                    ugpfComponents.append("\n");
                }
                ugpfComponents.append(chooserTemplate.toString());
            } else if (ctl instanceof NLInputBox) {
                StringTemplate inputTemplate = ugpfTemplateGroup.getInstanceOf("input");
                String var = ((NLInputBox) ctl).getVariable();
                Object val = ((NLInputBox) ctl).getInitialValue();
                inputTemplate.setAttribute("variableName", camelCase(var, false));
                if (val != null) {
                    inputTemplate.setAttribute("value", val);
                }
                if (ugpfComponents.length() != 0) {
                    ugpfComponents.append("\n");
                }
                ugpfComponents.append(inputTemplate.toString());
            } else if (ctl instanceof NLSwitch) {
                StringTemplate switchTemplate = ugpfTemplateGroup.getInstanceOf("switch");
                String var = ((NLSwitch) ctl).getVariable();
                Boolean on = (Boolean) ((NLSwitch) ctl).getInitialValue();
                switchTemplate.setAttribute("variableName", camelCase(var, false));
                if (on != null) {
                    switchTemplate.setAttribute("selected", on);
                }
                if (ugpfComponents.length() != 0) {
                    ugpfComponents.append("\n");
                }
                ugpfComponents.append(switchTemplate.toString());
            } else if (ctl instanceof NLSlider) {
                StringTemplate sliderTemplate = ugpfTemplateGroup.getInstanceOf("slider");
                String var = ((NLSlider) ctl).getVariable();
                double minVal = ((NLSlider) ctl).getMinimum();
                double increment = ((NLSlider) ctl).getStep();
                double maxVal = ((NLSlider) ctl).getMaximum();
                Number val = (Number) ((NLSlider) ctl).getInitialValue();
                String units = ((NLSlider) ctl).getUnits();
                sliderTemplate.setAttribute("variableName", camelCase(var, false));
                sliderTemplate.setAttribute("minVal", minVal);
                sliderTemplate.setAttribute("increment", increment);
                sliderTemplate.setAttribute("maxVal", maxVal);
                sliderTemplate.setAttribute("val", val);
                if (units != null) {
                    sliderTemplate.setAttribute("units", units);
                }
                if (ugpfComponents.length() != 0) {
                    ugpfComponents.append("\n");
                }
                ugpfComponents.append(sliderTemplate.toString());
            }
        }
        ugpfTemplate.setAttribute("components", ugpfComponents.toString());

        createFileResource(relogoSourceFolder, upccInstantiationName,
                new ByteArrayInputStream(ugpfTemplate.toString().getBytes("UTF-8")));
    }
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

/**
 * Building a ContentElement, this funciton is calles by all the other
 * parseContentElement(..) functions//w ww.j ava 2 s.  c  o  m
 */
private ContentElement parseContentElement(SpanManager sm, ContentElementParsingParameters cepp,
        LinkedList<Span> lineSpans, ContentElement result) {

    List<Link> localLinks = new ArrayList<Link>();
    List<Template> localTemplates = new ArrayList<Template>();

    List<Span> boldSpans = new ArrayList<Span>();
    List<Span> italicSpans = new ArrayList<Span>();
    sm.manageList(boldSpans);
    sm.manageList(italicSpans);

    List<Span> managedSpans = new ArrayList<Span>();
    sm.manageList(managedSpans);

    Span contentElementRange = new Span(lineSpans.getFirst().getStart(), lineSpans.getLast().getEnd()).trim(sm);
    managedSpans.add(contentElementRange);

    // set the SrcSpan
    if (calculateSrcSpans) {
        result.setSrcSpan(new SrcSpan(sm.getSrcPos(contentElementRange.getStart()),
                sm.getSrcPos(contentElementRange.getEnd())));
    }

    sm.manageList(lineSpans);
    while (!lineSpans.isEmpty()) {
        Span line = lineSpans.getFirst();

        parseBoldAndItalicSpans(sm, line, boldSpans, italicSpans);

        // External links
        parseExternalLinks(sm, line, "http://", managedSpans, localLinks, result);
        parseExternalLinks(sm, line, "https://", managedSpans, localLinks, result);
        parseExternalLinks(sm, line, "ftp://", managedSpans, localLinks, result);
        parseExternalLinks(sm, line, "mailto:", managedSpans, localLinks, result);

        // end of linewhise opperations
        lineSpans.removeFirst();
    }
    sm.removeManagedList(lineSpans);

    // Links
    int i;
    i = 0;
    while (i < cepp.linkSpans.size()) {
        if (contentElementRange.hits(cepp.linkSpans.get(i))) {
            Span linkSpan = cepp.linkSpans.remove(i);
            managedSpans.add(linkSpan);
            Link l = cepp.links.remove(i).setHomeElement(result);
            localLinks.add(l);
            if (!showImageText && l.getType() == Link.type.IMAGE) {
                // deletes the Image Text from the ContentElement Text.
                sm.delete(linkSpan);
            }
        } else {
            i++;
        }
    }

    // Templates
    i = 0;
    while (i < cepp.templateSpans.size()) {
        Span ts = cepp.templateSpans.get(i);
        if (contentElementRange.hits(ts)) {
            ResolvedTemplate rt = cepp.templates.remove(i);

            if (rt.getPostParseReplacement() != null) {
                sm.replace(ts, rt.getPostParseReplacement());
            }
            cepp.templateSpans.remove(i);

            Object parsedObject = rt.getParsedObject();
            if (parsedObject != null) {
                managedSpans.add(ts);

                Class parsedObjectClass = parsedObject.getClass();
                if (parsedObjectClass == Template.class) {
                    localTemplates.add((Template) parsedObject);
                } else if (parsedObjectClass == Link.class) {
                    localLinks.add(((Link) parsedObject).setHomeElement(result));
                } else {
                    localTemplates.add(rt.getTemplate());
                }
            }
        } else {
            i++;
        }
    }

    // HTML/XML Tags
    i = 0;
    List<Span> tags = new ArrayList<Span>();
    while (i < cepp.tagSpans.size()) {
        Span s = cepp.tagSpans.get(i);
        if (contentElementRange.hits(s)) {
            cepp.tagSpans.remove(i);
            if (deleteTags) {
                sm.delete(s);
            } else {
                tags.add(s);
                managedSpans.add(s);
            }
        } else {
            i++;
        }
    }

    // noWiki
    i = 0;
    List<Span> localNoWikiSpans = new ArrayList<Span>();
    while (i < cepp.noWikiSpans.size()) {
        Span s = cepp.noWikiSpans.get(i);
        if (contentElementRange.hits(s)) {
            cepp.noWikiSpans.remove(i);
            sm.replace(s, cepp.noWikiStrings.remove(i));
            localNoWikiSpans.add(s);
            managedSpans.add(s);
        } else {
            i++;
        }
    }

    // MATH Tags
    i = 0;
    List<Span> mathSpans = new ArrayList<Span>();
    while (i < cepp.mathSpans.size()) {
        Span s = cepp.mathSpans.get(i);
        if (contentElementRange.hits(s)) {
            cepp.mathSpans.remove(i);

            if (showMathTagContent) {
                mathSpans.add(s);
                managedSpans.add(s);
                sm.replace(s, cepp.mathStrings.remove(i));
            } else {
                sm.delete(s);
            }
        } else {
            i++;
        }
    }

    result.setText(sm.substring(contentElementRange));

    // managed spans must be removed here and not earlier, because every
    // change in the SpanManager affects the Spans!
    sm.removeManagedList(boldSpans);
    sm.removeManagedList(italicSpans);
    sm.removeManagedList(managedSpans);

    // contentElementRange ist auch noch in managedSpans !!! deswegen:
    final int adjust = -contentElementRange.getStart();
    for (Span s : boldSpans) {
        s.adjust(adjust);
    }
    for (Span s : italicSpans) {
        s.adjust(adjust);
    }
    for (Span s : managedSpans) {
        s.adjust(adjust);
    }

    result.setFormatSpans(FormatType.BOLD, boldSpans);
    result.setFormatSpans(FormatType.ITALIC, italicSpans);
    result.setFormatSpans(FormatType.TAG, tags);
    result.setFormatSpans(FormatType.MATH, mathSpans);
    result.setFormatSpans(FormatType.NOWIKI, localNoWikiSpans);

    result.setLinks(sortLinks(localLinks));
    result.setTemplates(sortTemplates(localTemplates));

    return result;
}