Example usage for javax.servlet.jsp JspWriter println

List of usage examples for javax.servlet.jsp JspWriter println

Introduction

In this page you can find the example usage for javax.servlet.jsp JspWriter println.

Prototype


abstract public void println(Object x) throws IOException;

Source Link

Document

Print an Object and then terminate the line.

Usage

From source file:org.disit.servicemap.api.ServiceMapApi.java

public void queryFulltext(JspWriter out, RepositoryConnection con, String textToSearch, String selection,
        String dist, String limit) throws Exception {
    Configuration conf = Configuration.getInstance();
    String sparqlType = conf.get("sparqlType", "virtuoso");
    String km4cVersion = conf.get("km4cVersion", "new");
    String[] coords = null;/*from www  .  j a  v a 2  s  . c  o m*/

    if (selection != null && selection.contains(";")) {
        coords = selection.split(";");
    }

    String queryText = "PREFIX luc: <http://www.ontotext.com/owlim/lucene#>\n"
            + "PREFIX km4c:<http://www.disit.org/km4city/schema#>\n"
            + "PREFIX km4cr:<http://www.disit.org/km4city/resource#>\n"
            + "PREFIX geo:<http://www.w3.org/2003/01/geo/wgs84_pos#>\n"
            + "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>\n"
            + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX schema:<http://schema.org/>\n" + "PREFIX omgeo:<http://www.ontotext.com/owlim/geo#>\n"
            + "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX foaf:<http://xmlns.com/foaf/0.1/>\n"
            + "SELECT DISTINCT ?ser ?long ?lat ?sType ?sTypeIta ?sCategory ?sName ?txt ?x WHERE {\n"
            + ServiceMap.textSearchQueryFragment("?ser", "?p", textToSearch) + (km4cVersion.equals(
                    "old") ? "  OPTIONAL { ?ser km4c:hasServiceCategory ?cat.\n" + "  ?cat rdfs:label ?sTypeIta. FILTER(LANG(?sTypeIta)=\"it\") }\n" : " {\n" + "  ?ser a ?sType. FILTER(?sType!=km4c:RegularService && ?sType!=km4c:Service && ?sType!=km4c:DigitalLocation && ?sType!=km4c:TransverseService)\n" + "  OPTIONAL { ?sType rdfs:subClassOf ?sCategory. FILTER(STRSTARTS(STR(?sCategory),\"http://www.disit.org/km4city/schema#\"))}\n" + "  ?sType rdfs:label ?sTypeIta. FILTER(LANG(?sTypeIta)=\"it\")\n" + " }\n")
            + " OPTIONAL {{?ser schema:name ?sName } UNION { ?ser foaf:name ?sName }}\n" + " {\n"
            + "  ?ser geo:lat ?lat .\n" + "  ?ser geo:long ?long .\n"
            + ServiceMap.geoSearchQueryFragment("?ser", coords, dist) + " } UNION {\n"
            + "  ?ser km4c:hasAccess ?entry.\n" + "    ?entry geo:lat ?lat.\n" + "    ?entry geo:long ?long.\n"
            + ServiceMap.geoSearchQueryFragment("?entry", coords, dist)
            /*+ "} UNION {"
             + " ?ser km4c:hasStreetNumber/km4c:hasExternalAccess ?entry."
             + " ?entry geo:lat ?lat."
             + " ?entry geo:long ?long." 
            + ServiceMap.geoSearchQueryFragment("?entry", coords, dist)*/
            + " }\n" + "} ORDER BY DESC(?sc)";
    if (!"0".equals(limit)) {
        queryText += " LIMIT " + limit;
    }
    TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryText);
    long start = System.nanoTime();
    TupleQueryResult result = tupleQuery.evaluate();
    logQuery(queryText, "free-text-search", sparqlType, textToSearch + ";" + limit, System.nanoTime() - start);
    int i = 0;
    out.println("{ " + "\"type\": \"FeatureCollection\", " + "\"features\": [ ");
    while (result.hasNext()) {
        if (i != 0) {
            out.println(", ");
        }
        BindingSet bindingSet = result.next();

        String serviceUri = bindingSet.getValue("ser").stringValue();
        String serviceLat = "";
        if (bindingSet.getValue("lat") != null) {
            serviceLat = bindingSet.getValue("lat").stringValue();
        }
        String serviceLong = "";
        if (bindingSet.getValue("long") != null) {
            serviceLong = bindingSet.getValue("long").stringValue();
        }
        String label = "";
        if (bindingSet.getValue("sTypeIta") != null) {
            label = bindingSet.getValue("sTypeIta").stringValue();
            //label = Character.toLowerCase(label.charAt(0)) + label.substring(1);
            label = label.replace(" ", "_");
            label = label.replace("'", "");
        }
        // DICHIARAZIONE VARIABILI serviceType e serviceCategory per ICONA
        String subCategory = "";
        if (bindingSet.getValue("sType") != null) {
            subCategory = bindingSet.getValue("sType").stringValue();
            subCategory = subCategory.replace("http://www.disit.org/km4city/schema#", "");
            subCategory = Character.toLowerCase(subCategory.charAt(0)) + subCategory.substring(1);
            subCategory = subCategory.replace(" ", "_");
        }

        String category = "";
        if (bindingSet.getValue("sCategory") != null) {
            category = bindingSet.getValue("sCategory").stringValue();
            category = category.replace("http://www.disit.org/km4city/schema#", "");
            category = Character.toLowerCase(category.charAt(0)) + category.substring(1);
            category = category.replace(" ", "_");
        }
        String sName = "";
        if (bindingSet.getValue("sName") != null) {
            sName = bindingSet.getValue("sName").stringValue();
        } else {
            sName = subCategory.replace("_", " ").toUpperCase();
        }

        // Controllo categoria SensorSite e BusStop per ricerca testuale.
        String serviceType = "";
        String valueOfLinee = "";

        //Da verificare se OK
        /*if (subCategory.equals("sensorSite")) {
        serviceType = "RoadSensor";
        } else if (subCategory.equals("busStop")) {
        serviceType = "NearBusStop";
        TupleQueryResult resultLinee =  queryBusLines(sName, con);
        if(resultLinee != null){
        while (resultLinee.hasNext()) {
            BindingSet bindingSetLinee = resultLinee.next();
            String idLinee = bindingSetLinee.getValue("id").stringValue();
            valueOfLinee = valueOfLinee + " - "+idLinee;
        }
        if(valueOfLinee.length()>3)
          valueOfLinee = valueOfLinee.substring(3);
        }
        } else if(! "".equals(category)){
        serviceType = category + "_" + subCategory;
        }*/

        serviceType = category + "_" + subCategory;
        if (subCategory.equals("BusStop")) {
            TupleQueryResult resultLinee = queryBusLines(sName, con);
            if (resultLinee != null) {
                while (resultLinee.hasNext()) {
                    BindingSet bindingSetLinee = resultLinee.next();
                    String idLinee = bindingSetLinee.getValue("id").stringValue();
                    valueOfLinee = valueOfLinee + " - " + idLinee;
                }
                if (valueOfLinee.length() > 3)
                    valueOfLinee = valueOfLinee.substring(3);
            }
        }

        String txt = "";
        if (bindingSet.getValue("txt") != null) {
            txt = bindingSet.getValue("txt").stringValue();
        }
        out.println("{ " + " \"geometry\": {  " + "     \"type\": \"Point\",  " + "    \"coordinates\": [  "
                + "      " + serviceLong + ",  " + "      " + serviceLat + "  " + " ]  " + "},  "
                + "\"type\": \"Feature\",  " + "\"properties\": {  " + "    \"serviceUri\": \"" + serviceUri
                + "\", "
                // *** INSERIMENTO serviceType
                // **********************************************
                + "\"nome\": \"" + ServiceMap.escapeJSON(sName) + "\", ");
        if (!"".equals(category))
            out.println("\"tipo\": \"servizio\", " + "    \"serviceType\": \""
                    + escapeJSON(mapServiceType(serviceType)) + "\", ");
        out.println("\"type\": \"" + ServiceMap.escapeJSON(label) + "\", " + "    \"linee\": \""
                + escapeJSON(valueOfLinee) + "\" " + "}, " + "\"id\": " + Integer.toString(i + 1) + "  "
                // + "\"query\": \"" + queryString + "\" "
                + "}");
        i++;
    }
    out.println("] " + "}");
}

From source file:org.apache.hadoop.hdfs.server.datanode.DatanodeJspHelper.java

static void generateFileDetails(JspWriter out, HttpServletRequest req, Configuration conf)
        throws IOException, InterruptedException {

    long startOffset = 0;
    int datanodePort;

    final Long blockId = JspHelper.validateLong(req.getParameter("blockId"));
    if (blockId == null) {
        out.print("Invalid input (blockId absent)");
        return;/*from  w  ww  . jav a 2s  . c o m*/
    }
    String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);

    String datanodePortStr = req.getParameter("datanodePort");
    if (datanodePortStr == null) {
        out.print("Invalid input (datanodePort absent)");
        return;
    }
    datanodePort = Integer.parseInt(datanodePortStr);

    final Long genStamp = JspHelper.validateLong(req.getParameter("genstamp"));
    if (genStamp == null) {
        out.print("Invalid input (genstamp absent)");
        return;
    }
    String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null)
        namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);
    final String nnAddr = StringEscapeUtils.escapeHtml(req.getParameter(JspHelper.NAMENODE_ADDRESS));
    if (nnAddr == null) {
        out.print(JspHelper.NAMENODE_ADDRESS + " url param is null");
        return;
    }

    final int chunkSizeToView = JspHelper.string2ChunkSizeToView(req.getParameter("chunkSizeToView"),
            getDefaultChunkSize(conf));

    String startOffsetStr = req.getParameter("startOffset");
    if (startOffsetStr == null || Long.parseLong(startOffsetStr) < 0)
        startOffset = 0;
    else
        startOffset = Long.parseLong(startOffsetStr);

    String path = StringEscapeUtils.unescapeHtml(req.getParameter("filename"));
    if (path == null) {
        path = req.getPathInfo() == null ? "/" : req.getPathInfo();
    }
    final String filename = JspHelper.validatePath(path);
    if (filename == null) {
        out.print("Invalid input");
        return;
    }

    final String blockSizeStr = req.getParameter("blockSize");
    if (blockSizeStr == null || blockSizeStr.length() == 0) {
        out.print("Invalid input");
        return;
    }
    long blockSize = Long.parseLong(blockSizeStr);

    final DFSClient dfs = getDFSClient(ugi, nnAddr, conf);
    List<LocatedBlock> blocks = dfs.getNamenode().getBlockLocations(filename, 0, Long.MAX_VALUE)
            .getLocatedBlocks();
    // Add the various links for looking at the file contents
    // URL for downloading the full file
    String downloadUrl = "/streamFile" + ServletUtil.encodePath(filename)
            + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr, true)
            + JspHelper.getDelegationTokenUrlParam(tokenString);
    out.print("<a name=\"viewOptions\"></a>");
    out.print("<a href=\"" + downloadUrl + "\">Download this file</a><br>");

    DatanodeInfo chosenNode;
    // URL for TAIL
    LocatedBlock lastBlk = blocks.get(blocks.size() - 1);
    try {
        chosenNode = JspHelper.bestNode(lastBlk, conf);
    } catch (IOException e) {
        out.print(e.toString());
        dfs.close();
        return;
    }

    String tailUrl = "///" + JspHelper.Url.authority(req.getScheme(), chosenNode) + "/tail.jsp?filename="
            + URLEncoder.encode(filename, "UTF-8") + "&namenodeInfoPort=" + namenodeInfoPort
            + "&chunkSizeToView=" + chunkSizeToView + JspHelper.getDelegationTokenUrlParam(tokenString)
            + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr) + "&referrer="
            + URLEncoder.encode(req.getRequestURL() + "?" + req.getQueryString(), "UTF-8");
    out.print("<a href=\"" + tailUrl + "\">Tail this file</a><br>");

    out.print("<form action=\"/browseBlock.jsp\" method=GET>");
    out.print("<b>Chunk size to view (in bytes, up to file's DFS block size): </b>");
    out.print("<input type=\"hidden\" name=\"blockId\" value=\"" + blockId + "\">");
    out.print("<input type=\"hidden\" name=\"blockSize\" value=\"" + blockSize + "\">");
    out.print("<input type=\"hidden\" name=\"startOffset\" value=\"" + startOffset + "\">");
    out.print("<input type=\"hidden\" name=\"filename\" value=\"" + filename + "\">");
    out.print("<input type=\"hidden\" name=\"genstamp\" value=\"" + genStamp + "\">");
    out.print("<input type=\"hidden\" name=\"datanodePort\" value=\"" + datanodePort + "\">");
    out.print("<input type=\"hidden\" name=\"namenodeInfoPort\" value=\"" + namenodeInfoPort + "\">");
    out.print("<input type=\"hidden\" name=\"" + JspHelper.NAMENODE_ADDRESS + "\" value=\"" + nnAddr + "\">");
    out.print("<input type=\"text\" name=\"chunkSizeToView\" value=" + chunkSizeToView
            + " size=10 maxlength=10>");
    out.print("&nbsp;&nbsp;<input type=\"submit\" name=\"submit\" value=\"Refresh\">");
    out.print("</form>");
    out.print("<hr>");
    out.print("<a name=\"blockDetails\"></a>");
    out.print("<B>Total number of blocks: " + blocks.size() + "</B><br>");
    // generate a table and dump the info
    out.println("\n<table>");

    String nnCanonicalName = JspHelper.canonicalize(nnAddr);
    for (LocatedBlock cur : blocks) {
        out.print("<tr>");
        final String blockidstring = Long.toString(cur.getBlock().getBlockId());
        blockSize = cur.getBlock().getNumBytes();
        out.print("<td>" + blockidstring + ":</td>");
        DatanodeInfo[] locs = cur.getLocations();
        for (int j = 0; j < locs.length; j++) {
            String datanodeAddr = locs[j].getXferAddr();
            datanodePort = locs[j].getXferPort();
            String blockUrl = "///" + JspHelper.Url.authority(req.getScheme(), locs[j])
                    + "/browseBlock.jsp?blockId=" + blockidstring + "&blockSize=" + blockSize + "&filename="
                    + URLEncoder.encode(filename, "UTF-8") + "&datanodePort=" + datanodePort + "&genstamp="
                    + cur.getBlock().getGenerationStamp() + "&namenodeInfoPort=" + namenodeInfoPort
                    + "&chunkSizeToView=" + chunkSizeToView + JspHelper.getDelegationTokenUrlParam(tokenString)
                    + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr);

            String blockInfoUrl = "///" + nnCanonicalName + ":" + namenodeInfoPort
                    + "/block_info_xml.jsp?blockId=" + blockidstring;
            out.print("<td>&nbsp</td><td><a href=\"" + blockUrl + "\">" + datanodeAddr + "</a></td><td>"
                    + "<a href=\"" + blockInfoUrl + "\">View Block Info</a></td>");
        }
        out.println("</tr>");
    }
    out.println("</table>");
    out.print("<hr>");
    out.print("<br><a href=\"///" + nnCanonicalName + ":" + namenodeInfoPort
            + "/dfshealth.jsp\">Go back to DFS home</a>");
    dfs.close();
}

