Example usage for org.apache.commons.lang StringEscapeUtils escapeHtml

List of usage examples for org.apache.commons.lang StringEscapeUtils escapeHtml

Introduction

In this page you can find the example usage for org.apache.commons.lang StringEscapeUtils escapeHtml.

Prototype

public static String escapeHtml(String input) 

Source Link

Usage

From source file:edu.harvard.iq.dataverse.RolePermissionFragment.java

private void assignRole(RoleAssignee ra, DataverseRole r) {
    try {/*from   ww w  .  jav a  2  s  .  c o m*/
        String privateUrlToken = null;
        commandEngine.submit(new AssignRoleCommand(ra, r, dvObject, dvRequestService.getDataverseRequest(),
                privateUrlToken));
        JH.addMessage(FacesMessage.SEVERITY_INFO,
                "Role " + r.getName() + " assigned to " + ra.getDisplayInfo().getTitle() + " on "
                        + StringEscapeUtils.escapeHtml(dvObject.getDisplayName()));
    } catch (CommandException ex) {
        JH.addMessage(FacesMessage.SEVERITY_ERROR, "Can't assign role: " + ex.getMessage());
    }
}

From source file:com.evolveum.midpoint.web.component.wf.processes.itemApproval.ItemApprovalPanel.java

private void initLayout() {

    Label itemToBeApprovedLabel = new Label(ID_ITEM_TO_BE_APPROVED_LABEL,
            new StringResourceModel("${}", new AbstractReadOnlyModel<String>() {
                @Override//from w w w.  ja  v a2 s .  c  o m
                public String getObject() {
                    if (!model.getObject().isAnswered()) {
                        return "ItemApprovalPanel.itemToBeApproved";
                    } else {
                        Boolean result = model.getObject().getAnswerAsBoolean();
                        if (result == null) {
                            return "ItemApprovalPanel.itemThatWasCompleted"; // actually, this should not happen, if the process is ItemApproval
                        } else if (result) {
                            return "ItemApprovalPanel.itemThatWasApproved";
                        } else {
                            return "ItemApprovalPanel.itemThatWasRejected";
                        }
                    }
                }
            }));
    itemToBeApprovedLabel.add(new AttributeModifier("color", new AbstractReadOnlyModel<String>() {
        @Override
        public String getObject() {
            if (!model.getObject().isAnswered()) {
                return "black"; // should not be visible, anyway
            } else {
                Boolean result = model.getObject().getAnswerAsBoolean();
                if (result == null) {
                    return "black"; // actually, this should not happen, if the process is ItemApproval
                } else if (result) {
                    return "green";
                } else {
                    return "red";
                }
            }
        }
    }));
    add(itemToBeApprovedLabel);

    Label itemToBeApproved = new Label(ID_ITEM_TO_BE_APPROVED, new AbstractReadOnlyModel<String>() {

        @Override
        public String getObject() {

            ItemApprovalProcessState instanceState = (ItemApprovalProcessState) model.getObject()
                    .getInstanceState().getProcessSpecificState();
            ItemApprovalRequestType approvalRequestType = instanceState.getApprovalRequest();

            if (approvalRequestType == null) {
                return "?";
            } else {
                Object item = approvalRequestType.getItemToApprove();
                if (item instanceof AssignmentType) {
                    AssignmentType assignmentType = (AssignmentType) item;
                    if (assignmentType.getTarget() != null) {
                        return assignmentType.getTarget().toString();
                    } else if (assignmentType.getTargetRef() != null) {
                        return assignmentType.getTargetRef().getOid() + " ("
                                + assignmentType.getTargetRef().getType() + ")";
                    } else {
                        return "?";
                    }
                } else {
                    return item != null ? item.toString() : "(none)";
                }
            }
        }
    });
    add(itemToBeApproved);

    // todo i18n
    Label approvalSchema = new Label(ID_APPROVAL_SCHEMA, new AbstractReadOnlyModel() {
        @Override
        public Object getObject() {
            StringBuilder retval = new StringBuilder();

            ItemApprovalProcessState instanceState = (ItemApprovalProcessState) model.getObject()
                    .getInstanceState().getProcessSpecificState();
            ItemApprovalRequestType approvalRequestType = instanceState.getApprovalRequest();

            if (approvalRequestType == null) {
                return "?";
            } else {
                ApprovalSchemaType approvalSchema = approvalRequestType.getApprovalSchema();
                if (approvalSchema != null) {
                    if (approvalSchema.getName() != null) {
                        retval.append("<b>");
                        retval.append(StringEscapeUtils.escapeHtml(approvalSchema.getName()));
                        retval.append("</b>");
                    }
                    if (approvalSchema.getDescription() != null) {
                        retval.append(" (");
                        retval.append(StringEscapeUtils.escapeHtml(approvalSchema.getDescription()));
                        retval.append(")");
                    }
                    if (approvalSchema.getName() != null || approvalSchema.getDescription() != null) {
                        retval.append("<br/>");
                    }
                    retval.append("Levels:<p/><ol>");
                    for (ApprovalLevelType level : approvalSchema.getLevel()) {
                        retval.append("<li>");
                        if (level.getName() != null) {
                            retval.append(StringEscapeUtils.escapeHtml(level.getName()));
                        } else {
                            retval.append("unnamed level");
                        }
                        if (level.getDescription() != null) {
                            retval.append(" (");
                            retval.append(StringEscapeUtils.escapeHtml(level.getDescription()));
                            retval.append(")");
                        }
                        if (level.getEvaluationStrategy() != null) {
                            retval.append(" [" + level.getEvaluationStrategy() + "]");
                        }
                        if (level.getAutomaticallyApproved() != null) {
                            String desc = level.getAutomaticallyApproved().getDescription();
                            if (desc != null) {
                                retval.append(" (auto-approval condition: " + StringEscapeUtils.escapeHtml(desc)
                                        + ")");
                            } else {
                                retval.append(" (auto-approval condition present)");
                            }
                        }
                        retval.append("<br/>Approvers:<ul>");
                        for (ObjectReferenceType approverRef : level.getApproverRef()) {
                            retval.append("<li>");
                            retval.append(approverRef.getOid());
                            if (approverRef.getType() != null) {
                                retval.append(" (" + approverRef.getType().getLocalPart() + ")");
                            }
                            if (approverRef.getDescription() != null) {
                                retval.append(" - " + approverRef.getDescription());
                            }
                            retval.append("</li>");
                        }
                        for (ExpressionType expression : level.getApproverExpression()) {
                            retval.append("<li>Expression: ");
                            // todo display the expression
                            if (expression.getDescription() != null) {
                                retval.append(StringEscapeUtils.escapeHtml(expression.getDescription()));
                            } else {
                                retval.append("(...)");
                            }
                            retval.append("</li>");
                        }
                    }

                    retval.append("</ul>"); // ends the list of approvers
                    retval.append("</ol>"); // ends the list of levels
                }
            }
            return retval.toString();
        }
    });
    approvalSchema.setEscapeModelStrings(false);
    add(approvalSchema);

    add(new Label(ID_DECISIONS_DONE_LABEL,
            new StringResourceModel("ItemApprovalPanel.decisionsDoneWhenFinishedIs_${finished}", model)));

    add(new DecisionsPanel(ID_DECISIONS_DONE, new AbstractReadOnlyModel<List<DecisionDto>>() {
        @Override
        public List<DecisionDto> getObject() {
            List<DecisionDto> retval = new ArrayList<>();
            ProcessInstanceDto processInstanceDto = model.getObject();
            processInstanceDto.reviveIfNeeded(ItemApprovalPanel.this);
            ItemApprovalProcessState instanceState = (ItemApprovalProcessState) processInstanceDto
                    .getInstanceState().getProcessSpecificState();
            List<DecisionType> allDecisions = instanceState.getDecisions();
            if (allDecisions != null) {
                for (DecisionType decision : allDecisions) {
                    retval.add(new DecisionDto(decision));
                }
            }
            return retval;
        }
    }));

    VisibleEnableBehaviour visibleIfRunning = new VisibleEnableBehaviour() {
        @Override
        public boolean isVisible() {
            return !model.getObject().isFinished();
        }
    };

    Label workItemsPanelLabel = new Label(ID_CURRENT_WORK_ITEMS_LABEL,
            new ResourceModel("ItemApprovalPanel.currentWorkItems"));
    workItemsPanelLabel.add(visibleIfRunning);
    add(workItemsPanelLabel);

    WorkItemsPanel workItemsPanel = new WorkItemsPanel(ID_CURRENT_WORK_ITEMS,
            new PropertyModel<List<WorkItemDto>>(model, "workItems"));
    workItemsPanel.add(visibleIfRunning);
    add(workItemsPanel);
}

