javatips.net counter

Java Examples for org.apache.commons.lang.StringEscapeUtils

The following java examples will help you to understand the usage of org.apache.commons.lang.StringEscapeUtils. These source code samples are taken from different open source projects.

Example 1
Project: polly-master  File: EscapeProvider.java View source code
@Override
public void setup() throws SetupException {
    // HACK: this is a hack to expose html escaping from apache
    //       commons to all plugins with avoiding a new dependency 
    HTMLTools.UTIL = new HTMLTools.HTMLToolsUtil() {

        @Override
        public String escape(String s) {
            return StringEscapeUtils.escapeHtml(s);
        }

        @Override
        public String unsecape(String s) {
            return StringEscapeUtils.unescapeHtml(s);
        }

        @Override
        public void gainFieldAccess(Map<String, Object> targetContext, Class<?> container, String key) {
            targetContext.put(key, new FieldMethodizer(container.getName()));
        }
    };
}
Example 2
Project: dk-master  File: FundManagementService.java View source code
/**
	 * 财务管理 充值记录查询
	 * 
	 * @return
	 */
public void queryRechargeRecordList(PageBean<Map<String, Object>> pageBean, String userName, String reStartTime, String reEndTime, int rechargeType, Integer result) throws SQLException, DataException {
    Connection conn = connectionManager.getConnection();
    // 手机变更状态不为空
    String command = "";
    if (userName != null) {
        command += " and username like '%" + StringEscapeUtils.escapeSql(userName) + "%' ";
    }
    if (//
    rechargeType != //
    -100) {
        command += " and rechargeType =" + rechargeType;
    }
    if (reStartTime != null) {
        command += " and rechargeTime >='" + StringEscapeUtils.escapeSql(reStartTime) + "' and rechargeTime <='" + StringEscapeUtils.escapeSql(reEndTime) + "'";
    }
    if (result >= 0) {
        command += " and result =" + result;
    }
    try {
        dataPage(conn, pageBean, "v_t_user_rechargedetails_list", "*", " order by id desc ", command);
    } catch (SQLException e) {
        log.error(e);
        e.printStackTrace();
        throw e;
    } catch (DataException e) {
        log.error(e);
        e.printStackTrace();
        throw e;
    } finally {
        conn.close();
    }
}
Example 3
Project: liferay-ide-master  File: LocaleBundleValidationService.java View source code
public Status compute() {
    final Element modelElement = context(Element.class);
    if (!modelElement.disposed() && modelElement instanceof SupportedLocales) {
        final IProject project = modelElement.adapt(IProject.class);
        final Portlet portlet = modelElement.nearest(Portlet.class);
        final IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot();
        final IClasspathEntry[] cpEntries = CoreUtil.getClasspathEntries(project);
        if (cpEntries != null) {
            final String locale = modelElement.property(context(ValueProperty.class)).text(false);
            final Value<Path> resourceBundle = portlet.getResourceBundle();
            if (locale == null) {
                return Status.createErrorStatus(Resources.localeMustNotEmpty);
            } else {
                final String bundleName = resourceBundle.text();
                if (resourceBundle != null && bundleName != null) {
                    final String localeString = PortletUtil.localeString(locale);
                    final String ioFileName = PortletUtil.convertJavaToIoFileName(bundleName, RB_FILE_EXTENSION, localeString);
                    for (IClasspathEntry iClasspathEntry : cpEntries) {
                        if (IClasspathEntry.CPE_SOURCE == iClasspathEntry.getEntryKind()) {
                            IPath entryPath = wroot.getFolder(iClasspathEntry.getPath()).getLocation();
                            entryPath = entryPath.append(ioFileName);
                            IFile resourceBundleFile = wroot.getFileForLocation(entryPath);
                            if (resourceBundleFile != null && resourceBundleFile.exists()) {
                                return Status.createOkStatus();
                            } else {
                                return Status.createWarningStatus(Resources.bind(StringEscapeUtils.unescapeJava(Resources.noResourceBundle), new Object[] { locale, bundleName, localeString }));
                            }
                        }
                    }
                }
            }
        }
    }
    return Status.createOkStatus();
}
Example 4
Project: jeboorker-master  File: CoverpageBookProcessor.java View source code
private String createCoverpageHtml(String title, String imageHref) {
    return "" + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "\t<head>\n" + "\t\t<title>Cover</title>\n" + "\t\t<style type=\"text/css\"> img { max-width: 100%; } </style>\n" + "\t</head>\n" + "\t<body>\n" + "\t\t<div id=\"cover-image\">\n" + "\t\t\t<img src=\"" + StringEscapeUtils.escapeHtml(imageHref) + "\" alt=\"" + StringEscapeUtils.escapeHtml(title) + "\"/>\n" + "\t\t</div>\n" + "\t</body>\n" + "</html>\n";
}
Example 5
Project: openwayback-master  File: BubbleCalendarData.java View source code
protected void init() {
    CaptureSearchResults cResults = results.getCaptureResults();
    WaybackRequest wbRequest = results.getWbRequest();
    String searchUrl = UrlOperations.stripDefaultPortFromUrl(wbRequest.getRequestUrl());
    searchUrlForHTML = StringEscapeUtils.escapeHtml(searchUrl);
    searchUrlForJS = StringEscapeUtils.escapeJavaScript(searchUrl);
    firstResultDate = cResults.getFirstResultDate();
    firstResultReplayUrl = StringEscapeUtils.escapeHtml(results.resultToReplayUrl(cResults.getResults().getFirst()));
    lastResultDate = cResults.getLastResultDate();
    lastResultReplayUrl = StringEscapeUtils.escapeHtml(results.resultToReplayUrl(cResults.getResults().getLast()));
    Date searchStartDate = wbRequest.getStartDate();
    Date searchEndDate = wbRequest.getEndDate();
    months = capturePartitioner.getRange(monthSize, searchStartDate, searchEndDate);
    years = partitionPartitioner.getRange(yearSize, searchStartDate, searchEndDate);
    // To build the graph, we need to break all the results into 1 month
    // partitions, so partition all the results into the months:
    capturePartitioner.populate(months, cResults.iterator());
    // To fill in the calendar, we need to break the current year into day
    // sized partitions, so first partition those months into years:
    partitionPartitioner.populate(years, months.iterator());
    // find the active year:
    Partition<Partition<CaptureSearchResult>> activeYear = null;
    for (Partition<Partition<CaptureSearchResult>> year : years) {
        if (year.isContainsClosest()) {
            activeYear = year;
            break;
        }
    }
    // TODO: check anyways:
    if (activeYear == null) {
        activeYear = years.get(years.size() - 1);
    }
    //		String yearStr = fmt.format("{0,date,yyyy}",activeYear.getStart());
    //		yearNum = Integer.parseInt(yearStr);
    Calendar cal = Calendar.getInstance(calendarTimeZone);
    cal.setTime(activeYear.getStart());
    yearNum = cal.get(Calendar.YEAR);
    numYearResults = activeYear.getTotal();
    // now unroll the months in the active year into day-sized partitions:
    List<Partition<CaptureSearchResult>> days = capturePartitioner.getRange(daySize, activeYear.getStart(), activeYear.getEnd());
    for (Partition<CaptureSearchResult> month : activeYear.list()) {
        capturePartitioner.populate(days, month.iterator());
    }
    // finally, spool the days of the current year into 12 month-sized
    // partitions:
    monthsByDay = partitionPartitioner.getRange(monthSize, activeYear.getStart(), activeYear.getEnd());
    partitionPartitioner.populate(monthsByDay, days.iterator());
    dataStartMSSE = years.get(0).getStart().getTime();
    dataEndMSSE = years.get(years.size() - 1).getEnd().getTime();
    numResults = cResults.getMatchingCount();
}
Example 6
Project: OpenClinica-master  File: DataEntryServlet.java View source code
/**
     * Get the input beans - the EventCRFBean and the SectionBean. For both beans, look first in the request attributes to see if the bean has been stored
     * there. If not, look in the parameters for the bean id, and then retrieve the bean from the database. The beans are stored as protected class members.
     * @param request TODO
     */
