Example usage for javax.servlet.http HttpServletResponse encodeUrl

List of usage examples for javax.servlet.http HttpServletResponse encodeUrl

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse encodeUrl.

Prototype

@Deprecated
public String encodeUrl(String url);

Source Link

Usage

From source file:jp.terasoluna.fw.web.struts.taglib.PageLinksTag.java

/**
 * y?[W?N?StringBuilder?B/*from   w  ww  .  jav a2s. c o  m*/
 * 
 * @param sb ?StringBuilder
 * @param row \?s?
 * @param startIndex \JnCfbNX
 * @param totalCount ?S??
 */
protected void addDirectLink(StringBuilder sb, int row, int startIndex, int totalCount) {

    //TagUtilsCX^X??
    TagUtils tagUtils = TagUtils.getInstance();

    // X|Xp??[^
    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();

    //ANVURL
    String url = null;
    url = response.encodeURL(tagUtils.getActionMappingURL(action, pageContext));

    //y?[WWvpN??w\??
    String directLinkNo = links.get(MAX_DSP_SIZE);
    if (directLinkNo != null) {
        try {
            maxPageCount = Integer.parseInt(directLinkNo);
        } catch (NumberFormatException e) {
            // NumberFormatException????A
            // v?peBmaxDirectLinkCount
            // ftHglgp
        }
    }

    //Sy?[W??B
    int pageCount = getPageCount(row, totalCount);

    //?y?[WCfbNX?B
    int pageIndex = getPageIndex(row, startIndex);

    //\??Iy?[W\Jny?[W
    int startPage = 0;
    int endPage = 0;

    //Sy?[W??Ay?[W?N\??A
    //?A\y?[WCfbNX?Ay?[W?N\?
    //???A\Jny?[WCfbNX?A\y?[WCfbNX
    //??B
    //?ASy?[W??FPOy?[W?Ay?[W?N\??FT?A
    //\y?[WCfbNX?FT???AstartPageQ
    //endPageT?B???A\N?u3 4 5 6 7?v?B
    if (pageCount > maxPageCount && pageIndex > (maxPageCount / 2)) {

        //\??Iy?[W?y?[W??B
        endPage = maxPageCount;

        startPage = (pageIndex - (endPage / 2)) - 1;
        if (startPage + endPage > pageCount) {
            startPage = pageCount - endPage;
        }
    } else {
        endPage = pageCount < maxPageCount ? pageCount : maxPageCount;
        startPage = 0;
    }

    //y?[W?N???[v
    int size = startPage + endPage;
    for (int i = startPage; i < size; i++) {
        int idx = i + 1;
        if (pageIndex == idx) {
            sb.append("<b>");
            sb.append(idx);
            sb.append("</b>&nbsp;");
        } else {
            // y?[WWvpN^OZbg
            sb.append("<a href=\"" + url);
            if (url.indexOf("?") < 0) {
                sb.append("?");
            } else {
                sb.append("&");
            }
            sb.append(rowProperty);
            sb.append("=");
            sb.append(row);
            sb.append("&");
            sb.append(indexProperty);
            sb.append("=");
            sb.append(i * row);
            sb.append("\">");
            sb.append(idx);
            sb.append("</a>&nbsp;");
        }
    }
}

From source file:info.jtrac.util.ItemUtils.java