From source file:info.magnolia.templating.jsp.taglib.SimpleNavigationTag.java

/**
 * Draws page children as an unordered list.
 * /*from ww w . ja v  a  2s .c  o  m*/
 * @param page current page
 * @param activePage active page
 * @param out jsp writer
 * @throws IOException jspwriter exception
 * @throws RepositoryException any exception thrown during repository reading
 */
private void drawChildren(Content page, Content activePage, JspWriter out)
        throws IOException, RepositoryException {

    Collection<Content> children = new ArrayList<Content>(page.getChildren(ItemType.CONTENT));

    if (children.size() == 0) {
        return;
    }

    out.print("<ul class=\"level");
    out.print(page.getLevel());
    if (style != null && page.getLevel() == startLevel) {
        out.print(" ");
        out.print(style);
    }
    out.print("\">");

    Iterator<Content> iter = children.iterator();
    // loop through all children and discard those we don't want to display
    while (iter.hasNext()) {
        final Content child = iter.next();

        if (expandAll.equalsIgnoreCase(EXPAND_NONE) || expandAll.equalsIgnoreCase(EXPAND_SHOW)) {
            if (child.getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA))
                    .getBoolean()) {
                iter.remove();
                continue;
            }
            // use a filter
            if (filter != null) {
                if (!filter.accept(child)) {
                    iter.remove();
                    continue;
                }
            }
        } else {
            if (child.getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA))
                    .getBoolean()) {
                iter.remove();
                continue;
            }
        }
    }

    boolean isFirst = true;
    Iterator<Content> visibleIt = children.iterator();
    while (visibleIt.hasNext()) {
        Content child = visibleIt.next();
        List<String> cssClasses = new ArrayList<String>(4);

        NodeData nodeData = I18nContentSupportFactory.getI18nSupport().getNodeData(child,
                NODEDATA_NAVIGATIONTITLE);
        String title = null;
        if (nodeData != null) {
            title = nodeData.getString(StringUtils.EMPTY);
        }

        // if nav title is not set, the main title is taken
        if (StringUtils.isEmpty(title)) {
            title = child.getTitle();
        }

        // if main title is not set, the name of the page is taken
        if (StringUtils.isEmpty(title)) {
            title = child.getName();
        }

        boolean showChildren = false;
        boolean self = false;

        if (!expandAll.equalsIgnoreCase(EXPAND_NONE)) {
            showChildren = true;
        }

        if (activePage.getHandle().equals(child.getHandle())) {
            // self
            showChildren = true;
            self = true;
            cssClasses.add(CSS_LI_ACTIVE);
        } else if (!showChildren) {
            showChildren = child.getLevel() <= activePage.getAncestors().size() && StringUtils
                    .equals(activePage.getAncestor(child.getLevel()).getHandle(), child.getHandle());
        }

        if (!showChildren) {
            showChildren = child
                    .getNodeData(StringUtils.defaultString(this.openMenu, DEFAULT_OPENMENU_NODEDATA))
                    .getBoolean();
        }

        if (endLevel > 0) {
            showChildren &= child.getLevel() < endLevel;
        }

        cssClasses.add(hasVisibleChildren(child) ? showChildren ? CSS_LI_OPEN : CSS_LI_CLOSED : CSS_LI_LEAF);

        if (child.getLevel() < activePage.getLevel()
                && activePage.getAncestor(child.getLevel()).getHandle().equals(child.getHandle())) {
            cssClasses.add(CSS_LI_TRAIL);
        }

        if (StringUtils.isNotEmpty(classProperty) && child.hasNodeData(classProperty)) {
            cssClasses.add(child.getNodeData(classProperty).getString(StringUtils.EMPTY));
        }

        if (markFirstAndLastElement && isFirst) {
            cssClasses.add(CSS_LI_FIRST);
            isFirst = false;
        }

        if (markFirstAndLastElement && !visibleIt.hasNext()) {
            cssClasses.add(CSS_LI_LAST);
        }

        StringBuffer css = new StringBuffer(cssClasses.size() * 10);
        Iterator<String> iterator = cssClasses.iterator();
        while (iterator.hasNext()) {
            css.append(iterator.next());
            if (iterator.hasNext()) {
                css.append(" ");
            }
        }

        out.print("<li class=\"");
        out.print(css.toString());
        out.print("\">");

        if (self) {
            out.println("<strong>");
        }

        String accesskey = null;
        if (child.getNodeData(NODEDATA_ACCESSKEY) != null) {
            accesskey = child.getNodeData(NODEDATA_ACCESSKEY).getString(StringUtils.EMPTY);
        }

        out.print("<a href=\"");
        out.print(((HttpServletRequest) this.pageContext.getRequest()).getContextPath());
        out.print(I18nContentSupportFactory.getI18nSupport().toI18NURI(child.getHandle()));
        out.print(".html\"");

        if (StringUtils.isNotEmpty(accesskey)) {
            out.print(" accesskey=\"");
            out.print(accesskey);
            out.print("\"");
        }

        if (nofollow != null && child.getNodeData(this.nofollow).getBoolean()) {
            out.print(" rel=\"nofollow\"");
        }

        out.print(">");

        if (StringUtils.isNotEmpty(this.wrapperElement)) {
            out.print("<" + this.wrapperElement + ">");
        }

        out.print(StringEscapeUtils.escapeHtml(title));

        if (StringUtils.isNotEmpty(this.wrapperElement)) {
            out.print("</" + this.wrapperElement + ">");
        }

        out.print(" </a>");

        if (self) {
            out.println("</strong>");
        }

        if (showChildren) {
            drawChildren(child, activePage, out);
        }
        out.print("</li>");
    }

    out.print("</ul>");
}

From source file:org.dspace.app.webui.jsptag.ItemListTag.java