From source file:com.onehippo.gogreen.components.search.AbstractSearchComponent.java

protected boolean showFacetedDocuments(HstRequest request) {
    HippoBean bean = getContentBean(request);
    if (bean instanceof HippoFacetChildNavigationBean) {
        String query = SearchInputParsingUtils.parse(getQuery(request), false);
        HippoFacetNavigationBean facetBean = BeanUtils.getFacetNavigationBean(request, query, objectConverter);
        HippoDocumentIterator<HippoBean> facetIt = facetBean.getResultSet()
                .getDocumentIterator(HippoBean.class);
        int facetCount = facetBean.getCount().intValue();
        int pageSize = getPageSize(request);
        int currentPage = getCurrentPage(request);
        PageableCollection<HippoBean> results = new PageableCollection<HippoBean>(facetIt, facetCount, pageSize,
                currentPage);/* w  w  w .  j  a  v  a 2s  . c o m*/
        request.setAttribute("searchResult", results);
        request.setAttribute("query", StringEscapeUtils.escapeHtml(query));
        return true;
    } else {
        return false;
    }
}

From source file:dk.dma.epd.common.text.Formatter.java

/**
 * A very simple and crude conversion of plain text into HTML.
 * //from   www . j  av  a  2s. co m
 * @param str
 *            the string to format
 * @return the resulting HTML
 */