private static String getAsHtml(Item item, HttpServletRequest request, HttpServletResponse response,
        MessageSource ms, Locale loc) {

    boolean isWeb = request != null && response != null;

    String tableStyle = " class='jtrac'";
    String tdStyle = "";
    String thStyle = "";
    String altStyle = " class='alt'";
    String labelStyle = " class='label'";

    if (!isWeb) {
        // inline CSS so that HTML mail works across most mail-reader clients
        String tdCommonStyle = "border: 1px solid black";
        tableStyle = " class='jtrac' style='border-collapse: collapse; font-family: Arial; font-size: 75%'";
        tdStyle = " style='" + tdCommonStyle + "'";
        thStyle = " style='" + tdCommonStyle + "; background: #CCCCCC'";
        altStyle = " style='background: #e1ecfe'";
        labelStyle = " style='" + tdCommonStyle
                + "; background: #CCCCCC; font-weight: bold; text-align: right'";
    }/*from   w  w  w  .  jav a  2s . co  m*/

    StringBuffer sb = new StringBuffer();
    sb.append("<table width='100%'" + tableStyle + ">");
    sb.append("<tr" + altStyle + ">");
    sb.append("  <td" + labelStyle + ">" + fmt("id", ms, loc) + "</td>");
    sb.append("  <td" + tdStyle + ">" + item.getRefId() + "</td>");
    sb.append("  <td" + labelStyle + ">" + fmt("relatedItems", ms, loc) + "</td>");
    sb.append("  <td colspan='3'" + tdStyle + ">");
    if (item.getRelatedItems() != null || item.getRelatingItems() != null) {
        String flowUrlParam = null;
        String flowUrl = null;
        if (isWeb) {
            flowUrlParam = "_flowExecutionKey=" + request.getAttribute("flowExecutionKey");
            flowUrl = "/flow?" + flowUrlParam;
        }
        if (item.getRelatedItems() != null) {
            // ItemViewForm itemViewForm = null;
            if (isWeb) {
                // itemViewForm = (ItemViewForm) request.getAttribute("itemViewForm");
                sb.append("<input type='hidden' name='_removeRelated'/>");
            }
            for (ItemItem itemItem : item.getRelatedItems()) {
                String refId = itemItem.getRelatedItem().getRefId();
                if (isWeb) {
                    String checked = "";
                    Set<Long> set = null; // itemViewForm.getRemoveRelated();
                    if (set != null && set.contains(itemItem.getId())) {
                        checked = " checked='true'";
                    }
                    String url = flowUrl + "&_eventId=viewRelated&itemId=" + itemItem.getRelatedItem().getId();
                    refId = "<a href='" + response.encodeURL(request.getContextPath() + url) + "'>" + refId
                            + "</a>" + "<input type='checkbox' name='removeRelated' value='" + itemItem.getId()
                            + "' title='" + fmt("remove", ms, loc) + "'" + checked + "/>";
                }
                sb.append(fmt(itemItem.getRelationText(), ms, loc) + " " + refId + " ");
            }
        }
        if (item.getRelatingItems() != null) {
            for (ItemItem itemItem : item.getRelatingItems()) {
                String refId = itemItem.getItem().getRefId();
                if (isWeb) {
                    String url = flowUrl + "&_eventId=viewRelated&itemId=" + itemItem.getItem().getId();
                    refId = "<a href='" + response.encodeURL(request.getContextPath() + url) + "'>" + refId
                            + "</a>";
                }
                sb.append(refId + " " + fmt(itemItem.getRelationText() + "This", ms, loc) + ". ");
            }
        }
    }
    sb.append("  </td>");
    sb.append("</tr>");
    sb.append("<tr>");
    sb.append("  <td width='15%'" + labelStyle + ">" + fmt("status", ms, loc) + "</td>");
    sb.append("  <td" + tdStyle + ">" + item.getStatusValue() + "</td>");
    sb.append("  <td" + labelStyle + ">" + fmt("loggedBy", ms, loc) + "</td>");
    sb.append("  <td" + tdStyle + ">" + item.getLoggedBy().getName() + "</td>");
    sb.append("  <td" + labelStyle + ">" + fmt("assignedTo", ms, loc) + "</td>");
    sb.append("  <td width='15%'" + tdStyle + ">"
            + (item.getAssignedTo() == null ? "" : item.getAssignedTo().getName()) + "</td>");
    sb.append("</tr>");
    sb.append("<tr" + altStyle + ">");
    sb.append("  <td" + labelStyle + ">" + fmt("summary", ms, loc) + "</td>");
    sb.append("  <td colspan='5'" + tdStyle + ">" + HtmlUtils.htmlEscape(item.getSummary()) + "</td>");
    sb.append("</tr>");
    sb.append("<tr>");
    sb.append("  <td valign='top'" + labelStyle + ">" + fmt("detail", ms, loc) + "</td>");
    sb.append("  <td colspan='5'" + tdStyle + ">" + fixWhiteSpace(item.getDetail()) + "</td>");
    sb.append("</tr>");

    int row = 0;
    Map<Field.Name, Field> fields = item.getSpace().getMetadata().getFields();
    for (Field.Name fieldName : item.getSpace().getMetadata().getFieldOrder()) {
        Field field = fields.get(fieldName);
        sb.append("<tr" + (row % 2 == 0 ? altStyle : "") + ">");
        sb.append("  <td" + labelStyle + ">" + field.getLabel() + "</td>");
        sb.append("  <td colspan='5'" + tdStyle + ">" + item.getCustomValue(fieldName) + "</td>");
        sb.append("</tr>");
        row++;
    }
    sb.append("</table>");

    //=========================== HISTORY ==================================
    sb.append("<br/>&nbsp;<b" + tableStyle + ">" + fmt("history", ms, loc) + "</b>");
    sb.append("<table width='100%'" + tableStyle + ">");
    sb.append("<tr>");
    sb.append("  <th" + thStyle + ">" + fmt("loggedBy", ms, loc) + "</th><th" + thStyle + ">"
            + fmt("status", ms, loc) + "</th>" + "<th" + thStyle + ">" + fmt("assignedTo", ms, loc) + "</th><th"
            + thStyle + ">" + fmt("comment", ms, loc) + "</th><th" + thStyle + ">" + fmt("timeStamp", ms, loc)
            + "</th>");
    List<Field> editable = item.getSpace().getMetadata().getEditableFields();
    for (Field field : editable) {
        sb.append("<th" + thStyle + ">" + field.getLabel() + "</th>");
    }
    sb.append("</tr>");

    if (item.getHistory() != null) {
        row = 1;
        for (History history : item.getHistory()) {
            sb.append("<tr valign='top'" + (row % 2 == 0 ? altStyle : "") + ">");
            sb.append("  <td" + tdStyle + ">" + history.getLoggedBy().getName() + "</td>");
            sb.append("  <td" + tdStyle + ">" + history.getStatusValue() + "</td>");
            sb.append("  <td" + tdStyle + ">"
                    + (history.getAssignedTo() == null ? "" : history.getAssignedTo().getName()) + "</td>");
            sb.append("  <td" + tdStyle + ">");
            Attachment attachment = history.getAttachment();
            if (attachment != null) {
                if (request != null && response != null) {
                    String href = response.encodeURL(request.getContextPath() + "/app/attachments/"
                            + attachment.getFileName() + "?filePrefix=" + attachment.getFilePrefix());
                    sb.append("<a target='_blank' href='" + href + "'>" + attachment.getFileName()
                            + "</a>&nbsp;");
                } else {
                    sb.append("(attachment:&nbsp;" + attachment.getFileName() + ")&nbsp;");
                }
            }
            sb.append(fixWhiteSpace(history.getComment()));
            sb.append("  </td>");
            sb.append("  <td" + tdStyle + ">" + history.getTimeStamp() + "</td>");
            for (Field field : editable) {
                sb.append("<td" + tdStyle + ">" + history.getCustomValue(field.getName()) + "</td>");
            }
            sb.append("</tr>");
            row++;
        }
    }
    sb.append("</table>");
    return sb.toString();
}

