List of usage examples for java.lang StringBuffer replace
@Override public synchronized StringBuffer replace(int start, int end, String str)
From source file:com.topsec.tsm.sim.report.web.ReportController.java
/** * /*from w w w. j ava 2s . c o m*/ */ @RequestMapping("reportQuery") @SuppressWarnings("unchecked") public String reportQuery(SID sid, HttpServletRequest request, HttpServletResponse response) throws Exception { boolean fromRest = false; if (request.getParameter("fromRest") != null) { fromRest = Boolean.parseBoolean(request.getParameter("fromRest")); } JSONObject json = new JSONObject(); ReportBean bean = new ReportBean(); bean = ReportUiUtil.tidyFormBean(bean, request); String onlyByDvctype = request.getParameter("onlyByDvctype"); String[] talCategory = bean.getTalCategory(); ReportModel.setBeanPropery(bean); RptMasterTbService rptMasterTbImp = (RptMasterTbService) SpringContextServlet.springCtx .getBean(ReportUiConfig.MstBean); List<Map<String, Object>> subResult = rptMasterTbImp.queryTmpList(ReportUiConfig.MstSubSql, new Object[] { StringUtil.toInt(bean.getMstrptid(), StringUtil.toInt(bean.getTalTop(), 5)) }); StringBuffer layout = new StringBuffer(); Map<Integer, Integer> rowColumns = ReportModel.getRowColumns(subResult); Map<String, Object> params = new HashMap<String, Object>(); params.put("dvcType", bean.getDvctype()); params.put("talTop", bean.getTalTop()); params.put("mstId", bean.getMstrptid()); params.put("eTime", bean.getTalEndTime()); if ("Esm/Topsec/SimEvent".equals(bean.getDvctype()) || "Esm/Topsec/SystemLog".equals(bean.getDvctype()) || "Esm/Topsec/SystemRunLog".equals(bean.getDvctype()) || "Log/Global/Detail".equals(bean.getDvctype())) { onlyByDvctype = "onlyByDvctype"; } String sUrl = null; List<SimDatasource> simDatasources = dataSourceService.getDataSourceByDvcType(bean.getDvctype()); removeRepeatDs(simDatasources); Set<AuthUserDevice> devices = ObjectUtils.nvl(sid.getUserDevice(), Collections.<AuthUserDevice>emptySet()); List<SimDatasource> dslist = new ArrayList<SimDatasource>(); if (sid.isOperator()) { SimDatasource dsource = new SimDatasource(); dsource.setDeviceIp(""); dsource.setSecurityObjectType(bean.getDvctype()); dsource.setAuditorNodeId(""); dslist.add(0, dsource); dslist.addAll(simDatasources); } else { BeanToPropertyValueTransformer trans = new BeanToPropertyValueTransformer("ip"); Collection<String> userDeviceIPs = (Collection<String>) CollectionUtils.collect(devices, trans); for (SimDatasource simDatasource : simDatasources) { if (userDeviceIPs.contains(simDatasource.getDeviceIp())) { dslist.add(simDatasource); } } } int screenWidth = StringUtil.toInt(request.getParameter("screenWidth"), 1280) - 25 - 200; boolean flag = "onlyByDvctype".equals(onlyByDvctype); SimDatasource selectDataSource = getSelectDataSource(dslist, bean, flag, request); AssetObject assetObject = null == selectDataSource ? null : AssetFacade.getInstance().getAssetByIp(selectDataSource.getDeviceIp()); if (fromRest) { json.put("selectDataSourceId", selectDataSource == null ? 0 : selectDataSource.getResourceId()); json.put("selectDataSourceName", selectDataSource == null ? "" : assetObject.getName()); } request.setAttribute("selectDataSourceId", selectDataSource == null ? 0 : selectDataSource.getResourceId()); request.setAttribute("selectDataSourceName", selectDataSource == null ? "" : assetObject.getName()); StringBuffer subUrl = new StringBuffer(); Map layoutValue = new HashMap(); for (int i = 0, len = subResult.size(); i < len; i++) { params.remove("sTime"); Map subMap = subResult.get(i); if (i == 0) { bean.setViewItem(StringUtil.toString(subMap.get("viewItem"), "")); } Integer row = (Integer) subMap.get("subRow"); layout.append(row + ":" + subMap.get("subColumn") + ","); if (GlobalUtil.isNullOrEmpty(subMap)) { continue; } boolean qushi = StringUtil.booleanVal(subMap.get("chartProperty")); String tableSql = StringUtil.nvl((String) subMap.get("tableSql")); String subName = StringUtil.nvl((String) subMap.get("subName")); String mstName = StringUtil.nvl((String) subMap.get("mstName")); String pageSql = StringUtil.nvl((String) subMap.get("pagesql")); String chartSql = StringUtil.nvl((String) subMap.get("chartSql")); String nowTime = ReportUiUtil.getNowTime(ReportUiConfig.dFormat1); String talEndTime = bean.getTalEndTime(); if (qushi && (subName.contains("") || subName.contains("") || subName.contains("") || subName.contains("") || mstName.contains("") || mstName.contains("") || mstName.contains("") || mstName.contains(""))) { bean.setTalEndTime(nowTime); params.put("eTime", bean.getTalEndTime()); if (tableSql.indexOf("Hour") > 20 || tableSql.indexOf("_hour") > 20) { params.put("sTime", ReportUiUtil.toStartTime("hour", bean.getTalEndTime())); } else if (tableSql.indexOf("Day") > 20 || tableSql.indexOf("_day") > 20) { params.put("sTime", ReportUiUtil.toStartTime("day", bean.getTalEndTime())); } else if (tableSql.indexOf("Month") > 20 || tableSql.indexOf("_month") > 20) { params.put("sTime", ReportUiUtil.toStartTime("month", bean.getTalEndTime())); } else if (pageSql.indexOf("Hour") > 20 || pageSql.indexOf("_hour") > 20 || chartSql.indexOf("Hour") > 20) { params.put("sTime", ReportUiUtil.toStartTime("hour", bean.getTalEndTime())); } else if (pageSql.indexOf("Day") > 20 || pageSql.indexOf("_day") > 20 || chartSql.indexOf("Day") > 20) { params.put("sTime", ReportUiUtil.toStartTime("day", bean.getTalEndTime())); } else if (pageSql.indexOf("Month") > 20 || pageSql.indexOf("_month") > 20 || chartSql.indexOf("Month") > 20) { params.put("sTime", ReportUiUtil.toStartTime("month", bean.getTalEndTime())); } else { params.put("sTime", bean.getTalStartTime()); } } else if (subName.indexOf("") > 1) { bean.setTalEndTime(nowTime); params.put("eTime", bean.getTalEndTime()); if (tableSql.indexOf("Hour") > 20 || tableSql.indexOf("_hour") > 20) { params.put("sTime", ReportUiUtil.toStartTime("undefined", bean.getTalEndTime())); } else { params.put("sTime", bean.getTalStartTime()); } String startTime = params.get("sTime").toString(); String endTime = params.get("eTime").toString(); subName = subName + " " + startTime.substring(5) + " - " + endTime.substring(10) + "";//endTime.substring(10,endTime.length()-4)+"0:00"; subMap.put("subName", subName); } else { params.put("sTime", bean.getTalStartTime()); } bean.setTalEndTime(talEndTime); sUrl = getUrl(ReportUiConfig.subUrl, request, params, bean.getTalCategory()).toString(); subUrl.replace(0, subUrl.length(), sUrl); subUrl.append("&").append(ReportUiConfig.subrptid).append("=").append(subMap.get("subId")); subUrl.substring(0, subUrl.length()); int column = rowColumns.get(row); String width = String.valueOf((screenWidth - 10 * column) / column); String _column = subMap.get("subColumn").toString(); layoutValue.put(row + _column, ReportUiUtil.createSubTitle(subMap, width, subUrl.toString(), bean.getTalCategory(), StringUtil.toInt(bean.getTalTop(), 5))); } if (talCategory != null) { if (fromRest) json.put("superiorUrl", getSuperiorUrl(request, params, bean.getTalCategory()).toString()); request.setAttribute("superiorUrl", getSuperiorUrl(request, params, bean.getTalCategory()).toString()); } if (!GlobalUtil.isNullOrEmpty(subResult) && subResult.size() > 0) { if (!GlobalUtil.isNullOrEmpty(subResult.get(0).get("mstName"))) { if (fromRest) { json.put("title", subResult.get(0).get("mstName")); } request.setAttribute("title", subResult.get(0).get("mstName")); } } String htmlLayout = ReportModel.createMstTable(layout.toString(), layoutValue); StringBuffer sb = getExportUrl(request, params, talCategory); request.setAttribute("expUrl", sb.toString()); request.setAttribute("layout", htmlLayout); request.setAttribute("bean", bean); request.setAttribute("dslist", dslist); if (fromRest) { json.put("expUrl", sb.toString()); json.put("layout", htmlLayout); json.put("bean", JSONObject.toJSON(bean)); json.put("dslist", JSONObject.toJSON(dslist)); return json.toString(); } return "/page/report/base_report_detail"; }
From source file:org.infoglue.deliver.invokers.DecoratedComponentBasedHTMLPageInvoker.java
/** * This method adds the necessary html to a template to make it right-clickable. *///from ww w .j av a 2 s. c o m private String decorateTemplate(TemplateController templateController, String template, DeliveryContext deliveryContext, InfoGlueComponent component) { Timer timer = new Timer(); timer.setActive(false); String decoratedTemplate = template; try { String cmsBaseUrl = CmsPropertyHandler.getCmsBaseUrl(); String componentEditorUrl = CmsPropertyHandler.getComponentEditorUrl(); InfoGluePrincipal principal = templateController.getPrincipal(); String cmsUserName = (String) templateController.getHttpServletRequest().getSession() .getAttribute("cmsUserName"); if (cmsUserName != null && !CmsPropertyHandler.getAnonymousUser().equalsIgnoreCase(cmsUserName)) { InfoGluePrincipal newPrincipal = templateController.getPrincipal(cmsUserName); if (newPrincipal != null) principal = newPrincipal; } Locale locale = templateController.getLocaleAvailableInTool(principal); boolean hasAccessToAccessRights = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.ChangeSlotAccess", ""); boolean hasAccessToAddComponent = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.AddComponent", "" + component.getContentId() + "_" + component.getCleanedSlotName()); boolean hasAccessToDeleteComponent = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.DeleteComponent", "" + component.getContentId() + "_" + component.getCleanedSlotName()); boolean hasAccessToChangeComponent = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.ChangeComponent", "" + component.getContentId() + "_" + component.getCleanedSlotName()); boolean hasSaveTemplateAccess = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.SavePageTemplate", true, false, true); boolean hasSubmitToPublishAccess = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.SubmitToPublish", true, false, true); boolean hasPageStructureAccess = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.PageStructure", true, false, true); boolean hasOpenInNewWindowAccess = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.OpenInNewWindow", true, false, true); boolean hasViewSourceAccess = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.ViewSource", true, false, true); boolean showNotifyUserOfPage = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.NotifyUserOfPage", true, false, true); boolean showContentNotifications = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.ContentNotifications", true, false, true); boolean showPageNotifications = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.PageNotifications", true, false, true); boolean showW3CValidator = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.W3CValidator", true, false, true); boolean showLanguageMenu = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.ShowLanguageMenu", true, false, true); boolean showHomeButton = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.ShowHomeButton", true, false, true); boolean showMySettingsButton = AccessRightController.getController().getIsPrincipalAuthorized( templateController.getDatabase(), principal, "ComponentEditor.ShowMySettingsButton", true, false, true); String useApprovalFlow = CmsPropertyHandler.getUseApprovalFlow(); String autoShowApprovalButtons = CmsPropertyHandler.getAutoShowApprovalButtons(); String extraHeader = FileHelper.getFileAsString(new File(CmsPropertyHandler.getContextDiskPath() + (CmsPropertyHandler.getContextDiskPath().endsWith("/") ? "" : "/") + "preview/pageComponentEditorHeader.vm"), "iso-8859-1"); String extraBody = FileHelper.getFileAsString(new File(CmsPropertyHandler.getContextDiskPath() + (CmsPropertyHandler.getContextDiskPath().endsWith("/") ? "" : "/") + "preview/pageComponentEditorBody.vm"), "iso-8859-1"); boolean oldUseFullUrl = this.getTemplateController().getDeliveryContext().getUseFullUrl(); this.getTemplateController().getDeliveryContext().setUseFullUrl(true); String parameters = "repositoryId=" + templateController.getSiteNode().getRepositoryId() + "&siteNodeId=" + templateController.getSiteNodeId() + "&languageId=" + templateController.getLanguageId() + "&contentId=" + templateController.getContentId() + "&componentId=" + this.getRequest().getParameter("activatedComponentId") + "&componentContentId=" + this.getRequest().getParameter("componentContentId") + "&showSimple=false&showLegend=false&originalUrl=" + URLEncoder.encode(this.getTemplateController().getCurrentPageUrl(), "UTF-8"); String WYSIWYGEditorFile = "ckeditor/ckeditor.js"; if (!CmsPropertyHandler.getPrefferedWYSIWYG().equals("ckeditor4")) WYSIWYGEditorFile = "FCKEditor/fckeditor.js"; StringBuffer path = getPagePathAsCommaseparatedIds(templateController); extraHeader = extraHeader.replaceAll("\\$\\{focusElementId\\}", "" + this.getRequest().getParameter("focusElementId")); extraHeader = extraHeader.replaceAll("\\$\\{cmsBaseUrl\\}", cmsBaseUrl); extraHeader = extraHeader.replaceAll("\\$\\{contextName\\}", this.getRequest().getContextPath()); extraHeader = extraHeader.replaceAll("\\$\\{componentEditorUrl\\}", componentEditorUrl); if (principal.getName().equalsIgnoreCase(CmsPropertyHandler.getAnonymousUser())) extraHeader = extraHeader.replaceAll("\\$\\{limitedUserWarning\\}", "alert('Your session must have expired as you are now in decorated mode as " + principal.getName() + ". Please close browser and login again.');"); else extraHeader = extraHeader.replaceAll("\\$\\{limitedUserWarning\\}", ""); //extraHeader = extraHeader.replaceAll("\\$\\{currentUrl\\}", URLEncoder.encode(this.getTemplateController().getCurrentPageUrl(), "UTF-8")); extraHeader = extraHeader.replaceAll("\\$\\{currentUrl\\}", URLEncoder.encode(this.getTemplateController().getOriginalFullURL(), "UTF-8")); extraHeader = extraHeader.replaceAll("\\$\\{activatedComponentId\\}", "" + this.getRequest().getParameter("activatedComponentId")); extraHeader = extraHeader.replaceAll("\\$\\{parameters\\}", parameters); extraHeader = extraHeader.replaceAll("\\$\\{siteNodeId\\}", "" + templateController.getSiteNodeId()); extraHeader = extraHeader.replaceAll("\\$\\{languageId\\}", "" + templateController.getLanguageId()); extraHeader = extraHeader.replaceAll("\\$\\{contentId\\}", "" + templateController.getContentId()); extraHeader = extraHeader.replaceAll("\\$\\{metaInfoContentId\\}", "" + templateController.getMetaInformationContentId()); extraHeader = extraHeader.replaceAll("\\$\\{parentSiteNodeId\\}", "" + templateController.getSiteNode().getParentSiteNodeId()); extraHeader = extraHeader.replaceAll("\\$\\{repositoryId\\}", "" + templateController.getSiteNode().getRepositoryId()); extraHeader = extraHeader.replaceAll("\\$\\{path\\}", "" + path.substring(1)); extraHeader = extraHeader.replaceAll("\\$\\{userPrefferredLanguageCode\\}", "" + CmsPropertyHandler.getPreferredLanguageCode(principal.getName())); extraHeader = extraHeader.replaceAll("\\$\\{userPrefferredWYSIWYG\\}", "" + CmsPropertyHandler.getPrefferedWYSIWYG()); extraHeader = extraHeader.replaceAll("\\$\\{WYSIWYGEditorJS\\}", WYSIWYGEditorFile); extraHeader = extraHeader.replaceAll("\\$\\{publishedLabel\\}", getLocalizedString(locale, "tool.contenttool.state.published")); if (CmsPropertyHandler.getPersonalDisableEditOnSightToolbar(principal.getName())) { extraHeader = extraHeader.replaceAll("\\$\\{editOnSightFooterToolbarIsActive\\}", "false"); extraHeader = extraHeader.replaceAll("\\$\\{editOnSightFooterToolbarOverideCSS\\}", ".editOnSightFooterToolbar{display:none}"); } else { extraHeader = extraHeader.replaceAll("\\$\\{editOnSightFooterToolbarIsActive\\}", "true"); extraHeader = extraHeader.replaceAll("\\$\\{editOnSightFooterToolbarOverideCSS\\}", ""); } if (CmsPropertyHandler.getShowInlinePropertiesIcon().equalsIgnoreCase("false")) { extraHeader = extraHeader.replaceAll("\\$\\{useInlinePropertiesIcon\\}", "false"); } else { extraHeader = extraHeader.replaceAll("\\$\\{useInlinePropertiesIcon\\}", "true"); } if (getRequest().getParameter("approveEntityName") != null && !getRequest().getParameter("approveEntityName").equals("") && getRequest().getParameter("approveEntityId") != null && !getRequest().getParameter("approveEntityId").equals("")) { extraHeader = extraHeader.replaceAll("\\$\\{approveEntityName\\}", "" + getRequest().getParameter("approveEntityName")); extraHeader = extraHeader.replaceAll("\\$\\{approveEntityId\\}", "" + getRequest().getParameter("approveEntityId")); extraHeader = extraHeader.replaceAll("\\$\\{publishingEventId\\}", "" + getRequest().getParameter("publishingEventId")); } else { extraHeader = extraHeader.replaceAll("\\$\\{approveEntityName\\}", ""); extraHeader = extraHeader.replaceAll("\\$\\{approveEntityId\\}", ""); extraHeader = extraHeader.replaceAll("\\$\\{publishingEventId\\}", ""); } StringBuffer skinCSS = new StringBuffer(); String theme = CmsPropertyHandler.getTheme(principal.getName()); if (!theme.equalsIgnoreCase("Default")) { skinCSS.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + this.getRequest().getContextPath() + "/css/skins/" + theme + "/componentEditor.css\" />"); String themeFileJQueryUI = CmsPropertyHandler.getThemeFile(theme, "jquery-ui.css"); if (themeFileJQueryUI != null) skinCSS.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + this.getRequest().getContextPath() + "/css/skins/" + theme + "/jquery-ui.css\" />"); else skinCSS.append( "<link rel=\"stylesheet\" type=\"text/css\" href=\"script/jqueryplugins-latest/ui/css/jquery-ui.css\" />"); } else { skinCSS.append( "<link rel=\"stylesheet\" type=\"text/css\" href=\"script/jqueryplugins-latest/ui/css/jquery-ui.css\" />"); } extraHeader = extraHeader.replaceAll("\\$\\{skinDeliveryCSS\\}", skinCSS.toString()); String sortBaseUrl = componentEditorUrl + "ViewSiteNodePageComponents!moveComponent.action?siteNodeId=" + templateController.getSiteNodeId() + "&languageId=" + templateController.getLanguageId() + "&contentId=" + templateController.getContentId() + "&showSimple=" + this.getTemplateController().getDeliveryContext().getShowSimple() + ""; extraHeader = extraHeader.replaceAll("\\$\\{sortBaseUrl\\}", sortBaseUrl); this.getTemplateController().getDeliveryContext().setUseFullUrl(oldUseFullUrl); String changeUrl = componentEditorUrl + "ViewSiteNodePageComponents!listComponentsForChange.action?siteNodeId=" + templateController.getSiteNodeId() + "&languageId=" + templateController.getLanguageId() + "&contentId=" + templateController.getContentId() + "&componentId=" + component.getId() + "&slotId=base&showSimple=" + this.getTemplateController().getDeliveryContext().getShowSimple(); extraBody = extraBody + "<script type=\"text/javascript\">$(function() { initializeComponentEventHandler('base0_" + component.getId() + "Comp', '" + component.getId() + "', '', '" + componentEditorUrl + "ViewSiteNodePageComponents!deleteComponent.action?siteNodeId=" + templateController.getSiteNodeId() + "&languageId=" + templateController.getLanguageId() + "&contentId=" + templateController.getContentId() + "&componentId=" + component.getId() + "&slotId=base&showSimple=" + this.getTemplateController().getDeliveryContext().getShowSimple() + "','" + changeUrl + "'); }); </script>"; String submitToPublishHTML = getLocalizedString(locale, "deliver.editOnSight.submitToPublish"); String addComponentHTML = getLocalizedString(locale, "deliver.editOnSight.addComponentHTML"); String deleteComponentHTML = getLocalizedString(locale, "deliver.editOnSight.deleteComponentHTML"); String changeComponentHTML = getLocalizedString(locale, "deliver.editOnSight.changeComponentHTML"); String accessRightsHTML = getLocalizedString(locale, "deliver.editOnSight.accessRightsHTML"); String pageComponentsHTML = getLocalizedString(locale, "deliver.editOnSight.pageComponentsHTML"); String viewSourceHTML = getLocalizedString(locale, "deliver.editOnSight.viewSourceHTML"); String componentEditorInNewWindowHTML = getLocalizedString(locale, "deliver.editOnSight.componentEditorInNewWindowHTML"); String savePageTemplateHTML = getLocalizedString(locale, "deliver.editOnSight.savePageTemplateHTML"); String savePagePartTemplateHTML = getLocalizedString(locale, "deliver.editOnSight.savePagePartTemplateHTML"); String editHTML = getLocalizedString(locale, "deliver.editOnSight.editHTML"); String editInlineHTML = getLocalizedString(locale, "deliver.editOnSight.editContentInlineLabel"); String propertiesHTML = getLocalizedString(locale, "deliver.editOnSight.propertiesHTML"); String favouriteComponentsHeader = getLocalizedString(locale, "tool.common.favouriteComponentsHeader"); String noActionAvailableHTML = getLocalizedString(locale, "deliver.editOnSight.noActionAvailableHTML"); String notifyLabel = getLocalizedString(locale, "deliver.editOnSight.notifyLabel"); String subscribeToContentLabel = getLocalizedString(locale, "deliver.editOnSight.subscribeToContentLabel"); String subscribeToPageLabel = getLocalizedString(locale, "deliver.editOnSight.subscribeToPageLabel"); String translateContentLabel = getLocalizedString(locale, "deliver.editOnSight.translateContentLabel"); String confirmDeleteLabel = getLocalizedString(locale, "deliver.editOnSight.confirmDeleteLabel"); String leaveWarningOnDirtyPageText = getLocalizedString(locale, "deliver.editOnSight.leaveWarningOnDirtyPage.text"); String saveTemplateUrl = "saveComponentStructure('" + componentEditorUrl + "CreatePageTemplate!input.action?contentId=" + templateController.getSiteNode(deliveryContext.getSiteNodeId()).getMetaInfoContentId() + "');"; String savePartTemplateUrl = "savePartComponentStructure('" + componentEditorUrl + "CreatePageTemplate!input.action?contentId=" + templateController.getSiteNode(deliveryContext.getSiteNodeId()).getMetaInfoContentId() + "');"; if (!hasSaveTemplateAccess) { saveTemplateUrl = "alert('Not authorized to save template');"; savePartTemplateUrl = "alert('Not authorized to save part template');"; } String personalStartUrl = "/"; String repositoryId = CmsPropertyHandler.getPreferredRepositoryId(principal.getName()); logger.info("repositoryId: " + repositoryId); if (repositoryId == null) { List<RepositoryVO> repos = RepositoryController.getController() .getAuthorizedRepositoryVOList(principal, false); if (repos.size() > 0) repositoryId = "" + repos.get(0).getId(); } if (repositoryId != null) { SiteNodeVO siteNodeVO = SiteNodeController.getController() .getRootSiteNodeVO(new Integer(repositoryId), templateController.getDatabase()); personalStartUrl = "ViewPage!renderDecoratedPage.action?siteNodeId=" + siteNodeVO.getId(); } String returnAddress = "" + componentEditorUrl + "ViewInlineOperationMessages.action"; String notifyUrl = componentEditorUrl + "CreateEmail!inputChooseRecipientsV3.action?enableUsers=true&originalUrl=" + URLEncoder.encode(templateController.getOriginalFullURL().replaceFirst("cmsUserName=.*?", ""), "utf-8") + "&returnAddress=" + URLEncoder.encode(returnAddress, "utf-8") + "&extraTextProperty=tool.managementtool.createEmailNotificationPageExtraText.text"; String pageSubscriptionUrl = componentEditorUrl + "Subscriptions!input.action?interceptionPointCategory=SiteNodeVersion&entityName=" + SiteNode.class.getName() + "&entityId=" + templateController.getSiteNodeId() + "&returnAddress=" + URLEncoder.encode(returnAddress, "utf-8"); extraBody = extraBody.replaceAll("\\$siteNodeId", "" + templateController.getSiteNodeId()); extraBody = extraBody.replaceAll("\\$languageId", "" + templateController.getLanguageId()); extraBody = extraBody.replaceAll("\\$repositoryId", "" + templateController.getSiteNode().getRepositoryId()); extraBody = extraBody.replaceAll("\\$originalFullURL", URLEncoder.encode(templateController.getOriginalFullURL(), "UTF-8")); extraBody = extraBody.replaceAll("\\$notifyUrl", notifyUrl); extraBody = extraBody.replaceAll("\\$pageSubscriptionUrl", pageSubscriptionUrl); extraBody = extraBody.replaceAll("\\$editHTML", editHTML); extraBody = extraBody.replaceAll("\\$submitToPublishHTML", submitToPublishHTML); extraBody = extraBody.replaceAll("\\$confirmDeleteLabel", confirmDeleteLabel); extraBody = extraBody.replaceAll("\\$\\{leaveWarningOnDirtyPageText\\}", leaveWarningOnDirtyPageText); extraBody = extraBody.replaceAll("\\$notifyHTML", notifyLabel); extraBody = extraBody.replaceAll("\\$subscribeToContentHTML", subscribeToContentLabel); extraBody = extraBody.replaceAll("\\$subscribeToPageHTML", subscribeToPageLabel); extraBody = extraBody.replaceAll("\\$addComponentHTML", addComponentHTML); extraBody = extraBody.replaceAll("\\$deleteComponentHTML", deleteComponentHTML); extraBody = extraBody.replaceAll("\\$changeComponentHTML", changeComponentHTML); extraBody = extraBody.replaceAll("\\$accessRightsHTML", accessRightsHTML); extraBody = extraBody.replaceAll("\\$pageComponents", pageComponentsHTML); extraBody = extraBody.replaceAll("\\$componentEditorInNewWindowHTML", componentEditorInNewWindowHTML); extraBody = extraBody.replaceAll("\\$savePageTemplateHTML", savePageTemplateHTML); extraBody = extraBody.replaceAll("\\$savePagePartTemplateHTML", savePagePartTemplateHTML); extraBody = extraBody.replaceAll("\\$saveTemplateUrl", saveTemplateUrl); extraBody = extraBody.replaceAll("\\$savePartTemplateUrl", savePartTemplateUrl); extraBody = extraBody.replaceAll("\\$viewSource", viewSourceHTML); extraBody = extraBody.replaceAll("\\$propertiesHTML", propertiesHTML); extraBody = extraBody.replaceAll("\\$favouriteComponentsHeader", favouriteComponentsHeader); extraBody = extraBody.replaceAll("\\$noActionAvailableHTML", noActionAvailableHTML); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.pendingPageApproval.title\\}", getLocalizedString(locale, "deliver.editOnSight.pendingPageApproval.title")); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.pendingContentApproval.title\\}", getLocalizedString(locale, "deliver.editOnSight.pendingContentApproval.title")); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarInlineEditing.title\\}", getLocalizedString(locale, "deliver.editOnSight.toolbarInlineEditing.title")); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarState.title\\}", getLocalizedString(locale, "deliver.editOnSight.toolbarState.title")); extraBody = extraBody.replaceAll("\\$\\{tool.contenttool.approve.label\\}", getLocalizedString(locale, "tool.contenttool.approve.label")); extraBody = extraBody.replaceAll("\\$\\{tool.contenttool.deny.label\\}", getLocalizedString(locale, "tool.contenttool.deny.label")); extraBody = extraBody.replaceAll("\\$\\{tool.common.saveButton.label\\}", getLocalizedString(locale, "tool.common.saveButton.label")); extraBody = extraBody.replaceAll("\\$\\{tool.common.cancelButton.label\\}", getLocalizedString(locale, "tool.common.cancelButton.label")); extraBody = extraBody.replaceAll("\\$\\{tool.common.publishing.publishButtonLabel\\}", getLocalizedString(locale, "tool.common.publishing.publishButtonLabel")); extraBody = extraBody.replaceAll("\\$\\{tool.structuretool.toolbarV3.previewPageLabel\\}", getLocalizedString(locale, "tool.structuretool.toolbarV3.previewPageLabel")); extraBody = extraBody.replaceAll("\\$\\{tool.structuretool.toolbarV3.previewMediumScreenPageLabel\\}", getLocalizedString(locale, "tool.structuretool.toolbarV3.previewMediumScreenPageLabel")); extraBody = extraBody.replaceAll("\\$\\{tool.structuretool.toolbarV3.previewSmallScreenPageLabel\\}", getLocalizedString(locale, "tool.structuretool.toolbarV3.previewSmallScreenPageLabel")); extraBody = extraBody.replaceAll("\\$\\{tool.structuretool.toolbarV3.disableEditmodeNotAllowed\\}", getLocalizedString(locale, "tool.structuretool.toolbarV3.disableEditmodeNotAllowed")); extraBody = extraBody.replaceAll("\\$\\{homeURL\\}", personalStartUrl); extraBody = extraBody.replaceAll("\\$\\{currentLanguageCode\\}", "" + templateController .getLanguageCode(templateController.getLanguageId()).getLanguage().toUpperCase()); extraBody = extraBody.replaceAll("\\$\\{currentLanguageName\\}", templateController .getLanguageCode(templateController.getLanguageId()).getDisplayName().toUpperCase()); StringBuffer languagesSB = new StringBuffer(); List<LanguageVO> languages = templateController.getAvailableLanguages(); for (LanguageVO language : languages) { if (language.getId() != templateController.getLanguageId()) languagesSB.append("<li style=\"margin-bottom: 6px;\"><a style=\"color: black;\" href=\"" + templateController.getCurrentPageUrl().replaceAll( "languageId=" + templateController.getLanguageId(), "languageId=" + language.getId()) + "\">" + language.getLanguageCode().toUpperCase() + "</a></li>"); } extraBody = extraBody.replaceAll("\\$\\{languageList\\}", languagesSB.toString()); extraBody = extraBody.replaceAll("\\$addComponentJavascript", "window.hasAccessToAddComponent" + component.getId() + "_" + component.getCleanedSlotName() + " = " + hasAccessToAddComponent + ";"); extraBody = extraBody.replaceAll("\\$deleteComponentJavascript", "window.hasAccessToDeleteComponent" + component.getId() + "_" + component.getCleanedSlotName() + " = " + hasAccessToDeleteComponent + ";"); extraBody = extraBody.replaceAll("\\$changeComponentJavascript", "window.hasAccessToChangeComponent" + component.getId() + "_" + component.getCleanedSlotName() + " = " + hasAccessToChangeComponent + ";"); extraBody = extraBody.replaceAll("\\$changeAccessJavascript", "window.hasAccessToAccessRights" + " = " + hasAccessToAccessRights + ";"); extraBody = extraBody.replaceAll("\\$submitToPublishJavascript", "window.hasAccessToSubmitToPublish = " + hasSubmitToPublishAccess + ";"); extraBody = extraBody.replaceAll("\\$pageStructureJavascript", "window.hasPageStructureAccess = " + hasPageStructureAccess + ";"); extraBody = extraBody.replaceAll("\\$openInNewWindowJavascript", "window.hasOpenInNewWindowAccess = " + hasOpenInNewWindowAccess + ";"); extraBody = extraBody.replaceAll("\\$allowViewSourceJavascript", "window.hasAccessToViewSource = " + hasViewSourceAccess + ";"); extraBody = extraBody.replaceAll("\\$allowSavePageTemplateJavascript", "window.hasAccessToSavePageTemplate = " + hasSaveTemplateAccess + ";"); extraBody = extraBody.replaceAll("\\$submitToNotifyJavascript", "window.hasAccessToNotifyUserOfPage = " + showNotifyUserOfPage + ";"); extraBody = extraBody.replaceAll("\\$contentNotificationsJavascript", "window.hasAccessToContentNotifications = " + showContentNotifications + ";"); extraBody = extraBody.replaceAll("\\$pageNotificationsJavascript", "window.hasAccessToPageNotifications = " + showPageNotifications + ";"); extraBody = extraBody.replaceAll("\\$W3CValidatorJavascript", "window.hasAccessToW3CValidator = " + showW3CValidator + ";"); extraBody = extraBody.replaceAll("\\$ShowLanguageMenuJavascript", "window.hasAccessToShowLanguageMenu = " + showLanguageMenu + ";"); extraBody = extraBody.replaceAll("\\$ShowApproveButtonsJavascript", "window.useApprovalFlow = " + useApprovalFlow + ";"); extraBody = extraBody.replaceAll("\\$autoShowApprovalButtonsJavascript", "window.autoShowApprovalButtons = " + autoShowApprovalButtons + ";"); extraBody = extraBody.replaceAll("\\$useDoubleClickOnTextToInlineEdit", "" + CmsPropertyHandler.getUseDoubleClickOnTextToInlineEdit()); extraBody = extraBody.replaceAll("\\$showHomeButtonJavascript", "window.showHomeButton = " + showHomeButton + ";"); extraBody = extraBody.replaceAll("\\$showMySettingsButtonJavascript", "window.showMySettingsButton = " + showMySettingsButton + ";"); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarHomeButton.title\\}", getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())), "deliver.editOnSight.toolbarHomeButton.title")); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarValidateW3CButton.title\\}", getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())), "deliver.editOnSight.toolbarValidateW3CButton.title")); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarNewWindowButton.title\\}", getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())), "deliver.editOnSight.toolbarNewWindowButton.title")); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarMySettingsButton.title\\}", getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())), "deliver.editOnSight.toolbarMySettingsButton.title")); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarValidateW3CErrorsQuestion.label\\}", getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())), "deliver.editOnSight.toolbarValidateW3CErrorsQuestion.label")); extraBody = extraBody.replaceAll("\\$\\{deliver.editOnSight.toolbarValidateW3CNoErrors.label\\}", getLocalizedString(new Locale(CmsPropertyHandler.getPreferredLanguageCode(principal.getName())), "deliver.editOnSight.toolbarValidateW3CNoErrors.label")); StringBuffer userDefinedButtonsSB = new StringBuffer(); List<ToolbarButton> buttons = AdminToolbarService.getService().getFooterToolbarButtons( "tool.deliver.editOnSight.toolbarRight", principal, locale, templateController.getHttpServletRequest(), true); for (ToolbarButton button : buttons) { try { if (button.getCustomMarkup() == null) { userDefinedButtonsSB .append("<div id=\"" + button.getId() + "\" class=\"right editOnSightToolbarButton " + button.getCssClass() + "\" title=\"" + button.getTitle() + "\" onclick=\"" + button.getActionURL() + "\"></div>"); } else { if (button.getCustomMarkupPlacement().equals("before")) userDefinedButtonsSB.append("" + button.getCustomMarkup()); userDefinedButtonsSB .append("<div id=\"" + button.getId() + "\" class=\"right editOnSightToolbarButton " + button.getCssClass() + "\" title=\"" + button.getTitle() + "\" onclick=\"" + button.getActionURL() + "\">" + (button.getCustomMarkupPlacement().equals("inside") ? button.getCustomMarkup() : "") + "</div>"); if (button.getCustomMarkupPlacement().equals("after")) userDefinedButtonsSB.append("" + button.getCustomMarkup()); } } catch (Exception e) { logger.warn("Problem adding custome EOS button: " + e.getMessage(), e); } } extraBody = extraBody.replaceAll("\\$\\{userDefinedButtons\\}", userDefinedButtonsSB.toString()); //List tasks = getTasks(); //component.setTasks(tasks); //String tasks = templateController.getContentAttribute(component.getContentId(), "ComponentTasks", true); /* Map context = new HashMap(); context.put("templateLogic", templateController); StringWriter cacheString = new StringWriter(); PrintWriter cachedStream = new PrintWriter(cacheString); new VelocityTemplateProcessor().renderTemplate(context, cachedStream, extraBody); extraBody = cacheString.toString(); */ //extraHeader.replaceAll() timer.printElapsedTime("Read files"); StringBuffer modifiedTemplate = new StringBuffer(template); //Adding stuff in the header int indexOfHeadEndTag = modifiedTemplate.indexOf("</head"); if (indexOfHeadEndTag == -1) indexOfHeadEndTag = modifiedTemplate.indexOf("</HEAD"); if (indexOfHeadEndTag > -1) { modifiedTemplate = modifiedTemplate.replace(indexOfHeadEndTag, modifiedTemplate.indexOf(">", indexOfHeadEndTag) + 1, extraHeader); } else { int indexOfHTMLStartTag = modifiedTemplate.indexOf("<html"); if (indexOfHTMLStartTag == -1) { indexOfHTMLStartTag = modifiedTemplate.indexOf("<HTML"); } if (indexOfHTMLStartTag > -1) { modifiedTemplate = modifiedTemplate .insert(modifiedTemplate.indexOf(">", indexOfHTMLStartTag) + 1, "<head>" + extraHeader); } else { logger.info( "The current template is not a valid document. It does not comply with the simplest standards such as having a correct header."); } } timer.printElapsedTime("Header handled"); //Adding stuff in the body int indexOfBodyStartTag = modifiedTemplate.indexOf("<body"); if (indexOfBodyStartTag == -1) indexOfBodyStartTag = modifiedTemplate.indexOf("<BODY"); if (indexOfBodyStartTag > -1) { //String pageComponentStructureDiv = ""; String pageComponentStructureDiv = getPageComponentStructureDiv(templateController, deliveryContext.getSiteNodeId(), deliveryContext.getLanguageId(), component); timer.printElapsedTime("pageComponentStructureDiv"); String componentPaletteDiv = getComponentPaletteDiv(deliveryContext.getSiteNodeId(), deliveryContext.getLanguageId(), templateController); //String componentPaletteDiv = ""; timer.printElapsedTime("componentPaletteDiv"); modifiedTemplate = modifiedTemplate.insert(modifiedTemplate.indexOf(">", indexOfBodyStartTag) + 1, extraBody + pageComponentStructureDiv + componentPaletteDiv); } else { logger.info( "The current template is not a valid document. It does not comply with the simplest standards such as having a correct body."); } timer.printElapsedTime("Body handled"); decoratedTemplate = modifiedTemplate.toString(); } catch (Exception e) { e.printStackTrace(); logger.warn( "An error occurred when deliver tried to decorate your template to enable onSiteEditing. Reason " + e.getMessage(), e); } return decoratedTemplate; }
From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java
public void getConvertedLetter(StringBuffer textLetter, StringBuffer htmlLetter, ArrayList<String[]> phValuePairs) { String expr = "[#]{1}[a-zA-Z]+[:]{1}[a-zA-Z]+[#]{1}"; Pattern p = Pattern.compile(expr); Matcher m = p.matcher(textLetter); int st_i = 0; int end_i = 0; boolean matched = false; while (m.find()) { String table = ""; // String woHash = ""; table = m.group();/*from w w w .j a v a2s . c om*/ // woHash = table.substring(1, table.length() - 1); // String[] sp = woHash.split(":"); for (int i = 0; i < phValuePairs.size(); i++) { if (table.equals("#" + phValuePairs.get(i)[0] + ":" + phValuePairs.get(i)[1] + "#")) { st_i = textLetter.indexOf(table); end_i = st_i + table.length(); if (st_i >= 0) { textLetter.replace(st_i, end_i, phValuePairs.get(i)[2]); //moved in last m = p.matcher(textLetter); //break; } st_i = htmlLetter.indexOf(table); end_i = st_i + table.length(); if (st_i >= 0) { htmlLetter.replace(st_i, end_i, phValuePairs.get(i)[2]); // break; } m = p.matcher(textLetter); matched = true; break; } } if (!matched) { st_i = textLetter.indexOf(table); end_i = st_i + table.length(); if (st_i >= 0) { textLetter.replace(st_i, end_i, "@~" + table.substring(1, table.length() - 1) + "@~"); //moved in last m = p.matcher(textLetter); //break; } st_i = htmlLetter.indexOf(table); end_i = st_i + table.length(); if (st_i >= 0) { htmlLetter.replace(st_i, end_i, "@~" + table.substring(1, table.length() - 1) + "@~"); // break; } m = p.matcher(textLetter); matched = false; } } }
From source file:architecture.common.util.TextUtils.java
private final static void linkEmail(StringBuffer str) { int lastEndIndex = -1; // Store the index position of the end char of // last email address found... main: while (true) { // get index of '@'... int atIndex = str.indexOf("@", lastEndIndex + 1); if (atIndex == -1) { break; } else {//from ww w .j a va 2s . c o m // Get the whole email address... // Get the part before '@' by moving backwards and taking each // character // until we encounter an invalid URL char... String partBeforeAt = ""; int linkStartIndex = atIndex; boolean reachedStart = false; while (!reachedStart) { linkStartIndex--; if (linkStartIndex < 0) { reachedStart = true; } else { char c = str.charAt(linkStartIndex); // if we find these chars in an email, then it's part of // a url, so lets leave it alone // Are there any other chars we should abort email // checking for?? if ((c == '?') || (c == '&') || (c == '=') || (c == '/') || (c == '%')) { lastEndIndex = atIndex + 1; continue main; } if (isValidEmailChar(c)) { partBeforeAt = c + partBeforeAt; } else { reachedStart = true; } } } // Increment linkStartIndex back by 1 to reflect the real // starting index of the // email address... linkStartIndex++; // Get the part after '@' by doing pretty much the same except // moving // forward instead of backwards. String partAfterAt = ""; int linkEndIndex = atIndex; boolean reachedEnd = false; while (!reachedEnd) { linkEndIndex++; if (linkEndIndex == str.length()) { reachedEnd = true; } else { char c = str.charAt(linkEndIndex); if (isValidEmailChar(c)) { partAfterAt += c; } else { reachedEnd = true; } } } // Decrement linkEndIndex back by 1 to reflect the real ending // index of the // email address... linkEndIndex--; // Reassemble the whole email address... String emailStr = partBeforeAt + '@' + partAfterAt; // If the last chars of emailStr is a '.', ':', '-', '/' or '~' // then we exclude those chars. // The '.' at the end could be just a fullstop to a sentence and // we don't want // that to be part of an email address (which would then be // invalid). // Pretty much the same for the other symbols - we don't want // them at the end of any email // address cos' this would stuff the address up. while (true) { char lastChar = emailStr.charAt(emailStr.length() - 1); if ((lastChar == '.') || (lastChar == ':') || (lastChar == '-') || (lastChar == '/') || (lastChar == '~')) { emailStr = emailStr.substring(0, emailStr.length() - 1); linkEndIndex--; } else { break; } } // Verify if email is valid... if (verifyEmail(emailStr)) { // Construct the hyperlink for the email address... String emailLink = "<a href='mailto:" + emailStr + "'>" + emailStr + "</a>"; // Take the part of the str before the email address, the // part after, and add // the emailLink between those two parts, so that in effect // the original email // address is replaced by a hyperlink to it... str.replace(linkStartIndex, linkEndIndex + 1, emailLink); // Set lastEndIndex to reflect the position of the end of // emailLink // within the whole string... lastEndIndex = (linkStartIndex - 1) + emailLink.length(); } else { // lastEndIndex is different from the one above cos' there's // no // <a href...> tags added... lastEndIndex = (linkStartIndex - 1) + emailStr.length(); } } } }
From source file:org.agnitas.beans.impl.MailingImpl.java
@Override public String getPreview(String input_org, int inputType, int customerID, boolean overwriteMailtype, ApplicationContext con) throws Exception { DynamicTag aktTag = null;/*from w w w . j a v a 2 s . c o m*/ DynamicTag tmpTag = null; DynamicTag contentTag = null; String contentString = null; DynamicTagContent aContent = null; DynamicTagContent aTmpContent = null; Target aTarget = null; int aTargetID = 0; Hashtable<String, DynamicTag> allTags = new Hashtable<String, DynamicTag>(); Hashtable<String, Target> allTargets = new Hashtable<String, Target>(); Interpreter aBsh = null; String input = input_org; TargetDao tDao = (TargetDao) con.getBean("TargetDao"); StringBuffer output = new StringBuffer(this.personalizeText(input, customerID, con)); searchPos = 0; aBsh = AgnUtils.getBshInterpreter(companyID, customerID, con); if (overwriteMailtype) { aBsh.set("mailtype", new Integer(inputType)); } if (aBsh == null) { throw new Exception("error.template.dyntags"); } Iterator<DynamicTag> it = this.dynTags.values().iterator(); while (it.hasNext()) { aktTag = it.next(); tmpTag = (DynamicTag) con.getBean("DynamicTag"); tmpTag.setDynName(aktTag.getDynName()); Map<String, DynamicTagContent> contentMap = aktTag.getDynContent(); if (contentMap != null) { Iterator<DynamicTagContent> it2 = contentMap.values().iterator(); while (it2.hasNext()) { aContent = it2.next(); aTmpContent = (DynamicTagContent) con.getBean("DynamicTagContent"); aTmpContent.setDynName(aContent.getDynName()); aTmpContent.setDynOrder(aContent.getDynOrder()); aTmpContent.setDynContent(this.personalizeText(aContent.getDynContent(), customerID, con)); aTmpContent.setTargetID(aContent.getTargetID()); aTmpContent.setId(aContent.getId()); tmpTag.addContent(aTmpContent); } } allTags.put(aktTag.getDynName(), tmpTag); } aContent = null; this.searchPos = 0; while ((aktTag = findNextDynTag(output.toString(), con)) != null) { searchPos = aktTag.getStartTagStart(); // always search from // beginning of last found // tag if (allTags.containsKey(aktTag.getDynName())) { contentTag = (DynamicTag) allTags.get(aktTag.getDynName()); Map<String, DynamicTagContent> contentMap = contentTag.getDynContent(); contentString = null; // reset always if (contentMap != null) { Iterator<DynamicTagContent> it3 = contentMap.values().iterator(); while (it3.hasNext()) { aContent = it3.next(); aTargetID = aContent.getTargetID(); if (allTargets.containsKey(Integer.toString(aTargetID))) { aTarget = (Target) allTargets.get(Integer.toString(aTargetID)); } else { aTarget = tDao.getTarget(aTargetID, this.companyID); if (aTarget == null) { aTarget = (Target) con.getBean("Target"); aTarget.setCompanyID(this.companyID); aTarget.setId(aTargetID); } allTargets.put(Integer.toString(aTarget.getId()), aTarget); } aTargetID = aTarget.getId(); if (aTargetID == 0) { // Target fits contentString = aContent.getDynContent(); break; // stop processing list of content } else { if (aTarget.isCustomerInGroup(aBsh)) { contentString = aContent.getDynContent(); break; // stop processing list of content } } } } // insert content if found content if (contentString != null) { if (aktTag.isComplex()) { output.delete(aktTag.getEndTagStart(), aktTag.getEndTagEnd()); output.replace(aktTag.getValueTagStart(), aktTag.getValueTagEnd(), contentString); output.delete(aktTag.getStartTagStart(), aktTag.getStartTagEnd()); } else { output.replace(aktTag.getStartTagStart(), aktTag.getStartTagEnd(), contentString); } } else { if (aktTag.isComplex()) { output.delete(aktTag.getStartTagStart(), aktTag.getEndTagEnd()); } else { output.delete(aktTag.getStartTagStart(), aktTag.getStartTagEnd()); } } } else { // dyntag not found in list, throw exception! throw new Exception("error.template.dyntags"); } } if (inputType == MailingImpl.INPUT_TYPE_TEXT) { if (this.getEmailParam().getLinefeed() > 0) { output = new StringBuffer(SafeString.cutLineLength(SafeString.removeHTMLTags(output.toString()), this.getEmailParam().getLinefeed())); } else { output = new StringBuffer(SafeString.removeHTMLTags(output.toString())); } } output = new StringBuffer(this.insertTrackableLinks(output.toString(), customerID, con)); return output.toString(); }
From source file:org.eclipse.wb.internal.core.utils.ast.AstEditor.java
/** * Examples:/*www. j a va 2s.c om*/ * * <pre> * SWT.NONE = org.eclipse.swt.SWT.NONE * new JButton() = new javax.swing.JButton() * </pre> * * @param theNode * the {@link ASTNode} to get the source. * @param transformer * the {@link Function} that can participate in node to source transformation by * providing alternative source for some nodes. Can be <code>null</code>, in not * additional transformation required. If transformer returns not <code>null</code>, we * use it instead of its original source; if <code>null</code> - we continue with * original source. * * @return the source of {@link ASTNode} in "external form", i.e. with fully qualified types. */ @SuppressWarnings("restriction") public String getExternalSource(final ASTNode theNode, final Function<ASTNode, String> transformer) { final StringBuffer buffer = new StringBuffer(getSource(theNode)); // remember positions for all nodes final Map<ASTNode, Integer> nodePositions = Maps.newHashMap(); theNode.accept(new ASTVisitor() { @Override public void postVisit(ASTNode _node) { nodePositions.put(_node, _node.getStartPosition()); } }); // replace "name" with "qualified name" theNode.accept(new org.eclipse.jdt.internal.corext.dom.GenericVisitor() { @Override protected boolean visitNode(ASTNode node) { if (transformer != null) { String source = transformer.apply(node); if (source != null) { replace(node, source); return false; } } return true; } @Override public void endVisit(SimpleName name) { if (!AstNodeUtils.isVariable(name)) { StructuralPropertyDescriptor location = name.getLocationInParent(); if (location == SimpleType.NAME_PROPERTY || location == QualifiedName.QUALIFIER_PROPERTY || location == ClassInstanceCreation.NAME_PROPERTY || location == MethodInvocation.EXPRESSION_PROPERTY) { String fullyQualifiedName = AstNodeUtils.getFullyQualifiedName(name, false); replace(name, fullyQualifiedName); } } } /** * Replace given ASTNode with different source, with updating positions for other nodes. */ private void replace(ASTNode node, String newSource) { int nodePosition = nodePositions.get(node); // update source { int sourceStart = nodePosition - theNode.getStartPosition(); int sourceEnd = sourceStart + node.getLength(); buffer.replace(sourceStart, sourceEnd, newSource); } // update positions for nodes int lengthDelta = newSource.length() - node.getLength(); for (Map.Entry<ASTNode, Integer> entry : nodePositions.entrySet()) { Integer position = entry.getValue(); if (position > nodePosition) { entry.setValue(position + lengthDelta); } } } }); // OK, we have updated source return buffer.toString(); }
From source file:org.etudes.component.app.melete.ModuleDB.java
public void deleteModules(List delModules, List allModules, String courseId, String userId) throws Exception { long starttime = System.currentTimeMillis(); Transaction tx = null;/* ww w .j a va 2 s. c o m*/ //If not all modules of the course need to be deleted if (delModules.size() != allModules.size()) { logger.debug("delete some Modules begin"); ArrayList<DelModuleInfo> DelModuleInfoList = new ArrayList<DelModuleInfo>(0); List delResourcesList; try { // Get resources for modules that need to be deleted delResourcesList = getActiveResourcesFromList(delModules); allModules.removeAll(delModules); if ((delResourcesList != null) && (delResourcesList.size() > 0)) { List<String> allActiveResources = getActiveResourcesFromList(allModules); if (allActiveResources != null && delResourcesList != null) { logger.debug("active list and all" + delResourcesList.size() + " ; " + allActiveResources.size()); delResourcesList.removeAll(allActiveResources); } } // get all module-ids and section_ids // update seq_no for each deleted_module StringBuffer allModuleIds = new StringBuffer("("); StringBuffer allSectionIds = new StringBuffer("("); ArrayList<StringBuffer> allSectionIdsArray = new ArrayList<StringBuffer>(); String delModuleIds = null; //String delSectionIds = null; int count = 1; for (Iterator dmIter = delModules.iterator(); dmIter.hasNext();) { Module dm = (Module) dmIter.next(); allModuleIds.append(dm.getModuleId().toString() + ","); Map delSections = dm.getSections(); if (delSections != null && !delSections.isEmpty()) { for (Iterator i = delSections.keySet().iterator(); i.hasNext();) { if (count % MAX_IN_CLAUSES == 0) { allSectionIds.append(i.next() + ")"); allSectionIdsArray.add(allSectionIds); allSectionIds = new StringBuffer("("); } else { allSectionIds.append(i.next() + ","); } count++; } } Map delDeletedSections = dm.getDeletedSections(); if (delDeletedSections != null && !delDeletedSections.isEmpty()) { for (Iterator i1 = delDeletedSections.keySet().iterator(); i1.hasNext();) { if (count % MAX_IN_CLAUSES == 0) { allSectionIds.append(i1.next() + ")"); allSectionIdsArray.add(allSectionIds); allSectionIds = new StringBuffer("("); } else { allSectionIds.append(i1.next() + ","); } count++; } } // record seq_no and id DelModuleInfoList .add(new DelModuleInfo(dm.getModuleId().toString(), dm.getCoursemodule().getSeqNo())); } if (allModuleIds.lastIndexOf(",") != -1) delModuleIds = allModuleIds.substring(0, allModuleIds.lastIndexOf(",")) + " )"; //if (allSectionIds.lastIndexOf(",") != -1) delSectionIds = allSectionIds.substring(0, allSectionIds.lastIndexOf(",")) + " )"; if (allSectionIds.lastIndexOf(",") != -1) { if (count % MAX_IN_CLAUSES != 0) { allSectionIds.replace(allSectionIds.lastIndexOf(","), allSectionIds.lastIndexOf(",") + 1, ")"); allSectionIdsArray.add(allSectionIds); } } Session session = hibernateUtil.currentSession(); tx = session.beginTransaction(); String delMeleteResourceStr; int deletedEntities; // delete modules and sections String updSectionResourceStr = "update SectionResource sr set sr.resource = null where sr.section in "; String delSectionResourceStr = "delete SectionResource sr where sr.section in "; String delBookmarksStr = "delete Bookmark bm where bm.sectionId in "; String delSectionStr = "delete Section s where s.moduleId in " + delModuleIds; String delCourseModuleStr = "delete CourseModule cm where cm.moduleId in " + delModuleIds; String delModuleshDatesStr = "delete ModuleShdates msh where msh.moduleId in " + delModuleIds; String delSpecialAccStr = "delete SpecialAccess sa where sa.moduleId in " + delModuleIds; String delModuleStr = "delete Module m where m.moduleId in " + delModuleIds; if (allSectionIdsArray != null) { for (int i = 0; i < allSectionIdsArray.size(); i++) { allSectionIds = allSectionIdsArray.get(i); deletedEntities = session.createQuery(updSectionResourceStr + allSectionIds.toString()) .executeUpdate(); deletedEntities = session.createQuery(delSectionResourceStr + allSectionIds.toString()) .executeUpdate(); logger.debug("section resource deleted" + deletedEntities); deletedEntities = session.createQuery(delBookmarksStr + allSectionIds.toString()) .executeUpdate(); logger.debug("Boomkarks deleted " + deletedEntities); } } if (delModuleIds != null) { deletedEntities = session.createQuery(delSectionStr).executeUpdate(); logger.debug("section deleted" + deletedEntities); deletedEntities = session.createQuery(delCourseModuleStr).executeUpdate(); logger.debug("course module deleted" + deletedEntities); deletedEntities = session.createQuery(delModuleshDatesStr).executeUpdate(); deletedEntities = session.createQuery(delSpecialAccStr).executeUpdate(); logger.debug("special access deleted" + deletedEntities); deletedEntities = session.createQuery(delModuleStr).executeUpdate(); logger.debug("module deleted" + deletedEntities); } // delete module collection logger.debug("updating seq_number now"); List<CourseModule> courseModules = new ArrayList<CourseModule>(0); for (ListIterator i = allModules.listIterator(); i.hasNext();) { Module mdbean = (Module) i.next(); courseModules.add((CourseModule) mdbean.getCoursemodule()); } assignSeqs(session, courseModules); // delete resources if ((delResourcesList != null) && (delResourcesList.size() > 0)) { StringBuffer delResourceIds = new StringBuffer("("); // delete melete resource and from content resource for (Iterator delIter = delResourcesList.listIterator(); delIter.hasNext();) { String delResourceId = (String) delIter.next(); if ((delResourceId == null) || (delResourceId.trim().length() == 0)) { logger.warn("NULL or empty resource id found in delete process "); continue; } delResourceIds.append("'" + delResourceId + "',"); } //Ensuring that there are no empty resource ids if ((delResourceIds.length() > 4) && (delResourceIds.lastIndexOf(",") != -1)) { delResourceIds = new StringBuffer( delResourceIds.substring(0, delResourceIds.lastIndexOf(",")) + " )"); delMeleteResourceStr = "delete MeleteResource mr where mr.resourceId in " + delResourceIds; deletedEntities = session.createQuery(delMeleteResourceStr).executeUpdate(); logger.debug("melete resource deleted" + deletedEntities); } } tx.commit(); } catch (HibernateException he) { if (tx != null) tx.rollback(); logger.error(he.toString()); throw he; } catch (Exception e) { if (tx != null) tx.rollback(); logger.error(e.toString()); e.printStackTrace(); throw e; } finally { try { hibernateUtil.closeSession(); } catch (HibernateException he) { logger.error(he.toString()); throw he; } } logger.debug("Successfully cleared Melete tables"); logger.debug("Removing module collections now"); Collections.reverse(DelModuleInfoList); for (DelModuleInfo dmi : DelModuleInfoList) { meleteCHService.removeCollection(courseId, "module_" + dmi.getId()); } logger.debug("Removing upload collection resources"); for (Iterator delIter = delResourcesList.listIterator(); delIter.hasNext();) { String delResourceId = (String) delIter.next(); if ((delResourceId == null) || (delResourceId.trim().length() == 0)) { logger.warn("NULL or empty resource id found in delete process "); continue; } //TypeEditor sections will have been removed already if (delResourceId.startsWith("/private/meleteDocs/" + courseId + "/uploads/")) { meleteCHService.removeResource(delResourceId); } } long endtime = System.currentTimeMillis(); logger.debug("delete some modules ends " + (endtime - starttime)); } else { logger.debug("delete all Modules begin"); try { Session session = hibernateUtil.currentSession(); tx = session.beginTransaction(); StringBuffer allModuleIds = new StringBuffer("("); String delModuleIds = null; for (Iterator dmIter = delModules.iterator(); dmIter.hasNext();) { Module dm = (Module) dmIter.next(); allModuleIds.append(dm.getModuleId().toString() + ","); } if (allModuleIds.lastIndexOf(",") != -1) delModuleIds = allModuleIds.substring(0, allModuleIds.lastIndexOf(",")) + " )"; deleteEverything(courseId, session, delModuleIds); //remove entire collection try { meleteCHService.removeCollection(courseId, null); } catch (Exception removeColl) { //do nothing } tx.commit(); } catch (HibernateException he) { if (tx != null) tx.rollback(); logger.error(he.toString()); throw he; } catch (Exception e) { if (tx != null) tx.rollback(); logger.error(e.toString()); e.printStackTrace(); throw e; } finally { try { hibernateUtil.closeSession(); } catch (HibernateException he) { logger.error(he.toString()); throw he; } } long endtime = System.currentTimeMillis(); logger.debug("delete all modules ends " + (endtime - starttime)); } }
From source file:org.pentaho.di.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr) { File masterZipfile = null;/*from www .j a va 2 s. c om*/ // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { logError(BaseMessages.getString(PKG, "JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) { props.put("mail." + protocol + ".port", environmentSubstitute(port)); } if (log.isDebug()) { props.put("mail.debug", "true"); } if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* * authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new * PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(log.isDebug()); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. msg.setHeader("Sensitivity", sensitivity); // Possible values are normal, personal, private, company-confidential } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) { sender_address = sender_name + '<' + sender_address + '>'; } msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(BaseMessages.getString(PKG, "JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) { address[i] = new InternetAddress(reply_Address_List[i]); } msg.setReplyTo(address); } // Split the mail-address: space separated String[] destinations = environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) { address[i] = new InternetAddress(destinations[i]); } msg.setRecipients(Message.RecipientType.TO, address); String realCC = environmentSubstitute(getDestinationCc()); if (!Const.isEmpty(realCC)) { // Split the mail-address Cc: space separated String[] destinationsCc = realCC.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) { addressCc[i] = new InternetAddress(destinationsCc[i]); } msg.setRecipients(Message.RecipientType.CC, addressCc); } String realBCc = environmentSubstitute(getDestinationBCc()); if (!Const.isEmpty(realBCc)) { // Split the mail-address BCc: space separated String[] destinationsBCc = realBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) { addressBCc[i] = new InternetAddress(destinationsBCc[i]); } msg.setRecipients(Message.RecipientType.BCC, addressBCc); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); String endRow = isUseHTML() ? "<br>" : Const.CR; String realComment = environmentSubstitute(comment); if (!Const.isEmpty(realComment)) { messageText.append(realComment).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Job")).append(endRow); messageText.append("-----").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getRepositoryDirectory()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntry") + " : ") .append(getName()).append(endRow); messageText.append(Const.CR); } if (includeDate) { messageText.append(endRow).append(BaseMessages.getString(PKG, "JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(endRow).append(endRow); } if (!onlySendComment && result != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PreviousResult") + ":") .append(endRow); messageText.append("-----------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRejected") + " : ") .append(result.getNrLinesRejected()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(endRow); messageText.append(endRow); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.ContactInfo") + " :") .append(endRow); messageText.append("---------------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(endRow); messageText.append(endRow); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PathToJobentry") + ":") .append(endRow); messageText.append("------------------------").append(endRow); addBacktracking(jobTracker, messageText); if (isUseHTML()) { messageText.replace(0, messageText.length(), messageText.toString().replace(Const.CR, endRow)); } } } MimeMultipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // Attached files counter int nrattachedFiles = 0; // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else { part1.setText(messageText.toString()); } parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) { found = true; } } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // insist on base64 to preserve line endings files.addHeader("Content-Transfer-Encoding", "base64"); // add the part with the file in the BodyPart(); parts.addBodyPart(files); nrattachedFiles++; logBasic("Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) { found = true; } } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); try { int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } } finally { inputStream.close(); } zipOutputStream.closeEntry(); nrattachedFiles++; logBasic("Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { logError("Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { logError("Unable to close attachement zip file archive : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } int nrEmbeddedImages = 0; if (embeddedimages != null && embeddedimages.length > 0) { FileObject imageFile = null; for (int i = 0; i < embeddedimages.length; i++) { String realImageFile = environmentSubstitute(embeddedimages[i]); String realcontenID = environmentSubstitute(contentids[i]); if (messageText.indexOf("cid:" + realcontenID) < 0) { if (log.isDebug()) { log.logDebug("Image [" + realImageFile + "] is not used in message body!"); } } else { try { boolean found = false; imageFile = KettleVFS.getFileObject(realImageFile, this); if (imageFile.exists() && imageFile.getType() == FileType.FILE) { found = true; } else { log.logError("We can not find [" + realImageFile + "] or it is not a file"); } if (found) { // Create part for the image MimeBodyPart messageBodyPart = new MimeBodyPart(); // Load the image URLDataSource fds = new URLDataSource(imageFile.getURL()); messageBodyPart.setDataHandler(new DataHandler(fds)); // Setting the header messageBodyPart.setHeader("Content-ID", "<" + realcontenID + ">"); // Add part to multi-part parts.addBodyPart(messageBodyPart); nrEmbeddedImages++; log.logBasic("Image '" + fds.getName() + "' was embedded in message."); } } catch (Exception e) { log.logError( "Error embedding image [" + realImageFile + "] in message : " + e.toString()); log.logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (imageFile != null) { try { imageFile.close(); } catch (Exception e) { /* Ignore */ } } } } } } if (nrEmbeddedImages > 0 && nrattachedFiles == 0) { // If we need to embedd images... // We need to create a "multipart/related" message. // otherwise image will appear as attached file parts.setSubType("related"); } // put all parts together msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); String authPass = getPassword(authenticationPassword); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) { transport.close(); } } } catch (IOException e) { logError("Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { logError("Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { logError(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { logError(" " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { logError(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { logError(" " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { // System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { logError(" " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java
/** * Build the concatenated strings for the Class Scheme Items display. * * @param rec_//w w w. ja v a 2 s . co m * The data returned from Oracle. * @return An array of the full concatenated names for sorting later. */ private schemeTree[] buildSchemeItemList(Results3 rec_) { // Get the maximum number of levels and the maximum length of a single // name. int maxLvl = 0; int maxLen = 0; for (int ndx = 1; ndx < rec_._data.length; ++ndx) { if (maxLvl < rec_._data[ndx]._id3) maxLvl = rec_._data[ndx]._id3; if (rec_._data[ndx]._label1 != null && maxLen < rec_._data[ndx]._label1.length()) maxLen = rec_._data[ndx]._label1.length(); if (rec_._data[ndx]._label2 != null && maxLen < rec_._data[ndx]._label2.length()) maxLen = rec_._data[ndx]._label2.length(); } ++maxLvl; // Build and array of prefixes for the levels. String prefix[] = new String[maxLvl]; prefix[0] = ""; if (maxLvl > 1) { prefix[1] = ""; for (int ndx = 2; ndx < prefix.length; ++ndx) { prefix[ndx] = prefix[ndx - 1] + " "; } } // In addition to creating the display labels we must also // create an array used to sort everything alphabetically. // The easiest is to create a fully concatenated label of a // individuals hierarchy. _schemeItemList = new String[rec_._data.length]; maxLvl *= maxLen; StringBuffer fullBuff = new StringBuffer(maxLvl); fullBuff.setLength(maxLvl); schemeTree tree[] = new schemeTree[_schemeItemList.length]; // Loop through the name list. _schemeItemList[0] = rec_._data[0]._label1; tree[0] = new schemeTree("", 0); for (int ndx = 1; ndx < _schemeItemList.length; ++ndx) { // Create the concatenated sort string. int buffOff = (rec_._data[ndx]._id3 < 2) ? 0 : (rec_._data[ndx]._id3 * maxLen); fullBuff.replace(buffOff, maxLvl, rec_._data[ndx]._label1); fullBuff.setLength(maxLvl); // Create the display label. if (rec_._data[ndx]._id3 == 1) { if (rec_._data[ndx]._label2 == null) { _schemeItemList[ndx] = rec_._data[ndx]._label1; } else { _schemeItemList[ndx] = rec_._data[ndx]._label1 + " (" + rec_._data[ndx]._label2 + ")"; fullBuff.replace(buffOff + maxLen, maxLvl, rec_._data[ndx]._label2); fullBuff.setLength(maxLvl); } } else { _schemeItemList[ndx] = prefix[rec_._data[ndx]._id3] + rec_._data[ndx]._label1; } tree[ndx] = new schemeTree(fullBuff.toString(), ndx); } return tree; }
From source file:com.topsec.tsm.sim.report.web.ReportController.java
/** * /*from ww w. ja v a 2 s. c o m*/ */ @RequestMapping("moreReport") public String moreReport(SID sid, HttpServletRequest request, HttpServletResponse response) { boolean fromRest = false; if (request.getParameter("fromRest") != null) { fromRest = Boolean.parseBoolean(request.getParameter("fromRest")); } JSONObject jsonObj = new JSONObject(); ReportBean bean = new ReportBean(); String onlyByDvctype = request.getParameter("onlyByDvctype"); bean = ReportUiUtil.tidyFormBean(bean, request); String[] talCategory = bean.getTalCategory(); RptMasterTbService rptMasterTbImp = (RptMasterTbService) SpringContextServlet.springCtx .getBean(ReportUiConfig.MstBean); List<Map> subList = rptMasterTbImp.queryTmpList(ReportUiConfig.PaginationSql, new Object[] { StringUtil.toInt(bean.getSubrptid(), 0) }); JSONObject obj = null; StringBuffer url = null; String surl = ""; boolean flag = false; try { SID.setCurrentUser(sid); if (subList.size() > 0) { Map subMap = (Map) subList.get(0); String subTitle = subMap.get("subName").toString(); String mstType = request.getParameter("msttype"); subTitle = ReportUiUtil.viewRptName(subTitle, mstType); request.setAttribute("subName", subTitle); if (fromRest) { jsonObj.put("subName", subTitle); } String deviceType = bean.getDvctype(); // ?lable String paginationViewFiled = null; String paginationHtmFiled = null; // sqlmap if (!GlobalUtil.isNullOrEmpty(subMap)) { if (!GlobalUtil.isNullOrEmpty(subMap.get("paginationViewFiled"))) { paginationViewFiled = subMap.get("paginationViewFiled").toString(); } if (!GlobalUtil.isNullOrEmpty(subMap.get("paginationHtmFiled"))) { paginationHtmFiled = subMap.get("paginationHtmFiled").toString(); } } List sqlParam = ReportUiUtil.getPaginationItem(request, paginationHtmFiled);// ?? sqlParam.add(bean.getTalStartTime());// 3? sqlParam.add(bean.getTalEndTime());// ?4? if (!bean.getDvcaddress().equals("")) { if (deviceType.equals(LogKeyInfo.LOG_SYSTEM_TYPE) || deviceType.equals("Log/Global/Detail")) { } else { if (onlyByDvctype != null && onlyByDvctype.equals("onlyByDvctype")) { } else { sqlParam.add(bean.getDvcaddress()); // dvcaddress 5? } } } if (!GlobalUtil.isNullOrEmpty(talCategory)) { for (String str : talCategory) { if (null != str) { str = str.substring(str.indexOf("***") + 3); if (str.indexOf("%") > -1) { try { str = new String(str.getBytes("iso-8859-1"), "UTF-8"); str = URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } sqlParam.add(str); } } } String pageNum = "1";// ? int pageSize = bean.getPagesize() == null ? 10 : Integer.parseInt(bean.getPagesize()); String pagein = request.getParameter("pagein"); String pageingo = request.getParameter("pageingo"); String pageIndex = request.getParameter("pageIndex"); if (ReportUiUtil.checkNull(pageIndex)) { pageNum = pageIndex; } else if (ReportUiUtil.checkNull(pagein) && ReportUiUtil.checkNull(pageingo)) { pageNum = pagein; } String[] nodeId = request.getParameterValues("nodeId"); Map<String, Object> rsMap = null; String subId = request.getParameter(ReportUiConfig.subrptid); String sTime = bean.getTalStartTime(); String eTime = bean.getTalEndTime(); List<Map> subList1 = rptMasterTbImp.queryTmpList(ReportUiConfig.SubTitleSql, new Object[] { StringUtil.toInt(subId, 0) }); JSONObject json = null; Map<String, Object> rsMap1 = null; if (subList1.size() > 0) { Map subMap1 = (Map) subList1.get(0); List<String> deviceTypes = ReportModel.getDeviceTypeList(dataSourceService, SID.currentUser()); List<String> deviceIps = ReportModel.getDeviceIpList(dataSourceService, SID.currentUser()); request.setAttribute("moredat", "999"); rsMap1 = ReportModel.getSubTitleData(rptMasterTbImp, deviceTypes, deviceIps, subMap1, sTime, eTime, subId, false, request); } rsMap = rsMap1; String viewParamItem = ReportModel.createSearchItem(paginationViewFiled, paginationHtmFiled); request.setAttribute("viewParamItem", viewParamItem); if (fromRest) { jsonObj.put("viewParamItem", viewParamItem); } int sumPage = 0; if (rsMap != null) { sumPage = StringUtil.toInt(StringUtil.toString(rsMap.get("sumPage"), "0")); } // request.setAttribute("pages", ReportModel.getPages(sumPage, pageSize)); request.setAttribute("sumdata", sumPage); // ? request.setAttribute("pageIndex", pageNum); if (fromRest) { jsonObj.put("pages", ReportModel.getPages(sumPage, pageSize)); jsonObj.put("sumdata", sumPage); // ? jsonObj.put("pageIndex", pageNum); } Map<Object, Object> data = ReportModel.reformingResult(subMap, rsMap); int chartType = StringUtil.toInt(subMap.get("chartType").toString(), 0); if (chartType > 0 && chartType < 4) { flag = true; } Map params = new HashMap(); params.put("dvcType", request.getParameter("dvctype")); params.put("talTop", request.getParameter("talTop")); params.put("sTime", bean.getTalStartTime()); params.put("eTime", bean.getTalEndTime()); String chartLink = StringUtil.toString(subMap.get("chartLink"), "0"); int _chartLink = Integer.valueOf(chartLink); url = getUrl(ReportUiConfig.reportUrl, request, params, bean.getTalCategory()); surl = url.toString(); if (_chartLink > 0) { url.append("&superiorId=").append(subList.get(0).get("mstId")).append("&") .append(ReportUiConfig.mstrptid).append("=").append(chartLink); } data.put("url", _chartLink > 0 ? url.toString() : ""); url.replace(0, url.length(), surl).replace(0, ReportUiConfig.reportUrl.length(), ReportUiConfig.moreUrl); url.append("&").append(ReportUiConfig.mstrptid).append("=").append(subList.get(0).get("mstId")) .append("&").append(ReportUiConfig.subrptid).append("=").append(bean.getSubrptid()); data.put("moreUrl", url.toString()); request.setAttribute("moreUrl", url.toString()); if (fromRest) { jsonObj.put("moreUrl", url.toString()); } ChartTable table = CreateChartFactory.getInstance().reformingChartTable(data); obj = moreRptAssembleData(table, StringUtil.toInt(pageNum), pageSize); url.replace(0, url.length(), surl); url.append("&").append(ReportUiConfig.mstrptid).append("=").append(subList.get(0).get("mstId")); } if (subList != null) { request.setAttribute("title", subList.get(0).get("subName")); if (fromRest) { jsonObj.put("title", subList.get(0).get("subName")); } } List<SimDatasource> dslist = new ArrayList<SimDatasource>(); SimDatasource dsource = new SimDatasource(); if ("onlyByDvctype".equals(onlyByDvctype)) { dsource.setDeviceIp(""); dsource.setNodeId(""); } else { dsource.setDeviceIp(request.getParameter("dvcaddress")); dsource.setNodeId(request.getParameter("nodeId")); } dsource.setSecurityObjectType(bean.getDvctype()); dslist.add(0, dsource); request.setAttribute("dslist", dslist); request.setAttribute("flag", flag); request.setAttribute("goUrl", url != null ? url.toString() : ""); request.setAttribute("tableOptions", obj); request.setAttribute("bean", bean); if (fromRest) { jsonObj.put("dslist", dslist); jsonObj.put("flag", flag); jsonObj.put("goUrl", url != null ? url.toString() : ""); jsonObj.put("tableOptions", obj); jsonObj.put("bean", bean); return JSON.toJSONString(jsonObj); } } finally { SID.removeCurrentUser(); } return "/page/report/more_report"; }