public static String formatHtml(String str) {
    // Sanity checks
    if (str == null) {
        return str;
    }

    str = StringEscapeUtils.escapeHtml(str);
    str = str.replaceAll("\n", "<br/>");
    return str;
}

From source file:cc.kune.core.server.manager.I18nManagerDefaultTest.java

/**
 * Insert data.//from   w  w w .  j a va 2  s  . c  o  m
 */
@Before
public void insertData() {
    openTransaction();
    final I18nLanguage english = new I18nLanguage(Long.valueOf(1819), "English", "English", "en");
    final I18nLanguage spanish = new I18nLanguage(Long.valueOf(5889), "Spanish", "Espaol", "es");
    final I18nLanguage afrikaans = new I18nLanguage(Long.valueOf(114), "Afrikaans", "Afrikaans", "af");
    final I18nLanguage greek = new I18nLanguage(Long.valueOf(1793), "Greek", "", "el");
    languageManager.persist(english);
    languageManager.persist(spanish);
    languageManager.persist(afrikaans);
    languageManager.persist(greek);
    translationManager
            .persist(new I18nTranslation("Sunday [weekday]", english, "Sunday", "note for translators"));
    translationManager
            .persist(new I18nTranslation("January [month]", english, "January", "note for translators"));
    translationManager
            .persist(new I18nTranslation("January [month]", spanish, "Enero", "note for translators"));
    translationManager
            .persist(new I18nTranslation("Sunday [weekday]", afrikaans, "Sondag", "note for translators"));
    translationManager.persist(
            new I18nTranslation("January [month]", greek, "?", "note for translators"));
    translationManager.persist(new I18nTranslation(StringEscapeUtils.escapeHtml("[%s] users"), english,
            StringEscapeUtils.escapeHtml("[%s] users"), "note for translators"));
    translationManager.persist(new I18nTranslation(StringEscapeUtils.escapeHtml("[%d] users"), english,
            StringEscapeUtils.escapeHtml("[%d] users"), "note for translators"));
    final I18nCountry gb = new I18nCountry(Long.valueOf(75), "GB", "GBP", ".", "%n", "", ".",
            "United Kingdom", "western", ",");
    countryManager.persist(gb);
}

From source file:it.eng.spagobi.commons.presentation.tags.LovColumnsSelectorTag.java