From source file:SessionSnoop.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("count");
    if (count == null)
        count = new Integer(1);
    else/* w  ww.j a v  a2 s.c  o  m*/
        count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);

    out.println("<HTML><HEAD><TITLE>Session Count</TITLE></HEAD>");
    out.println("<BODY><H1>Session Count</H1>");

    out.println("You've visited this page " + count + ((count == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null)
        count = new Integer(1);
    else/* ww  w  .ja v  a  2s  . c om*/
        count = new Integer(count.intValue() + 1);
    session.setAttribute("snoop.count", count);

    out.println("<HTML><HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
}

From source file:net.sourceforge.hunterj.javadocViewer.JavadocViewerServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*  ww w .ja v  a 2 s . co  m*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String toRemove = request.getParameter(JVConst.DOCHOME_OPTS_REMOVE.value);
    String realJavadocHome = request.getParameter(JVConst.DOCHOME_PARAM.value);

    if (StringUtils.isNotEmpty(toRemove)) {
        this.removeJavadocHome(request.getSession(), toRemove);
        return;
    }
    if (StringUtils.isEmpty(realJavadocHome)) {
        realJavadocHome = (String) request.getSession().getAttribute(JVConst.DOCHOME_ATTR.value);
        if (StringUtils.isEmpty(realJavadocHome)) {
            request.setAttribute(JVConst.DOCHOME_ERROR.value,
                    new FileNotFoundException("No javadoc home is selected."));
            this.dispatchToView(request, response);
            return;
        }
    }
    // Check to see if the local file path is valid.
    if (!isRemoteResource(realJavadocHome) && Files.notExists(Paths.get(realJavadocHome))) {
        request.setAttribute(JVConst.DOCHOME_ERROR.value,
                new FileNotFoundException("\"".concat(realJavadocHome).concat("\" is not a valid file path.")));
        this.dispatchToView(request, response);
        return;
    }

    // handle sub-requests by iframes for files, not under the servlet context
    String[] urlParts = request.getRequestURI().split(JVConst.DOCHOME_URL_PART.value);
    if (urlParts.length == 2 && realJavadocHome != null) {
        String filePath = realJavadocHome.concat(urlParts[1]);

        // Handle requests to remote servers
        if (this.isRemoteResource(realJavadocHome)) {
            this.doGetRemoteResource(response, filePath);
            return;
        }
        request.setAttribute(FileServlet.ABS_FILE_PATH, filePath);
        RequestDispatcher dispatch = request
                .getRequestDispatcher(response.encodeURL(FileServlet.FILE_SERVE_URI));
        dispatch.forward(request, response);
        return;
    }
    // At this point the request is for the main viewer page and is probably correct/valid.
    this.checkJavadocHome(request.getSession(), realJavadocHome);
    request.getSession().setAttribute(JVConst.DOCHOME_ATTR.value, realJavadocHome);
    this.dispatchToView(request, response);
}

From source file:org.hyperic.hq.ui.action.portlet.criticalalerts.RSSAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    RSSFeed feed = getNewRSSFeed(request);

    // Set title//w  w w.  jav  a  2  s .  c  om
    MessageResources res = getResources(request);
    feed.setTitle(res.getMessage("dash.home.CriticalAlerts"));

    String user = getUsername(request);
    List<Escalatable> list;
    try {
        // Set the managingEditor
        setManagingEditor(request);

        // Get user preferences
        ConfigResponse preferences = getUserPreferences(request, user);

        int count = Integer.parseInt(preferences.getValue(".dashContent.criticalalerts.numberOfAlerts").trim());
        int priority = Integer.parseInt(preferences.getValue(".dashContent.criticalalerts.priority").trim());
        long timeRange = Long.parseLong(preferences.getValue(".dashContent.criticalalerts.past").trim());

        list = eventsBoss.findRecentAlerts(user, count, priority, timeRange, null);
    } catch (Exception e) {
        log.warn("Error finding recent alerts", e);
        list = new ArrayList<Escalatable>();
    }

    for (Escalatable alert : list) {
        AlertDefinitionInterface defInfo = alert.getDefinition().getDefinitionInfo();
        AppdefEntityID aeid = AppdefUtil.newAppdefEntityId(defInfo.getResource());

        DateSpecifics specs = new DateSpecifics();
        specs.setDateFormat(
                new SimpleDateFormat(res.getMessage(Constants.UNIT_FORMAT_PREFIX_KEY + "epoch-millis")));

        FormattedNumber fmtd = UnitsFormat.format(new UnitNumber(alert.getAlertInfo().getTimestamp(),
                UnitsConstants.UNIT_DATE, UnitsConstants.SCALE_MILLI), request.getLocale(), specs);
        UriTemplate uriTemplate = new UriTemplate(
                feed.getBaseUrl() + "/alerts/Alerts.do?mode={mode}&a={alertId}&eid={entityId}");
        String desc;
        if (alert.getAlertInfo().isFixed()) {
            desc = fmtd.toString() + " "
                    + res.getMessage("parenthesis", res.getMessage("resource.common.alert.action.fixed.label"));
        } else {
            desc = "<table cellspacing=4><tr>" + "<td>" + fmtd.toString() + "</td>" + "<td><a href='"
                    + response.encodeURL(
                            uriTemplate.expand("FIXED", alert.getId(), aeid.getAppdefKey()).toASCIIString())
                    + "'>" + res.getMessage("resource.common.alert.action.fixed.label") + "</a></td>";

            if (alert.isAcknowledgeable()) {
                desc += "<td><a href='"
                        + response.encodeURL(uriTemplate
                                .expand("ACKNOWLEDGE", alert.getId(), aeid.getAppdefKey()).toASCIIString())
                        + "'>" + res.getMessage("resource.common.alert.action.acknowledge.label")
                        + "</a></td></tr></table>";

            }
        }

        AuthzSubject subject = authzBoss.getCurrentSubject(user);
        AppdefEntityValue resource = new AppdefEntityValue(aeid, subject);

        String link = response
                .encodeURL(uriTemplate.expand("viewAlert", alert.getId(), aeid.getAppdefKey()).toASCIIString());

        feed.addItem(resource.getName() + " " + defInfo.getName(), link, desc,
                alert.getAlertInfo().getTimestamp());
    }
    request.setAttribute("rssFeed", feed);

    return mapping.findForward(Constants.RSS_URL);
}