protected void getInputBeans(HttpServletRequest request) throws InsufficientPermissionException {
    HttpSession session = request.getSession();
    StudyBean currentStudy = (StudyBean) session.getAttribute("study");
    // BWP >>we should have the correct crfVersionId, in order to acquire
    // the correct
    // section IDs
    FormProcessor fp = new FormProcessor(request);
    EventCRFDAO ecdao = new EventCRFDAO(getDataSource());
    SectionDAO sdao = new SectionDAO(getDataSource());
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    //JN:Happening when drilling down?
    if (ecb == null) {
        int eventCRFId = fp.getInt(INPUT_EVENT_CRF_ID, true);
        LOGGER.debug("found event crf id: " + eventCRFId);
        if (eventCRFId > 0) {
            LOGGER.debug("***NOTE*** that we didnt have to create an event crf because we already have one: " + eventCRFId);
            // there is an event CRF already, only need to update
            ecb = (EventCRFBean) ecdao.findByPK(eventCRFId);
            // ecb.setUpdatedDate(new Date());
            // ecb.setUpdater(ub);
            // ecb = (EventCRFBean) ecdao.update(ecb);
            // logger.trace("found an event crf id "+eventCRFId);
            // YW 11-12-2007 << if interviewer or/and interview date
            // has/have been updated for study/site from "blank" to
            // "pre-populated"
            // But at this point, this update only shows on web page and
            // will not be updated to database.
            int studyEventId = fp.getInt(INPUT_STUDY_EVENT_ID);
            request.setAttribute(INPUT_EVENT_CRF, ecb);
            if (studyEventId > 0) {
                StudyEventDAO sedao = new StudyEventDAO(getDataSource());
                StudyEventBean sEvent = (StudyEventBean) sedao.findByPK(studyEventId);
                ecb = updateECB(sEvent, request);
            }
            request.setAttribute(INPUT_EVENT_CRF, ecb);
        // YW >>
        } else {
            // CRF id <=0, so we need to create a new CRF
            // use toCreateCRF as a flag to prevent user to submit event CRF
            // more than once
            // for example, user reloads the page
            String toCreateCRF = (String) session.getAttribute("to_create_crf");
            if (StringUtil.isBlank(toCreateCRF) || "0".equals(toCreateCRF)) {
                session.setAttribute("to_create_crf", "1");
            }
            try {
                // if (ecb.getInterviewerName() != null) {
                LOGGER.debug("Initial: to create an event CRF.");
                String toCreateCRF1 = (String) session.getAttribute("to_create_crf");
                if (!StringUtil.isBlank(toCreateCRF1) && "1".equals(toCreateCRF1)) {
                    ecb = createEventCRF(request, fp);
                    session.setAttribute("ecb", ecb);
                    request.setAttribute(INPUT_EVENT_CRF, ecb);
                    session.setAttribute("to_create_crf", "0");
                } else {
                    ecb = (EventCRFBean) session.getAttribute("ecb");
                }
            // }
            } catch (InconsistentStateException ie) {
                ie.printStackTrace();
                addPageMessage(ie.getOpenClinicaMessage(), request);
                throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET, ie.getOpenClinicaMessage(), "1");
            } catch (NullPointerException ne) {
                ne.printStackTrace();
                addPageMessage(ne.getMessage(), request);
                throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET, ne.getMessage(), "1");
            }
        }
    }
    // added to allow sections shown on this page
    DisplayTableOfContentsBean displayBean = new DisplayTableOfContentsBean();
    displayBean = TableOfContentsServlet.getDisplayBean(ecb, getDataSource(), currentStudy);
    // escape apostrophe in event name
    displayBean.getStudyEventDefinition().setName(StringEscapeUtils.escapeJavaScript(displayBean.getStudyEventDefinition().getName()));
    request.setAttribute(TOC_DISPLAY, displayBean);
    int sectionId = fp.getInt(INPUT_SECTION_ID, true);
    ArrayList sections;
    if (sectionId <= 0) {
        StudyEventDAO studyEventDao = new StudyEventDAO(getDataSource());
        int maximumSampleOrdinal = studyEventDao.getMaxSampleOrdinal(displayBean.getStudyEventDefinition(), displayBean.getStudySubject());
        request.setAttribute("maximumSampleOrdinal", maximumSampleOrdinal);
        sections = sdao.findAllByCRFVersionId(ecb.getCRFVersionId());
        for (int i = 0; i < sections.size(); i++) {
            SectionBean sb = (SectionBean) sections.get(i);
            // find the first section of this CRF
            sectionId = sb.getId();
            break;
        }
    }
    SectionBean sb = new SectionBean();
    if (sectionId > 0) {
        // int sectionId = fp.getInt(INPUT_SECTION_ID, true);
        //synchronized(this)
        {
            sb = (SectionBean) sdao.findByPK(sectionId);
        }
    }
    int tabId = fp.getInt("tab", true);
    if (tabId <= 0) {
        tabId = 1;
    }
    request.setAttribute(INPUT_TAB, new Integer(tabId));
    request.setAttribute(SECTION_BEAN, sb);
}
Example 7
Project: skalli-master  File: ProjectEditPanelEntry.java View source code
private void layoutNewEditForm() {
    Form newForm;
    try {
        newForm = formService.createForm(project, context);
    } catch (RuntimeException e) {
        LOG.error("Failed to render '" + StringEscapeUtils.escapeHtml(getDisplayName()) + "' form", e);
        newForm = new Form();
        tray.addComponent(new Label("<span style=\"font-weight:bold;color:red\">Sorry, can't display this form. " + "An internal error occurred. Please notify the administrator.</span>", Label.CONTENT_XHTML));
    }
    if (form != null) {
        tray.replaceComponent(form, newForm);
    } else {
        tray.addComponent(newForm);
    }
    form = newForm;
    initFieldStates();
}
Example 8
Project: eclipse-integration-commons-master  File: DashboardMainPage.java View source code
private String trimText(String s) {
    // Remove html encoded entities
    s = StringEscapeUtils.unescapeHtml(s);
    // Remove line breaks and tabs
    s = s.replace("\n", " ");
    s = s.replace("\t", " ");
    // Remove whitespace between text
    String[] vals = s.split(" ");
    StringBuilder sb = new StringBuilder();
    for (String v : vals) {
        if (v.trim().length() > 0) {
            sb.append(v).append(" ");
        }
    }
    if (sb.length() > FEEDS_DESCRIPTION_MAX) {
        return sb.substring(0, findEndOfWord(sb, FEEDS_DESCRIPTION_MAX)) + " ...";
    // return sb.substring(0, FEEDS_DESCRIPTION_MAX) + " ...";
    }
    return sb.toString();
}
Example 9
Project: framework-master  File: MultipleValidationErrors.java View source code
@Override
protected void setup(VaadinRequest request) {
    BeanItem<PersonBeanWithValidationAnnotations> item = new BeanItem<>(new PersonBeanWithValidationAnnotations());
    final FieldGroup fieldGroup = new FieldGroup(item);
    bindTextField(item, fieldGroup, "First Name", "firstName");
    bindTextField(item, fieldGroup, "Last Name", "lastName");
    final Label validationErrors = new Label();
    validationErrors.setId("validationErrors");
    addComponent(validationErrors);
    addButton("Submit", new Button.ClickListener() {

        @Override
        public void buttonClick(Button.ClickEvent event) {
            validationErrors.setValue("");
            try {
                fieldGroup.commit();
            } catch (FieldGroup.CommitException e) {
                if (e.getCause() != null && e.getCause() instanceof Validator.InvalidValueException) {
                    validationErrors.setValue(StringEscapeUtils.unescapeHtml(AbstractErrorMessage.getErrorMessageForException(e.getCause()).getFormattedHtmlMessage()));
                }
            }
        }
    });
}
Example 10
Project: lucene-solr-master  File: LoadAdminUiServlet.java View source code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // security: SOLR-7966 - avoid clickjacking for admin interface
    response.addHeader("X-Frame-Options", "DENY");
    // This attribute is set by the SolrDispatchFilter
    String admin = request.getRequestURI().substring(request.getContextPath().length());
    CoreContainer cores = (CoreContainer) request.getAttribute("org.apache.solr.CoreContainer");
    InputStream in = getServletContext().getResourceAsStream(admin);
    Writer out = null;
    if (in != null && cores != null) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            // Protect container owned streams from being closed by us, see SOLR-8933
            out = new OutputStreamWriter(new CloseShieldOutputStream(response.getOutputStream()), StandardCharsets.UTF_8);
            String html = IOUtils.toString(in, "UTF-8");
            Package pack = SolrCore.class.getPackage();
            String[] search = new String[] { "${contextPath}", "${adminPath}", "${version}" };
            String[] replace = new String[] { StringEscapeUtils.escapeJavaScript(request.getContextPath()), StringEscapeUtils.escapeJavaScript(CommonParams.CORES_HANDLER_PATH), StringEscapeUtils.escapeJavaScript(pack.getSpecificationVersion()) };
            out.write(StringUtils.replaceEach(html, search, replace));
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    } else {
        response.sendError(404);
    }
}
Example 11
Project: tdq-studio-se-master  File: SoundexFrequencyExplorer.java View source code
@Override
protected String getInstantiatedClause() {
    // get function which convert data into a pattern
    String function = getFunction();
    // colName.
    if (function != null && (DbmsLanguageFactory.isInfomix(this.dbmsLanguage.getDbmsName()) || DbmsLanguageFactory.isOracle(this.dbmsLanguage.getDbmsName()))) {
        function = columnName;
    }
    // ~11005
    // MOD mzhao bug 9740 2009-11-10
    String clause = entity.isLabelNull() || function == null ? columnName + dbmsLanguage.isNull() : dbmsLanguage.getSoundexPrefix() + //$NON-NLS-1$ 
    "(" + function + ")" + dbmsLanguage.equal() + dbmsLanguage.getSoundexPrefix() + "('" + StringEscapeUtils.escapeSql(entity.getKey().toString()) + //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
    "')";
    return clause;
}
Example 12
Project: Desktop-master  File: AddOnsController.java View source code
/** make the translations of this add-on known system-wide. */
public static void registerAddOnResources(final AddOnProperties addOn, final ResourceController resourceController) {
    HashSet<String> languages = new HashSet<String>();
    languages.add(resourceController.getLanguageCode());
    languages.add(resourceController.getDefaultLanguageCode());
    for (String language : languages) {
        final Map<String, String> resources = addOn.getTranslations().get(language);
        if (resources != null) {
            for (Entry<String, String> entry : resources.entrySet()) {
                if (entry.getValue().indexOf('\\') != -1) {
                    entry.setValue(StringEscapeUtils.unescapeJava(entry.getValue()));
                }
            }
            resourceController.addLanguageResources(language, addOptionPanelPrefix(resources, addOn.getName()));
            resourceController.addLanguageResources(language, resources);
        }
    }
}
Example 13
Project: warlock2-master  File: StormFrontElement.java View source code
public String toXML(String prefix, boolean prettyPrint, boolean includeChildren) {
    StringBuffer xml = new StringBuffer();
    xml.append(prefix + "<" + name);
    if (attributes.getList().size() > 0) {
        xml.append(" ");
        for (Iterator<StormFrontAttribute> iter = attributes.getList().iterator(); iter.hasNext(); ) {
            StormFrontAttribute attribute = iter.next();
            xml.append(attribute.getName());
            xml.append("=");
            xml.append("\"");
            xml.append(StringEscapeUtils.escapeXml(attribute.getValue()));
            xml.append("\"");
            if (iter.hasNext())
                xml.append(" ");
        }
    }
    boolean hasContent = false;
    if (elements.size() > 0 || getText().length() > 0) {
        hasContent = true;
        xml.append(">");
        if (prettyPrint)
            xml.append("\n");
    }
    if (elements.size() > 0) {
        if (includeChildren) {
            for (StormFrontElement element : elements) {
                xml.append(element.toXML(prettyPrint ? prefix + "  " : "", prettyPrint, true));
            }
        }
    }
    if (getText().length() > 0) {
        xml.append(StringEscapeUtils.escapeXml(getText()));
    }
    if (hasContent) {
        xml.append(/* FIXME can't do this because it gets passed on as content: prefix +*/
        "</" + name + ">");
        if (prettyPrint)
            xml.append("\n");
    } else {
        xml.append("/>");
        if (prettyPrint)
            xml.append("\n");
    }
    return xml.toString();
}
Example 14
Project: iaf-master  File: MessageStoreSender.java View source code
public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
    if (sessionKeys != null) {
        List<String> list = new ArrayList<String>();
        list.add(StringEscapeUtils.escapeCsv(message));
        StringTokenizer tokenizer = new StringTokenizer(sessionKeys, ",");
        while (tokenizer.hasMoreElements()) {
            String sessionKey = (String) tokenizer.nextElement();
            list.add(StringEscapeUtils.escapeCsv((String) prc.getSession().get(sessionKey)));
        }
        StrBuilder sb = new StrBuilder();
        sb.appendWithSeparators(list, ",");
        message = sb.toString();
    }
    String messageId = prc.getSession().getMessageId();
    if (prc != null && paramList != null && paramList.findParameter("messageId") != null) {
        try {
            messageId = (String) prc.getValueMap(paramList).get("messageId");
        } catch (ParameterException e) {
            throw new SenderException("Could not resolve parameter messageId", e);
        }
    }
    return storeMessage(messageId, correlationID, new Date(), null, null, message);
}
Example 15
Project: HDP-2.2-Patched-master  File: CapacitySchedulerPage.java View source code
@Override
protected void render(Block html) {
    StringBuilder activeUserList = new StringBuilder("");
    ResourceInfo usedResources = lqinfo.getResourcesUsed();
    ArrayList<UserInfo> users = lqinfo.getUsers().getUsersList();
    for (UserInfo entry : users) {
        activeUserList.append(entry.getUsername()).append(" <").append(getPercentage(entry.getResourcesUsed(), usedResources)).append(", Schedulable Apps: " + entry.getNumActiveApplications()).append(", Non-Schedulable Apps: " + entry.getNumPendingApplications()).append(//Force line break
        "><br style='display:block'>");
    }
    ResponseInfo ri = info("\'" + lqinfo.getQueuePath().substring(5) + "\' Queue Status")._("Queue State:", lqinfo.getQueueState())._("Used Capacity:", percent(lqinfo.getUsedCapacity() / 100))._("Absolute Used Capacity:", percent(lqinfo.getAbsoluteUsedCapacity() / 100))._("Absolute Capacity:", percent(lqinfo.getAbsoluteCapacity() / 100))._("Absolute Max Capacity:", percent(lqinfo.getAbsoluteMaxCapacity() / 100))._("Used Resources:", StringEscapeUtils.escapeHtml(lqinfo.getUsedResources().toString()))._("Num Schedulable Applications:", Integer.toString(lqinfo.getNumActiveApplications()))._("Num Non-Schedulable Applications:", Integer.toString(lqinfo.getNumPendingApplications()))._("Num Containers:", Integer.toString(lqinfo.getNumContainers()))._("Max Applications:", Integer.toString(lqinfo.getMaxApplications()))._("Max Applications Per User:", Integer.toString(lqinfo.getMaxApplicationsPerUser()))._("Max Schedulable Applications:", Integer.toString(lqinfo.getMaxActiveApplications()))._("Max Schedulable Applications Per User:", Integer.toString(lqinfo.getMaxActiveApplicationsPerUser()))._("Configured Capacity:", percent(lqinfo.getCapacity() / 100))._("Configured Max Capacity:", percent(lqinfo.getMaxCapacity() / 100))._("Configured Minimum User Limit Percent:", Integer.toString(lqinfo.getUserLimit()) + "%")._("Configured User Limit Factor:", String.format("%.1f", lqinfo.getUserLimitFactor()))._r("Active users: ", activeUserList.toString());
    html._(InfoBlock.class);
    // clear the info contents so this queue's info doesn't accumulate into another queue's info
    ri.clear();
}
Example 16
Project: hadoop-on-lustre2-master  File: FairSchedulerPage.java View source code
@Override
protected void render(Block html) {
    ResponseInfo ri = info("\'" + qinfo.getQueueName() + "\' Queue Status")._("Used Resources:", StringEscapeUtils.escapeHtml(qinfo.getUsedResources().toString()))._("Num Active Applications:", qinfo.getNumActiveApplications())._("Num Pending Applications:", qinfo.getNumPendingApplications())._("Min Resources:", StringEscapeUtils.escapeHtml(qinfo.getMinResources().toString()))._("Max Resources:", StringEscapeUtils.escapeHtml(qinfo.getMaxResources().toString()));
    int maxApps = qinfo.getMaxApplications();
    if (maxApps < Integer.MAX_VALUE) {
        ri._("Max Running Applications:", qinfo.getMaxApplications());
    }
    ri._("Fair Share:", StringEscapeUtils.escapeHtml(qinfo.getFairShare().toString()));
    html._(InfoBlock.class);
    // clear the info contents so this queue's info doesn't accumulate into another queue's info
    ri.clear();
}
Example 17
Project: WordPress-Android-master  File: CommentDetailFragment.java View source code
@Override
public void onActionResult(CommentActionResult result) {
    mIsSubmittingReply = false;
    if (result.isSuccess() && mOnCommentChangeListener != null)
        mOnCommentChangeListener.onCommentChanged(ChangeType.REPLIED);
    if (isAdded()) {
        mEditReply.setEnabled(true);
        mSubmitReplyBtn.setVisibility(View.VISIBLE);
        progress.setVisibility(View.GONE);
        updateStatusViews();
        if (result.isSuccess()) {
            ToastUtils.showToast(getActivity(), getString(R.string.note_reply_successful));
            mEditReply.setText(null);
            mEditReply.getAutoSaveTextHelper().clearSavedText(mEditReply);
            // approve the comment
            if (mComment != null && mComment.getStatusEnum() != CommentStatus.APPROVED) {
                moderateComment(CommentStatus.APPROVED);
            }
        } else {
            String errorMessage = TextUtils.isEmpty(result.getMessage()) ? getString(R.string.reply_failed) : result.getMessage();
            String strUnEscapeHTML = StringEscapeUtils.unescapeHtml(errorMessage);
            ToastUtils.showToast(getActivity(), strUnEscapeHTML, ToastUtils.Duration.LONG);
            // refocus editor on failure and show soft keyboard
            EditTextUtils.showSoftInput(mEditReply);
        }
    }
}
Example 18
Project: linshare-core-master  File: AntiSamyServiceImpl.java View source code
@Override
public String clean(String value) throws BusinessException {
    if (value == null)
        return null;
    try {
        CleanResults cr = new AntiSamy().scan(value, policy);
        if (cr.getNumberOfErrors() > 0)
            logger.warn("Striped invalid chracters in : " + value);
        return StringEscapeUtils.unescapeHtml(cr.getCleanHTML().trim());
    } catch (ScanException e) {
        throw new BusinessException(BusinessErrorCode.XSSFILTER_SCAN_FAILED, "Antisamy is not able to scan the field");
    } catch (PolicyException e) {
        throw new BusinessException(BusinessErrorCode.XSSFILTER_SCAN_FAILED, "Antisamy is not able to scan the field");
    }
}
Example 19
Project: aipo-master  File: ALSessionValidator.java View source code
/**
   *
   * @param data
   * @throws Exception
   */