protected void makeTable() throws JspException {
    // get the column names from the module response config
    List columnNames = new ArrayList();
    List columnNamesSB = moduleConfig.getAttributeAsList("COLUMNS.COLUMN");
    if (columnNamesSB != null && columnNamesSB.size() > 0) {
        Iterator it = columnNamesSB.iterator();
        while (it.hasNext()) {
            SourceBean columnSB = (SourceBean) it.next();
            String columnName = (String) columnSB.getAttribute("name");
            if (columnName != null)
                columnNames.add(columnName);
        }// w ww .  j  ava2  s.co m
    }

    /*
    // get the column names from the first row of the list
    // TODO check if all the rows have the same columns
    List columnNames = new ArrayList();
    SourceBean rowsSB = (SourceBean)moduleResponse.getAttribute("PAGED_LIST.ROWS");
    List rows = null;
    if(rowsSB!=null) {
       rows = rowsSB.getAttributeAsList("ROW");
       // take the first row 
       if(rows.size()!=0) {
    SourceBean row = (SourceBean)rows.get(0);
    List attributes = row.getContainedAttributes();
    Iterator iterAttr = attributes.iterator();
    while(iterAttr.hasNext()) {
       SourceBeanAttribute attrsba = (SourceBeanAttribute)iterAttr.next();
       columnNames.add(attrsba.getKey());
    }
       }
    }
    */

    // create the columns table selector
    htmlStream.append("<table class=\"object-details-table\" style=\"width:100%;\">\n");
    htmlStream.append("   <tr >\n");
    htmlStream.append("      <td style=\"background:rgb(254,232,186);\" class=\"portlet-section-header\">"
            + columnsField + "</td>\n");
    htmlStream.append(
            "       <td class=\"portlet-section-header\" style=\"background:rgb(254,232,186);text-align:center;width:120px;\">"
                    + valueColumnsField + "</td>\n");
    htmlStream.append(
            "       <td class=\"portlet-section-header\" style=\"background:rgb(254,232,186);text-align:center;width:150px;\">"
                    + descriptionColumnsField + "</td>\n");
    htmlStream.append(
            "       <td class=\"portlet-section-header\" style=\"background:rgb(254,232,186);text-align:center;width:150px;\">"
                    + visColumnsField + "<td>\n");
    htmlStream.append("   </tr>\n");

    String[] visColArr = visibleColumns.toUpperCase().split(",");
    List visColList = Arrays.asList(visColArr);
    Iterator iterCoNames = columnNames.iterator();
    while (iterCoNames.hasNext()) {
        String colName = (String) iterCoNames.next();
        String checked = " ";
        String selectedValue = " ";
        String selectedDescr = " ";
        colName = StringEscapeUtils.escapeHtml(colName);
        if (colName.equalsIgnoreCase(valueColumn)) {
            selectedValue = " checked ";
        }
        if (colName.equalsIgnoreCase(descriptionColumn)) {
            selectedDescr = " checked ";
        }
        if (visColList.contains(colName.toUpperCase())) {
            checked = " checked ";
        }

        htmlStream.append("   <tr>\n");
        htmlStream.append("   <td style=\"background:rgb(251,247,227);\" class=\"portlet-section-body\">"
                + colName + "\n");
        htmlStream.append("      <INPUT type='hidden' value='" + colName + "' name='column' />\n");
        htmlStream.append("   </td>\n");
        htmlStream.append(
                "   <td align=\"center\" style=\"background:rgb(251,247,227); align=\"center\" class=\"portlet-section-body\">\n");
        htmlStream.append("      <INPUT " + selectedValue + " type='radio' value='" + colName
                + "' name='valueColumn' />\n");
        htmlStream.append("   </td>\n");
        htmlStream.append(
                "   <td align=\"center\" style=\"background:rgb(251,247,227); align=\"center\" class=\"portlet-section-body\">\n");
        htmlStream.append("      <INPUT " + selectedDescr + " type='radio' value='" + colName
                + "' name='descriptionColumn' />\n");
        htmlStream.append("   </td>\n");
        htmlStream.append(
                "   <td align=\"center\" style=\"background:rgb(251,247,227); align=\"center\" class=\"portlet-section-body\">\n");
        htmlStream.append("      <INPUT " + checked + " type='checkbox' value='" + colName
                + "' name='visibleColumn' />\n");
        htmlStream.append("   </td>\n");
        htmlStream.append("   </tr>\n");
    }
    htmlStream.append("<table>\n");
}