From source file:gr.abiss.calipso.util.ItemUtils.java

private static String getAsHtml(Item item, HttpServletRequest request, HttpServletResponse response,
        MessageSource ms, Locale loc) {

    boolean isWeb = request != null && response != null;

    String tableStyle = " class='calipsoService'";
    String tdStyle = "";
    String thStyle = "";
    String altStyle = " class='alt'";
    String labelStyle = " class='label'";

    if (!isWeb) {
        // inline CSS so that HTML mail works across most mail-reader clients
        String tdCommonStyle = "border: 1px solid black";
        tableStyle = " class='calipsoService' style='border-collapse: collapse; font-family: Arial; font-size: 75%'";
        tdStyle = " style='" + tdCommonStyle + "'";
        thStyle = " style='" + tdCommonStyle + "; background: #ededed'";
        altStyle = " style='background: #fffcdd'";
        labelStyle = " style='" + tdCommonStyle
                + "; background: #ededed; font-weight: bold; text-align: right'";
    }/*from ww  w. jav  a 2 s  .c om*/

    StringBuffer sb = new StringBuffer();
    sb.append("<table width='100%'" + tableStyle + ">");
    sb.append("<tr" + altStyle + ">");
    sb.append("  <td" + labelStyle + ">" + fmt("item_view.id", ms, loc) + "</td>");
    sb.append("  <td" + tdStyle + ">" + item.getUniqueRefId() + "</td>");
    sb.append("  <td" + labelStyle + ">" + fmt("item_view.relatedItems", ms, loc) + "</td>");
    sb.append("  <td colspan='3'" + tdStyle + ">");
    if (item.getRelatedItems() != null || item.getRelatingItems() != null) {
        String flowUrlParam = null;
        String flowUrl = null;
        if (isWeb) {
            flowUrlParam = "_flowExecutionKey=" + request.getAttribute("flowExecutionKey");
            flowUrl = "/flow?" + flowUrlParam;
        }
        if (item.getRelatedItems() != null) {
            // ItemViewForm itemViewForm = null;
            if (isWeb) {
                // itemViewForm = (ItemViewForm) request.getAttribute("itemViewForm");
                sb.append("<input type='hidden' name='_removeRelated'/>");
            }
            for (ItemItem itemItem : item.getRelatedItems()) {
                String refId = itemItem.getRelatedItem().getUniqueRefId();
                if (isWeb) {
                    String checked = "";
                    Set<Long> set = null; // itemViewForm.getRemoveRelated();
                    if (set != null && set.contains(itemItem.getId())) {
                        checked = " checked='true'";
                    }
                    String url = flowUrl + "&_eventId=viewRelated&itemId=" + itemItem.getRelatedItem().getId();
                    refId = "<a href='" + response.encodeURL(request.getContextPath() + url) + "'>" + refId
                            + "</a>" + "<input type='checkbox' name='removeRelated' value='" + itemItem.getId()
                            + "' title='" + fmt("item_view.remove", ms, loc) + "'" + checked + "/>";
                }
                sb.append(fmt(itemItem.getRelationText(), ms, loc) + " " + refId + " ");
            }
        }
        if (item.getRelatingItems() != null) {
            for (ItemItem itemItem : item.getRelatingItems()) {
                String refId = itemItem.getItem().getUniqueRefId();
                if (isWeb) {
                    String url = flowUrl + "&_eventId=viewRelated&itemId=" + itemItem.getItem().getId();
                    refId = "<a href='" + response.encodeURL(request.getContextPath() + url) + "'>" + refId
                            + "</a>";
                }
                sb.append(refId + " " + fmt(itemItem.getRelationText() + "This", ms, loc) + ". ");
            }
        }
    }
    sb.append("  </td>");
    sb.append("</tr>");
    sb.append("<tr>");
    sb.append("  <td width='15%'" + labelStyle + ">" + fmt("item_view.status", ms, loc) + "</td>");
    sb.append("  <td" + tdStyle + ">" + item.getStatusValue() + "</td>");
    sb.append("  <td" + labelStyle + ">" + fmt("item_view.loggedBy", ms, loc) + "</td>");
    sb.append("  <td" + tdStyle + ">" + item.getLoggedBy().getName() + "</td>");
    sb.append("  <td" + labelStyle + ">" + fmt("item_view.assignedTo", ms, loc) + "</td>");
    sb.append("  <td width='15%'" + tdStyle + ">"
            + (item.getAssignedTo() == null ? "" : item.getAssignedTo().getName()) + "</td>");
    sb.append("</tr>");
    sb.append("<tr" + altStyle + ">");
    sb.append("  <td" + labelStyle + ">" + fmt("item_view.summary", ms, loc) + "</td>");
    sb.append("  <td colspan='5'" + tdStyle + ">" + HtmlUtils.htmlEscape(item.getSummary()) + "</td>");
    sb.append("</tr>");
    sb.append("<tr>");
    sb.append("  <td valign='top'" + labelStyle + ">" + fmt("item_view.detail", ms, loc) + "</td>");
    sb.append("  <td colspan='5'" + tdStyle + ">" + fixWhiteSpace(item.getDetail()) + "</td>");
    sb.append("</tr>");

    int row = 0;
    Map<Field.Name, Field> fields = item.getSpace().getMetadata().getFields();
    for (Field.Name fieldName : item.getSpace().getMetadata().getFieldOrder()) {
        Field field = fields.get(fieldName);
        sb.append("<tr" + (row % 2 == 0 ? altStyle : "") + ">");
        sb.append("  <td" + labelStyle + ">" + field.getLabel() + "</td>");
        sb.append("  <td colspan='5'" + tdStyle + ">" + item.getCustomValue(field) + "</td>");
        sb.append("</tr>");
        row++;
    }
    sb.append("</table>");

    //=========================== ASSETS ===================================

    if (item.getSpace().isAssetEnabled()) {
        sb.append("<br/>&nbsp;<b" + tableStyle + ">" + fmt("item_view.assets", ms, loc) + "</b>");
        sb.append("<table width='100%'" + tableStyle + ">");

        //Header
        sb.append("<tr>");
        sb.append("  <th" + thStyle + ">" + fmt("item_view.assetType", ms, loc) + "</th><th" + thStyle + ">"
                + fmt("item_view.inventoryCode", ms, loc) + "</th>" + "<th" + thStyle + ">"
                + fmt("item_view.supportStartDate", ms, loc) + "</th><th" + thStyle + ">"
                + fmt("item_view.supportEndDate", ms, loc) + "</th><th" + thStyle + ">"
                + fmt("item_view.Attributes", ms, loc) + "</th>");
        sb.append("</tr>");

        //Detail
        if (item.getAssets() != null) {
            row = 1;
            for (Asset asset : item.getAssets()) {
                sb.append("<tr valign='top'" + (row % 2 == 0 ? altStyle : "") + ">");
                sb.append("  <td" + tdStyle + ">"
                        + fmt(asset.getAssetType().getNameTranslationResourceKey(), ms, loc) + "</td>"); //Asset Type
                sb.append("  <td" + tdStyle + ">" + asset.getInventoryCode() + "</td>"); // Inventory Code
                sb.append("  <td" + tdStyle + ">" + asset.getSupportStartDate() + "</td>"); // Support Start Date
                sb.append("  <td" + tdStyle + ">" + asset.getSupportEndDate() + "</td>"); // Support End Date
                sb.append("  <td" + tdStyle + ">" + "" + "</td>"); // Custom Attributes
                sb.append("</tr>");
                row++;
            } //for
        } //if

        sb.append("</table>");
    } //if

    //=========================== HISTORY ==================================

    sb.append("<br/>&nbsp;<b" + tableStyle + ">" + fmt("item_view.history", ms, loc) + "</b>");
    sb.append("<table width='100%'" + tableStyle + ">");
    sb.append("<tr>");
    sb.append("  <th" + thStyle + ">" + fmt("item_view.loggedBy", ms, loc) + "</th><th" + thStyle + ">"
            + fmt("item_view.status", ms, loc) + "</th>" + "<th" + thStyle + ">"
            + fmt("item_view.assignedTo", ms, loc) + "</th><th" + thStyle + ">"
            + fmt("item_view.comment", ms, loc) + "</th><th" + thStyle + ">"
            + fmt("item_view.timeStamp", ms, loc) + "</th>");
    List<Field> editable = item.getSpace().getMetadata().getEditableFields();
    for (Field field : editable) {
        sb.append("<th" + thStyle + ">" + field.getLabel() + "</th>");
    }
    sb.append("</tr>");

    if (item.getHistory() != null) {
        row = 1;
        for (History history : item.getHistory()) {
            sb.append("<tr valign='top'" + (row % 2 == 0 ? altStyle : "") + ">");
            sb.append("  <td" + tdStyle + ">" + history.getLoggedBy().getName() + "</td>");
            sb.append("  <td" + tdStyle + ">" + history.getStatusValue() + "</td>");
            sb.append("  <td" + tdStyle + ">"
                    + (history.getAssignedTo() == null ? "" : history.getAssignedTo().getName()) + "</td>");
            sb.append("  <td" + tdStyle + ">");
            Set<Attachment> attachments = history.getAttachments();
            if (attachments != null && attachments.size() > 0) {
                for (Attachment attachment : attachments) {
                    if (request != null && response != null) {
                        String href = response.encodeURL(request.getContextPath() + "/app/attachments/"
                                + attachment.getFileName() + "?filePrefix=" + attachment.getFilePrefix());
                        sb.append("<a target='_blank' href='" + href + "'>" + attachment.getFileName()
                                + "</a>&nbsp;");
                    } else {
                        sb.append("(attachment:&nbsp;" + attachment.getFileName() + ")&nbsp;<br />");
                    }
                }
            }
            sb.append(fixWhiteSpace(history.getComment()));
            sb.append("  </td>");
            sb.append("  <td" + tdStyle + ">" + history.getTimeStamp() + "</td>");
            for (Field field : editable) {
                sb.append("<td" + tdStyle + ">" + history.getCustomValue(field) + "</td>");
            }
            sb.append("</tr>");
            row++;
        }
    }
    sb.append("</table>");
    return sb.toString();
}