@Override
public void doPerform(RunData data) throws Exception {
    try {
        // first, invoke our superclass action to make sure
        // we follow Turbine evolutions
        // FIXME: if the user is not found (this can happen, for instance,
        // if the anonymous user is not in the DB), it throws a terrible exception
        // in the user's face
        boolean hasError = false;
        try {
            super.doPerform(data);
        } catch (Throwable other) {
            data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_ERROR));
            String message = other.getMessage() != null ? other.getMessage() : other.toString();
            data.setMessage(message);
            data.setStackTrace(org.apache.turbine.util.StringUtils.stackTrace(other), other);
            hasError = true;
        }
        JetspeedUser user = (JetspeedUser) data.getUser();
        if (!hasError) {
            // it.
            if ((user == null || !user.hasLoggedIn()) && JetspeedResources.getBoolean("automatic.logon.enable", false)) {
                // currently
                if (data.getRequest().getCookies() != null) {
                    // check for user in cookie
                    String userName = data.getCookies().getString("username", "");
                    String loginCookieValue = data.getCookies().getString("logincookie", "");
                    if (userName.length() > 0 && loginCookieValue.length() > 0) {
                        try {
                            if (userName.equals(JetspeedSecurity.getAnonymousUser().getUserName())) {
                            }
                            user = JetspeedSecurity.getUser(userName);
                            if (user != null && !userName.equals(JetspeedSecurity.getAnonymousUser().getUserName())) {
                                if (user.getPerm("logincookie", "").equals(loginCookieValue)) {
                                    // cookie is present and correct - log the user in
                                    if (ALEipConstants.USER_STAT_ENABLED.equals(user.getDisabled())) {
                                        // IPA#70075625
                                        // Sesion Fixation 対策
                                        JetspeedRunData automaticloginjdata = null;
                                        try {
                                            automaticloginjdata = (JetspeedRunData) data;
                                        } catch (ClassCastException e) {
                                            logger.error("The RunData object does not implement the expected interface, " + "please verify the RunData factory settings", e);
                                            return;
                                        }
                                        // Session ID を再発行する
                                        automaticloginjdata.getSession().invalidate();
                                        automaticloginjdata.setSession(automaticloginjdata.getRequest().getSession(true));
                                        data.setUser(user);
                                        user.setHasLoggedIn(Boolean.TRUE);
                                        user.updateLastLogin();
                                        data.save();
                                        // イベントログに自動ログイン時にはイベントログを残さない。
                                        // for security
                                        data.getUser().setTemp(ALEipConstants.SECURE_ID, ALCommonUtils.getSecureRandomString());
                                    }
                                }
                            }
                        } catch (LoginException noSuchUser) {
                            logger.warn("User denied authentication: " + userName, noSuchUser);
                        } catch (org.apache.jetspeed.services.security.UnknownUserException unknownUser) {
                            logger.warn("Username from the cookie was not found: " + userName);
                        } catch (Exception other) {
                            logger.error(other);
                        }
                    }
                }
            }
            // now, define Jetspeed specific properties, using the customized
            // RunData properties
            JetspeedRunData jdata = null;
            try {
                jdata = (JetspeedRunData) data;
            } catch (ClassCastException e) {
                logger.error("The RunData object does not implement the expected interface, " + "please verify the RunData factory settings", e);
                return;
            }
            String language = data.getRequest().getParameter("js_language");
            if (null != language) {
                user.setPerm("language", language);
            }
            // Get the locale store it in the user object
            CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil.getServiceByName(LocalizationService.SERVICE_NAME);
            Locale locale = locService.getLocale(data);
            if (locale == null) {
                locale = new Locale(TurbineResources.getString("locale.default.language", "en"), TurbineResources.getString("locale.default.country", "US"));
            }
            data.getUser().setTemp("locale", locale);
            // if a portlet is referenced in the parameters request, store it
            // in the RunData object
            String paramPortlet = jdata.getParameters().getString("js_peid");
            if (paramPortlet != null && paramPortlet.length() > 0) {
                jdata.setJs_peid(paramPortlet);
            }
        }
    } catch (Throwable other) {
        setOrgParametersForError(data);
        data.setScreenTemplate(JetspeedResources.getString(TurbineConstants.TEMPLATE_ERROR));
        return;
    }
    // not login and can not connect database
    if (checkDbError(data)) {
        setOrgParametersForError(data);
        data.setScreenTemplate(ALConstants.DB_ERROR_TEMPLATE);
        return;
    }
    // CookieでセッションIDが渡されていなければエラー画面を表示
    if (data.getRequest().isRequestedSessionIdFromURL()) {
        JetspeedLink jsLink = JetspeedLinkFactory.getInstance(data);
        String url = jsLink.getHomePage().toString().replaceAll(";.*", "");
        data.setRedirectURI(url);
        return;
    }
    JetspeedUser loginuser = (JetspeedUser) data.getUser();
    if (isLogin(loginuser, data)) {
        try {
            JetspeedSecurityCache.load(loginuser.getUserName());
        } catch (Exception e1) {
            String message = e1.getMessage();
            if (message != null && message.indexOf(ALConstants.DB_ERROR_DETECT) != -1) {
                setOrgParametersForError(data);
                String template = data.getParameters().get("template");
                if (template.endsWith("DBError")) {
                    data.setScreenTemplate(ALConstants.DB_ERROR_TEMPLATE);
                } else {
                    ALEipUtils.redirectDBError(data);
                }
                return;
            }
        }
    }
    if (ALSessionUtils.isImageRequest(data)) {
        if (isLogin(loginuser, data)) {
            return;
        }
    }
    if (ALSessionUtils.isJsonScreen(data)) {
        if (isLogin(loginuser, data)) {
            return;
        }
    }
    if (data.getRequest().getAttribute(ALDigestAuthenticationFilter.REQUIRE_DIGEST_AUTH) != null) {
        HttpServletRequest hreq = data.getRequest();
        HttpServletResponse hres = data.getResponse();
        if (!isLogin(loginuser, data)) {
            String auth = hreq.getHeader("Authorization");
            if (auth == null) {
                requireAuth(hres);
                return;
            } else {
                try {
                    String decoded = decodeAuthHeader(auth);
                    int pos = decoded.indexOf(":");
                    String username = decoded.substring(0, pos);
                    String password = decoded.substring(pos + 1);
                    JetspeedUser juser = JetspeedSecurity.login(username, password);
                    data.getUser().setTemp(ALEipConstants.LAST_PASSWORD_LOGIN, new Date());
                    if (juser != null && "F".equals(juser.getDisabled())) {
                        JetspeedSecurity.saveUser(juser);
                    } else {
                        requireAuth(hres);
                        return;
                    }
                } catch (RuntimeException ex) {
                    requireAuth(hres);
                    return;
                } catch (Exception ex) {
                    requireAuth(hres);
                    return;
                }
            }
        }
        if (isICalRequest(data)) {
            data.setScreenTemplate("ScheduleiCalScreen");
            return;
        } else {
            hres.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }
    Context context = org.apache.turbine.services.velocity.TurbineVelocity.getContext(data);
    // for switching theme org by org
    setOrgParameters(data, context);
    // for preventing XSS on user name
    context.put("utils", new ALCommonUtils());
    context.put("l10n", ALLocalizationUtils.createLocalization(data));
    // Cookie無効エラーを検知している場合、ログインさせない
    if (!isLogin(loginuser, data) && !data.getParameters().get("template").equals("CookieError")) {
        String username = data.getParameters().getString("username", "");
        String password = data.getParameters().getString("password", "");
        if (username.length() > 0) {
            if (ALCellularUtils.isSmartPhone(data) && "admin".equals(username)) {
                data.setUser(JetspeedSecurity.getAnonymousUser());
                data.setMessage(ALLocalizationUtils.getl10n("LOGINACTION_LOGIN_ONLY_PC"));
                data.getUser().setHasLoggedIn(Boolean.FALSE);
            } else {
                try {
                    loginuser = JetspeedSecurity.login(username, password);
                    if (loginuser != null && "F".equals(loginuser.getDisabled())) {
                        JetspeedSecurity.saveUser(loginuser);
                    } else {
                        data.setUser(JetspeedSecurity.getAnonymousUser());
                        data.setMessage(ALLocalizationUtils.getl10n("LOGINACTION_INVALIDATION_USER"));
                        data.getUser().setHasLoggedIn(Boolean.FALSE);
                    }
                } catch (LoginException e) {
                }
            }
        }
    }
    String externalLoginUrl = ALConfigService.get(Property.EXTERNAL_LOGIN_URL);
    boolean isScreenTimeout = false;
    if (!isLogin(loginuser, data)) {
        // 未ログインの時
        // 理由等 :セッションが切れた時に、エラーメッセージの表示に不具合あり
        // 対処方法:ログイン画面以外でユーザがログインしていない場合はエラーページへスクリーンを変更
        String uri = data.getRequest().getRequestURI().trim();
        String template = data.getScreenTemplate();
        Class<?> cls = null;
        try {
            @SuppressWarnings("unchecked") Vector<String> packages = JetspeedResources.getVector("module.packages");
            for (String pk : packages) {
                try {
                    cls = Class.forName(new StringBuffer().append(pk).append(".screens.").append(template).toString());
                } catch (Throwable ignore) {
                }
            }
        } catch (Exception e) {
            cls = null;
        }
        String newTemplate = null;
        if (cls != null) {
            if (Class.forName("com.aimluck.eip.modules.screens.ALJSONScreen").isAssignableFrom(cls)) {
                newTemplate = "ALJSONTimeoutScreen";
            } else if (Class.forName("com.aimluck.eip.modules.screens.ALVelocityScreen").isAssignableFrom(cls)) {
                newTemplate = "ALVelocityTimeoutScreen";
            }
        }
        if (newTemplate != null) {
            isScreenTimeout = true;
            data.setScreenTemplate(newTemplate);
            // セッションの削除
            if (data.getSession() != null) {
                try {
                    data.getSession().invalidate();
                } catch (IllegalStateException ex) {
                    logger.debug("セッションは既に削除されています。");
                }
            }
        } else {
            String contextPath = ServletContextLocator.get().getContextPath();
            if ("/".equals(contextPath)) {
                contextPath = "";
            }
            String portalPath = contextPath + "/portal";
            if (!uri.equals(portalPath + "/") && !uri.equals(portalPath)) {
                data.setScreenTemplate("Timeout");
                if (!"".equals(externalLoginUrl)) {
                    // ログイン画面へリダイレクト
                    data.setRedirectURI(externalLoginUrl);
                }
                StringBuffer sb = new StringBuffer(uri);
                int count = 0;
                String key = null;
                Enumeration<?> enu = data.getRequest().getParameterNames();
                if (enu.hasMoreElements()) {
                    sb.append("?");
                }
                while (enu.hasMoreElements()) {
                    if (count != 0) {
                        sb.append("&");
                    }
                    key = (String) enu.nextElement();
                    sb.append(key).append("=").append(data.getRequest().getParameter(key));
                    count = count + 1;
                }
                if (data.getUser() != null) {
                    data.getUser().setTemp("redirect", StringEscapeUtils.escapeHtml(sb.toString()));
                    context.put("alEipUtils", new ALEipUtils());
                    context.put("alEipManager", ALEipManager.getInstance());
                }
                // セッションの削除
                if (data.getSession() != null) {
                    try {
                        data.getSession().invalidate();
                    } catch (IllegalStateException ex) {
                        logger.debug("セッションは既に削除されています。");
                    }
                }
            }
        }
    }
    JetspeedRunData jdata = null;
    try {
        jdata = (JetspeedRunData) data;
    } catch (ClassCastException e) {
        logger.error("The RunData object does not implement the expected interface, " + "please verify the RunData factory settings", e);
        return;
    }
    String language = data.getRequest().getParameter("js_language");
    if (null != language) {
        loginuser.setPerm("language", language);
    }
    CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil.getServiceByName(LocalizationService.SERVICE_NAME);
    Locale locale = locService.getLocale(data);
    if (locale == null) {
        locale = new Locale(TurbineResources.getString("locale.default.language", "en"), TurbineResources.getString("locale.default.country", "US"));
    }
    if (loginuser != null) {
        loginuser.setTemp("locale", locale);
    }
    String paramPortlet = jdata.getParameters().getString("js_peid");
    if (paramPortlet != null && paramPortlet.length() > 0) {
        jdata.setJs_peid(paramPortlet);
    }
    // Ajaxリクエストでセッションタイムアウトした場合はリダイレクトしない
    if (!isScreenTimeout && !"".equals(externalLoginUrl)) {
        HttpServletRequest request = data.getRequest();
        if (!isLogin(loginuser, data)) {
            StringBuilder buf = new StringBuilder();
            buf.append(request.getScheme()).append("://").append(request.getServerName());
            if (request.getServerPort() == 80 || request.getServerPort() == 443) {
            //
            } else {
                buf.append(":").append(request.getServerPort());
            }
            buf.append(request.getRequestURI());
            String queryString = request.getQueryString();
            if (queryString != null && !"".equals(queryString)) {
                buf.append("?").append(queryString);
            }
            String url = buf.toString();
            if (!url.equals(externalLoginUrl)) {
                data.setRedirectURI(externalLoginUrl);
            }
        }
    }
    if (isLogin(loginuser, data)) {
        ALPreExecuteService.migratePsml(data, context);
        boolean hasMessage = false;
        Map<String, Entry> portlets = ALEipUtils.getGlobalPortlets(data);
        Entry entry = portlets.get("Message");
        if (entry != null) {
            if (entry.getId().equals(jdata.getJs_peid())) {
                hasMessage = true;
            }
        }
        String client = ALEipUtils.getClient(data);
        boolean push = (!"IPHONE".equals(client)) || hasMessage;
        HttpServletRequest request = ((JetspeedRunData) data).getRequest();
        String requestUrl = request.getRequestURL().toString();
        String checkActivityUrl = ALConfigService.get(Property.CHECK_ACTIVITY_URL);
        String interval = ALConfigService.get(Property.CHECK_ACTIVITY_INTERVAL);
        ALEipUser eipUser = ALEipUtils.getALEipUser(data);
        String orgId = Database.getDomainName();
        String viewer = new StringBuilder(orgId).append(":").append(eipUser.getName().getValue()).toString();
        ALGadgetContext gadgetContext = new ALGadgetContext(data, viewer, "1", "/", 0);
        String relayUrl = ALConfigService.get(Property.CHECK_ACTIVITY_RELAY_URL);
        String rpctoken = String.valueOf(System.nanoTime());
        String checkUrl = new StringBuilder("".equals(checkActivityUrl) ? "check.html" : checkActivityUrl).append("?").append("st=").append(gadgetContext.getSecureToken()).append("&parent=").append(URLEncoder.encode(requestUrl, "utf-8")).append("&interval=").append(interval).append("&push=").append(push ? 1 : 0).append("#rpctoken=").append(rpctoken).toString();
        if (data.getSession() != null && Boolean.parseBoolean((String) data.getSession().getAttribute("changeToPc"))) {
            // PC表示切り替え用
            context.put("client", ALEipUtils.getClient(data));
        }
        context.put("requestUrl", requestUrl);
        context.put("relayUrl", relayUrl);
        context.put("rpctoken", rpctoken);
        context.put("checkUrl", checkUrl);
        context.put("st", gadgetContext.getSecureToken());
        context.put("hasAuthorityCustomize", ALEipUtils.getHasAuthority(data, context, ALAccessControlConstants.VALUE_ACL_UPDATE));
    }
}
Example 20
Project: FireflowEngine20-master  File: GetProcessDefsHandler.java View source code
protected void outputXmlWithinHtml(String processXml, HttpServletResponse resp, HttpServletRequest req) throws ServletException, IOException {
    HttpServletRequest request = req;
    String contextPath = request.getContextPath();
    if (contextPath == null)
        contextPath = "";
    if (contextPath.endsWith("/")) {
        contextPath = contextPath.substring(0, contextPath.length() - 1);
    }
    StringBuffer sbuf = new StringBuffer();
    sbuf.append("<!DOCTYPE html>\n").append("<html>\n").append("<head>\n").append("<script src=\"").append(contextPath).append(ClientWidgetBase.FIREFLOW_RESOURCE_SERVLET).append("/org/fireflow/webdesigner/resources/google-code-prettify/prettify.js\"></script>\n").append("<link rel=\"stylesheet\" href=\"").append(contextPath).append(ClientWidgetBase.FIREFLOW_RESOURCE_SERVLET).append("/org/fireflow/webdesigner/resources/google-code-prettify/prettify.css\"/>\n").append("<style>\n").append("body { margin: 0; padding: 0;font-size:12px }\n").append("pre { margin: 0 }\n").append("</style>\n").append("</head>\n").append("<body onload=\"prettyPrint();\">\n").append("<pre class=\"prettyprint lang-xml\">");
    String tmp = StringEscapeUtils.escapeXml(processXml);
    sbuf.append(tmp);
    sbuf.append("</pre>\n").append("</body>\n").append("</html>");
    // 设置contentType
    String encoding = Utils.findXmlCharset(processXml);
    resp.setContentType("text/html");
    resp.setCharacterEncoding(encoding);
    // 告诉浏览器不要缓存
    resp.setHeader("Pragma", "no-cache");
    resp.setHeader("Cache-Control", "no-cache");
    resp.setIntHeader("Expires", -1);
    byte[] byteArr = sbuf.toString().getBytes(encoding);
    OutputStream outStream = resp.getOutputStream();
    outStream.write(byteArr);
}
Example 21
Project: raven-aws-emr-kissmetrics-mapreduce-parser-redshift-master  File: KissmetricsRowParser.java View source code
/***
	 * Used to parse, escape and enrich Kissmetircs Json records
	 * 
	 * @param rawJsonRow
	 * @param fileNameInputToMapper
	 * @return
	 */