public int doStartTag() throws JspException {
    JspWriter out = pageContext.getOut();
    HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest();

    boolean emphasiseDate = false;
    boolean emphasiseTitle = false;

    if (emphColumn != null) {
        emphasiseDate = emphColumn.equalsIgnoreCase("date");
        emphasiseTitle = emphColumn.equalsIgnoreCase("title");
    }//from w  ww .ja v a  2s .co  m

    // get the elements to display
    String configLine = null;
    String widthLine = null;

    if (sortOption != null) {
        if (configLine == null) {
            configLine = ConfigurationManager
                    .getProperty("webui.itemlist.sort." + sortOption.getName() + ".columns");
            widthLine = ConfigurationManager
                    .getProperty("webui.itemlist.sort." + sortOption.getName() + ".widths");
        }

        if (configLine == null) {
            configLine = ConfigurationManager
                    .getProperty("webui.itemlist." + sortOption.getName() + ".columns");
            widthLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".widths");
        }
    }

    if (configLine == null) {
        configLine = ConfigurationManager.getProperty("webui.itemlist.columns");
        widthLine = ConfigurationManager.getProperty("webui.itemlist.widths");
    }

    // Have we read a field configration from dspace.cfg?
    if (configLine != null) {
        // If thumbnails are disabled, strip out any thumbnail column from the configuration
        if (!showThumbs && configLine.contains("thumbnail")) {
            // Ensure we haven't got any nulls
            configLine = configLine == null ? "" : configLine;
            widthLine = widthLine == null ? "" : widthLine;

            // Tokenize the field and width lines
            StringTokenizer llt = new StringTokenizer(configLine, ",");
            StringTokenizer wlt = new StringTokenizer(widthLine, ",");

            StringBuilder newLLine = new StringBuilder();
            StringBuilder newWLine = new StringBuilder();
            while (llt.hasMoreTokens() || wlt.hasMoreTokens()) {
                String listTok = llt.hasMoreTokens() ? llt.nextToken() : null;
                String widthTok = wlt.hasMoreTokens() ? wlt.nextToken() : null;

                // Only use the Field and Width tokens, if the field isn't 'thumbnail'
                if (listTok == null || !listTok.trim().equals("thumbnail")) {
                    if (listTok != null) {
                        if (newLLine.length() > 0) {
                            newLLine.append(",");
                        }

                        newLLine.append(listTok);
                    }

                    if (widthTok != null) {
                        if (newWLine.length() > 0) {
                            newWLine.append(",");
                        }

                        newWLine.append(widthTok);
                    }
                }
            }

            // Use the newly built configuration file
            configLine = newLLine.toString();
            widthLine = newWLine.toString();
        }
    } else {
        configLine = DEFAULT_LIST_FIELDS;
        widthLine = DEFAULT_LIST_WIDTHS;
    }

    // Arrays used to hold the information we will require when outputting each row
    String[] fieldArr = configLine == null ? new String[0] : configLine.split("\\s*,\\s*");
    String[] widthArr = widthLine == null ? new String[0] : widthLine.split("\\s*,\\s*");
    boolean isDate[] = new boolean[fieldArr.length];
    boolean emph[] = new boolean[fieldArr.length];
    boolean isAuthor[] = new boolean[fieldArr.length];
    boolean viewFull[] = new boolean[fieldArr.length];
    String[] browseType = new String[fieldArr.length];
    String[] cOddOrEven = new String[fieldArr.length];

    try {
        // Get the interlinking configuration too
        CrossLinks cl = new CrossLinks();

        // Get a width for the table
        String tablewidth = ConfigurationManager.getProperty("webui.itemlist.tablewidth");

        // If we have column widths, output a fixed layout table - faster for browsers to render
        // but not if we have to add an 'edit item' button - we can't know how big it will be
        if (widthArr.length > 0 && widthArr.length == fieldArr.length && !linkToEdit) {
            // If the table width has been specified, we can make this a fixed layout
            if (!StringUtils.isEmpty(tablewidth)) {
                out.println("<table style=\"width: " + tablewidth
                        + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
            } else {
                // Otherwise, don't constrain the width
                out.println(
                        "<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
            }

            // Output the known column widths
            out.print("<colgroup>");

            for (int w = 0; w < widthArr.length; w++) {
                out.print("<col width=\"");

                // For a thumbnail column of width '*', use the configured max width for thumbnails
                if (fieldArr[w].equals("thumbnail") && widthArr[w].equals("*")) {
                    out.print(thumbItemListMaxWidth);
                } else {
                    out.print(StringUtils.isEmpty(widthArr[w]) ? "*" : widthArr[w]);
                }

                out.print("\" />");
            }

            out.println("</colgroup>");
        } else if (!StringUtils.isEmpty(tablewidth)) {
            out.println("<table width=\"" + tablewidth
                    + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
        } else {
            out.println(
                    "<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
        }

        // Output the table headers
        out.println("<tr>");

        for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) {
            String field = fieldArr[colIdx].toLowerCase().trim();
            cOddOrEven[colIdx] = (((colIdx + 1) % 2) == 0 ? "Odd" : "Even");

            // find out if the field is a date
            if (field.indexOf("(date)") > 0) {
                field = field.replaceAll("\\(date\\)", "");
                isDate[colIdx] = true;
            }

            // Cache any modifications to field
            fieldArr[colIdx] = field;

            // find out if this is the author column
            if (field.equals(authorField)) {
                isAuthor[colIdx] = true;
            }

            // find out if this field needs to link out to other browse views
            if (cl.hasLink(field)) {
                browseType[colIdx] = cl.getLinkType(field);
                viewFull[colIdx] = BrowseIndex.getBrowseIndex(browseType[colIdx]).isItemIndex();
            }

            // find out if we are emphasising this field
            if (field.equals(emphColumn)) {
                emph[colIdx] = true;
            } else if ((field.equals(dateField) && emphasiseDate)
                    || (field.equals(titleField) && emphasiseTitle)) {
                emph[colIdx] = true;
            }

            // prepare the strings for the header
            String id = "t" + Integer.toString(colIdx + 1);
            String css = "oddRow" + cOddOrEven[colIdx] + "Col";
            String message = "itemlist." + field;

            // output the header
            out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[colIdx] ? "<strong>" : "")
                    + LocaleSupport.getLocalizedMessage(pageContext, message)
                    + (emph[colIdx] ? "</strong>" : "") + "</th>");
        }

        if (linkToEdit) {
            String id = "t" + Integer.toString(cOddOrEven.length + 1);
            String css = "oddRow" + cOddOrEven[cOddOrEven.length - 2] + "Col";

            // output the header
            out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[emph.length - 2] ? "<strong>" : "")
                    + "&nbsp;" //LocaleSupport.getLocalizedMessage(pageContext, message)
                    + (emph[emph.length - 2] ? "</strong>" : "") + "</th>");
        }

        out.print("</tr>");

        // now output each item row
        for (int i = 0; i < items.length; i++) {
            // now prepare the XHTML frag for this division
            out.print("<tr>");
            String rOddOrEven;
            if (i == highlightRow) {
                rOddOrEven = "highlight";
            } else {
                rOddOrEven = ((i & 1) == 1 ? "odd" : "even");
            }

            for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) {
                String field = fieldArr[colIdx];

                // get the schema and the element qualifier pair
                // (Note, the schema is not used for anything yet)
                // (second note, I hate this bit of code.  There must be
                // a much more elegant way of doing this.  Tomcat has
                // some weird problems with variations on this code that
                // I tried, which is why it has ended up the way it is)
                StringTokenizer eq = new StringTokenizer(field, ".");

                String[] tokens = { "", "", "" };
                int k = 0;
                while (eq.hasMoreTokens()) {
                    tokens[k] = eq.nextToken().toLowerCase().trim();
                    k++;
                }
                String schema = tokens[0];
                String element = tokens[1];
                String qualifier = tokens[2];

                // first get hold of the relevant metadata for this column
                DCValue[] metadataArray;
                if (qualifier.equals("*")) {
                    metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY);
                } else if (qualifier.equals("")) {
                    metadataArray = items[i].getMetadata(schema, element, null, Item.ANY);
                } else {
                    metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY);
                }

                // save on a null check which would make the code untidy
                if (metadataArray == null) {
                    metadataArray = new DCValue[0];
                }

                // now prepare the content of the table division
                String metadata = "-";
                if (field.equals("thumbnail")) {
                    metadata = getThumbMarkup(hrq, items[i]);
                }
                if (metadataArray.length > 0) {
                    // format the date field correctly
                    if (isDate[colIdx]) {
                        DCDate dd = new DCDate(metadataArray[0].value);
                        metadata = UIUtil.displayDate(dd, false, false, hrq);
                    }
                    // format the title field correctly for withdrawn items (ie. don't link)
                    else if (field.equals(titleField) && items[i].isWithdrawn()) {
                        metadata = Utils.addEntities(metadataArray[0].value);
                    }
                    // format the title field correctly
                    else if (field.equals(titleField)) {
                        metadata = "<a href=\"" + hrq.getContextPath() + "/handle/" + items[i].getHandle()
                                + "\">" + Utils.addEntities(metadataArray[0].value) + "</a>";
                    }
                    // format all other fields
                    else {
                        // limit the number of records if this is the author field (if
                        // -1, then the limit is the full list)
                        boolean truncated = false;
                        int loopLimit = metadataArray.length;
                        if (isAuthor[colIdx]) {
                            int fieldMax = (authorLimit > 0 ? authorLimit : metadataArray.length);
                            loopLimit = (fieldMax > metadataArray.length ? metadataArray.length : fieldMax);
                            truncated = (fieldMax < metadataArray.length);
                            log.debug("Limiting output of field " + field + " to " + Integer.toString(loopLimit)
                                    + " from an original " + Integer.toString(metadataArray.length));
                        }

                        StringBuffer sb = new StringBuffer();
                        for (int j = 0; j < loopLimit; j++) {
                            String startLink = "";
                            String endLink = "";
                            if (!StringUtils.isEmpty(browseType[colIdx]) && !disableCrossLinks) {
                                String argument;
                                String value;
                                if (metadataArray[j].authority != null
                                        && metadataArray[j].confidence >= MetadataAuthorityManager.getManager()
                                                .getMinConfidence(metadataArray[j].schema,
                                                        metadataArray[j].element, metadataArray[j].qualifier)) {
                                    argument = "authority";
                                    value = metadataArray[j].authority;
                                } else {
                                    argument = "value";
                                    value = metadataArray[j].value;
                                }
                                if (viewFull[colIdx]) {
                                    argument = "vfocus";
                                }
                                startLink = "<a href=\"" + hrq.getContextPath() + "/browse?type="
                                        + browseType[colIdx] + "&amp;" + argument + "="
                                        + URLEncoder.encode(value, "UTF-8");

                                if (metadataArray[j].language != null) {
                                    startLink = startLink + "&amp;" + argument + "_lang="
                                            + URLEncoder.encode(metadataArray[j].language, "UTF-8");
                                }

                                if ("authority".equals(argument)) {
                                    startLink += "\" class=\"authority " + browseType[colIdx] + "\">";
                                } else {
                                    startLink = startLink + "\">";
                                }
                                endLink = "</a>";
                            }
                            sb.append(startLink);
                            sb.append(Utils.addEntities(metadataArray[j].value));
                            sb.append(endLink);
                            if (j < (loopLimit - 1)) {
                                sb.append("; ");
                            }
                        }
                        if (truncated) {
                            String etal = LocaleSupport.getLocalizedMessage(pageContext, "itemlist.et-al");
                            sb.append(", ").append(etal);
                        }
                        metadata = "<em>" + sb.toString() + "</em>";
                    }
                }

                // prepare extra special layout requirements for dates
                String extras = "";
                if (isDate[colIdx]) {
                    extras = "nowrap=\"nowrap\" align=\"right\"";
                }

                String id = "t" + Integer.toString(colIdx + 1);
                out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row" + cOddOrEven[colIdx]
                        + "Col\" " + extras + ">" + (emph[colIdx] ? "<strong>" : "") + metadata
                        + (emph[colIdx] ? "</strong>" : "") + "</td>");
            }

            // Add column for 'edit item' links
            if (linkToEdit) {
                String id = "t" + Integer.toString(cOddOrEven.length + 1);

                out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row"
                        + cOddOrEven[cOddOrEven.length - 2] + "Col\" nowrap>" + "<form method=\"get\" action=\""
                        + hrq.getContextPath() + "/tools/edit-item\">"
                        + "<input type=\"hidden\" name=\"handle\" value=\"" + items[i].getHandle() + "\" />"
                        + "<input type=\"submit\" value=\"Edit Item\" /></form>" + "</td>");
            }

            out.println("</tr>");
        }

        // close the table
        out.println("</table>");
    } catch (IOException ie) {
        throw new JspException(ie);
    } catch (BrowseException e) {
        throw new JspException(e);
    }

    return SKIP_BODY;
}

From source file:org.disit.servicemap.api.ServiceMapApi.java