From source file:com.wso2telco.gsma.authenticators.sms.SMSAuthenticator.java

protected SMSMessage getRedirectInitAuthentication(HttpServletResponse response, AuthenticationContext context,
        UserStatus userStatus) throws AuthenticationFailedException {
    SMSMessage smsMessage = null;/*from   w ww.ja  v  a 2  s  .  c  o  m*/
    String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();
    String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
            context.getCallerSessionKey(), context.getContextIdentifier());

    if (log.isDebugEnabled()) {
        log.debug("Query parameters : " + queryParams);
    }

    try {
        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        } else {
            // Insert entry to DB only if this is not a retry
            DBUtils.insertUserResponse(context.getContextIdentifier(), String.valueOf(UserResponse.PENDING));
        }

        //MSISDN will be saved in the context in the MSISDNAuthenticator
        String msisdn = (String) context.getProperty(Constants.MSISDN);
        Application application = new Application();

        MobileConnectConfig connectConfig = configurationService.getDataHolder().getMobileConnectConfig();
        MobileConnectConfig.SMSConfig smsConfig = connectConfig.getSmsConfig();

        String encryptedContextIdentifier = AESencrp.encrypt(context.getContextIdentifier());
        String messageURL = connectConfig.getSmsConfig().getAuthUrl() + Constants.AUTH_URL_ID_PREFIX;

        Map<String, String> paramMap = Util.createQueryParamMap(queryParams);
        String client_id = paramMap.get(Constants.CLIENT_ID);
        String operator = (String) context.getProperty(Constants.OPERATOR);

        if (smsConfig.isShortUrl()) {
            // If a URL shortening service is enabled, then we need to encrypt the context identifier, create the
            // message URL and shorten it.
            SelectShortUrl selectShortUrl = new SelectShortUrl();
            messageURL = selectShortUrl.getShortUrl(smsConfig.getShortUrlClass(),
                    messageURL + response.encodeURL(encryptedContextIdentifier), smsConfig.getAccessToken(),
                    smsConfig.getShortUrlService());
        } else {
            // If a URL shortening service is not enabled, we need to created a hash key for the encrypted
            // context identifier and insert a database entry mapping ths hash key to the context identifier.
            // This is done to shorten the message URL as much as possible.
            String hashForContextId = getHashForContextId(encryptedContextIdentifier);
            messageURL += hashForContextId;
            DBUtils.insertHashKeyContextIdentifierMapping(hashForContextId, context.getContextIdentifier());
        }

        // prepare the USSD message from template
        HashMap<String, String> variableMap = new HashMap<String, String>();
        variableMap.put("application", application.changeApplicationName(
                context.getSequenceConfig().getApplicationConfig().getApplicationName()));
        variableMap.put("link", messageURL);
        boolean isRegistering = (boolean) context.getProperty(Constants.IS_REGISTERING);
        OutboundMessage.MessageType messageType = OutboundMessage.MessageType.SMS_LOGIN;

        if (isRegistering) {
            messageType = OutboundMessage.MessageType.SMS_REGISTRATION;
        }
        String messageText = OutboundMessage.prepare(client_id, messageType, variableMap, operator);

        if (log.isDebugEnabled()) {
            log.debug("Message URL: " + messageURL);
            log.debug("Message: " + messageText);
            log.debug("Operator: " + operator);
        }

        DBUtils.insertAuthFlowStatus(msisdn, Constants.STATUS_PENDING, context.getContextIdentifier());

        smsMessage = new SMSMessage();
        smsMessage.setMsisdn(msisdn);
        smsMessage.setMessageText(messageText);
        smsMessage.setOperator(operator);
        smsMessage.setClient_id(client_id);
        smsMessage.setRedirectURL(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                + "&authenticators=" + getName() + ":" + "LOCAL" + retryParam);

    } catch (Exception e) {
        DataPublisherUtil.updateAndPublishUserStatus(userStatus,
                DataPublisherUtil.UserState.SMS_AUTH_PROCESSING_FAIL, e.getMessage());
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
    return smsMessage;
}