public static KeyRowWrapper parseJsonRowToValidJson(Text rawJsonRow, String fileNameInputToMapper, String filePath) {
    String jsonString = "";
    boolean wasOctalParsingNeeded = false;
    try {
        System.setProperty("file.encoding", "UTF-8");
        s = rawJsonRow.toString();
        Charset charSet = Charset.forName("UTF-8");
        byte[] encoded = s.getBytes(charSet);
        decodedStrRaw = new String(encoded, charSet);
        // Test new Apache Lang3
        // decodedStr = StringEscapeUtils.unescapeJava(decodedStr);
        //Replace any remaining Octal encoded Characters
        decodedStrParsed = replaceOctalUft8Char(decodedStrRaw);
        if (decodedStrParsed.compareTo(decodedStrRaw) == 0) {
            wasOctalParsingNeeded = false;
        } else {
            wasOctalParsingNeeded = true;
        }
        if (decodedStrParsed != null && decodedStrParsed != "") {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(decodedStrParsed);
            // get email and user_id
            if (jsonObject.get("_p2") != null) {
                p2 = jsonObject.get("_p2").toString().toLowerCase();
                if (p2.contains("@")) {
                    jsonObject.put("user_email", p2);
                    jsonObject.put("user_email_back", p2);
                } else if (p2 != null && p2.length() > 0) {
                    jsonObject.put("user_km_id", p2);
                }
            }
            // get email and user_id
            if (jsonObject.get("_p") != null) {
                p = jsonObject.get("_p").toString().toLowerCase();
                if (p.contains("@")) {
                    jsonObject.put("user_email", p);
                    jsonObject.put("user_email_back", p);
                } else if (p != null && p.length() > 0) {
                    jsonObject.put("user_km_id", p);
                }
            }
            // Add Event
            if (jsonObject.get("_n") != null) {
                event = jsonObject.get("_n").toString();
                if (event != null) {
                    jsonObject.put("event", event);
                }
            }
            // add unix timestamp and datetime
            long currentDateTime = System.currentTimeMillis();
            Date currentDate = new Date(currentDateTime);
            if (jsonObject.get("_t") == null) {
                return (new KeyRowWrapper(jsonString, null, TRACKING_COUNTER.INVALID_JSON_ROW, TRACKING_COUNTER.INVALID_DATE));
            }
            long kmTimeDateMilliSeconds;
            long kmTimeDateMilliSecondsMobile;
            try {
                tTimestampValue = (String) jsonObject.get("_t").toString();
                //See if new record with server timestamp
                if (jsonObject.get("_server_timestamp") != null) {
                    serverTimestampValue = (String) jsonObject.get("_server_timestamp").toString();
                } else {
                    serverTimestampValue = "0";
                }
                //Deal with mobile timedate cases
                if (jsonObject.get("_c") != null) {
                    if (serverTimestampValue.equals("0")) {
                        timestampValueOutput = tTimestampValue;
                        kmTimeDateMilliSecondsMobile = 0;
                    } else {
                        timestampValueOutput = serverTimestampValue;
                        mobileTimestampValueOutput = tTimestampValue;
                        jsonObject.put("km_timestamp_mobile", mobileTimestampValueOutput);
                        kmTimeDateMilliSecondsMobile = Long.parseLong(mobileTimestampValueOutput) * 1000;
                    }
                } else //Ignore server time
                {
                    //TODO Need a way to resolve mobile identify events
                    serverTimestampValue = "0";
                    timestampValueOutput = tTimestampValue;
                    kmTimeDateMilliSecondsMobile = 0;
                }
                jsonObject.put("km_timestamp", timestampValueOutput);
                kmTimeDateMilliSeconds = Long.parseLong(timestampValueOutput) * 1000;
            } catch (Exception e) {
                return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.INVALID_JSON_ROW, TRACKING_COUNTER.INVALID_DATE));
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(kmTimeDateMilliSeconds);
            String event_timedate = dateFormatter.format(calendar.getTime());
            jsonObject.put("event_timedate", event_timedate);
            if (kmTimeDateMilliSecondsMobile > 0) {
                calendar.setTimeInMillis(kmTimeDateMilliSecondsMobile);
                String event_timedate_mobile = dateFormatter.format(calendar.getTime());
                jsonObject.put("event_timedate_mobile", event_timedate_mobile);
            }
            // add Map Reduce json_filename
            jsonObject.put("filename", fileNameInputToMapper);
            jsonString = jsonObject.toString();
            //Add bucket path
            jsonObject.put("bucket", filePath);
            jsonString = jsonObject.toString();
            return (new KeyRowWrapper(jsonString, timestampValueOutput, TRACKING_COUNTER.VALID_JSON_ROW, wasOctalParsingNeeded ? null : TRACKING_COUNTER.OCTAL_PARSING_NEEDED));
        }
    } catch (Exception e) {
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        logger.error(errors.toString());
        logger.error("log - file " + fileNameInputToMapper);
        System.out.println("file " + fileNameInputToMapper);
        logger.error("log - row content: " + rawJsonRow.toString().replace("\t", ""));
        System.err.println("row content: " + rawJsonRow.toString().replace("\t", ""));
        System.err.println("Error skipping row");
        logger.error("Log - Error skipping row");
    }
    return null;
}
Example 22
Project: yarn-comment-master  File: DatanodeJspHelper.java View source code
static void generateDirectoryStructure(JspWriter out, HttpServletRequest req, HttpServletResponse resp, Configuration conf) throws IOException, InterruptedException {
    final String dir = JspHelper.validatePath(StringEscapeUtils.unescapeHtml(req.getParameter("dir")));
    if (dir == null) {
        out.print("Invalid input");
        return;
    }
    String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);
    String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null)
        namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);
    final String nnAddr = req.getParameter(JspHelper.NAMENODE_ADDRESS);
    if (nnAddr == null) {
        out.print(JspHelper.NAMENODE_ADDRESS + " url param is null");
        return;
    }
    DFSClient dfs = getDFSClient(ugi, nnAddr, conf);
    String target = dir;
    final HdfsFileStatus targetStatus = dfs.getFileInfo(target);
    if (targetStatus == null) {
        // not exists
        out.print("<h3>File or directory : " + target + " does not exist</h3>");
        JspHelper.printGotoForm(out, namenodeInfoPort, tokenString, target, nnAddr);
    } else {
        if (!targetStatus.isDir()) {
            // a file
            List<LocatedBlock> blocks = dfs.getNamenode().getBlockLocations(dir, 0, 1).getLocatedBlocks();
            LocatedBlock firstBlock = null;
            DatanodeInfo[] locations = null;
            if (blocks.size() > 0) {
                firstBlock = blocks.get(0);
                locations = firstBlock.getLocations();
            }
            if (locations == null || locations.length == 0) {
                out.print("Empty file");
            } else {
                DatanodeInfo chosenNode = JspHelper.bestNode(firstBlock, conf);
                String fqdn = canonicalize(chosenNode.getHost());
                String datanodeAddr = chosenNode.getName();
                int datanodePort = Integer.parseInt(datanodeAddr.substring(datanodeAddr.indexOf(':') + 1, datanodeAddr.length()));
                String redirectLocation = "http://" + fqdn + ":" + chosenNode.getInfoPort() + "/browseBlock.jsp?blockId=" + firstBlock.getBlock().getBlockId() + "&blockSize=" + firstBlock.getBlock().getNumBytes() + "&genstamp=" + firstBlock.getBlock().getGenerationStamp() + "&filename=" + URLEncoder.encode(dir, "UTF-8") + "&datanodePort=" + datanodePort + "&namenodeInfoPort=" + namenodeInfoPort + JspHelper.getDelegationTokenUrlParam(tokenString) + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr);
                resp.sendRedirect(redirectLocation);
            }
            return;
        }
        // directory
        // generate a table and dump the info
        String[] headings = { "Name", "Type", "Size", "Replication", "Block Size", "Modification Time", "Permission", "Owner", "Group" };
        out.print("<h3>Contents of directory ");
        JspHelper.printPathWithLinks(dir, out, namenodeInfoPort, tokenString, nnAddr);
        out.print("</h3><hr>");
        JspHelper.printGotoForm(out, namenodeInfoPort, tokenString, dir, nnAddr);
        out.print("<hr>");
        File f = new File(dir);
        String parent;
        if ((parent = f.getParent()) != null)
            out.print("<a href=\"" + req.getRequestURL() + "?dir=" + parent + "&namenodeInfoPort=" + namenodeInfoPort + JspHelper.getDelegationTokenUrlParam(tokenString) + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr) + "\">Go to parent directory</a><br>");
        DirectoryListing thisListing = dfs.listPaths(target, HdfsFileStatus.EMPTY_NAME);
        if (thisListing == null || thisListing.getPartialListing().length == 0) {
            out.print("Empty directory");
        } else {
            JspHelper.addTableHeader(out);
            int row = 0;
            JspHelper.addTableRow(out, headings, row++);
            String cols[] = new String[headings.length];
            do {
                HdfsFileStatus[] files = thisListing.getPartialListing();
                for (int i = 0; i < files.length; i++) {
                    String localFileName = files[i].getLocalName();
                    // Get the location of the first block of the file
                    if (!files[i].isDir()) {
                        cols[1] = "file";
                        cols[2] = StringUtils.byteDesc(files[i].getLen());
                        cols[3] = Short.toString(files[i].getReplication());
                        cols[4] = StringUtils.byteDesc(files[i].getBlockSize());
                    } else {
                        cols[1] = "dir";
                        cols[2] = "";
                        cols[3] = "";
                        cols[4] = "";
                    }
                    String datanodeUrl = req.getRequestURL() + "?dir=" + URLEncoder.encode(files[i].getFullName(target), "UTF-8") + "&namenodeInfoPort=" + namenodeInfoPort + JspHelper.getDelegationTokenUrlParam(tokenString) + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr);
                    cols[0] = "<a href=\"" + datanodeUrl + "\">" + localFileName + "</a>";
                    cols[5] = lsDateFormat.format(new Date((files[i].getModificationTime())));
                    cols[6] = files[i].getPermission().toString();
                    cols[7] = files[i].getOwner();
                    cols[8] = files[i].getGroup();
                    JspHelper.addTableRow(out, cols, row++);
                }
                if (!thisListing.hasMore()) {
                    break;
                }
                thisListing = dfs.listPaths(target, thisListing.getLastName());
            } while (thisListing != null);
            JspHelper.addTableFooter(out);
        }
    }
    out.print("<br><a href=\"http://" + canonicalize(nnAddr) + ":" + namenodeInfoPort + "/dfshealth.jsp\">Go back to DFS home</a>");
    dfs.close();
}
Example 23
Project: eGov-master  File: ReceiptAction.java View source code
/**
     * This method is invoked when user creates a receipt.
     *
     * @return
     */