From source file:com.krawler.crm.reportBuilder.bizservice.ReportBuilderServiceImpl.java

@Override
public JSONObject getReportMetadata(JSONObject commData, boolean export, int reportno, StringBuffer searchJson,
        ArrayList<CustomReportColumns> quickSearchCol, ArrayList<CustomReportColumns> groupCol,
        ArrayList<String> dataIndexList, ArrayList<String> refTableList,
        HashMap<String, String> dataIndexReftableMap, boolean detailFlag) {
    JSONObject jobjTemp = new JSONObject();
    JSONArray jarrColumns = new JSONArray();
    JSONArray jarrRecords = new JSONArray();
    JSONArray jarrDateFields = new JSONArray();
    JSONObject jMeta = new JSONObject();
    try {/*from w  ww.  ja va 2 s .  c  o m*/
        String rcategory = "";
        boolean groupflag = false;
        boolean summaryflag = false;
        String reportdesc = "";
        String groupcolumn = "";
        CustomReportList customReportObj = null;
        String refTable = "";
        ArrayList filter_params = new ArrayList();
        ArrayList filter_names = new ArrayList();
        filter_names.add("c.reportno.rno");
        filter_params.add(reportno);
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("filter_names", filter_names);
        requestParams.put("filter_params", filter_params);
        KwlReturnObject kmsg = reportBuilderDaoObj.getCustomReportConfig(requestParams);
        List<CustomReportColumns> ll = kmsg.getEntityList();
        for (CustomReportColumns obj : ll) {
            customReportObj = obj.getReportno();
            rcategory = customReportObj.getRcategory();
            groupflag = (customReportObj.isGroupflag() && !detailFlag);
            summaryflag = customReportObj.isSummaryflag();
            if (!StringUtil.isNullOrEmpty(customReportObj.getRdescription())) {
                reportdesc = customReportObj.getRdescription();
            } else {
                reportdesc = customReportObj.getRname();
            }
            String xtype = obj.getXtype();
            if (groupflag) {
                if (!obj.isGroupflag()) {
                    if (!(xtype.equals("2") && !obj.getSummarytype().isEmpty())) {
                        continue;
                    }
                }
            }
            jobjTemp = new JSONObject();
            jobjTemp.put("header", obj.getDisplayname());
            jobjTemp.put("tip", StringEscapeUtils.escapeHtml(obj.getDisplayname()));
            //                    jobjTemp.put("title", obj.getDisplayname());// Not require 
            jobjTemp.put("pdfwidth", 60);
            //                    jobjTemp.put("sortable", true);
            jobjTemp.put("dataIndex", obj.getDataIndex().replace(".", "#"));
            if (groupflag) {
                String dataindex = "";
                if (obj.isGroupflag()) {
                    jobjTemp.put("groupcolumn", true);
                    groupcolumn = obj.getDataIndex().replace(".", "#");
                    //                            if(xtype.equals("8") && obj.getDataIndex().contains("customdata")) {
                    //                                refTableList.add(obj.getRefTable());
                    //                            }
                }
                if (!obj.getSummarytype().isEmpty()) {
                    dataindex = obj.getSummarytype() + "(" + obj.getDataIndex().replace(".", "#") + "*1)";
                    jobjTemp.put("dataIndex", dataindex);
                }
            }
            jobjTemp.put("renderer",
                    StringUtil.isNullOrEmpty(obj.getRenderer()) ? "" : getCustomRenderer(obj.getRenderer()));
            jobjTemp.put("summaryType",
                    StringUtil.isNullOrEmpty(obj.getSummarytype()) ? "" : obj.getSummarytype());
            String align = "left";
            if (xtype.equals("2")) {//Number field
                align = "right";
            } else if (xtype.equals("3")) {//Date field
                align = "center";
                jobjTemp.put("xtype", "datefield");
            }
            jobjTemp.put("align", align);
            jarrColumns.put(jobjTemp);

            jobjTemp = new JSONObject();
            jobjTemp.put("name", obj.getDataIndex().replace(".", "#"));
            if (groupflag) {
                if (!obj.getSummarytype().isEmpty()) {
                    jobjTemp.put("name",
                            obj.getSummarytype() + "(" + obj.getDataIndex().replace(".", "#") + "*1)");
                }
                if (obj.isGroupflag()) {
                    JSONObject jobjTemp1 = new JSONObject();
                    jobjTemp1.put("name", obj.getDataIndex().replace(".", "#") + "_id");
                    jarrRecords.put(jobjTemp1);
                }
            }
            if (xtype.equals("3")) {//For date field
                jobjTemp.put("type", "date");
                jobjTemp.put("dateFormat", "time");

                JSONObject jobjTemp1 = new JSONObject();
                jobjTemp1.put("dataindex", obj.getDataIndex());
                jobjTemp1.put("displayname", obj.getDisplayname());
                jarrDateFields.put(jobjTemp1);
            }
            jarrRecords.put(jobjTemp);
            if (groupflag) {
                if (!obj.getSummarytype().isEmpty()) {
                    dataIndexList.add(obj.getSummarytype() + "(" + obj.getDataIndex() + "*1)");
                } else {
                    dataIndexList.add(obj.getDataIndex());
                }
                groupCol.add(obj);
            } else {
                dataIndexList.add(obj.getDataIndex());
            }
            String rcategoryTable = "";
            if (rcategory.equals(Constants.MODULE_LEAD)) {
                rcategoryTable = Constants.Crm_lead;
            } else if (rcategory.equals(Constants.MODULE_PRODUCT)) {
                rcategoryTable = Constants.Crm_product;
            } else if (rcategory.equals(Constants.MODULE_CONTACT)) {
                rcategoryTable = Constants.Crm_contact;
            } else if (rcategory.equals(Constants.MODULE_OPPORTUNITY)) {
                rcategoryTable = Constants.Crm_opportunity;
            } else if (rcategory.equals(Constants.MODULE_ACCOUNT)) {
                rcategoryTable = Constants.Crm_account;
            } else if (rcategory.equals(Constants.Crm_Case_modulename)) {
                rcategoryTable = Constants.Crm_case;
            }

            if (!rcategoryTable.equals(obj.getDataIndex().split("\\.")[0])) {
                refTableList.add(obj.getDataIndex().split("\\.")[0]);
            }
            refTableList.add(obj.getRefTable());
            dataIndexReftableMap.put(obj.getDataIndex().replace(".", "#"), obj.getRefTable());

            if (StringUtil.isNullOrEmpty(searchJson.toString())) {
                searchJson.append(obj.getReportno().getRfilterjson());
            }
            if (obj.isQuicksearch()) {
                quickSearchCol.add(obj);
            }
        }

        commData.put("columns", jarrColumns);
        if (jarrDateFields.length() == 0) {//Add date columns in Date filter dropdown
            if (rcategory.equals(Constants.MODULE_LEAD)) {
                refTable = Constants.Crm_lead;
            } else if (rcategory.equals(Constants.MODULE_PRODUCT)) {
                refTable = Constants.Crm_product;
            } else if (rcategory.equals(Constants.MODULE_CONTACT)) {
                refTable = Constants.Crm_contact;
            } else if (rcategory.equals(Constants.MODULE_OPPORTUNITY)) {
                refTable = Constants.Crm_opportunity;
            } else if (rcategory.equals(Constants.MODULE_ACCOUNT)) {
                refTable = Constants.Crm_account;
            } else if (rcategory.equals(Constants.Crm_Case_modulename)) {
                refTable = Constants.Crm_case;
            }
            JSONObject jobjTemp1 = new JSONObject();
            jobjTemp1.put("dataindex", refTable + ".createdon");
            jobjTemp1.put("displayname", rcategory + " Creation Date");
            jarrDateFields.put(jobjTemp1);
        }
        commData.put("datecolumns", jarrDateFields);
        commData.put("summaryflag", summaryflag);
        commData.put("groupflag", groupflag);
        commData.put("groupcolumn", groupcolumn);
        commData.put("reportdesc", reportdesc);
        jMeta.put("totalProperty", "totalCount");
        jMeta.put("root", "coldata");
        jMeta.put("fields", jarrRecords);
        //                jMeta.put("sortInfo", "{field: 'crm_lead#industryid',direction: 'ASC'}");
        commData.put("metaData", jMeta);
    } catch (Exception e) {
        LOGGER.warn(e.getMessage(), e);
    }
    return commData;
}