From source file:com.sun.faban.harness.webclient.XFormServlet.java

/**
 * A get request starts a new form./*w  ww  . j a  v  a2 s .  c  om*/
 *
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException Error in request handling
 * @throws IOException Error doing other IO
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    Adapter adapter = null;

    String templateFile = (String) session.getAttribute("faban.submit.template");
    String styleSheet = (String) session.getAttribute("faban.submit.stylesheet");

    String srcURL = new File(templateFile).toURI().toString();

    logger.finer("benchmark.template: " + srcURL);
    session.removeAttribute("faban.submit.template");
    session.removeAttribute("faban.submit.stylesheet");

    try {
        String requestURI = request.getRequestURI();
        String formURI = null;
        String contextPath = request.getContextPath();
        String benchPath = contextPath + "/bm_submit/";
        if (requestURI.startsWith(benchPath)) {
            int idx = requestURI.indexOf('/', benchPath.length());
            String benchName = requestURI.substring(benchPath.length(), idx);
            String formName = requestURI.substring(idx + 1);
            formURI = com.sun.faban.harness.common.Config.FABAN_HOME + "benchmarks/" + benchName + "/META-INF/"
                    + formName;
        } else {
            StringBuffer buffer = new StringBuffer(request.getScheme());
            buffer.append("://");
            buffer.append(request.getServerName());
            buffer.append(":");
            buffer.append(request.getServerPort());
            buffer.append(request.getContextPath());
            buffer.append(request.getParameter("form"));
            formURI = buffer.toString();
        }

        if (formURI == null) {
            throw new IOException("Resource not found: " + formURI);
        }
        logger.finer("Form URI: " + formURI);

        String css = request.getParameter("css");
        String actionURL = response.encodeURL(request.getRequestURI());
        logger.finer("actionURL: " + actionURL);

        // Find the base URL used by Faban. We do not use Config.FABAN_URL
        // because this base URL can vary by the interface name the Faban
        // master is accessed in this session. Otherwise it is identical.
        StringBuffer baseURL = request.getRequestURL();
        int uriLength = baseURL.length() - requestURI.length() + contextPath.length();
        baseURL.setLength(++uriLength); // Add the ending slash

        adapter = new Adapter();
        if (configFile != null && configFile.length() > 0)
            adapter.setConfigPath(configFile);

        File xsl = null;
        if (styleSheet != null)
            xsl = new File(styleSheet);

        if (xsl != null && xsl.exists()) {
            adapter.xslPath = xsl.getParent();
            adapter.stylesheet = xsl.getName();
        } else {
            adapter.xslPath = xsltDir;
            adapter.stylesheet = "faban.xsl";
        }

        adapter.baseURI = baseURL.toString();
        adapter.formURI = formURI;
        adapter.actionURL = actionURL;
        adapter.beanCtx.put("chiba.web.uploadDir", uploadDir);
        adapter.beanCtx.put("chiba.useragent", request.getHeader("User-Agent"));
        adapter.beanCtx.put("chiba.web.request", request);
        adapter.beanCtx.put("chiba.web.session", session);
        adapter.beanCtx.put("benchmark.template", srcURL);

        if (css != null) {
            adapter.CSSFile = css;
            logger.fine("using css stylesheet: " + css);
        }

        Map servletMap = new HashMap();
        servletMap.put(ChibaAdapter.SESSION_ID, session.getId());
        adapter.beanCtx.put(ChibaAdapter.SUBMISSION_RESPONSE, servletMap);

        Enumeration params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String s = (String) params.nextElement();
            //store all request-params we don't use in the beanCtx map
            if (!(s.equals("form") || s.equals("xslt") || s.equals("css") || s.equals("action_url"))) {
                String value = request.getParameter(s);
                adapter.beanCtx.put(s, value);
                logger.finer("added request param '" + s + "' to beanCtx");
            }
        }
        adapter.init();
        adapter.execute();

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        adapter.generator.setOutput(out);
        adapter.buildUI();
        session.setAttribute("chiba.adapter", adapter);
        out.close();
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception processing XForms", e);
        shutdown(adapter, session, e, request, response);
    }
}