@ValidationErrorPage(value = "new")
@Action(value = "/receipts/receipt-save")
public String save() {
    // try {
    List<InstrumentHeader> receiptInstrList = new ArrayList<InstrumentHeader>(0);
    LOGGER.info("Receipt creation process is started !!!!!!");
    ReceiptHeader rhForValidation = null;
    String returnValue = "";
    final long startTimeMillis = System.currentTimeMillis();
    if (manualReceiptNumber != null && manualReceiptDate != null) {
        final CFinancialYear financialYear = collectionsUtil.getFinancialYearforDate(manualReceiptDate);
        rhForValidation = receiptHeaderService.findByNamedQuery(CollectionConstants.QUERY_RECEIPT_BY_SERVICE_MANUALRECEIPTNO_AND_DATE, manualReceiptNumber, receiptHeader.getService().getCode(), financialYear.getStartingDate(), financialYear.getEndingDate(), CollectionConstants.RECEIPT_STATUS_CODE_CANCELLED);
    }
    if (rhForValidation == null) {
        // For interday cancellation
        if (oldReceiptId != null) {
            final ReceiptHeader receiptHeaderToBeCancelled = receiptHeaderService.findById(oldReceiptId, false);
            receiptHeaderToBeCancelled.setStatus(statusDAO.getStatusByModuleAndCode(CollectionConstants.MODULE_NAME_RECEIPTHEADER, CollectionConstants.RECEIPT_STATUS_CODE_CANCELLED));
            receiptHeaderToBeCancelled.setReasonForCancellation(reasonForCancellation);
            // set isReconciled to false before calling update to
            // billing system for
            // cancel receipt
            receiptHeaderToBeCancelled.setIsReconciled(false);
            receiptHeaderService.persist(receiptHeaderToBeCancelled);
            if (receiptHeaderToBeCancelled.getReceipttype() == CollectionConstants.RECEIPT_TYPE_BILL) {
                populateReceiptModelWithExistingReceiptInfo(receiptHeaderToBeCancelled);
                LOGGER.info("Receipt Cancelled with Receipt Number(recreateNewReceiptOnCancellation): " + receiptHeaderToBeCancelled.getReceiptnumber() + "; Consumer Code: " + receiptHeaderToBeCancelled.getConsumerCode());
            }
        }
        if (billSource.equalsIgnoreCase("misc")) {
            createMisc();
            if (!setMiscReceiptDetails())
                returnValue = NEW;
        } else {
            if (callbackForApportioning && !overrideAccountHeads)
                apportionBillAmount();
            if (receiptDetailList == null || receiptDetailList.isEmpty() || receiptDetailList.size() == 0)
                throw new ApplicationRuntimeException("Receipt could not be created as the apportioned receipt detail list is empty");
            else {
                BigDecimal totalCreditAmount = BigDecimal.ZERO;
                for (final ReceiptDetail receiptDetail : receiptDetailList) totalCreditAmount = totalCreditAmount.add(receiptDetail.getCramount());
                if (totalCreditAmount.intValue() == 0)
                    throw new ApplicationRuntimeException("Apportioning Failed at the Billing System: " + receiptHeader.getService().getCode() + ", for bill number: " + receiptHeader.getReferencenumber());
                else
                    receiptHeader.setReceiptDetails(new HashSet(receiptDetailList));
            }
        }
        int noOfNewlyCreatedReceipts = 0;
        boolean setInstrument = true;
        // The cancelled receipt can be excluded from this processing.
        if (receiptHeader.getStatus() == null) {
            noOfNewlyCreatedReceipts++;
            // number before persist
            if (manualReceiptDate == null)
                receiptHeader.setReceiptdate(new Date());
            else {
                // If the receipt has been manually created, the receipt
                // date is same as the date of manual creation.
                // set Createdby, in MySavelistner if createdBy is null
                // it set both createdBy and createdDate with
                // currentDate.
                // Thus overridding the manualReceiptDate set above
                // receiptHeader.setCreatedBy(collectionsUtil.getLoggedInUser());
                receiptHeader.setManualreceiptdate(manualReceiptDate);
                receiptHeader.setReceiptdate(manualReceiptDate);
                receiptHeader.setVoucherDate(manualReceiptDate);
            }
            if (manualReceiptNumber != null)
                receiptHeader.setManualreceiptnumber(manualReceiptNumber);
            if (isBillSourcemisc()) {
                receiptHeader.setReceipttype(CollectionConstants.RECEIPT_TYPE_ADHOC);
                receiptHeader.setVoucherDate(voucherDate);
                receiptHeader.setReceiptdate(voucherDate);
                receiptHeader.setVoucherNum(voucherNum);
                receiptHeader.setIsReconciled(Boolean.TRUE);
                receiptHeader.setManualreceiptdate(manualReceiptDate);
                receiptHeader.setPayeeName(StringEscapeUtils.unescapeHtml(paidBy));
            } else {
                receiptHeader.setReceipttype(CollectionConstants.RECEIPT_TYPE_BILL);
                receiptHeader.setIsModifiable(Boolean.TRUE);
                receiptHeader.setIsReconciled(Boolean.FALSE);
            }
            // serviceType =
            // receiptHeader.getService().getServiceType();
            receiptHeader.setCollectiontype(CollectionConstants.COLLECTION_TYPE_COUNTER);
            receiptHeader.setLocation(collectionsUtil.getLocationOfUser(getSession()));
            receiptHeader.setStatus(collectionsUtil.getStatusForModuleAndCode(CollectionConstants.MODULE_NAME_RECEIPTHEADER, CollectionConstants.RECEIPT_STATUS_CODE_TO_BE_SUBMITTED));
            receiptHeader.setPaidBy(StringEscapeUtils.unescapeHtml(paidBy));
            receiptHeader.setSource(Source.SYSTEM.toString());
            // field of this new receipt.
            if (getOldReceiptId() != null)
                receiptHeader.setReceiptHeader(receiptHeaderService.findById(getOldReceiptId(), false));
            if (setInstrument) {
                receiptInstrList = populateInstrumentDetails();
                setInstrument = false;
            }
            receiptHeader.setReceiptInstrument(new HashSet(receiptInstrList));
            BigDecimal debitAmount = BigDecimal.ZERO;
            for (final ReceiptDetail creditChangeReceiptDetail : receiptDetailList) for (final ReceiptDetail receiptDetail : receiptHeader.getReceiptDetails()) if (creditChangeReceiptDetail.getReceiptHeader().getReferencenumber().equals(receiptDetail.getReceiptHeader().getReferencenumber()) && receiptDetail.getOrdernumber().equals(creditChangeReceiptDetail.getOrdernumber())) {
                receiptDetail.setCramount(creditChangeReceiptDetail.getCramount());
                receiptDetail.setDramount(creditChangeReceiptDetail.getDramount());
                // calculate sum of creditamounts as a debit
                // value to create a
                // debit account head and add to receipt details
                debitAmount = debitAmount.add(creditChangeReceiptDetail.getCramount());
                debitAmount = debitAmount.subtract(creditChangeReceiptDetail.getDramount());
            }
            if (chequeInstrumenttotal != null && chequeInstrumenttotal.compareTo(BigDecimal.ZERO) != 0)
                receiptHeader.setTotalAmount(chequeInstrumenttotal);
            if (cashOrCardInstrumenttotal != null && cashOrCardInstrumenttotal.compareTo(BigDecimal.ZERO) != 0)
                receiptHeader.setTotalAmount(cashOrCardInstrumenttotal);
            if (isBillSourcemisc())
                receiptHeader.addReceiptDetail(collectionCommon.addDebitAccountHeadDetails(totalDebitAmount, receiptHeader, chequeInstrumenttotal, cashOrCardInstrumenttotal, instrumentTypeCashOrCard));
            else
                receiptHeader.addReceiptDetail(collectionCommon.addDebitAccountHeadDetails(debitAmount, receiptHeader, chequeInstrumenttotal, cashOrCardInstrumenttotal, instrumentTypeCashOrCard));
        }
        // }// end of looping through receipt headers
        // }// end of looping through model receipt payee list
        LOGGER.info("Call back for apportioning is completed");
        // billing system
        receiptHeaderService.populateAndPersistReceipts(receiptHeader, receiptInstrList);
        // populate all receipt header ids except the cancelled receipt
        // (in effect the newly created receipts)
        selectedReceipts = new Long[noOfNewlyCreatedReceipts];
        int i = 0;
        if (!receiptHeader.getId().equals(oldReceiptId)) {
            selectedReceipts[i] = receiptHeader.getId();
            i++;
        }
        // ReceiptHeader rh = null
        // ;//modelPayeeList.get(0).getReceiptHeaders().iterator().next();
        final long elapsedTimeMillis = System.currentTimeMillis() - startTimeMillis;
        LOGGER.info("$$$$$$ Receipt Persisted with Receipt Number: " + receiptHeader.getReceiptnumber() + (receiptHeader.getConsumerCode() != null ? " and consumer code: " + receiptHeader.getConsumerCode() : "") + "; Time taken(ms) = " + elapsedTimeMillis);
        // Do not invoke print receipt in case of bulk upload.
        if (!receiptBulkUpload)
            returnValue = printReceipts();
        else
            returnValue = SUCCESS;
    } else {
        if (rhForValidation.getService().getCode().equals(CollectionConstants.SERVICECODE_PROPERTYTAX))
            addActionError("Entered Manual receipt number already exists for the index number" + rhForValidation.getConsumerCode() + ".Please enter a valid manual receipt number and create the receipt.");
        else
            addActionError("Receipt already exists for the service ");
        returnValue = NEW;
    }
    return returnValue;
}
Example 24
Project: dataverse-master  File: DataversePage.java View source code
public String saveSavedSearch() {
    if (linkingDataverseId == null) {
        JsfHelper.addErrorMessage("You must select a linking dataverse.");
        return "";
    }
    linkingDataverse = dataverseService.find(linkingDataverseId);
    AuthenticatedUser savedSearchCreator = getAuthenticatedUser();
    if (savedSearchCreator == null) {
        String msg = "Only authenticated users can save a search.";
        logger.severe(msg);
        JsfHelper.addErrorMessage(msg);
        return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true";
    }
    SavedSearch savedSearch = new SavedSearch(searchIncludeFragment.getQuery(), linkingDataverse, savedSearchCreator);
    savedSearch.setSavedSearchFilterQueries(new ArrayList<>());
    for (String filterQuery : searchIncludeFragment.getFilterQueriesDebug()) {
        /**
             * @todo Why are there null's here anyway? Turn on debug and figure
             * this out.
             */
        if (filterQuery != null && !filterQuery.isEmpty()) {
            SavedSearchFilterQuery ssfq = new SavedSearchFilterQuery(filterQuery, savedSearch);
            savedSearch.getSavedSearchFilterQueries().add(ssfq);
        }
    }
    CreateSavedSearchCommand cmd = new CreateSavedSearchCommand(dvRequestService.getDataverseRequest(), linkingDataverse, savedSearch);
    try {
        commandEngine.submit(cmd);
        List<String> arguments = new ArrayList<>();
        String linkString = "<a href=\"/dataverse/" + linkingDataverse.getAlias() + "\">" + StringEscapeUtils.escapeHtml(linkingDataverse.getDisplayName()) + "</a>";
        arguments.add(linkString);
        String successMessageString = BundleUtil.getStringFromBundle("dataverse.saved.search.success", arguments);
        JsfHelper.addSuccessMessage(successMessageString);
        return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true";
    } catch (CommandException ex) {
        String msg = "There was a problem linking this search to yours: " + ex;
        logger.severe(msg);
        JsfHelper.addErrorMessage(BundleUtil.getStringFromBundle("dataverse.saved.search.failure") + " " + ex);
        return "/dataverse.xhtml?alias=" + dataverse.getAlias() + "&faces-redirect=true";
    }
}
Example 25
Project: Katari-master  File: DatabaseTestSupport.java View source code
/** Runs a set of sql sentences stored in a file.
   *
   * Sentences in the file are delimited by a line ending in ;.
   *
   * @param connection the database connection to use to run the sql sentences.
   * It cannot be null.
   *
   * @param fileName the String with the file name.
   */