From source file:com.sonymobile.backlogtool.Story.java

public String getCustomer() {
    return StringEscapeUtils.escapeHtml(customer);
}

From source file:at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet.java

/**
 * Verifies the signed authentication block and redirects the browser
 * to the online application requested, adding a parameter needed for
 * retrieving the authentication data.// w  ww . j av  a  2  s.  co  m
 * <br>
 * Request parameters:
 * <ul>
 * <li>MOASessionID: ID of associated authentication session</li>
 * <li>XMLResponse: <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
 * </ul>
 * Response:
 * <ul>
 * <li>Status: <code>302</code></li>
 * <li>Header <code>"Location"</code>: URL of the online application requested, with
 *                   parameters <code>"Target"</code>(only if the online application is
 *            a public service) and <code>"SAMLArtifact"</code> added</li>
 * <li>Error status: <code>500</code>
 * </ul>
 * @see AuthenticationServer#verifyAuthenticationBlock
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Logger.debug("POST VerifyAuthenticationBlock");

    Logger.warn(getClass().getName() + " is deprecated and should not be used any more.");

    resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
    resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
    resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
    resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

    String pendingRequestID = null;

    Map<String, String> parameters;
    try {
        parameters = getParameters(req);
    } catch (FileUploadException e) {
        Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
        throw new IOException(e.getMessage());

    }
    String sessionID = req.getParameter(PARAM_SESSIONID);
    String createXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE);

    // escape parameter strings
    sessionID = StringEscapeUtils.escapeHtml(sessionID);
    pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID);

    String redirectURL = null;
    try {
        // check parameter
        if (!ParamValidatorUtils.isValidSessionID(sessionID))
            throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");
        if (!ParamValidatorUtils.isValidXMLDocument(createXMLSignatureResponse))
            throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_XMLRESPONSE, "auth.12");

        AuthenticationSession session = AuthenticationServer.getSession(sessionID);

        //change MOASessionID
        sessionID = AuthenticationSessionStoreage.changeSessionID(session);

        String samlArtifactBase64 = AuthenticationServer.getInstance().verifyAuthenticationBlock(session,
                createXMLSignatureResponse);

        if (samlArtifactBase64 == null) {
            //mandate Mode

            AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance();
            ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter();
            SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(),
                    connectionParameters);

            // get identitity link as byte[]
            Element elem = session.getIdentityLink().getSamlAssertion();
            String s = DOMUtils.serializeNode(elem);

            //System.out.println("IDL: " + s);

            byte[] idl = s.getBytes("UTF-8");

            // redirect url
            // build redirect(to the GetMISSessionIdSerlvet)

            //change MOASessionID before MIS request
            String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session);

            redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), GET_MIS_SESSIONID,
                    newMOASessionID);

            String oaURL = session.getOAURLRequested();
            OAAuthParameter oaParam = authConf.getOnlineApplicationParameter(oaURL);
            List<String> profiles = oaParam.getMandateProfiles();

            if (profiles == null) {
                Logger.error("No Mandate/Profile for OA configured.");
                throw new AuthenticationException("config.21", new Object[] { GET_MIS_SESSIONID });
            }

            //                 String profilesArray[] = profiles.split(",");             
            //                 for(int i = 0; i < profilesArray.length; i++) {
            //                    profilesArray[i] = profilesArray[i].trim();
            //                 }

            String oaFriendlyName = oaParam.getFriendlyName();
            String mandateReferenceValue = session.getMandateReferenceValue();
            byte[] cert = session.getEncodedSignerCertificate();
            byte[] authBlock = session.getAuthBlock().getBytes("UTF-8");

            //TODO: check in case of SSO!!!
            String targetType = null;
            if (oaParam.getBusinessService()) {
                String id = oaParam.getIdentityLinkDomainIdentifier();
                if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
                    targetType = id;
                else
                    targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + session.getDomainIdentifier();

            } else {
                targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
            }

            MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest(connectionParameters.getUrl(), idl,
                    cert, oaFriendlyName, redirectURL, mandateReferenceValue, profiles, targetType, authBlock,
                    sslFactory);

            if (misSessionID == null) {
                Logger.error("Fehler bei Anfrage an Vollmachten Service. MIS Session ID ist null.");
                throw new MISSimpleClientException("Fehler bei Anfrage an Vollmachten Service.");
            }

            String redirectMISGUI = misSessionID.getRedirectURL();
            session.setMISSessionID(misSessionID.getSessiondId());

            try {
                AuthenticationSessionStoreage.storeSession(session);
            } catch (MOADatabaseException e) {
                throw new MOAIDException("Session store error", null);
            }

            resp.setStatus(302);
            resp.addHeader("Location", redirectMISGUI);
            Logger.debug("REDIRECT TO: " + redirectURL);
        } else {

            if (!samlArtifactBase64.equals("Redirect to Input Processor")) {
                /*redirectURL = session.getOAURLRequested();
                if (!session.getBusinessService()) {
                   redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8"));
                        
                }
                redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8"));
                redirectURL = resp.encodeRedirectURL(redirectURL);*/

                redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(),
                        ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID),
                        samlArtifactBase64);

            } else {
                redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(),
                        AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, session.getSessionID());
            }

            resp.setContentType("text/html");
            resp.setStatus(302);

            resp.addHeader("Location", redirectURL);
            Logger.debug("REDIRECT TO: " + redirectURL);

        }

    }

    catch (MOAIDException ex) {
        handleError(null, ex, req, resp, pendingRequestID);

    } catch (GeneralSecurityException e) {
        handleError(null, e, req, resp, pendingRequestID);

    } catch (PKIException e) {
        handleError(null, e, req, resp, pendingRequestID);

    } catch (TransformerException e) {
        handleError(null, e, req, resp, pendingRequestID);

    } catch (Exception e) {
        Logger.error("AuthBlockValidation has an interal Error.", e);
    }

    finally {
        ConfigurationDBUtils.closeSession();
    }

}