public void queryMunicipalityServices(JspWriter out, RepositoryConnection con, String selection,
        String categorie, String textToSearch, String risultatiBus, String risultatiSensori,
        String risultatiServizi) throws Exception {
    Configuration conf = Configuration.getInstance();
    String sparqlType = conf.get("sparqlType", "virtuoso");
    String km4cVersion = conf.get("km4cVersion", "new");
    List<String> listaCategorie = new ArrayList<>();
    if (categorie != null && !"".equals(categorie)) {
        String[] arrayCategorie = categorie.split(";");
        // GESTIONE CATEGORIE
        listaCategorie = Arrays.asList(arrayCategorie);
    }//from  w  w w . ja  va 2 s  .  c  o m
    String nomeComune = selection.substring(selection.indexOf("COMUNE di") + 10);
    String filtroLocalita = "";
    filtroLocalita += "{ ?ser km4c:hasAccess ?entry . ";
    filtroLocalita += "   ?entry geo:lat ?elat . ";
    filtroLocalita += "    FILTER (?elat>40) ";
    filtroLocalita += "    ?entry geo:long ?elong . ";
    filtroLocalita += "    FILTER (?elong>10) ";
    filtroLocalita += "   ?nc km4c:hasExternalAccess ?entry . ";
    filtroLocalita += "  ?nc km4c:belongToRoad ?road . ";
    filtroLocalita += "  ?road km4c:inMunicipalityOf ?mun . ";
    filtroLocalita += "?mun foaf:name \"" + nomeComune + "\"^^xsd:string . }";
    filtroLocalita += "UNION";
    filtroLocalita += "{";
    filtroLocalita += "?ser km4c:isInRoad ?road . ";
    filtroLocalita += "   ?ser geo:lat ?elat . ";
    filtroLocalita += "    FILTER (?elat>40) ";
    filtroLocalita += "    ?ser geo:long ?elong . ";
    filtroLocalita += "    FILTER (?elong>10) ";
    filtroLocalita += "?road km4c:inMunicipalityOf ?mun . ";
    filtroLocalita += "?mun foaf:name \"" + nomeComune + "\"^^xsd:string . ";
    filtroLocalita += "}";

    String fc = "";
    try {
        fc = ServiceMap.filterServices(listaCategorie);
    } catch (Exception e) {
        e.printStackTrace();
    }
    int b = 0;
    int numeroBus = 0;
    //if (listaCategorie.contains("NearBusStops")) {  OLD
    if (listaCategorie.contains("BusStop")) {
        String queryString = "PREFIX km4c:<http://www.disit.org/km4city/schema#>\n"
                + "PREFIX km4cr:<http://www.disit.org/km4city/resource#>\n"
                + "PREFIX geo:<http://www.w3.org/2003/01/geo/wgs84_pos#>\n"
                + "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>\n"
                + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
                + "PREFIX schema:<http://schema.org/#>\n"
                + "PREFIX omgeo:<http://www.ontotext.com/owlim/geo#>\n"
                + "PREFIX foaf:<http://xmlns.com/foaf/0.1/>\n"
                + "SELECT DISTINCT ?bs ?nomeFermata ?bslat ?bslong ?x WHERE {\n"
                + " ?bs rdf:type km4c:BusStop.\n" + " ?bs foaf:name ?nomeFermata.\n"
                + ServiceMap.textSearchQueryFragment("?bs", "foaf:name", textToSearch)
                //+ " FILTER ( datatype(?nomeFermata ) = xsd:string ).\n"
                + " ?bs geo:lat ?bslat.\n"
                //+ " FILTER (?bslat>40)\n"
                //+ " FILTER ( datatype(?bslat ) = xsd:float )\n"
                + " ?bs geo:long ?bslong.\n"
                //+ " FILTER ( datatype(?bslong ) = xsd:float )\n"
                //+ " FILTER (?bslong>10)\n"
                + " ?bs km4c:isInMunicipality ?com.\n" + " ?com foaf:name \"" + nomeComune + "\"^^xsd:string.\n"
                + "}";
        if (!risultatiBus.equals("0")) {
            queryString += " LIMIT " + risultatiBus;
        }
        TupleQuery tupleQueryBusStop = con.prepareTupleQuery(QueryLanguage.SPARQL,
                filterQuery(queryString, km4cVersion));
        TupleQueryResult resultBS = tupleQueryBusStop.evaluate();
        ServiceMap.logQuery(queryString, "API-fermate", sparqlType, nomeComune + ";" + textToSearch, 0);

        out.println("{\"Fermate\": ");
        out.println("{ " + "\"type\": \"FeatureCollection\", " + "\"features\": [ ");
        while (resultBS.hasNext()) {
            BindingSet bindingSetBS = resultBS.next();
            String valueOfBS = bindingSetBS.getValue("bs").stringValue();
            String valueOfNomeFermata = bindingSetBS.getValue("nomeFermata").stringValue();
            String valueOfBSLat = bindingSetBS.getValue("bslat").stringValue();
            String valueOfBSLong = bindingSetBS.getValue("bslong").stringValue();

            if (b != 0) {
                out.println(", ");
            }

            out.println("{ " + " \"geometry\": {  " + "     \"type\": \"Point\",  " + "    \"coordinates\": [  "
                    + "       " + valueOfBSLong + ",  " + "      " + valueOfBSLat + "  " + " ]  " + "},  "
                    + "\"type\": \"Feature\",  " + "\"properties\": {  " + "    \"nome\": \""
                    + escapeJSON(valueOfNomeFermata) + "\", " + "    \"tipo\": \"fermata\", "
                    + "    \"serviceUri\": \"" + valueOfBS + "\" " + "}, " + "\"id\": "
                    + Integer.toString(b + 1) + "  " + "}");
            b++;
            numeroBus++;
        }
        out.println("]}");
        //if (categorie.equals("NearBusStop")) {
        if (categorie.equals("BusStop")) {
            out.println("}");
        }
    }
    int numeroSensori = 0;
    //if (listaCategorie.contains("RoadSensor")) {
    if (listaCategorie.contains("SensorSite")) {
        String queryStringSensori = "PREFIX km4c:<http://www.disit.org/km4city/schema#> "
                + "PREFIX km4cr:<http://www.disit.org/km4city/resource#>"
                + "PREFIX geo:<http://www.w3.org/2003/01/geo/wgs84_pos#> "
                + "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#> "
                + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
                + "PREFIX schema:<http://schema.org/#>" + "PREFIX dcterms:<http://purl.org/dc/terms/>"
                + "PREFIX dct:<http://purl.org/dc/terms/#>"
                + "PREFIX omgeo:<http://www.ontotext.com/owlim/geo#> "
                + "PREFIX foaf:<http://xmlns.com/foaf/0.1/> "
                + "PREFIX skos:<http://www.w3.org/2004/02/skos/core#>"
                + "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> "
                + "select distinct ?sensor ?idSensore  ?lat ?long ?address ?x where{"
                + "?sensor rdf:type km4c:SensorSite ."
                + ServiceMap.textSearchQueryFragment("?sensor", "?p", textToSearch) + "?sensor geo:lat ?lat ."
                //+ " FILTER regex(str(?lat), \"^4\") ."
                + "?sensor geo:long ?long ." + "?sensor <http://purl.org/dc/terms/identifier> ?idSensore ."
                + "?sensor km4c:placedOnRoad ?road ." + "?road km4c:inMunicipalityOf ?mun ."
                + "?mun foaf:name \"" + nomeComune + "\"^^xsd:string ."
                + "?sensor <http://schema.org/streetAddress> ?address ." + "}";
        if (!risultatiSensori.equals("0")) {

            queryStringSensori += " LIMIT " + risultatiSensori;
        }
        TupleQuery tupleQuerySensori = con.prepareTupleQuery(QueryLanguage.SPARQL,
                filterQuery(queryStringSensori, km4cVersion));
        TupleQueryResult resultSensori = tupleQuerySensori.evaluate();
        ServiceMap.logQuery(queryStringSensori, "API-sensori", sparqlType, nomeComune + ";" + textToSearch, 0);
        //if (!listaCategorie.contains("NearBusStops")) {
        if (!listaCategorie.contains("BusStop")) {
            out.println("{\"Sensori\": ");
        } else {
            out.println(",\"Sensori\":");
        }
        out.println("{ " + "\"type\": \"FeatureCollection\", " + "\"features\": [ ");
        int s = 0;
        while (resultSensori.hasNext()) {
            // out.println(result);
            BindingSet bindingSetSensori = resultSensori.next();
            String valueOfId = bindingSetSensori.getValue("idSensore").stringValue();
            String valueOfIdService = bindingSetSensori.getValue("sensor").stringValue();
            String valueOfLat = bindingSetSensori.getValue("lat").stringValue();

            String valueOfLong = bindingSetSensori.getValue("long").stringValue();
            String valueOfAddress = bindingSetSensori.getValue("address").stringValue();

            if (s != 0) {
                out.println(", ");
            }

            out.println("{ " + " \"geometry\": {  " + "     \"type\": \"Point\",  " + "    \"coordinates\": [  "
                    + "       " + valueOfLong + ",  " + "      " + valueOfLat + "  " + " ]  " + "},  "
                    + "\"type\": \"Feature\",  " + "\"properties\": {  " + "    \"nome\": \""
                    + escapeJSON(valueOfId) + "\", " + "    \"tipo\": \"sensore\", " + "    \"serviceUri\": \""
                    + valueOfIdService + "\", " + "    \"indirizzo\": \"" + escapeJSON(valueOfAddress) + "\" "
                    + "},  " + "\"id\": " + Integer.toString(s + 1) + "  " + "}");

            s++;
            numeroSensori++;

        }
        out.println("]}");
        //if (categorie.equals("RoadSensor") || categorie.equals("RoadSensor;NearBusStops")) {
        if (categorie.equals("SensorSite") || categorie.equals("SensorSite;BusStop")) {
            out.println("}");
        }
    }
    int numeroServizi = 0;
    //if (!categorie.equals("NearBusStops") && !categorie.equals("RoadSensor") && !categorie.equals("RoadSensor;NearBusStops") && !categorie.equals("NearBusStops;RoadSensor")) {
    if (!categorie.equals("BusStop") && !categorie.equals("SensorSite")
            && !categorie.equals("SensorSite;BusStop") && !categorie.equals("BusStop;SensorSite")) {
        String queryStringServices = "PREFIX km4c:<http://www.disit.org/km4city/schema#>\n"
                + "PREFIX km4cr:<http://www.disit.org/km4city/resource#>\n"
                + "PREFIX geo:<http://www.w3.org/2003/01/geo/wgs84_pos#>\n"
                + "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>\n"
                + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
                + "PREFIX schema:<http://schema.org/>\n" + "PREFIX dcterms:<http://purl.org/dc/terms/>\n"
                + "PREFIX dc:<http://purl.org/dc/elements/1.1/>\n"
                + "PREFIX omgeo:<http://www.ontotext.com/owlim/geo#>\n"
                + "PREFIX foaf:<http://xmlns.com/foaf/0.1/>\n"
                + "PREFIX skos:<http://www.w3.org/2004/02/skos/core#>\n"
                + "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n"
                + "SELECT distinct ?ser ?serAddress ?serNumber ?elat ?elong ?sName ?sType ?email ?note ?labelIta ?multimedia ?description ?identifier WHERE {\n"
                + " ?ser rdf:type km4c:Service"
                + (sparqlType.equals("virtuoso") ? " OPTION (inference \"urn:ontology\")" : "") + ".\n"
                + " OPTIONAL{?ser schema:name ?sName. }\n" + " ?ser schema:streetAddress ?serAddress.\n"
                + " OPTIONAL {?ser km4c:houseNumber ?serNumber}.\n"
                + " OPTIONAL {?ser dc:description ?description FILTER(LANG(?description) = \"it\")}\n"
                + " OPTIONAL {?ser km4c:multimediaResource ?multimedia }\n"
                + " OPTIONAL { ?ser dcterms:identifier ?identifier }\n" + " OPTIONAL {?ser skos:note ?note }\n"
                + " OPTIONAL {?ser schema:email ?email }\n"
                + ServiceMap.textSearchQueryFragment("?ser", "?p", textToSearch) + filtroLocalita + fc
                + " ?ser a ?sType. FILTER(?sType!=km4c:RegularService && ?sType!=km4c:Service && ?sType!=km4c:DigitalLocation && ?sType!=km4c:TransverseService)\n"
                + " ?sType rdfs:label ?labelIta. FILTER(LANG(?labelIta)=\"it\")\n" + "}";
        if (!risultatiServizi.equals("0")) {
            queryStringServices += " LIMIT " + risultatiServizi;
        }
        TupleQuery tupleQueryServices = con.prepareTupleQuery(QueryLanguage.SPARQL,
                filterQuery(queryStringServices, km4cVersion));
        TupleQueryResult resultServices = tupleQueryServices.evaluate();
        ServiceMap.logQuery(queryStringServices, "API-servizi", sparqlType,
                nomeComune + ";" + textToSearch + ";" + categorie, 0);

        //if (!listaCategorie.contains("NearBusStops") && !listaCategorie.contains("RoadSensor")) {
        if (!listaCategorie.contains("BusStop") && !listaCategorie.contains("SensorSite")) {
            out.println("{\"Servizi\": ");
        } else {
            out.println(", \"Servizi\": ");
        }
        out.println("{ " + "\"type\": \"FeatureCollection\", " + "\"features\": [ ");

        int t = 0;
        while (resultServices.hasNext()) {
            BindingSet bindingSetServices = resultServices.next();
            String valueOfSer = bindingSetServices.getValue("ser").stringValue();
            String valueOfSName = "";
            if (bindingSetServices.getValue("sName") != null) {
                valueOfSName = bindingSetServices.getValue("sName").stringValue();
            }
            String valueOfSerAddress = bindingSetServices.getValue("serAddress").stringValue();
            String valueOfSerNumber = "";
            if (bindingSetServices.getValue("serNumber") != null) {
                valueOfSerNumber = bindingSetServices.getValue("serNumber").stringValue();
            }
            String valueOfSType = bindingSetServices.getValue("sType").stringValue();
            String valueOfSTypeIta = "";
            if (bindingSetServices.getValue("labelIta") != null) {
                valueOfSTypeIta = bindingSetServices.getValue("labelIta").stringValue();
            }
            String valueOfELat = bindingSetServices.getValue("elat").stringValue();
            String valueOfELong = bindingSetServices.getValue("elong").stringValue();
            String valueOfNote = "";
            if (bindingSetServices.getValue("note") != null) {
                valueOfNote = bindingSetServices.getValue("note").stringValue();
            }

            String valueOfEmail = "";
            if (bindingSetServices.getValue("email") != null) {
                valueOfEmail = bindingSetServices.getValue("email").stringValue();
            }

            //valueOfSTypeIta = Character.toLowerCase(valueOfSTypeIta.charAt(0)) + valueOfSTypeIta.substring(1);
            valueOfSTypeIta = valueOfSTypeIta.replace(" ", "_");
            valueOfSTypeIta = valueOfSTypeIta.replace("'", "");

            Normalizer.normalize(valueOfNote, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
            valueOfNote = valueOfNote.replaceAll("[^A-Za-z0-9 ]+", "");

            valueOfEmail = valueOfEmail.replace("\"^^<http://www.w3.org/2001/XMLSchema#string>", "");
            valueOfEmail = valueOfEmail.replace("\"", "");

            if (t != 0) {
                out.println(", ");
            }
            out.println("{ " + " \"geometry\": {  " + "     \"type\": \"Point\",  " + "    \"coordinates\": [  "
                    + "       " + valueOfELong + ",  " + "      " + valueOfELat + "  " + " ]  " + "},  "
                    + "\"type\": \"Feature\",  " + "\"properties\": {  " + "    \"nome\": \""
                    + escapeJSON(valueOfSName) + "\", " + "    \"tipo\": \"" + escapeJSON(valueOfSTypeIta)
                    + "\", " + "    \"email\": \"" + valueOfEmail + "\", " + "    \"note\": \""
                    + escapeJSON(valueOfNote) + "\", " + "    \"serviceUri\": \"" + valueOfSer + "\", "
                    + "    \"indirizzo\": \"" + escapeJSON(valueOfSerAddress) + "\", \"numero\": \""
                    + escapeJSON(valueOfSerNumber) + "\" " + "}, " + "\"id\": " + Integer.toString(t + 1) + "  "
                    + "}");
            t++;
            numeroServizi++;
        }
        out.println("]}}");
    }
}

From source file:org.disit.servicemap.api.ServiceMapApi.java

public void queryService(JspWriter out, RepositoryConnection con, String idService) throws Exception {
    Configuration conf = Configuration.getInstance();
    String sparqlType = conf.get("sparqlType", "virtuoso");
    String km4cVersion = conf.get("km4cVersion", "new");
    int i = 0;/*from   w  w w  .  j a v  a 2  s  .co  m*/
    String queryService = "PREFIX km4c:<http://www.disit.org/km4city/schema#> "
            + "PREFIX km4cr:<http://www.disit.org/km4city/resource#>"
            + "PREFIX geo:<http://www.w3.org/2003/01/geo/wgs84_pos#> "
            + "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#> "
            + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "PREFIX schema:<http://schema.org/>"
            //+ "PREFIX omgeo:<http://www.ontotext.com/owlim/geo#> "
            //+ "PREFIX foaf:<http://xmlns.com/foaf/0.1/> "
            + "PREFIX skos:<http://www.w3.org/2004/02/skos/core#>"
            //+ "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> "
            + "PREFIX dcterms:<http://purl.org/dc/terms/>"
            + "SELECT ?serAddress ?serNumber ?elat ?elong ?sName ?sType ?type ?sCategory ?sTypeIta ?email ?note ?multimedia ?descriptionEng ?descriptionIta ?phone ?fax ?website ?prov ?city ?cap WHERE{"
            + " {" + "  <" + idService + "> km4c:hasAccess ?entry ." + "  ?entry geo:lat ?elat . "
            //+ "  FILTER (?elat>40) "
            + "  ?entry geo:long ?elong . "
            //+ "  FILTER (?elong>10) ."
            + " }UNION{" + "  <" + idService + "> km4c:isInRoad ?road." + "  <" + idService + "> geo:lat ?elat."
            //+ "  FILTER (?elat>40) "
            + "  <" + idService + "> geo:long ?elong."
            //+ "  FILTER (?elong>10) ."
            + " }UNION{" + "  <" + idService + "> geo:lat ?elat."
            //+ "  FILTER (?elat>40) "
            + "  <" + idService + "> geo:long ?elong."
            //+ "  FILTER (?elong>10) ."
            + " }" + "   OPTIONAL {<" + idService + "> schema:name ?sName.}" + "   OPTIONAL { <" + idService
            + "> schema:streetAddress ?serAddress.}"
            + (km4cVersion.equals("old")
                    ? " <" + idService + "> km4c:hasServiceCategory ?cat ." + " ?cat rdfs:label ?nome . "
                            + " BIND (?nome  AS ?sType) ." + " BIND (?nome  AS ?sTypeIta) ."
                            + " FILTER(LANG(?nome) = \"it\") ." + " OPTIONAL {<" + idService
                            + "> <http://purl.org/dc/elements/1.1/description> ?description ."
                            + " FILTER(LANG(?description) = \"it\")} ."
                    : " <" + idService + "> a ?type . FILTER(?type!=km4c:RegularService && ?type!=km4c:Service)"
                            + " ?type rdfs:label ?nome . " + " ?type rdfs:subClassOf ?sCategory. "
                            + " BIND (?nome  AS ?sType) ." + " BIND (?nome  AS ?sTypeIta) ."
                            + " FILTER(LANG(?nome) = \"it\") .")
            + "   OPTIONAL {<" + idService + "> km4c:houseNumber ?serNumber} ." + "   OPTIONAL {<" + idService
            + "> dcterms:description ?descriptionIta"
            //+ " FILTER(LANG(?descriptionEng) = \"en\")"
            + "}" + "   OPTIONAL {<" + idService
            + "> dcterms:description ?descriptionEng FILTER(?descriptionEng!=?descriptionIta)"
            //+ " FILTER(LANG(?descriptionIta) = \"it\")"
            + "}" + "   OPTIONAL {<" + idService + "> km4c:multimediaResource ?multimedia} ." + "   OPTIONAL {<"
            + idService + "> skos:note ?note} . " + "   OPTIONAL {<" + idService + "> schema:email ?email } . "
            // AGGIUNTA CAMPI DA VISUALIZZARE NELLA SCHEDA
            + " OPTIONAL {<" + idService + "> schema:faxNumber ?fax }" + " OPTIONAL {<" + idService
            + "> schema:telephone ?phone }" + " OPTIONAL {<" + idService + "> schema:addressRegion ?prov }"
            + " OPTIONAL {<" + idService + "> schema:addressLocality ?city }" + " OPTIONAL {<" + idService
            + "> schema:postalCode ?cap }" + " OPTIONAL {<" + idService + "> schema:url ?website }"
            // ---- FINE CAMPI AGGIUNTI ---
            + "}LIMIT 1";
    // out.println("count = "+count);
    String queryDBpedia = "PREFIX km4c:<http://www.disit.org/km4city/schema#>\n"
            + "PREFIX cito:<http://purl.org/spar/cito/>\n" + "SELECT ?linkDBpedia WHERE{\n" + " OPTIONAL {<"
            + idService + "> km4c:isInRoad ?road.\n" + "?road cito:cites ?linkDBpedia.}\n" + "}";

    out.println("{ \"Service\":" + "{\"type\": \"FeatureCollection\", " + "\"features\": [ ");
    TupleQuery tupleQueryService = con.prepareTupleQuery(QueryLanguage.SPARQL, queryService);
    TupleQueryResult resultService = tupleQueryService.evaluate();
    String TOS = "";
    String NOS = "";
    TupleQuery tupleQueryDBpedia = con.prepareTupleQuery(QueryLanguage.SPARQL, queryDBpedia);
    TupleQueryResult resultDBpedia = tupleQueryDBpedia.evaluate();
    String valueOfDBpedia = "[";

    while (resultService.hasNext()) {
        BindingSet bindingSetService = resultService.next();
        while (resultDBpedia.hasNext()) {

            BindingSet bindingSetDBpedia = resultDBpedia.next();
            if (bindingSetDBpedia.getValue("linkDBpedia") != null) {
                if (!("[".equals(valueOfDBpedia))) {
                    valueOfDBpedia = valueOfDBpedia + ", \""
                            + bindingSetDBpedia.getValue("linkDBpedia").stringValue() + "\"";
                } else {
                    valueOfDBpedia = valueOfDBpedia + "\""
                            + bindingSetDBpedia.getValue("linkDBpedia").stringValue() + "\"";
                }
            }
        }
        valueOfDBpedia = valueOfDBpedia + "]";
        String valueOfSerAddress = "";
        if (bindingSetService.getValue("serAddress") != null) {
            valueOfSerAddress = bindingSetService.getValue("serAddress").stringValue();
        }
        String valueOfSerNumber = "";
        if (bindingSetService.getValue("serNumber") != null) {
            valueOfSerNumber = bindingSetService.getValue("serNumber").stringValue();
        }

        String valueOfSType = bindingSetService.getValue("sType").stringValue();
        String valueOfSTypeIta = "";
        if (bindingSetService.getValue("sTypeIta") != null) {
            valueOfSTypeIta = bindingSetService.getValue("sTypeIta").stringValue();
        }

        // DICHIARAZIONE VARIABILI serviceType e serviceCategory per ICONA
        String subCategory = "";
        if (bindingSetService.getValue("type") != null) {
            subCategory = bindingSetService.getValue("type").stringValue();
            subCategory = subCategory.replace("http://www.disit.org/km4city/schema#", "");
            //subCategory = Character.toLowerCase(subCategory.charAt(0)) + subCategory.substring(1);
            //subCategory = subCategory.replace(" ", "_");
        }

        String category = "";
        if (bindingSetService.getValue("sCategory") != null) {
            category = bindingSetService.getValue("sCategory").stringValue();
            category = category.replace("http://www.disit.org/km4city/schema#", "");
            //category = Character.toLowerCase(category.charAt(0)) + category.substring(1);
            //category = category.replace(" ", "_");
        }

        String serviceType = category + "_" + subCategory;

        // controllo del Nome per i Geolocated Object
        String valueOfSName = "";
        if (bindingSetService.getValue("sName") != null) {
            valueOfSName = bindingSetService.getValue("sName").stringValue();
        } else {
            valueOfSName = subCategory.replace("_", " ").toUpperCase();
        }
        String valueOfELat = bindingSetService.getValue("elat").stringValue();
        String valueOfELong = bindingSetService.getValue("elong").stringValue();
        String valueOfNote = "";
        if (bindingSetService.getValue("note") != null) {
            valueOfNote = bindingSetService.getValue("note").stringValue();
        }

        String valueOfEmail = "";
        if (bindingSetService.getValue("email") != null) {
            valueOfEmail = bindingSetService.getValue("email").stringValue();
        }
        String valueOfMultimediaResource = "";
        if (bindingSetService.getValue("multimedia") != null) {
            valueOfMultimediaResource = bindingSetService.getValue("multimedia").stringValue();
        }
        String valueOfDescriptionIta = "";
        if (bindingSetService.getValue("descriptionIta") != null) {
            valueOfDescriptionIta = bindingSetService.getValue("descriptionIta").stringValue();
        }
        String valueOfDescriptionEng = "";
        if (bindingSetService.getValue("descriptionEng") != null) {
            valueOfDescriptionEng = bindingSetService.getValue("descriptionEng").stringValue();
        }
        //AGGIUNTA CAMPI DA VISUALIZZARE SU SCHEDA
        String valueOfFax = "";
        if (bindingSetService.getValue("fax") != null) {
            valueOfFax = bindingSetService.getValue("fax").stringValue();
        }
        String valueOfPhone = "";
        if (bindingSetService.getValue("phone") != null) {
            valueOfPhone = bindingSetService.getValue("phone").stringValue();
        }
        String valueOfProv = "";
        if (bindingSetService.getValue("prov") != null) {
            valueOfProv = bindingSetService.getValue("prov").stringValue();
        }
        String valueOfCity = "";
        if (bindingSetService.getValue("city") != null) {
            valueOfCity = bindingSetService.getValue("city").stringValue();
        }
        String valueOfUrl = "";
        if (bindingSetService.getValue("website") != null) {
            valueOfUrl = bindingSetService.getValue("website").stringValue();
        }
        String valueOfCap = "";
        if (bindingSetService.getValue("cap") != null) {
            valueOfCap = bindingSetService.getValue("cap").stringValue();
        }

        // ---- FINE AGGIUNTA ---
        NOS = valueOfSName;

        //valueOfSTypeIta = Character.toLowerCase(valueOfSTypeIta.charAt(0)) + valueOfSTypeIta.substring(1);
        valueOfSTypeIta = valueOfSTypeIta.replace(" ", "_");
        valueOfSTypeIta = valueOfSTypeIta.replace("@it", "");
        TOS = valueOfSTypeIta;

        Normalizer.normalize(valueOfNote, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");
        valueOfNote = valueOfNote.replaceAll("[^A-Za-z0-9 ]+", "");

        if (i != 0) {
            out.println(", ");
        }

        out.println("{ " + " \"geometry\": {  " + "     \"type\": \"Point\",  " + "    \"coordinates\": [  "
                + "       " + valueOfELong + ",  " + "      " + valueOfELat + "  " + " ]  " + "},  "
                + "\"type\": \"Feature\",  " + "\"properties\": {  " + "    \"nome\": \""
                + escapeJSON(valueOfSName) + "\", " + "    \"tipo\": \"" + TOS + "\", "
                // *** INSERIMENTO serviceType
                + "    \"serviceType\": \"" + escapeJSON(mapServiceType(serviceType)) + "\", "
                + "    \"phone\": \"" + valueOfPhone + "\", " + "    \"fax\": \"" + valueOfFax + "\", "
                + "    \"website\": \"" + valueOfUrl + "\", " + "    \"province\": \"" + valueOfProv + "\", "
                + "    \"city\": \"" + valueOfCity + "\", " + "    \"cap\": \"" + valueOfCap + "\", "
                // **********************************************
                + "    \"email\": \"" + escapeJSON(valueOfEmail) + "\", " + "    \"linkDBpedia\": "
                + valueOfDBpedia + ", " + "    \"note\": \"" + escapeJSON(valueOfNote) + "\", "
                + "    \"description\": \"" + escapeJSON(valueOfDescriptionIta) + "\", "
                + "    \"description2\": \"" + escapeJSON(valueOfDescriptionEng) + "\", "
                + "    \"multimedia\": \"" + valueOfMultimediaResource + "\", " + "    \"serviceUri\": \""
                + idService + "\", " + "    \"indirizzo\": \"" + valueOfSerAddress + "\", \"numero\": \""
                + valueOfSerNumber + "\" " + "}, " + "\"id\": " + Integer.toString(i + 1) + "  " + "}");
        i++;
    }
    out.println("] }");
    if ("Parcheggio_auto".equals(TOS)) {
        String queryStringParkingStatus = "  PREFIX km4c:<http://www.disit.org/km4city/schema#>"
                + "PREFIX km4cr:<http://www.disit.org/km4city/resource#>"
                + "PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>"
                + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
                + "PREFIX schema:<http://schema.org/#>" + "PREFIX time:<http://www.w3.org/2006/time#>"
                + "SELECT distinct ?situationRecord ?instantDateTime ?occupancy ?free ?occupied ?capacity ?cpStatus WHERE { "
                + "   ?cps km4c:observeCarPark <" + idService + ">." + "   ?cps km4c:capacity ?capacity."
                + "   ?situationRecord km4c:relatedToSensor ?cps."
                + "   ?situationRecord km4c:observationTime ?time."
                + "   ?time <http://purl.org/dc/terms/identifier> ?instantDateTime."
                + "   ?situationRecord km4c:parkOccupancy ?occupancy." + "   ?situationRecord km4c:free ?free."
                + "   ?situationRecord km4c:carParkStatus ?cpStatus."
                + "   ?situationRecord km4c:occupied ?occupied." + "} ORDER BY DESC (?instantDateTime) LIMIT 1";
        TupleQuery tupleQueryParking = con.prepareTupleQuery(QueryLanguage.SPARQL, queryStringParkingStatus);
        TupleQueryResult resultParkingStatus = tupleQueryParking.evaluate();
        out.println(",\"realtime\": ");
        if (resultParkingStatus.hasNext()) {
            out.println("{ \"head\": {" + "\"parcheggio\":[ " + "\"" + NOS + "\"" + "]," + "\"vars\":[ "
                    + "\"Capacit\", " + "\"PostiLiberi\"," + "\"PostiOccupati\"," + "\"Occupazione\","
                    + "\"Aggiornamento\"" + "]" + "},");
            out.println("\"results\": {");
            out.println("\"bindings\": [");

            int p = 0;
            while (resultParkingStatus.hasNext()) {
                BindingSet bindingSetParking = resultParkingStatus.next();

                String valueOfInstantDateTime = "";
                if (bindingSetParking.getValue("instantDateTime") != null) {
                    valueOfInstantDateTime = bindingSetParking.getValue("instantDateTime").stringValue();
                }
                String valueOfOccupancy = "";
                if (bindingSetParking.getValue("occupancy") != null) {
                    valueOfOccupancy = bindingSetParking.getValue("occupancy").stringValue();
                }
                String valueOfFree = "";
                if (bindingSetParking.getValue("free") != null) {
                    valueOfFree = bindingSetParking.getValue("free").stringValue();
                }
                String valueOfOccupied = "";
                if (bindingSetParking.getValue("occupied") != null) {
                    valueOfOccupied = bindingSetParking.getValue("occupied").stringValue();
                }
                String valueOfCapacity = "";
                if (bindingSetParking.getValue("capacity") != null) {
                    valueOfCapacity = bindingSetParking.getValue("capacity").stringValue();
                }
                String valueOfcpStatus = "";
                if (bindingSetParking.getValue("cpStatus") != null) {
                    valueOfcpStatus = bindingSetParking.getValue("cpStatus").stringValue();
                }

                if (p != 0) {
                    out.println(", ");
                }

                out.println("{" + "\"Capacit\": {" + "\"value\": \"" + valueOfCapacity + "\" " + " },"
                        + "\"PostiLiberi\": { " + "\"value\": \"" + valueOfFree + "\" " + " },"
                        + "\"PostiOccupati\": {" + "\"value\": \"" + valueOfOccupied + "\" " + " },"
                        + "\"Occupazione\": {" + "\"value\": \"" + valueOfOccupancy + "\" " + " },"
                        + "\"Stato\": {" + "\"value\": \"" + valueOfcpStatus + "\" " + " },"
                        + "\"Aggiornamento\": {" + "\"value\": \"" + valueOfInstantDateTime + "\" " + " }");
                out.println("}");
                p++;
            }
            out.println("]}}}");
        } else {
            out.println("{}}");
        }
    } else {
        out.println("}");
    }
}

From source file:org.dspace.app.webui.jsptag.AccessSettingTag.java

public int doStartTag() throws JspException {
    String legend = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.legend");
    String label_name = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.label_name");
    String label_group = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.label_group");
    String label_embargo = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.label_embargo");
    String label_date = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.label_date");
    String radio0 = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.radio0");
    String radio1 = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.radio1");
    String radio_help = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.radio_help");
    String label_reason = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.label_reason");
    String button_confirm = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.button_confirm");

    String help_name = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.name_help");
    String help_reason = LocaleSupport.getLocalizedMessage(pageContext,
            "org.dspace.app.webui.jsptag.access-setting.reason_help");

    JspWriter out = pageContext.getOut();
    StringBuffer sb = new StringBuffer();

    try {//from   ww  w.java  2 s  .c om
        HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest();
        Context context = UIUtil.obtainContext(hrq);

        // get startDate and reason of the resource policy of the target DSpaceObject
        List<ResourcePolicy> policies = null;
        if (!advanced && dso != null) {
            policies = AuthorizeManager.findPoliciesByDSOAndType(context, dso, ResourcePolicy.TYPE_CUSTOM);
        } else if (rp != null) {
            policies = new ArrayList<ResourcePolicy>();
            policies.add(rp);
        }

        String name = "";
        int group_id = 0;
        String startDate = "";
        String reason = "";
        String radio0Checked = " checked=\"checked\"";
        String radio1Checked = "";
        String disabled = " disabled=\"disabled\"";
        if (policies != null && policies.size() > 0) {
            ResourcePolicy rp = policies.get(0);
            name = (rp.getRpName() == null ? "" : rp.getRpName());
            group_id = rp.getGroup().getID();
            startDate = (rp.getStartDate() != null ? DateFormatUtils.format(rp.getStartDate(), "yyyy-MM-dd")
                    : "");
            reason = (rp.getRpDescription() == null ? "" : rp.getRpDescription());
            if (!startDate.equals("")) {
                radio0Checked = "";
                radio1Checked = " checked=\"checked\"";
                disabled = "";
            }
        }

        // if advanced embargo is disabled, embargo date and reason fields are always enabled
        if (!advanced) {
            disabled = "";
        }

        if (embargo) {
            // Name
            sb.append("<div class=\"form-group\">");
            sb.append(label_name).append("\n");
            sb.append("<p class=\"help-block\">").append(help_name).append("</p>").append("\n");
            sb.append(
                    "<input class=\"form-control\" name=\"name\" id=\"policy_name\" type=\"text\" maxlength=\"30\" value=\"")
                    .append(name).append("\" />\n");
            sb.append("</div>");

            // Group
            sb.append("<div class=\"form-group\">");
            sb.append(label_group).append("\n");
            sb.append("<select class=\"form-control\" name=\"group_id\" id=\"select_group\">\n");

            Group[] groups = getGroups(context, hrq, subInfo);
            if (groups != null) {
                for (Group group : groups) {
                    sb.append("<option value=\"").append(group.getID()).append("\"");
                    if (group_id == group.getID()) {
                        sb.append(" selected=\"selected\"");
                    }
                    sb.append(">").append(group.getName()).append("</option>\n");
                }
            } else {
                sb.append("<option value=\"0\" selected=\"selected\">Anonymous</option>\n");
            }
            sb.append("</select>\n");
            sb.append("</div>");
            // Select open or embargo
            sb.append(label_embargo).append("\n");
            sb.append("<div class=\"radio\">");
            sb.append("<label><input name=\"open_access_radios\" type=\"radio\" value=\"0\"")
                    .append(radio0Checked).append(" />").append(radio0).append("</label>\n");
            sb.append("</div>");
            sb.append("<div class=\"radio\">");
            sb.append("<label><input name=\"open_access_radios\" type=\"radio\" value=\"1\"")
                    .append(radio1Checked).append(" />").append(radio1).append("</label>\n");
            sb.append("</div>");

        }

        // Embargo Date
        if (hidden) {
            sb.append(
                    "<input name=\"embargo_until_date\" id=\"embargo_until_date_hidden\" type=\"hidden\" value=\"")
                    .append(startDate).append("\" />\n");
            ;
            sb.append("<input name=\"reason\" id=\"reason_hidden\" type=\"hidden\" value=\"").append(reason)
                    .append("\" />\n");
        } else {
            sb.append("<div class=\"form-group col-md-12\">");
            sb.append("<div class=\"col-md-2\">");
            sb.append(label_date);
            sb.append("</div>");
            sb.append("<div class=\"col-md-2\">");
            sb.append(
                    "<input class=\"form-control\" name=\"embargo_until_date\" id=\"embargo_until_date\" maxlength=\"10\" size=\"10\" type=\"text\" value=\"")
                    .append(startDate).append("\"").append(disabled).append(" />\n");
            sb.append("</div>");
            sb.append("<div class=\"col-md-8\">");
            sb.append("<span class=\"help-block\">" + radio_help + "</span>");
            sb.append("</div>");
            sb.append("</div>");
            // Reason                
            sb.append("<div class=\"form-group col-md-12\">");
            sb.append("<div class=\"col-md-12\">");
            sb.append(label_reason).append("\n");
            sb.append("</div>");
            sb.append("<div class=\"col-md-12\">");
            sb.append("<p class=\"help-block\">").append(help_reason).append("</p>").append("\n");
            sb.append("</div>");
            sb.append("<div class=\"col-md-12\">");
            sb.append("<textarea class=\"form-control\" name=\"reason\" id=\"reason\" cols=\"30\" rows=\"5\"")
                    .append(disabled).append(">").append(reason).append("</textarea>\n");
            sb.append("</div>");
            sb.append("</div>");
        }

        // Add policy button
        if (addpolicy) {

            sb.append(
                    "<input class=\"btn btn-success col-md-offset-5\" name=\"submit_add_policy\" type=\"submit\" value=\"")
                    .append(button_confirm).append("\" />\n");

        }

        out.println(sb.toString());
    } catch (IOException ie) {
        throw new JspException(ie);
    } catch (SQLException e) {
        throw new JspException(e);
    }

    return SKIP_BODY;
}

From source file:org.apache.jsp.fileUploader_jsp.java

public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;//  w  w  w  .  j  av a  2  s  .c om
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=utf-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("<!--\n");
        out.write("Copyright 2012 The Infinit.e Open Source Project\n");
        out.write("\n");
        out.write("Licensed under the Apache License, Version 2.0 (the \"License\");\n");
        out.write("you may not use this file except in compliance with the License.\n");
        out.write("You may obtain a copy of the License at\n");
        out.write("\n");
        out.write("  http://www.apache.org/licenses/LICENSE-2.0\n");
        out.write("\n");
        out.write("Unless required by applicable law or agreed to in writing, software\n");
        out.write("distributed under the License is distributed on an \"AS IS\" BASIS,\n");
        out.write("WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n");
        out.write("See the License for the specific language governing permissions and\n");
        out.write("limitations under the License.\n");
        out.write("-->\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
        out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
        out.write("<head>\n");
        out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n");
        out.write("<title>Infinit.e File Upload Tool</title>\n");
        out.write("<style media=\"screen\" type=\"text/css\">\n");
        out.write("\n");
        out.write("body \n");
        out.write("{\n");
        out.write("\tfont: 14px Arial,sans-serif;\n");
        out.write("}\n");
        out.write("h2\n");
        out.write("{\n");
        out.write("\tfont-family: \"Times New Roman\";\n");
        out.write("\tfont-style: italic;\n");
        out.write("\tfont-variant: normal;\n");
        out.write("\tfont-weight: normal;\n");
        out.write("\tfont-size: 24px;\n");
        out.write("\tline-height: 29px;\n");
        out.write("\tfont-size-adjust: none;\n");
        out.write("\tfont-stretch: normal;\n");
        out.write("\t-x-system-font: none;\n");
        out.write("\tcolor: #d2331f;\n");
        out.write("\tmargin-bottom: 25px;\n");
        out.write("}\n");
        out.write(".show {\n");
        out.write("display: ;\n");
        out.write("visibility: visible;\n");
        out.write("}\n");
        out.write(".hide {\n");
        out.write("display: none;\n");
        out.write("visibility: hidden;\n");
        out.write("}\n");
        out.write("</style>\n");
        out.write("<script language=\"javascript\" src=\"AppConstants.js\"> </script>\n");
        out.write("</head>\n");
        out.write("\n");
        out.write("<body onload=\"populate()\">\n");

        if (API_ROOT == null) {
            ServletContext context = session.getServletContext();
            String realContextPath = context.getRealPath("/");
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("javascript");
            try { // EC2 Machines
                FileReader reader = new FileReader(realContextPath + "/AppConstants.js");
                engine.eval(reader);
                reader.close();
                engine.eval("output = getEndPointUrl();");
                API_ROOT = (String) engine.get("output");
                SHARE_ROOT = API_ROOT + "share/get/";
            } catch (Exception je) {
                try { ////////////Windows + Tomcat
                    FileReader reader = new FileReader(realContextPath + "\\..\\AppConstants.js");
                    engine.eval(reader);
                    reader.close();
                    engine.eval("output = getEndPointUrl();");
                    API_ROOT = (String) engine.get("output");
                    SHARE_ROOT = API_ROOT + "share/get/";
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
            if (null == API_ROOT) {
                // Default to localhost
                API_ROOT = "http://localhost:8080/api/";
                SHARE_ROOT = "$infinite/share/get/";
            }

            if (API_ROOT.contains("localhost"))
                localCookie = true;
            else
                localCookie = false;
        }
        Boolean isLoggedIn = isLoggedIn(request, response);
        if (isLoggedIn == null) {
            out.println("The Infinit.e API cannot be reached.");
            out.println(API_ROOT);
        }

        else if (isLoggedIn == true) {
            showAll = (request.getParameter("sudo") != null);
            DEBUG_MODE = (request.getParameter("debug") != null);
            communityList = generateCommunityList(request, response);

            if (request.getParameter("logout") != null) {
                logOut(request, response);
                out.println("<div style=\" text-align: center;\">");
                out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                out.println("</div>");
            } else {

                out.println("<div style=\" text-align: center;\">");
                String contentType = request.getContentType();
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                    //      Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                    //      Parse the request
                    FileItemIterator iter = upload.getItemIterator(request);
                    byte[] fileBytes = null;
                    String fileDS = null;
                    byte[] iconBytes = null;
                    String iconDS = null;
                    Set<String> communities = new HashSet<String>();
                    boolean isFileSet = false;
                    while (iter.hasNext()) {
                        FileItemStream item = iter.next();
                        String name = item.getFieldName();
                        InputStream stream = item.openStream();
                        if (item.isFormField()) {
                            if (name.equalsIgnoreCase("communities")) {
                                communities.add(Streams.asString(stream));
                            } else
                                request.setAttribute(name, Streams.asString(stream));

                            //out.println("<b>" + name + ":</b>" + request.getAttribute(name).toString()+"</br>");
                        } else {
                            if (name.equalsIgnoreCase("file")) {
                                if (!item.getName().equals(""))
                                    isFileSet = true;
                                fileDS = item.getContentType();
                                fileBytes = IOUtils.toByteArray(stream);

                                // Check if this should be a java-archive (rather than just an octet stream)
                                if (fileDS.equals("application/octet-stream")) {
                                    ZipInputStream zis = new ZipInputStream(
                                            new ByteArrayInputStream(fileBytes));
                                    ZipEntry entry;
                                    while ((entry = zis.getNextEntry()) != null) {
                                        if (entry.getName().endsWith(".class")) {
                                            fileDS = "application/java-archive";
                                            break;
                                        }
                                    }
                                }
                                // Reset stream, and read
                            }
                        }
                    }

                    ////////////////////////////////////Delete Share ////////////////////////////////
                    if (request.getAttribute("deleteId") != null) {
                        String fileId = request.getAttribute("deleteId").toString();
                        if (fileId != null && fileId != "")
                            removeFromShare(fileId, request, response).toString();

                    }
                    ////////////////////////////////////Update Community Info////////////////////////////////
                    else if (null == fileBytes) {
                        String shareId = request.getAttribute("DBId").toString();
                        if (shareId != null && shareId != "")
                            addRemoveCommunities(shareId, communities, request, response);
                    } else {
                        //////////////////////////////////////////////////////////////////////////////////

                        Boolean newUpload = (request.getAttribute("DBId").toString().length() == 0);

                        ///////////////////////////////// SWF Manip  /////////////////////////////////
                        String shareId = request.getAttribute("DBId").toString();
                        String fileUrl = "";
                        String fileId = "";
                        String bin = request.getAttribute("binary").toString();
                        if (request.getAttribute("title") != null && request.getAttribute("description") != null
                                && fileBytes != null) {
                            if (!isFileSet) //if not a binary file or file was not changed
                            {
                                fileId = shareId;
                                if (shareId != null && shareId != "")
                                    addRemoveCommunities(shareId, communities, request, response);
                                out.println("File was not set, just updated communities.");
                            } else if (bin.equals("null")) //is a json file, make sure its okay and upload it
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        true, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            } else //is a binary, do normal
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        false, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            }

                            if (fileId.contains("Failed")) {
                                out.println(fileId);
                            } else {
                                fileUrl = SHARE_ROOT + fileId;
                                if (newUpload)
                                    out.println(
                                            "You have successfully added a file to the share, its location is: "
                                                    + fileUrl);
                                else
                                    out.println(
                                            "You have successfully updated a file on the share, its location is: "
                                                    + fileUrl);
                            }
                        } else {
                            fileUrl = null;
                            out.println("Error: Not enough information provided for file Upload");
                        }

                        ///////////////////////////////// End File Manip  /////////////////////////////////

                        out.println("</div>");
                    }
                } else {
                }

                out.write("\n");
                out.write("\t\n");
                out.write("\t<script>\n");
                out.write("\tfunction clearCommList()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  o.selected = false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction highlightComms(commList)\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  if(commList.indexOf(o.value) == -1)\n");
                out.write("\t\t\t\to.selected = false;\n");
                out.write("\t\t\t  else  \n");
                out.write("\t\t\t  \to.selected = true;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\tfunction populate()\n");
                out.write("\t{\n");
                out.write("\t\tvar typerow = document.getElementById('typerow');\n");
                out.write("\t\tvar type = document.getElementById('type');\n");
                out.write("\t\tvar title = document.getElementById('title');\n");
                out.write("\t\tvar description = document.getElementById('description');\n");
                out.write("\t\tvar file = document.getElementById('file');\n");
                out.write("\t\tvar created = document.getElementById('created');\n");
                out.write("\t\tvar DBId = document.getElementById('DBId');\n");
                out.write("\t\tvar deleteId = document.getElementById('deleteId');\n");
                out.write("\t\tvar deleteButton = document.getElementById('deleteButton');\n");
                out.write("\t\tvar share_url = document.getElementById('share_url');\n");
                out.write("\t\tvar owner_text = document.getElementById('owner_text');\n");
                out.write("\t\tvar owner = document.getElementById('owner');\n");
                out.write("\t\tvar url_row = document.getElementById('url_row');\n");
                out.write("\t\tvar dropdown = document.getElementById(\"upload_info\");\n");
                out.write("\t\tvar list = dropdown.options[dropdown.selectedIndex].value;\n");
                out.write("\t\tvar binary = document.getElementById(\"binary\");\n");
                out.write("\t\t\n");
                out.write("\t\tif (list == \"new\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"binary\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\tif ( list == \"newJSON\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"null\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\t//_id, created, title, description\n");
                out.write("\t\tsplit = list.split(\"$$$\");\n");
                out.write("\t\t\n");
                out.write("\t\tres_id = split[0];\n");
                out.write("\t\tres_created = split[1];\n");
                out.write("\t\tres_title = split[2];\n");
                out.write("\t\tres_description = split[3];\n");
                out.write("\t\tres_url = split[4];\n");
                out.write("\t\tcommunities = split[5];\n");
                out.write("\t\tres_owner = split[6];\n");
                out.write("\t\tres_binary = split[7];\t\t\n");
                out.write("\t\tres_type = split[8];\t\t\t\n");
                out.write("\t\t\n");
                out.write("\t\tif ( res_binary == \"null\" )\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t}\n");
                out.write("\t\telse\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t}\n");
                out.write("\t\ttitle.value = res_title;\n");
                out.write("\t\tdescription.value = res_description;\n");
                out.write("\t\tcreated.value = res_created;\n");
                out.write("\t\tDBId.value = res_id;\n");
                out.write("\t\tdeleteId.value = res_id;\n");
                out.write("\t\tshare_url.value = res_url;\n");
                out.write("\t\towner.value = res_owner;\t\t\n");
                out.write("\t\tdeleteButton.className = \"show\";\n");
                out.write("\t\towner.className = \"show\";\n");
                out.write("\t\towner_text.className = \"show\";\n");
                out.write("\t\turl_row.className = \"show\";\n");
                out.write("\t\thighlightComms(communities);\t\t\n");
                out.write("\t\tbinary.value = res_binary;\n");
                out.write("\t\ttype.value = res_type;\n");
                out.write("\t}\n");
                out.write("\t\tfunction validate_fields()\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle = document.getElementById('title').value;\n");
                out.write("\t\t\tdescription = document.getElementById('description').value;\n");
                out.write("\t\t\tfile = document.getElementById('file').value;\n");
                out.write("\t\t\tbinary = document.getElementById(\"binary\").value;\n");
                out.write("\t\t\ttype = document.getElementById(\"type\").value;\n");
                out.write("\t\t\t//share_url = document.getElementById('share_url').value;\n");
                out.write("\t\t\t//file_url = document.getElementById('file_url').value;\n");
                out.write("\t\t\t//file_check = document.getElementById('file_check').checked;\n");
                out.write("\t\t\t\n");
                out.write("\t\t\tif (title == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a title.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif (description == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a description.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif ( binary == \"null\" && type == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a type.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\t\n");
                out.write("\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction confirmDelete()\n");
                out.write("\t\t{\n");
                out.write(
                        "\t\t\tvar agree=confirm(\"Are you sure you wish to Delete this file from the File Share?\");\n");
                out.write("\t\t\tif (agree)\n");
                out.write("\t\t\t\treturn true ;\n");
                out.write("\t\t\telse\n");
                out.write("\t\t\t\treturn false ;\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction showResults()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tvar title = document.getElementById('DBId').value;\n");
                out.write("\t\t\tvar url = getEndPointUrl() + \"share/get/\" + title;\n");
                out.write("\t\t\twindow.open(url, '_blank');\n");
                out.write("\t\t\twindow.focus();\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\t// -->\n");
                out.write("\t\t</script>\n");
                out.write("\t</script>\n");
                out.write(
                        "\t\t<div id=\"uploader_outter_div\" name=\"uploader_outter_div\" align=\"center\" style=\"width:100%\" >\n");
                out.write(
                        "\t    \t<div id=\"uploader_div\" name=\"uploader_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:475px; margin:auto\">\n");
                out.write("\t        \t<h2>File Uploader</h2>\n");
                out.write("\t        \t<form id=\"search_form\" name=\"search_form\" method=\"get\">\n");
                out.write("\t        \t\t<div align=\"center\"\">\n");
                out.write("\t        \t\t<label for=\"ext\">Filter On</label>\n");
                out.write("\t\t\t\t\t  <select name=\"ext\" id=\"ext\" onchange=\"this.form.submit();\">\n");
                out.write("\t\t\t\t\t    ");

                out.print(populateMediaTypes(request, response));

                out.write("\n");
                out.write("\t\t\t\t\t  </select>\n");
                out.write("\t\t\t\t\t </div>\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t        \t<form id=\"delete_form\" name=\"delete_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return confirmDelete()\" >\n");
                out.write(
                        "\t        \t\t<select id=\"upload_info\" onchange=\"populate()\" name=\"upload_info\"><option value=\"new\">Upload New File</option><option value=\"newJSON\">Upload New JSON</option> ");

                out.print(populatePreviousUploads(request, response));

                out.write("</select>\n");
                out.write(
                        "\t        \t\t<input type=\"submit\" name=\"deleteButton\" id=\"deleteButton\" class=\"hidden\" value=\"Delete\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteId\" id=\"deleteId\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteFile\" id=\"deleteFile\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t            <form id=\"upload_form\" name=\"upload_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return validate_fields();\" >\n");
                out.write(
                        "\t                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px; padding-right:10px\">\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td colspan=\"2\" align=\"center\"></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Title:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"title\" id=\"title\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Description:</td>\n");
                out.write(
                        "\t                    <td><textarea rows=\"4\" cols=\"30\" name=\"description\" id=\"description\" ></textarea></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"typerow\">\n");
                out.write("\t                    <td>Type:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"type\" id=\"type\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td>Communities:</td>\n");
                out.write("\t                  \t<td>");

                out.print(communityList);

                out.write("</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td id=\"owner_text\">Owner:</td>\n");
                out.write("\t                  \t<td>\n");
                out.write(
                        "\t                    <input type=\"text\" name=\"owner\" id=\"owner\" readonly=\"readonly\" size=\"25\" />\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>File:</td>\n");
                out.write("\t                    <td><input type=\"file\" name=\"file\" id=\"file\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"url_row\" class=\"hide\">\n");
                out.write("\t                  \t<td>Share URL:</td>\n");
                out.write(
                        "\t                  \t<td><input type=\"text\" name=\"share_url\" id=\"share_url\" readonly=\"readonly\" size=\"38\"/>\n");
                out.write(
                        "\t                  \t<input type=\"button\" onclick=\"showResults()\" value=\"View\"/>\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                \t<td></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write(
                        "\t                    <td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"Submit\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                </table>\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"created\" id=\"created\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"DBId\" id=\"DBId\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"fileUrl\" id=\"fileUrl\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"binary\" id=\"binary\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t\t\t\t</form>\n");
                out.write("\t        </div>\n");
                out.write("\t        <form id=\"logout_form\" name=\"logout_form\" method=\"post\">\n");
                out.write(
                        "\t        \t<input type=\"submit\" name=\"logout\" id = \"logout\" value=\"Log Out\" />\n");
                out.write("\t        </form>\n");
                out.write("\t    </div>\n");
                out.write("\t    </p>\n");
                out.write("\t\n");

            }
        } else if (isLoggedIn == false) {
            //localCookie =(request.getParameter("local") != null);
            //System.out.println("LocalCookie = " + localCookie.toString());
            String errorMsg = "";
            if (request.getParameter("logintext") != null || request.getParameter("passwordtext") != null) {
                if (logMeIn(request.getParameter("logintext"), request.getParameter("passwordtext"), request,
                        response)) {
                    showAll = (request.getParameter("sudo") != null);
                    out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                    out.println("Login Success");
                } else {
                    errorMsg = "Log in Failed, Please Try again";
                }

            }

            out.write("\n");
            out.write("\n");
            out.write("<script>\n");
            out.write("\tfunction validate_fields()\n");
            out.write("\t{\n");
            out.write("\t\tuname = document.getElementById('logintext').value;\n");
            out.write("\t\tpword = document.getElementById('passwordtext').value;\n");
            out.write("\t\t\n");
            out.write("\t\tif (uname == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your username.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t\tif (pword == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your password.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t}\n");
            out.write("\n");
            out.write("\n");
            out.write("</script>\n");
            out.write(
                    "\t<div id=\"login_outter_div\" name=\"login_outter_div\" align=\"center\" style=\"width:100%\" >\n");
            out.write(
                    "    \t<div id=\"login_div\" name=\"login_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:450px; margin:auto\">\n");
            out.write("        \t<h2>Login</h2>\n");
            out.write(
                    "            <form id=\"login_form\" name=\"login_form\" method=\"post\" onsubmit=\"javascript:return validate_fields();\" >\n");
            out.write(
                    "                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px\">\n");
            out.write("                  <tr>\n");
            out.write("                    <td>User Name</td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write("                    <td>Password</td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td><input type=\"text\" name=\"logintext\" id=\"logintext\" width=\"190px\" /></td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write(
                    "                    <td><input type=\"password\" name=\"passwordtext\" id=\"passwordtext\" width=\"190px\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td colspan=\"3\" align=\"right\"><input name=\"Login\" type=\"submit\" value=\"Login\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                </table>\n");
            out.write("\t\t\t</form>\n");
            out.write("        </div>\n");
            out.write("    </div>\n");
            out.write("\t<div style=\"color: red; text-align: center;\"> ");
            out.print(errorMsg);
            out.write(" </div>\n");

        }

        out.write("\n");
        out.write("    \n");
        out.write("    \n");
        out.write("</body>\n");
        out.write("</html>");
    } catch (Throwable t) {
        if (!(t instanceof SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    out.clearBuffer();
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:org.dspace.app.webui.jsptag.BrowseListTag.java

public int doStartTag() throws JspException {
    JspWriter out = pageContext.getOut();
    HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest();

    /* just leave this out now
    boolean emphasiseDate = false;//from   www . j  av  a 2s.  co m
    boolean emphasiseTitle = false;
            
    if (emphColumn != null)
    {
    emphasiseDate = emphColumn.equalsIgnoreCase("date");
    emphasiseTitle = emphColumn.equalsIgnoreCase("title");
    }
    */

    // get the elements to display
    String browseListLine = null;
    String browseWidthLine = null;

    // As different indexes / sort options may require different columns to be displayed
    // try to obtain a custom configuration based for the browse that has been performed
    if (browseInfo != null) {
        SortOption so = browseInfo.getSortOption();
        BrowseIndex bix = browseInfo.getBrowseIndex();

        // We have obtained the index that was used for this browse
        if (bix != null) {
            // First, try to get a configuration for this browse and sort option combined
            if (so != null && browseListLine == null) {
                browseListLine = ConfigurationManager.getProperty(
                        "webui.itemlist.browse." + bix.getName() + ".sort." + so.getName() + ".columns");
                browseWidthLine = ConfigurationManager.getProperty(
                        "webui.itemlist.browse." + bix.getName() + ".sort." + so.getName() + ".widths");
            }

            // We haven't got a sort option defined, so get one for the index
            // - it may be required later
            if (so == null) {
                so = bix.getSortOption();
            }
        }

        // If no config found, attempt to get one for this sort option
        if (so != null && browseListLine == null) {
            browseListLine = ConfigurationManager
                    .getProperty("webui.itemlist.sort." + so.getName() + ".columns");
            browseWidthLine = ConfigurationManager
                    .getProperty("webui.itemlist.sort." + so.getName() + ".widths");
        }

        // If no config found, attempt to get one for this browse index
        if (bix != null && browseListLine == null) {
            browseListLine = ConfigurationManager
                    .getProperty("webui.itemlist.browse." + bix.getName() + ".columns");
            browseWidthLine = ConfigurationManager
                    .getProperty("webui.itemlist.browse." + bix.getName() + ".widths");
        }

        // If no config found, attempt to get a general one, using the sort name
        if (so != null && browseListLine == null) {
            browseListLine = ConfigurationManager.getProperty("webui.itemlist." + so.getName() + ".columns");
            browseWidthLine = ConfigurationManager.getProperty("webui.itemlist." + so.getName() + ".widths");
        }

        // If no config found, attempt to get a general one, using the index name
        if (bix != null && browseListLine == null) {
            browseListLine = ConfigurationManager.getProperty("webui.itemlist." + bix.getName() + ".columns");
            browseWidthLine = ConfigurationManager.getProperty("webui.itemlist." + bix.getName() + ".widths");
        }
    }

    if (browseListLine == null) {
        browseListLine = ConfigurationManager.getProperty("webui.itemlist.columns");
        browseWidthLine = ConfigurationManager.getProperty("webui.itemlist.widths");
    }

    // Have we read a field configration from dspace.cfg?
    if (browseListLine != null) {
        // If thumbnails are disabled, strip out any thumbnail column from the configuration
        if (!showThumbs && browseListLine.contains("thumbnail")) {
            // Ensure we haven't got any nulls
            browseListLine = browseListLine == null ? "" : browseListLine;
            browseWidthLine = browseWidthLine == null ? "" : browseWidthLine;

            // Tokenize the field and width lines
            StringTokenizer bllt = new StringTokenizer(browseListLine, ",");
            StringTokenizer bwlt = new StringTokenizer(browseWidthLine, ",");

            StringBuilder newBLLine = new StringBuilder();
            StringBuilder newBWLine = new StringBuilder();
            while (bllt.hasMoreTokens() || bwlt.hasMoreTokens()) {
                String browseListTok = bllt.hasMoreTokens() ? bllt.nextToken() : null;
                String browseWidthTok = bwlt.hasMoreTokens() ? bwlt.nextToken() : null;

                // Only use the Field and Width tokens, if the field isn't 'thumbnail'
                if (browseListTok == null || !browseListTok.trim().equals("thumbnail")) {
                    if (browseListTok != null) {
                        if (newBLLine.length() > 0) {
                            newBLLine.append(",");
                        }

                        newBLLine.append(browseListTok);
                    }

                    if (browseWidthTok != null) {
                        if (newBWLine.length() > 0) {
                            newBWLine.append(",");
                        }

                        newBWLine.append(browseWidthTok);
                    }
                }
            }

            // Use the newly built configuration file
            browseListLine = newBLLine.toString();
            browseWidthLine = newBWLine.toString();
        }
    } else {
        browseListLine = DEFAULT_LIST_FIELDS;
        browseWidthLine = DEFAULT_LIST_WIDTHS;
    }

    // Arrays used to hold the information we will require when outputting each row
    String[] fieldArr = browseListLine == null ? new String[0] : browseListLine.split("\\s*,\\s*");
    String[] widthArr = browseWidthLine == null ? new String[0] : browseWidthLine.split("\\s*,\\s*");
    boolean isDate[] = new boolean[fieldArr.length];
    boolean emph[] = new boolean[fieldArr.length];
    boolean isAuthor[] = new boolean[fieldArr.length];
    boolean viewFull[] = new boolean[fieldArr.length];
    String[] browseType = new String[fieldArr.length];
    String[] cOddOrEven = new String[fieldArr.length];

    try {
        // Get the interlinking configuration too
        CrossLinks cl = new CrossLinks();

        // Get a width for the table
        String tablewidth = ConfigurationManager.getProperty("webui.itemlist.tablewidth");

        // If we have column widths, try to use a fixed layout table - faster for browsers to render
        // but not if we have to add an 'edit item' button - we can't know how big it will be
        if (widthArr.length > 0 && widthArr.length == fieldArr.length && !linkToEdit) {
            // If the table width has been specified, we can make this a fixed layout
            if (!StringUtils.isEmpty(tablewidth)) {
                out.println("<table style=\"width: " + tablewidth
                        + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
            } else {
                // Otherwise, don't constrain the width
                out.println(
                        "<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
            }

            // Output the known column widths
            out.print("<colgroup>");

            for (int w = 0; w < widthArr.length; w++) {
                out.print("<col width=\"");

                // For a thumbnail column of width '*', use the configured max width for thumbnails
                if (fieldArr[w].equals("thumbnail") && widthArr[w].equals("*")) {
                    out.print(thumbItemListMaxWidth);
                } else {
                    out.print(StringUtils.isEmpty(widthArr[w]) ? "*" : widthArr[w]);
                }

                out.print("\" />");
            }

            out.println("</colgroup>");
        } else if (!StringUtils.isEmpty(tablewidth)) {
            out.println("<table width=\"" + tablewidth
                    + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
        } else {
            out.println(
                    "<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">");
        }

        // Output the table headers
        out.println("<tr>");

        for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) {
            String field = fieldArr[colIdx].toLowerCase().trim();
            cOddOrEven[colIdx] = (((colIdx + 1) % 2) == 0 ? "Odd" : "Even");

            // find out if the field is a date
            if (field.indexOf("(date)") > 0) {
                field = field.replaceAll("\\(date\\)", "");
                isDate[colIdx] = true;
            }

            // Cache any modifications to field
            fieldArr[colIdx] = field;

            // find out if this is the author column
            if (field.equals(authorField)) {
                isAuthor[colIdx] = true;
            }

            // find out if this field needs to link out to other browse views
            if (cl.hasLink(field)) {
                browseType[colIdx] = cl.getLinkType(field);
                viewFull[colIdx] = BrowseIndex.getBrowseIndex(browseType[colIdx]).isItemIndex();
            }

            // find out if we are emphasising this field
            /*
            if ((field.equals(dateField) && emphasiseDate) ||
                (field.equals(titleField) && emphasiseTitle))
            {
            emph[colIdx] = true;
            }
            */
            if (field.equals(emphColumn)) {
                emph[colIdx] = true;
            }

            // prepare the strings for the header
            String id = "t" + Integer.toString(colIdx + 1);
            String css = "oddRow" + cOddOrEven[colIdx] + "Col";
            String message = "itemlist." + field;

            // output the header
            out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[colIdx] ? "<strong>" : "")
                    + LocaleSupport.getLocalizedMessage(pageContext, message)
                    + (emph[colIdx] ? "</strong>" : "") + "</th>");
        }

        if (linkToEdit) {
            String id = "t" + Integer.toString(cOddOrEven.length + 1);
            String css = "oddRow" + cOddOrEven[cOddOrEven.length - 2] + "Col";

            // output the header
            out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[emph.length - 2] ? "<strong>" : "")
                    + "&nbsp;" //LocaleSupport.getLocalizedMessage(pageContext, message)
                    + (emph[emph.length - 2] ? "</strong>" : "") + "</th>");
        }

        out.print("</tr>");

        // now output each item row
        for (int i = 0; i < items.length; i++) {
            out.print("<tr>");
            // now prepare the XHTML frag for this division
            String rOddOrEven;
            if (i == highlightRow) {
                rOddOrEven = "highlight";
            } else {
                rOddOrEven = ((i & 1) == 1 ? "odd" : "even");
            }

            for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) {
                String field = fieldArr[colIdx];

                // get the schema and the element qualifier pair
                // (Note, the schema is not used for anything yet)
                // (second note, I hate this bit of code.  There must be
                // a much more elegant way of doing this.  Tomcat has
                // some weird problems with variations on this code that
                // I tried, which is why it has ended up the way it is)
                StringTokenizer eq = new StringTokenizer(field, ".");

                String[] tokens = { "", "", "" };
                int k = 0;
                while (eq.hasMoreTokens()) {
                    tokens[k] = eq.nextToken().toLowerCase().trim();
                    k++;
                }
                String schema = tokens[0];
                String element = tokens[1];
                String qualifier = tokens[2];

                // first get hold of the relevant metadata for this column
                DCValue[] metadataArray;
                if (qualifier.equals("*")) {
                    metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY);
                } else if (qualifier.equals("")) {
                    metadataArray = items[i].getMetadata(schema, element, null, Item.ANY);
                } else {
                    metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY);
                }

                // save on a null check which would make the code untidy
                if (metadataArray == null) {
                    metadataArray = new DCValue[0];
                }

                // now prepare the content of the table division
                String metadata = "-";
                if (field.equals("thumbnail")) {
                    metadata = getThumbMarkup(hrq, items[i]);
                } else if (metadataArray.length > 0) {
                    // format the date field correctly
                    if (isDate[colIdx]) {
                        DCDate dd = new DCDate(metadataArray[0].value);
                        metadata = UIUtil.displayDate(dd, false, false, hrq);
                    }
                    // format the title field correctly for withdrawn items (ie. don't link)
                    else if (field.equals(titleField) && items[i].isWithdrawn()) {
                        metadata = Utils.addEntities(metadataArray[0].value);
                    }
                    // format the title field correctly (as long as the item isn't withdrawn, link to it)
                    else if (field.equals(titleField)) {
                        metadata = "<a href=\"" + hrq.getContextPath() + "/handle/" + items[i].getHandle()
                                + "\">" + Utils.addEntities(metadataArray[0].value) + "</a>";
                    }
                    // format all other fields
                    else {
                        // limit the number of records if this is the author field (if
                        // -1, then the limit is the full list)
                        boolean truncated = false;
                        int loopLimit = metadataArray.length;
                        if (isAuthor[colIdx]) {
                            int fieldMax = (authorLimit == -1 ? metadataArray.length : authorLimit);
                            loopLimit = (fieldMax > metadataArray.length ? metadataArray.length : fieldMax);
                            truncated = (fieldMax < metadataArray.length);
                            log.debug("Limiting output of field " + field + " to " + Integer.toString(loopLimit)
                                    + " from an original " + Integer.toString(metadataArray.length));
                        }

                        StringBuffer sb = new StringBuffer();
                        for (int j = 0; j < loopLimit; j++) {
                            String startLink = "";
                            String endLink = "";
                            if (!StringUtils.isEmpty(browseType[colIdx]) && !disableCrossLinks) {
                                String argument;
                                String value;
                                if (metadataArray[j].authority != null
                                        && metadataArray[j].confidence >= MetadataAuthorityManager.getManager()
                                                .getMinConfidence(metadataArray[j].schema,
                                                        metadataArray[j].element, metadataArray[j].qualifier)) {
                                    argument = "authority";
                                    value = metadataArray[j].authority;
                                } else {
                                    argument = "value";
                                    value = metadataArray[j].value;
                                }
                                if (viewFull[colIdx]) {
                                    argument = "vfocus";
                                }
                                startLink = "<a href=\"" + hrq.getContextPath() + "/browse?type="
                                        + browseType[colIdx] + "&amp;" + argument + "="
                                        + URLEncoder.encode(value, "UTF-8");

                                if (metadataArray[j].language != null) {
                                    startLink = startLink + "&amp;" + argument + "_lang="
                                            + URLEncoder.encode(metadataArray[j].language, "UTF-8");
                                }

                                if ("authority".equals(argument)) {
                                    startLink += "\" class=\"authority " + browseType[colIdx] + "\">";
                                } else {
                                    startLink = startLink + "\">";
                                }
                                endLink = "</a>";
                            }
                            sb.append(startLink);
                            sb.append(Utils.addEntities(metadataArray[j].value));
                            sb.append(endLink);
                            if (j < (loopLimit - 1)) {
                                sb.append("; ");
                            }
                        }
                        if (truncated) {
                            String etal = LocaleSupport.getLocalizedMessage(pageContext, "itemlist.et-al");
                            sb.append(", ").append(etal);
                        }
                        metadata = "<em>" + sb.toString() + "</em>";
                    }
                }

                // prepare extra special layout requirements for dates
                String extras = "";
                if (isDate[colIdx]) {
                    extras = "nowrap=\"nowrap\" align=\"right\"";
                }

                String id = "t" + Integer.toString(colIdx + 1);
                out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row" + cOddOrEven[colIdx]
                        + "Col\" " + extras + ">" + (emph[colIdx] ? "<strong>" : "") + metadata
                        + (emph[colIdx] ? "</strong>" : "") + "</td>");
            }

            // Add column for 'edit item' links
            if (linkToEdit) {
                String id = "t" + Integer.toString(cOddOrEven.length + 1);

                out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row"
                        + cOddOrEven[cOddOrEven.length - 2] + "Col\" nowrap>" + "<form method=\"get\" action=\""
                        + hrq.getContextPath() + "/tools/edit-item\">"
                        + "<input type=\"hidden\" name=\"handle\" value=\"" + items[i].getHandle() + "\" />"
                        + "<input type=\"submit\" value=\"Edit Item\" /></form>" + "</td>");
            }

            out.println("</tr>");
        }

        // close the table
        out.println("</table>");
    } catch (IOException ie) {
        throw new JspException(ie);
    } catch (SQLException e) {
        throw new JspException(e);
    } catch (BrowseException e) {
        throw new JspException(e);
    }

    return SKIP_BODY;
}