public void runSqlSentences(final Connection connection, final String fileName) {
    log.trace("Entering runSqlSentences('" + fileName + "')");
    Validate.notNull(fileName, "The file name cannot be null.");
    String sentence = null;
    try {
        Statement statement = connection.createStatement();
        SqlSentencesParser parser = new SqlSentencesParser(fileName);
        while (null != (sentence = parser.readSentence())) {
            statement.execute(StringEscapeUtils.unescapeJava(sentence));
        }
    } catch (Exception e) {
        System.out.println("Error executing " + sentence);
        e.printStackTrace();
        System.exit(1);
    }
    log.trace("Leaving runSqlSentences");
}
Example 26
Project: ecms-develop-master  File: Utils.java View source code
/**
   * Gets the title.
   *
   * @param node the node
   * @return the title
   * @throws Exception the exception
   */
public static String getTitle(Node node) throws Exception {
    String title = null;
    if (node.hasProperty("exo:title")) {
        title = node.getProperty("exo:title").getValue().getString();
    } else if (node.hasNode("jcr:content")) {
        Node content = node.getNode("jcr:content");
        if (content.hasProperty("dc:title")) {
            try {
                title = content.getProperty("dc:title").getValues()[0].getString();
            } catch (PathNotFoundException ex) {
                title = null;
            } catch (ValueFormatException ex) {
                title = null;
            } catch (RepositoryException ex) {
                title = null;
            } catch (ArrayIndexOutOfBoundsException ex) {
                title = null;
            }
        }
    }
    if (StringUtils.isBlank(title)) {
        if (node.isNodeType("nt:frozenNode")) {
            String uuid = node.getProperty("jcr:frozenUuid").getString();
            Node originalNode = node.getSession().getNodeByUUID(uuid);
            title = originalNode.getName();
        } else {
            title = node.getName();
        }
    }
    return StringEscapeUtils.escapeHtml(Text.unescapeIllegalJcrChars(title));
}
Example 27
Project: cms-ce-master  File: SiteDebugInfoController.java View source code
/**
     * Create data info menu.
     */
private String createDataInfoMenu(String key, DataTraceInfo info, HttpServletRequest request, boolean isPage) {
    User user = securityService.getLoggedInPortalUser();
    SiteKey siteKey = info.getSiteKey();
    boolean hasAdmin = adminService.isSiteAdmin(user, siteKey);
    boolean hasDev = adminService.isDeveloper(user);
    String adminBaseUrl = getAdminBaseUrl(request);
    String baseUrl = getDebugBaseUrlWithHost(request, "__info__?key=" + key);
    StringBuffer str = new StringBuffer();
    // Header
    final String title = StringEscapeUtils.escapeHtml(info.getTitle());
    if (isPage) {
        str.append("<div style='float: left; width: 70%'><h3>").append(title).append("</h3></div>");
        str.append("<div style='float: left; width: 30%' id='ice-on-of-container'></div>");
    } else {
        str.append("<div><h3>").append(title).append("</h3></div>");
    }
    if (!info.getContentInfo().isEmpty() || hasAdmin) {
        str.append("<div class='ice-divider'><!-- --></div>");
    }
    // Content Wizard
    String contentWizardUrl = adminBaseUrl + "adminpage?page=960&op=createcontentwizard_step1&source=ice";
    str.append("<a href='javascript:void(0)'");
    str.append(" onclick='javascript:cms.ice.Utils.openWindow(\"").append(contentWizardUrl).append("\", 900, 600)'");
    str.append(" style='background-image:url(").append(adminBaseUrl).append("ice/images/icon_state_unsaved_draft.gif);'");
    str.append(">");
    str.append("<span class='ice-lang-placeholder-create-content'><!-- --></span>");
    str.append("</a>");
    if (!info.getContentInfo().isEmpty()) {
        str.append("<div class='ice-divider'><!-- --></div>");
    }
    // Edit content
    if (!info.getContentInfo().isEmpty()) {
        str.append("<div class='ice-menu-item-content-container'>");
        for (int contentKey : info.getContentInfo().keySet()) {
            str.append(createEditContentLink(adminBaseUrl, info.getContentInfo().get(contentKey), contentKey));
        }
        str.append("</div>");
    }
    // View render XML and View render trace
    if (hasAdmin || hasDev) {
        boolean showDivider = !info.getContentInfo().isEmpty() && hasAdmin || hasDev;
        if (showDivider) {
            str.append("<div class='ice-divider'><!-- --></div>");
        }
        String menuItemViewTraceText = isPage ? "<span class='ice-lang-placeholder-page-trace'><!-- --></span>" : "<span class='ice-lang-placeholder-portlet-trace'><!-- --></span>";
        String menuItemViewXMLText = isPage ? "<span class='ice-lang-placeholder-page-xml'><!-- --></span>" : "<span class='ice-lang-placeholder-portlet-xml'><!-- --></span>";
        str.append(createMenuInfoLink(menuItemViewTraceText, baseUrl + "&type=renderTrace", "_blank", adminBaseUrl + "ice/images/icon_xml.gif", null));
        str.append(createMenuInfoLink(menuItemViewXMLText, baseUrl + "&type=renderXml", "_blank", adminBaseUrl + "ice/images/icon_xml.gif", null));
    }
    // Edit object
    if (info instanceof PagePortletTraceInfo && hasAdmin) {
        PagePortletTraceInfo pageObjectTraceInfo = (PagePortletTraceInfo) info;
        SiteKey pageObjectSiteKey = pageObjectTraceInfo.getSiteKey();
        PortletKey portletKey = pageObjectTraceInfo.getKey();
        String editPortletUrl = adminBaseUrl + "adminpage?page=900&op=form&subop=popup&key=" + portletKey + "&menukey=" + pageObjectSiteKey.toInt() + "&fieldname=null&fieldrow=-1&callback=cms.ice.Utils.reloadPage";
        if (hasDev) {
            str.append("<div class='ice-divider'><!-- --></div>");
        }
        str.append("<a href='javascript:void(0)'");
        str.append(" onclick='cms.ice.Utils.openWindow(\"").append(editPortletUrl).append("\", 900, 600)'");
        str.append(" style='background-image:url(").append(adminBaseUrl).append("ice/images/icon_object.gif);'>");
        str.append("<span class='ice-lang-placeholder-edit-portlet'><!-- --></span>");
        str.append("</a>");
    }
    return str.toString();
}
Example 28
Project: records-management-master  File: RecordsManagementAuditServiceImpl.java View source code
/**
     * Writes the start of the audit trail stream to the given writer
     *
     * @param writer The writer to write to
     * @params params The parameters being used
     * @param reportFormat The format to write the header in
     * @throws IOException
     */