From source file:com.edgenius.wiki.render.impl.RenderContextImpl.java

public String buildURL(RenderPiece obj) {
    if (obj instanceof LinkModel) {
        //LinkModel need render absolute URL info, so here don't use toString() simply.
        LinkModel lm = ((LinkModel) obj);
        if (lm.getType() == LinkModel.LINK_TO_VIEW_FLAG) {
            if (RENDER_TARGET_PAGE.equals(target) || RENDER_TARGET_INDEX.equals(target)
                    || RENDER_TARGET_RICH_EDITOR.equals(target)) {
                //return empty - even index does not this link setup URL 
                return "";
            }//from  w ww.  j av  a  2 s .com

            //export URL: as all link will be in one page, so, all of them are anchor in this page.
            if (RENDER_TARGET_EXPORT.equals(target)) {
                //TODO: there are problem to handle extspace anchor!!!
                StringBuffer buf = new StringBuffer("<a href ='#");
                if (!StringUtils.isBlank(lm.getAnchor())) {
                    buf.append(lm.getAnchor());
                } else {
                    if (!StringUtils.isBlank(lm.getSpaceUname())) {
                        buf.append(StringEscapeUtils.escapeHtml(lm.getSpaceUname()));
                        if (!StringUtils.isBlank(lm.getLink()))
                            buf.append("_").append(StringEscapeUtils.escapeHtml(lm.getLink()));
                    }
                }
                buf.append("'>").append(lm.getView()).append("</a>").toString();
                return buf.toString();
            }

            if (RENDER_TARGET_PLAIN_VIEW.equals(target)) {
                String anchor = StringUtils.isBlank(lm.getAnchor()) ? ""
                        : EscapeUtil.escapeToken(lm.getAnchor().trim());
                return new StringBuffer("<a href ='")
                        .append(linkRenderHelper.getFullURL(this, lm.getSpaceUname(), lm.getLink(), anchor))
                        .append("'>").append(lm.getView()).append("</a>").toString();
            } else {

            }
        } else {
            //TODO: handle HyperLink type, not space, pageTitle model link 
            return lm.getView();
        }
    }
    return "";
}