From source file:com.wso2telco.gsma.authenticators.sms.ServerInitiatedSMSAuthenticator.java

protected SMSMessage getRedirectInitAuthentication(HttpServletResponse response, AuthenticationContext context,
        UserStatus userStatus) throws AuthenticationFailedException {
    SMSMessage smsMessage = null;/*from w  w  w. j  a  v a 2 s .  c o m*/
    String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(),
            context.getCallerSessionKey(), context.getContextIdentifier());

    if (log.isDebugEnabled()) {
        log.debug("Query parameters : " + queryParams);
    }

    try {
        String retryParam = "";

        if (context.isRetrying()) {
            retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
        } else {
            // Insert entry to DB only if this is not a retry
            DBUtils.insertUserResponse(context.getContextIdentifier(), UserResponse.PENDING.name());
        }

        //MSISDN will be saved in the context in the MSISDNAuthenticator
        String msisdn = (String) context.getProperty(Constants.MSISDN);
        Application application = new Application();

        MobileConnectConfig connectConfig = configurationService.getDataHolder().getMobileConnectConfig();
        MobileConnectConfig.SMSConfig smsConfig = connectConfig.getSmsConfig();

        String encryptedContextIdentifier = AESencrp.encrypt(context.getContextIdentifier());
        //String messageURL = connectConfig.getSmsConfig().getAuthUrl() + Constants.AUTH_URL_ID_PREFIX;
        String messageURL = mobileConnectConfigs.getBackChannelConfig().getSmsCallbackUrl()
                + Constants.AUTH_URL_ID_PREFIX; //todo: add to config

        Map<String, String> paramMap = Util.createQueryParamMap(queryParams);
        String client_id = paramMap.get(Constants.CLIENT_ID);
        String operator = (String) context.getProperty(Constants.OPERATOR);

        if (smsConfig.isShortUrl()) {
            // If a URL shortening service is enabled, then we need to encrypt the context identifier, create the
            // message URL and shorten it.
            log.info("URL shortening service is enabled");
            SelectShortUrl selectShortUrl = new SelectShortUrl();
            messageURL = selectShortUrl.getShortUrl(smsConfig.getShortUrlClass(),
                    messageURL + response.encodeURL(encryptedContextIdentifier), smsConfig.getAccessToken(),
                    smsConfig.getShortUrlService());
        } else {
            // If a URL shortening service is not enabled, we need to created a hash key for the encrypted
            // context identifier and insert a database entry mapping ths hash key to the context identifier.
            // This is done to shorten the message URL as much as possible.
            log.info("Generating hash key for the SMS");
            String hashForContextId = getHashForContextId(encryptedContextIdentifier);
            messageURL += hashForContextId;
            DBUtils.insertHashKeyContextIdentifierMapping(hashForContextId, context.getContextIdentifier());
        }

        // prepare the USSD message from template
        HashMap<String, String> variableMap = new HashMap<String, String>();
        variableMap.put("application", application.changeApplicationName(
                context.getSequenceConfig().getApplicationConfig().getApplicationName()));
        variableMap.put("link", messageURL);
        boolean isRegistering = (boolean) context.getProperty(Constants.IS_REGISTERING);
        OutboundMessage.MessageType messageType = OutboundMessage.MessageType.SMS_LOGIN;

        if (isRegistering) {
            messageType = OutboundMessage.MessageType.SMS_REGISTRATION;
        }
        String messageText = OutboundMessage.prepare(client_id, messageType, variableMap, operator);

        if (log.isDebugEnabled()) {
            log.debug("Message URL: " + messageURL);
            log.debug("Message: " + messageText);
            log.debug("Operator: " + operator);
        }

        DBUtils.insertAuthFlowStatus(msisdn, Constants.STATUS_PENDING, context.getContextIdentifier());

        smsMessage = new SMSMessage();
        smsMessage.setMsisdn(msisdn);
        smsMessage.setMessageText(messageText);
        smsMessage.setOperator(operator);
        smsMessage.setClient_id(client_id);
    } catch (Exception e) {
        DataPublisherUtil.updateAndPublishUserStatus(userStatus,
                DataPublisherUtil.UserState.SMS_AUTH_PROCESSING_FAIL, e.getMessage());
        log.error(AUTH_FAILED, e);
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
    return smsMessage;
}