private void writeAuditTrailHeader(Writer writer, RecordsManagementAuditQueryParameters params, ReportFormat reportFormat) throws IOException {
    if (writer == null) {
        return;
    }
    if (reportFormat == ReportFormat.HTML) {
        // write header as HTML
        writer.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
        writer.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n");
        writer.write("<title>");
        writer.write(I18NUtil.getMessage(MSG_AUDIT_REPORT));
        writer.write("</title></head>\n");
        writer.write("<style>\n");
        writer.write("body { font-family: arial,verdana; font-size: 81%; color: #333; }\n");
        writer.write(".label { margin-right: 5px; font-weight: bold; }\n");
        writer.write(".value { margin-right: 40px; }\n");
        writer.write(".audit-info { background-color: #efefef; padding: 10px; margin-bottom: 4px; }\n");
        writer.write(".audit-entry { border: 1px solid #bbb; margin-top: 15px; }\n");
        writer.write(".audit-entry-header { background-color: #bbb; padding: 8px; }\n");
        writer.write(".audit-entry-node { padding: 10px; }\n");
        writer.write(".changed-values-table { margin-left: 6px; margin-bottom: 2px;width: 99%; }\n");
        writer.write(".changed-values-table th { text-align: left; background-color: #eee; padding: 4px; }\n");
        writer.write(".changed-values-table td { width: 33%; padding: 4px; border-top: 1px solid #eee; }\n");
        writer.write("</style>\n");
        writer.write("<body>\n<h2>");
        writer.write(I18NUtil.getMessage(MSG_AUDIT_REPORT));
        writer.write("</h2>\n");
        writer.write("<div class=\"audit-info\">\n");
        writer.write("<span class=\"label\">From:</span>");
        writer.write("<span class=\"value\">");
        Date from = params.getDateFrom();
        writer.write(from == null ? "<Not Set>" : StringEscapeUtils.escapeHtml(from.toString()));
        writer.write("</span>");
        writer.write("<span class=\"label\">To:</span>");
        writer.write("<span class=\"value\">");
        Date to = params.getDateTo();
        writer.write(to == null ? "<Not Set>" : StringEscapeUtils.escapeHtml(to.toString()));
        writer.write("</span>");
        writer.write("<span class=\"label\">Property:</span>");
        writer.write("<span class=\"value\">");
        QName prop = params.getProperty();
        writer.write(prop == null ? "All" : StringEscapeUtils.escapeHtml(getPropertyLabel(prop)));
        writer.write("</span>");
        writer.write("<span class=\"label\">User:</span>");
        writer.write("<span class=\"value\">");
        writer.write(params.getUser() == null ? "All" : StringEscapeUtils.escapeHtml(params.getUser()));
        writer.write("</span>");
        writer.write("<span class=\"label\">Event:</span>");
        writer.write("<span class=\"value\">");
        writer.write(params.getEvent() == null ? "All" : StringEscapeUtils.escapeHtml(getAuditEventLabel(params.getEvent())));
        writer.write("</span>\n");
        writer.write("</div>\n");
    } else {
        // write header as JSON
        writer.write("{\n\t\"data\":\n\t{");
        writer.write("\n\t\t\"started\": \"");
        writer.write(ISO8601DateFormat.format(getStartOfDay(params.getDateFrom())));
        writer.write("\",\n\t\t\"stopped\": \"");
        writer.write(ISO8601DateFormat.format(getEndOfDay(params.getDateTo())));
        writer.write("\",\n\t\t\"enabled\": ");
        writer.write(Boolean.toString(isEnabled()));
        writer.write(",\n\t\t\"entries\":[");
    }
}
Example 29
Project: tmdm-studio-se-master  File: XSDTreeLabelProvider.java View source code
@Override
public String getText(Object obj) {
    if (obj instanceof XSDElementDeclaration) {
        String name = ((XSDElementDeclaration) obj).getName();
        if (((XSDElementDeclaration) obj).isAbstract()) {
            name += Messages.XSDTreeLabelProvider_0;
        }
        String tail = ((XSDElementDeclaration) obj).getTargetNamespace() != null ? //$NON-NLS-1$
        " : " + ((XSDElementDeclaration) obj).getTargetNamespace() : //$NON-NLS-1$
        "";
        return name + tail;
    }
    if (obj instanceof XSDParticle) {
        XSDParticle xsdParticle = (XSDParticle) obj;
        XSDParticleContent content = xsdParticle.getContent();
        XSDTerm xsdTerm = xsdParticle.getTerm();
        //$NON-NLS-1$
        String name = "";
        if (content instanceof XSDElementDeclaration) {
            XSDElementDeclaration decl = (XSDElementDeclaration) content;
            //$NON-NLS-1$
            name += (decl.getName() == null ? "" : decl.getName());
            if (decl.getTypeDefinition() == null) {
                //$NON-NLS-1$//$NON-NLS-2$
                name += " [" + ((XSDElementDeclaration) xsdTerm).getName() + "]";
            }
        } else if (content instanceof XSDModelGroup) {
            // log.info("SHOULD NOT HAPPEN????");
            if (xsdParticle.getContainer() instanceof XSDComplexTypeDefinition) {
                String ctdName = ((XSDComplexTypeDefinition) xsdParticle.getContainer()).getName();
                //$NON-NLS-1$
                name = (ctdName != null ? ctdName : "");
            }
        } else {
            //$NON-NLS-1$
            name = "[Any]";
        }
        if (!((xsdParticle.getMinOccurs() == 1) && (xsdParticle.getMaxOccurs() == 1))) {
            //$NON-NLS-1$
            name += "  [";
            name += xsdParticle.getMinOccurs();
            //$NON-NLS-1$
            name += "...";
            //$NON-NLS-1$//$NON-NLS-2$
            name += (xsdParticle.getMaxOccurs() == -1) ? "many" : "" + xsdParticle.getMaxOccurs();
            //$NON-NLS-1$
            name += "]";
        }
        return name;
    }
    if (obj instanceof XSDSimpleTypeDefinition) {
        return getSimpleTypeDefinition((XSDSimpleTypeDefinition) obj);
    }
    if (obj instanceof XSDModelGroup) {
        // return the name of the complex type definition
        XSDParticle particle = (XSDParticle) (((XSDModelGroup) obj).getContainer());
        XSDComplexTypeDefinition complexTypeDefinition = (XSDComplexTypeDefinition) particle.getContainer();
        String name = complexTypeDefinition.getName();
        if (name == null) {
            //$NON-NLS-1$
            name = "anonymous type ";
        }
        // return the occurence
        if (!((particle.getMinOccurs() == 1) && (particle.getMaxOccurs() == 1))) {
            //$NON-NLS-1$
            name += "  [";
            name += particle.getMinOccurs();
            //$NON-NLS-1$
            name += "...";
            //$NON-NLS-1$//$NON-NLS-2$
            name += (particle.getMaxOccurs() == -1) ? "many" : "" + particle.getMaxOccurs();
            //$NON-NLS-1$
            name += "]";
        }
        // get extend type
        XSDTypeDefinition extendType = complexTypeDefinition.getBaseTypeDefinition();
        //$NON-NLS-1$
        String extendTypeName = "";
        if (extendType != null && extendType != complexTypeDefinition && !"anyType".equals(extendType.getName())) {
            //$NON-NLS-1$
            //$NON-NLS-1$
            extendTypeName = ":" + extendType.getName();
        }
        XSDSchema schema = particle.getSchema();
        //$NON-NLS-1$
        String tail = "";
        if (schema != null && schema.getTargetNamespace() != null) {
            tail = //$NON-NLS-1$
            " : " + schema.getTargetNamespace();
        }
        return name + tail + extendTypeName;
    }
    if (obj instanceof XSDFacet) {
        //$NON-NLS-1$
        return ((XSDFacet) obj).getFacetName() + ": " + ((XSDFacet) obj).getLexicalValue();
    }
    if (obj instanceof XSDIdentityConstraintDefinition) {
        return ((XSDIdentityConstraintDefinition) obj).getName();
    }
    if (obj instanceof XSDXPathDefinition) {
        XSDXPathDefinition xpath = (XSDXPathDefinition) obj;
        return xpath.getValue();
    }
    if (obj instanceof XSDAttributeGroupDefinition) {
        XSDAttributeGroupDefinition attributeGroupDefinition = (XSDAttributeGroupDefinition) obj;
        //$NON-NLS-1$
        String name = (attributeGroupDefinition.getName() == null ? "" : attributeGroupDefinition.getName());
        if (attributeGroupDefinition.getContents().size() == 0) {
            //$NON-NLS-1$//$NON-NLS-2$
            name += " [" + attributeGroupDefinition.getResolvedAttributeGroupDefinition().getName() + "]";
        }
        return name;
    }
    if (obj instanceof XSDAttributeUse) {
        XSDAttributeUse attributeUse = (XSDAttributeUse) obj;
        String name = attributeUse.getAttributeDeclaration().getName();
        if (name == null) {
            //$NON-NLS-1$//$NON-NLS-2$
            name = " [" + attributeUse.getAttributeDeclaration().getResolvedAttributeDeclaration().getName() + "]";
        }
        return name;
    }
    if (obj instanceof XSDAttributeDeclaration) {
        XSDAttributeDeclaration attributeDec = (XSDAttributeDeclaration) obj;
        String name = attributeDec.getName();
        if (name == null) {
            name = attributeDec.getAliasName();
            if (name == null) {
                //$NON-NLS-1$
                name = " [null]";
            }
        }
        return name;
    }
    if (obj instanceof XSDAnnotation) {
        //$NON-NLS-1$
        return "Annotations";
    }
    if (obj instanceof Element) {
        try {
            Element e = (Element) obj;
            if (e.getLocalName().equals("documentation")) {
                //$NON-NLS-1$
                return "Documentation: " + e.getChildNodes().item(0).getNodeValue();
            } else if (e.getLocalName().equals("appinfo")) {
                //$NON-NLS-1$
                //$NON-NLS-1$
                String source = e.getAttribute("source");
                if (source != null) {
                    if (source.startsWith("X_Label_")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_1, Util.iso2lang.get(source.substring(8).toLowerCase()), e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_ForeignKey")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_2, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_ForeignKey_NotSep")) {
                        //$NON-NLS-1$
                        Boolean v = Boolean.valueOf(e.getChildNodes().item(0).getNodeValue());
                        return Messages.bind(Messages.XSDTreeLabelProvider_3, Messages.SimpleXpathInputDialog_sepFkTabPanel, v);
                    } else if (source.equals("X_Visible_Rule")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_4, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Default_Value_Rule")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_5, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_ForeignKeyInfo")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_6, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_ForeignKeyInfoFormat")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_20, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_PrimaryKeyInfo")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_7, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_SourceSystem")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_8, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_TargetSystem")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_9, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.startsWith("X_Description_")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_10, Util.iso2lang.get(source.substring(14).toLowerCase()), e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Write")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_11, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Deny_Create")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_12, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Deny_LogicalDelete")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_13, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Deny_PhysicalDelete")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_14, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Lookup_Field")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_15, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Workflow")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_16, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_Hide")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_17, e.getChildNodes().item(0).getNodeValue());
                    // add by ymli; bugId 0009157
                    } else if (source.equals("X_AutoExpand")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_18, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.startsWith("X_Facet")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_19, source.substring(2, 7), source.substring(8), e.getChildNodes().item(0).getNodeValue());
                    // made schematron show:Schematron: schematron
                    } else if (source.startsWith("X_Display_Format_")) {
                        //$NON-NLS-1$
                        return source + ": " + e.getChildNodes().item(0).getNodeValue();
                    } else if (source.equals("X_Schematron")) {
                        //$NON-NLS-1$
                        //$NON-NLS-1$
                        String pattern = (String) e.getFirstChild().getUserData("pattern_name");
                        if (pattern == null) {
                            Element el = Util.parse(e.getChildNodes().item(0).getNodeValue()).getDocumentElement();
                            if (el.getAttributes().getNamedItem("name") != null) {
                                //$NON-NLS-1$
                                //$NON-NLS-1$
                                pattern = el.getAttributes().getNamedItem("name").getTextContent();
                            }
                        }
                        return Messages.bind(Messages.XSDTreeLabelProvider_21, // e.getChildNodes().item(0).getNodeValue();
                        (pattern == null ? Messages.XSDTreeLabelProvider_22 : pattern));
                    // end
                    } else if (source.equals("X_Retrieve_FKinfos")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_23, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_FKIntegrity")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_24, e.getChildNodes().item(0).getNodeValue());
                    } else if (source.equals("X_FKIntegrity_Override")) {
                        //$NON-NLS-1$
                        return Messages.bind(Messages.XSDTreeLabelProvider_25, e.getChildNodes().item(0).getNodeValue());
                    }
                    if (source.equals("X_ForeignKey_Filter")) {
                        //$NON-NLS-1$
                        String nodeValue = e.getChildNodes().item(0).getNodeValue();
                        if (nodeValue.startsWith("$CFFP:")) {
                            //$NON-NLS-1$
                            nodeValue = StringEscapeUtils.unescapeXml(nodeValue).substring(6);
                        }
                        return Messages.bind(Messages.XSDTreeLabelProvider_26, nodeValue);
                    } else {
                        //$NON-NLS-1$
                        return source + ": " + Util.nodeToString((Element) obj);
                    }
                } else {
                    return Util.nodeToString((Element) obj);
                }
            } else {
                return Util.nodeToString((Element) obj);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    if (obj == null) {
        //$NON-NLS-1$
        return "NULL";
    }
    //$NON-NLS-1$//$NON-NLS-2$
    return "?? " + obj.getClass().getName() + " : " + obj.toString();
}
Example 30
Project: Magnolia-master  File: SimpleNavigationTag.java View source code
/**
     * Draws page children as an unordered list.
     * 
     * @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>");
}
Example 31
Project: gatein-portal-master  File: NewPortalConfigListener.java View source code
/**
     * Best effort to load and unmarshall a configuration.
     *
     * @param config the config object
     * @param owner the owner
     * @param fileName the file name
     * @param type the type to unmarshall to
     * @return the xml of the config or null
     * @throws Exception any exception
     * @param <T> the generic type to unmarshall to
     */
private <T> UnmarshalledObject<T> getConfig(NewPortalConfig config, String owner, String fileName, Class<T> type) throws Exception {
    log.debug("About to load config=" + config + " owner=" + owner + " fileName=" + fileName);
    //
    String ownerType = config.getOwnerType();
    // Get XML
    String path = "/" + ownerType + "/" + owner + "/" + fileName + ".xml";
    String xml = getDefaultConfig(config.getTemplateLocation(), path);
    //
    if (xml == null) {
        String templateName = config.getTemplateName() != null ? config.getTemplateName() : fileName;
        path = "/" + ownerType + "/template/" + templateName + "/" + fileName + ".xml";
        xml = getDefaultConfig(config.getTemplateLocation(), path);
        if (xml != null) {
            xml = OWNER_PATTERN.matcher(xml).replaceAll(StringEscapeUtils.escapeXml(owner));
        }
    }
    //
    if (xml != null) {
        boolean ok = false;
        try {
            final UnmarshalledObject<T> o = fromXML(config.getOwnerType(), owner, xml, type);
            ok = true;
            return o;
        } catch (JiBXException e) {
            log.error(e.getMessage() + " file: " + path, e);
            throw e;
        } finally {
            if (!ok) {
                log.error("Could not load file: " + path);
            }
        }
    }
    //
    return null;
}
Example 32
Project: wso2-synapse-master  File: PayloadFactoryMediator.java View source code
/**
     * Goes through SynapsePath argument list, evaluating each by calling stringValueOf and returns a HashMap String, String
     * array where each item will contain a hash map with key "evaluated expression" and value "SynapsePath type".
     * @param synCtx
     * @return
     */
private HashMap<String, ArgumentDetails>[] getArgValues(MessageContext synCtx) {
    HashMap<String, ArgumentDetails>[] argValues = new HashMap[pathArgumentList.size()];
    HashMap<String, ArgumentDetails> valueMap;
    String value = "";
    for (int i = 0; i < pathArgumentList.size(); ++i) {
        /*ToDo use foreach*/
        Argument arg = pathArgumentList.get(i);
        ArgumentDetails details = new ArgumentDetails();
        if (arg.getValue() != null) {
            value = arg.getValue();
            details.setXml(isXML(value, arg.isDeepCheck()));
            if (!details.isXml()) {
                value = StringEscapeUtils.escapeXml(value);
            }
            value = Matcher.quoteReplacement(value);
        } else if (arg.getExpression() != null) {
            value = arg.getExpression().stringValueOf(synCtx);
            details.setLiteral(arg.isLiteral());
            if (value != null) {
                // XML escape the result of an expression that produces a literal, if the target format
                // of the payload is XML.
                details.setXml(isXML(value, arg.isDeepCheck()));
                if (!details.isXml() && !arg.getExpression().getPathType().equals(SynapsePath.JSON_PATH) && XML_TYPE.equals(getType())) {
                    value = StringEscapeUtils.escapeXml(value);
                }
                value = Matcher.quoteReplacement(value);
            } else {
                value = "";
            }
        } else {
            handleException("Unexpected arg type detected", synCtx);
        }
        //value = value.replace(String.valueOf((char) 160), " ").trim();
        valueMap = new HashMap<String, ArgumentDetails>();
        if (null != arg.getExpression()) {
            details.setPathType(arg.getExpression().getPathType());
            details.setDeepCheck(arg.isDeepCheck());
            valueMap.put(value, details);
        } else {
            details.setPathType(SynapsePath.X_PATH);
            details.setDeepCheck(arg.isDeepCheck());
            valueMap.put(value, details);
        }
        argValues[i] = valueMap;
    }
    return argValues;
}
Example 33
Project: cids-server-master  File: CidsBean.java View source code
/**
     * DOCUMENT ME!
     *
     * @param   bean   DOCUMENT ME!
     * @param   depth  DOCUMENT ME!
     *
     * @return  DOCUMENT ME!
     */
// FIXME: use a JSON API such as Jackson
private String beanToJSONStringHelper(final CidsBean bean, final int depth) {
    final StringBuilder sb = new StringBuilder();
    final char[] einrueckung = new char[depth];
    for (int i = 0; i < einrueckung.length; ++i) {
        einrueckung[i] = '\t';
    }
    sb.append(einrueckung).append('{').append('\n');
    final String[] propNames = bean.getPropertyNames();
    for (int i = 0; i < propNames.length; ++i) {
        final String attribute = propNames[i];
        sb.append(einrueckung).append('\t').append('"').append(attribute).append("\": ");
        final Object object = bean.getProperty(attribute);
        if (object instanceof CidsBean) {
            sb.append('\n');
            sb.append(beanToJSONStringHelper((CidsBean) object, depth + 1));
            sb.append('\n');
        } else if (object instanceof List) {
            final List<CidsBean> collection = (List<CidsBean>) object;
            sb.append('\n').append(einrueckung).append('[');
            for (int j = 0; j < collection.size(); ++j) {
                final CidsBean colBean = collection.get(j);
                sb.append(beanToJSONStringHelper(colBean, depth + 1));
                if (j < (collection.size() - 1)) {
                    sb.append(',');
                    sb.append('\n');
                }
            }
            sb.append('\n').append(einrueckung).append(']');
        } else {
            sb.append('"').append(StringEscapeUtils.escapeJava(String.valueOf(object))).append('"');
        }
        if (i < (propNames.length - 1)) {
            sb.append(',');
        }
        sb.append('\n');
    }
    sb.append(einrueckung).append("}");
    return sb.toString();
}
Example 34
Project: crux-master  File: DefaultSchemaGenerator.java View source code
/**
	 * 
	 * @param out
	 * @param library
	 * @param added
	 * @param processorClass
	 */
protected void generateAttributes(PrintStream out, String library, Set<String> added, Class<?> processorClass) {
    TagAttributesDeclaration attrsDecl = processorClass.getAnnotation(TagAttributesDeclaration.class);
    if (attrsDecl != null) {
        for (TagAttributeDeclaration attr : attrsDecl.value()) {
            if (!added.contains(attr.value())) {
                out.print("<xs:attribute name=\"" + attr.value() + "\" type=\"" + getSchemaType(attr.type(), library, attr.supportsDataBinding()) + "\" ");
                if (attr.required()) {
                    out.print("use=\"required\" ");
                } else {
                    String defaultValue = attr.defaultValue();
                    if (defaultValue.length() > 0)
                        out.print("default=\"" + defaultValue + "\" ");
                }
                out.println(">");
                String attrDescription = attr.description();
                if (attrDescription != null && attrDescription.length() > 0) {
                    out.println("<xs:annotation>");
                    out.println("<xs:documentation>" + StringEscapeUtils.escapeXml(attrDescription) + "</xs:documentation>");
                    out.println("</xs:annotation>");
                }
                out.println("</xs:attribute>");
                added.add(attr.value());
            }
        }
    }
    TagAttributes attrs = processorClass.getAnnotation(TagAttributes.class);
    if (attrs != null) {
        for (TagAttribute attr : attrs.value()) {
            if (!added.contains(attr.value()) && !attr.xsdIgnore()) {
                out.print("<xs:attribute name=\"" + attr.value() + "\" type=\"" + getSchemaType(attr.type(), library, attr.supportsDataBinding()) + "\" ");
                if (attr.required()) {
                    out.print("use=\"required\" ");
                } else {
                    String defaultValue = attr.defaultValue();
                    if (defaultValue.length() > 0)
                        out.print("default=\"" + defaultValue + "\" ");
                }
                out.println(">");
                String attrDescription = attr.description();
                if (attrDescription != null && attrDescription.length() > 0) {
                    out.println("<xs:annotation>");
                    out.println("<xs:documentation>" + StringEscapeUtils.escapeXml(attrDescription) + "</xs:documentation>");
                    out.println("</xs:annotation>");
                }
                out.println("</xs:attribute>");
                added.add(attr.value());
            }
        }
    }
}