List of usage examples for java.lang StringBuffer insert
@Override public StringBuffer insert(int offset, double d)
From source file:org.infoglue.deliver.invokers.DecoratedComponentBasedHTMLPageInvoker.java
/** * This method adds the necessary html to a template to make it right-clickable. *//*w w w. j a v a2 s . com*/ 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.pentaho.di.purge.RepositoryCleanupUtil.java
/** * Ensure provided parameters are present and what we expect * //w ww. j a va 2 s . c om * @param arguments * @throws Exception */ private void validateParameters(Map<String, String> arguments) throws Exception { String aUrl = arguments.get(OPTION_PREFIX + URL); String aUser = arguments.get(OPTION_PREFIX + USER); String aPassword = arguments.get(OPTION_PREFIX + PASS); String aVerCount = arguments.get(OPTION_PREFIX + VER_COUNT); String aDelFrom = arguments.get(OPTION_PREFIX + DEL_DATE); String aPurgeFiles = arguments.get(OPTION_PREFIX + PURGE_FILES); String aPurgeRev = arguments.get(OPTION_PREFIX + PURGE_REV); String aPurgeShared = arguments.get(OPTION_PREFIX + PURGE_SHARED); String aLogLevel = arguments.get(OPTION_PREFIX + LOG_LEVEL); String aLogFile = arguments.get(OPTION_PREFIX + LOG_FILE); StringBuffer errors = new StringBuffer(); boolean isValidOperationSelected = false; fileFilter = "*.kjb|*.ktr"; repositoryPath = "/"; purgeShared = false; if (aLogLevel != null && !(aLogLevel.equals("DEBUG") || aLogLevel.equals("ERROR") || aLogLevel.equals("FATAL") || aLogLevel.equals("INFO") || aLogLevel.equals("OFF") || aLogLevel.equals("TRACE") || aLogLevel.equals("WARN"))) { errors.append(OPTION_PREFIX + LOG_LEVEL + "=" + aLogLevel + " " + Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0003.INVALID_LOGLEVEL") + "\n"); } else { logLevel = aLogLevel; } if (aLogFile != null) { File f = new File(aLogFile); if (f.exists() && f.isDirectory()) { errors.append(Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0004.FOLDER_EXISTS", OPTION_PREFIX + LOG_FILE) + "\n"); } logFile = aLogFile; } if (aUrl == null) { errors.append(Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0005.MISSING_PARAM", OPTION_PREFIX + URL) + "\n"); } else { url = aUrl; } if (aUser == null) { errors.append(Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0005.MISSING_PARAM", OPTION_PREFIX + USER) + "\n"); } else { username = aUser; } if (aPassword == null) { errors.append(Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0005.MISSING_PARAM", OPTION_PREFIX + PASS) + "\n"); } else { password = aPassword; } if (aPurgeFiles != null) { if ((aPurgeFiles.equalsIgnoreCase(Boolean.TRUE.toString()) || aPurgeFiles.equalsIgnoreCase(Boolean.FALSE.toString()))) { purgeFiles = Boolean.parseBoolean(aPurgeFiles); isValidOperationSelected = true; } else { errors.append(Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0006.INVALID_BOOLEAN", OPTION_PREFIX + PURGE_FILES + "=" + aPurgeFiles) + "\n"); } } if (aPurgeRev != null) { if (aPurgeRev.equalsIgnoreCase(Boolean.TRUE.toString()) || aPurgeRev.equalsIgnoreCase(Boolean.FALSE.toString())) { if (isValidOperationSelected) { errors.append(Messages.getInstance() .getString("REPOSITORY_CLEANUP_UTIL.ERROR_0010.INVALID_COMBINATION_OF_PARAMS") + "\n"); } else { purgeRev = Boolean.parseBoolean(aPurgeRev); isValidOperationSelected = true; } } else { errors.append(Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0006.INVALID_BOOLEAN", OPTION_PREFIX + PURGE_REV + "=" + aPurgeRev) + "\n"); } } if (aPurgeShared != null) { if (Boolean.parseBoolean(aPurgeFiles) != Boolean.TRUE) { errors.append(Messages.getInstance() .getString("REPOSITORY_CLEANUP_UTIL.ERROR_0014.INVALID_PURGE_SHARED")); } else { purgeShared = Boolean.parseBoolean(aPurgeShared); } } if (aDelFrom != null) { // only allow one operation if (isValidOperationSelected) { errors.append(Messages.getInstance() .getString("REPOSITORY_CLEANUP_UTIL.ERROR_0010.INVALID_COMBINATION_OF_PARAMS") + "\n"); } else { SimpleDateFormat sdf = new SimpleDateFormat(purgeBeforeDateFormat); sdf.setLenient(false); try { sdf.parse(aDelFrom); delFrom = aDelFrom; isValidOperationSelected = true; } catch (ParseException e) { errors.append(Messages.getInstance().getString( "REPOSITORY_CLEANUP_UTIL.ERROR_0008.IMPROPERLY_FORMATTED_DATE", OPTION_PREFIX + DEL_DATE + "=" + aDelFrom, purgeBeforeDateFormat) + "\n"); } } } if (aVerCount != null) { // only allow one operation if (isValidOperationSelected) { errors.append(Messages.getInstance() .getString("REPOSITORY_CLEANUP_UTIL.ERROR_0010.INVALID_COMBINATION_OF_PARAMS") + "\n"); } else { try { verCount = Integer.parseInt(aVerCount); isValidOperationSelected = true; } catch (NumberFormatException e) { errors.append( Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0009.INVALID_INTEGER", OPTION_PREFIX + VER_COUNT + "=" + aVerCount) + "\n"); } } } if (!isValidOperationSelected) { errors.append(Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0013.MISSING_OPERATION") + "\n"); } if (errors.length() != 0) { errors.insert(0, "\n\n" + Messages.getInstance().getString("REPOSITORY_CLEANUP_UTIL.ERROR_0011.ERRORS_HEADER") + "\n"); throw new Exception(errors.toString()); } }
From source file:org.dbgl.model.conf.Autoexec.java
public String toString(final Autoexec base, final Boolean prepareOnly) { StringBuffer result = new StringBuffer(); insertCustomSection(result, 0);//from ww w. j a va 2s.c o m if (!StringUtils.EMPTY.equals(keyb) && (base == null || !base.keyb.equals(keyb))) { result.append("keyb.com ").append(keyb).append(PlatformUtils.EOLN); } if (!StringUtils.EMPTY.equals(ipxnet) && (base == null || !base.ipxnet.equals(ipxnet))) { result.append("ipxnet.com ").append(ipxnet).append(PlatformUtils.EOLN); } List<Mount> mnts = null; if (base == null) { mnts = mountingpoints; } else { mnts = new ArrayList<Mount>(); for (int i = 0; i < mountingpoints.size(); i++) { if (i >= base.mountingpoints.size() || !mountingpoints.get(i).equals(base.mountingpoints.get(i))) { mnts.add(mountingpoints.get(i)); } } } for (Mount mount : mnts) { result.append(mount.toString()).append(PlatformUtils.EOLN); } if (!StringUtils.EMPTY.equals(mixer) && (base == null || !base.mixer.equals(mixer))) { result.append("mixer.com ").append(mixer).append(PlatformUtils.EOLN); } if (!StringUtils.EMPTY.equals(main)) { String[] dosboxLocation = convertToDosboxPath(main); result.append(dosboxLocation[0] + PlatformUtils.EOLN); // move to drive result.append("cd \\" + dosboxLocation[1] + PlatformUtils.EOLN); // move to dir if (loadfix) { result.append("loadfix -").append(loadfixValue > 0 ? loadfixValue : 64).append(PlatformUtils.EOLN); } insertCustomSection(result, 1); if (!prepareOnly) { if (loadhigh) { result.append("loadhigh "); } if (dosboxLocation[2].toLowerCase().endsWith(FileUtils.EXECUTABLES[2])) { result.append("call "); } result.append(dosboxLocation[2]); if (!StringUtils.EMPTY.equals(params)) { result.append(' ').append(params); } result.append(PlatformUtils.EOLN); insertCustomSection(result, 2); } } else if (!StringUtils.EMPTY.equals(img1)) { if (loadfix) { result.append("loadfix -").append(loadfixValue > 0 ? loadfixValue : 64).append(PlatformUtils.EOLN); } insertCustomSection(result, 1); if (!prepareOnly) { if (matchesMountedImage(img1)) { result.append("boot \"").append(img1).append("\""); } else { String[] dosboxLocation = convertToDosboxPath(img1); result.append("boot ").append(dosboxLocation[0]).append('\\').append(dosboxLocation[1]); if (!dosboxLocation[1].equals(StringUtils.EMPTY)) { result.append('\\'); } result.append(dosboxLocation[2]); } if (matchesMountedImage(img2)) { result.append(" \"").append(img2).append("\""); } else { if (!StringUtils.EMPTY.equals(img2)) { String[] dosboxLocation = convertToDosboxPath(img2); result.append(' ').append(dosboxLocation[0]).append('\\').append(dosboxLocation[1]); if (!dosboxLocation[1].equals(StringUtils.EMPTY)) { result.append('\\'); } result.append(dosboxLocation[2]); } } if (matchesMountedImage(img3)) { result.append(" \"").append(img3).append("\""); } else { if (!StringUtils.EMPTY.equals(img3)) { String[] dosboxLocation = convertToDosboxPath(img3); result.append(' ').append(dosboxLocation[0]).append('\\').append(dosboxLocation[1]); if (!dosboxLocation[1].equals(StringUtils.EMPTY)) { result.append('\\'); } result.append(dosboxLocation[2]); } } if (!StringUtils.EMPTY.equals(imgDriveletter)) { result.append(" -l ").append(imgDriveletter); } result.append(PlatformUtils.EOLN); insertCustomSection(result, 2); } } else { // template insertCustomSection(result, 1); insertCustomSection(result, 2); } if (!prepareOnly) { if (loadfix) { result.append("loadfix -f").append(PlatformUtils.EOLN); } insertCustomSection(result, 3); if (pause) { result.append("pause").append(PlatformUtils.EOLN); } if (exit) { result.append("exit").append(PlatformUtils.EOLN); } } if (result.length() > 0) { result.insert(0, "[autoexec]" + PlatformUtils.EOLN); } return result.toString(); }
From source file:com.lp.server.artikel.fastlanereader.ArtikellisteHandler.java
/** * builds the where clause of the HQL (Hibernate Query Language) statement * using the current query.//from www. j a v a 2 s .c o m * * @return the HQL where clause. */ private String buildWhereClause() { StringBuffer where = new StringBuffer(""); where = new StringBuffer(""); if (getQuery() != null && getQuery().getFilterBlock() != null && getQuery().getFilterBlock().filterKrit != null) { FilterBlock filterBlock = getQuery().getFilterBlock(); FilterKriterium[] filterKriterien = getQuery().getFilterBlock().filterKrit; String booleanOperator = filterBlock.boolOperator; boolean filterAdded = false; boolean bvolltext = false; for (int i = 0; i < filterKriterien.length; i++) { if (filterKriterien[i].isKrit) { if (filterAdded) { where.append(" " + booleanOperator); } filterAdded = true; if (filterKriterien[i].kritName.equals("artikelliste.c_nr")) { String s = ""; s = filterKriterien[i].value.toLowerCase(); filterKriterien[i].value = s; } if (filterKriterien[i].kritName.equals("c_volltext")) { filterKriterien[i].kritName = "aspr.c_bez"; } if (filterKriterien[i].kritName.equals("aspr.c_bez")) { filterKriterien[i].kritName = "aspr.c_bez"; String s = ""; s = filterKriterien[i].value.toLowerCase(); filterKriterien[i].value = s; bvolltext = true; } else { bvolltext = false; } if (bvolltext && !filterKriterien[i].kritName .equals(ArtikelFac.FLR_ARTIKELLIEFERANT_C_ARTIKELNRLIEFERANT)) { String suchstring = "lower(coalesce(aspr.c_bez,'')||' '||coalesce(aspr.c_kbez,'')||' '||coalesce(aspr.c_zbez,'')||' '||coalesce(aspr.c_zbez2,''))"; if (bAbmessungenStattZusatzbezeichnung) { suchstring += "||' '||lower(coalesce(geo.c_breitetext,'')||coalesce(cast(geo.f_breite as string),'')||case WHEN geo.f_hoehe IS NULL THEN '' ELSE 'x' END||coalesce(cast(geo.f_hoehe as string),'')||case WHEN geo.f_tiefe IS NULL THEN '' ELSE 'x' END||coalesce(cast(geo.f_tiefe as string),''))"; } if (bTextsucheInklusiveArtikelnummer) { suchstring += "||' '||lower(artikelliste.c_nr)"; } String[] teile = filterKriterien[i].value.toLowerCase().split(" "); where.append("("); for (int p = 0; p < teile.length; p++) { if (teile[p].startsWith("-")) { where.append(" NOT "); teile[p] = teile[p].substring(1); } where.append("lower(" + suchstring + ") like '%" + teile[p].toLowerCase() + "%'"); if (p < teile.length - 1) { where.append(" AND "); } } where.append(")"); } else if (filterKriterien[i].kritName .equals(ArtikelFac.FLR_ARTIKELLIEFERANT_C_ARTIKELNRLIEFERANT)) { where.append(" (lower(artikellieferantset." + filterKriterien[i].kritName + ")"); where.append(" " + filterKriterien[i].operator); where.append(" " + filterKriterien[i].value.toLowerCase()); where.append(" OR lower(artikellieferantset." + ArtikelFac.FLR_ARTIKELLIEFERANT_C_BEZBEILIEFERANT + ")"); where.append(" " + filterKriterien[i].operator); where.append(" " + filterKriterien[i].value.toLowerCase() + ")"); } else if (filterKriterien[i].kritName.equals("akag")) { where.append(" (lower(artikelliste.flrartikelgruppe.c_nr)"); where.append(" " + filterKriterien[i].operator); where.append(" " + filterKriterien[i].value.toLowerCase()); where.append(" OR lower(artikelliste.flrartikelklasse.c_nr)"); where.append(" " + filterKriterien[i].operator); where.append(" " + filterKriterien[i].value.toLowerCase() + ")"); } else { if (filterKriterien[i].isBIgnoreCase()) { where.append(" LOWER(" + filterKriterien[i].kritName + ")"); } else { where.append(" " + filterKriterien[i].kritName); } where.append(" " + filterKriterien[i].operator); if (filterKriterien[i].isBIgnoreCase()) { where.append(" " + filterKriterien[i].value.toLowerCase()); } else { where.append(" " + filterKriterien[i].value); } } } } if (filterAdded) { where.insert(0, " WHERE "); } } return where.toString(); }
From source file:CssCompressor.java
public void compress(Writer out, int linebreakpos) throws IOException { Pattern p;//from w w w . j av a 2s .c om Matcher m; String css; StringBuffer sb; int startIndex, endIndex; // Remove all comment blocks... startIndex = 0; boolean iemac = false; boolean preserve = false; sb = new StringBuffer(srcsb.toString()); while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) { preserve = sb.length() > startIndex + 2 && sb.charAt(startIndex + 2) == '!'; endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex < 0) { if (!preserve) { sb.delete(startIndex, sb.length()); } } else if (endIndex >= startIndex + 2) { if (sb.charAt(endIndex - 1) == '\\') { // Looks like a comment to hide rules from IE Mac. // Leave this comment, and the following one, alone... startIndex = endIndex + 2; iemac = true; } else if (iemac) { startIndex = endIndex + 2; iemac = false; } else if (!preserve) { sb.delete(startIndex, endIndex + 2); } else { startIndex = endIndex + 2; } } } css = sb.toString(); // Normalize all whitespace strings to single spaces. Easier to work // with that way. css = css.replaceAll("\\s+", " "); // Make a pseudo class for the Box Model Hack css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___"); // ---------where zk modify it sb = new StringBuffer(); p = Pattern.compile("\\$\\{([^\\}]+)\\}"); Matcher m1 = p.matcher(css); while (m1.find()) { String s1 = m1.group(); s1 = s1.replaceAll("\\$\\{", "__EL__"); s1 = s1.replaceAll(":", "__ELSP__"); s1 = s1.replaceAll("\\}", "__ELEND__"); m1.appendReplacement(sb, s1); } m1.appendTail(sb); css = sb.toString(); // ---------where zk modify it----end // Remove the spaces before the things that should not have spaces // before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___PSEUDOCLASSCOLON___"); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); css = css.replaceAll("___PSEUDOCLASSCOLON___", ":"); // Remove the spaces after the things that should not have spaces after // them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // Add the semicolon where it's missing. css = css.replaceAll("([^;\\}])}", "$1;}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0;", ":0;"); css = css.replaceAll(":0 0 0;", ":0;"); css = css.replaceAll(":0 0;", ":0;"); // Replace background-position:0; with background-position:0 0; css = css.replaceAll("background-position:0;", "background-position:0 0;"); // Replace 0.6 to .6, but only when preceded by : or a white-space css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the // next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (int i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); if (val < 16) { hexcolor.append("0"); } hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC. Note that we want to make sure // the color is not preceded by either ", " or =. Indeed, the property // filter: chroma(color="#FFFFFF"); // would become // filter: chroma(color="#FFF"); // which makes the filter break in IE. p = Pattern.compile( "([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { // Test for AABBCC pattern if (m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6)) && m.group(7).equalsIgnoreCase(m.group(8))) { m.appendReplacement(sb, m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)); } else { m.appendReplacement(sb, m.group()); } } m.appendTail(sb); css = sb.toString(); // Remove empty rules. css = css.replaceAll("[^\\}]+\\{;\\}", ""); if (linebreakpos >= 0) { // Some source control tools don't like it when files containing // lines longer // than, say 8000 characters, are checked in. The linebreak option // is used in // that case to split long lines after a specific column. int i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Replace the pseudo class for the Box Model Hack css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\""); // Replace multiple semi-colons in a row by a single one // See SF bug #1980989 css = css.replaceAll(";;+", ";"); // ---------where zk modify it css = css.replaceAll("__EL__", "\\$\\{"); css = css.replaceAll("__ELSP__", ":"); css = css.replaceAll("__ELEND__", "\\}"); // ---------where zk modify it----end // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); }
From source file:org.opencms.frontend.templateone.CmsTemplateNavigation.java
/** * This method builds a complete menu navigation with entries of all branches * from the specified folder.<p>//from w w w . java 2 s . com * * @param curNav the List of current navigation elements * @param styleClass the CSS class name of the <div> nodes * @param prefix the prefix to generate the unique menu node id. * @param currentDepth the depth of the current submenu * @param menuIndexes String representing the menu indexes in the manual XML configuration, if null, no manual configuration is used * @return the HTML to generate menu entries */ public StringBuffer getMenuNavigation(List curNav, String styleClass, String prefix, int currentDepth, String menuIndexes) { StringBuffer result = new StringBuffer(64); String showItemProperty; int navSize = curNav.size(); if (navSize > 0) { // at least one navigation entry present, create menu Map subNav = new HashMap(); Map subIndex = new HashMap(); boolean entryPresent = false; boolean manualConfig = CmsStringUtil.isNotEmpty(menuIndexes); // loop through all nav entries for (int i = 0; i < navSize; i++) { CmsJspNavElement ne = (CmsJspNavElement) curNav.get(i); String resName = ne.getResourceName(); String link = resName; if (link.startsWith("/")) { link = link(link); } showItemProperty = getHeadNavItemDefaultStringValue(); if (getCmsObject().existsResource(resName)) { showItemProperty = property(PROPERTY_HEADNAV_USE, resName, getHeadNavItemDefaultStringValue()); } else if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_NAVIGATION_CONFIG_ERR_2, resName, getRequestContext().getUri())); } boolean showEntry = manualConfig || Boolean.valueOf(showItemProperty).booleanValue(); if (showEntry) { entryPresent = true; List navEntries = new ArrayList(); // check if is depth smaller than maximum depth -> if so, get the navigation from this folder as well if (currentDepth < getMenuDepth()) { if (manualConfig) { // manual configuration, get nav entries from XML configuration file navEntries = getHeadNavItemsFromConfig(currentDepth + 1, menuIndexes + String.valueOf(i)); } else if (ne.isFolderLink()) { // entry is folder, get sub navigation navEntries = getNavigation().getNavigationForFolder(resName); } } String target = ne.getInfo(); if (CmsStringUtil.isEmpty(target)) { target = "_self"; } result.append(" <a class=\"mI\" href=\""); result.append(link); result.append("\" target=\""); result.append(target); result.append("\""); if ((ne.isFolderLink() && hasSubMenuEntries(navEntries)) || (manualConfig && navEntries.size() > 0)) { // sub menu(s) present, create special entry result.append(" onmouseover=\"menuItemMouseover(event, '"); result.append(prefix); result.append("_"); result.append(resName.hashCode()); result.append("');\">"); result.append("<span class=\"mIText\">"); result.append(ne.getNavText()); result.append("</span><span class=\"mIArrow\">▶</span></a>"); // add current entry to temporary Map to create the sub menus subNav.put(resName, navEntries); if (manualConfig) { // for manual configuration, additional information for the xpath is needed for the sub menus subIndex.put(resName, menuIndexes + String.valueOf(i)); } } else { // no sub menu present, create common menu entry result.append(">"); result.append(ne.getNavText()); result.append("</a>"); } } } result.append("</div>\n"); StringBuffer openTag = new StringBuffer(8); if ("menu0".equals(prefix) && showAccessibleVersion()) { // create div that is displayed for accessible version CmsMessages messages = new CmsMessages(CmsTemplateBean.MESSAGE_BUNDLE, getRequestContext().getLocale()); openTag.append("<div style=\"visibility: hidden; display:none;\">"); openTag.append("<h3>").append(messages.key("headline.accessible.nav.headline")).append("</h3>"); openTag.append("<p>").append(messages.key("headline.accessible.nav.text")).append("</p>"); openTag.append("</div>"); } if (entryPresent) { openTag.append("<div class=\""); openTag.append(styleClass); openTag.append("\" id=\""); openTag.append(prefix); openTag.append("\" onmouseover=\"menuMouseover(event);\">"); } else { openTag.append("<div style=\"visibility: hidden;\" id=\""); openTag.append(prefix); openTag.append("\">"); } result.insert(0, openTag); // add the sub menus recursively from temporary Map Iterator i = subNav.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String resName = (String) entry.getKey(); List navEntries = (List) entry.getValue(); String newIndex = menuIndexes; if (manualConfig) { // get the xpath information to build the submenus from the XML configuration newIndex = (String) subIndex.get(resName); } result.append(getMenuNavigation(navEntries, styleClass, prefix + "_" + resName.hashCode(), currentDepth + 1, newIndex)); } } return result; }
From source file:com.clustercontrol.collect.util.CollectGraphUtil.java
/** * ??????/* ww w . ja va2 s. c om*/ * * @param startDate DB???? * @param endDate DB???? * @param selectStartDate ? * @param selectEndDate ? * @return * @throws InvalidRole_Exception * @throws HinemosUnknown_Exception * @throws InvalidUserPass_Exception */ public static StringBuffer getAddGraphPlotJson(Long startDate, Long endDate, Long selectStartDate, Long selectEndDate) throws InvalidUserPass_Exception, HinemosUnknown_Exception, InvalidRole_Exception { m_log.debug("getAddGraphPlotJson() start"); StringBuffer sb = new StringBuffer(); int count = 0; boolean allbreak = false; for (CollectKeyInfoPK collectKeyInfo : getInstance().m_collectKeyInfoList) { String itemName = HinemosMessage.replace(collectKeyInfo.getItemName()); String monitorId = collectKeyInfo.getMonitorId(); String displayName = collectKeyInfo.getDisplayName(); for (Map.Entry<String, TreeMap<String, List<Integer>>> entry : getInstance().m_targetManagerFacilityCollectMap .entrySet()) { String managerName = entry.getKey(); Map<Integer, List<CollectData>> graphMap = getGraphDetailDataMap(managerName, monitorId, displayName, itemName, startDate, endDate); String itemNameDisplayNameMonitorId = itemName + displayName + monitorId; Map<String, Integer> collectIdMap = getFacilityCollectMap(itemNameDisplayNameMonitorId, managerName); // plot? List<String> plotList = parseGraphData(collectIdMap, graphMap); if (plotList == null || plotList.isEmpty()) { m_log.debug("getAddGraphPlotJson() plotDataList is Empty."); break; } // ?????? String thresholdStr = getThresholdData(managerName, monitorId); String thresholdInfoMin = "0"; String thresholdInfoMax = "0"; String thresholdWarnMin = "0"; String thresholdWarnMax = "0"; String measure = ""; String pluginId = ""; String graphRange = Boolean.FALSE.toString(); // graphrange???json????? String isHttpSce = Boolean.FALSE.toString(); if (thresholdStr != null) { thresholdInfoMin = thresholdStr.split(",")[0]; thresholdInfoMax = thresholdStr.split(",")[1]; thresholdWarnMin = thresholdStr.split(",")[2]; thresholdWarnMax = thresholdStr.split(",")[3]; measure = thresholdStr.split(",")[4]; pluginId = thresholdStr.split(",")[5]; graphRange = thresholdStr.split(",")[6]; isHttpSce = thresholdStr.split(",")[7]; } // #?split??addPoints for (String plotStr : plotList) { String split_plot[] = plotStr.split(SQUARE_SEPARATOR); String facilityId = split_plot[0]; String collectId = split_plot[1]; String plot = split_plot[2]; String facilityName = getInstance().m_managerFacilityIdNameMap .get(managerName + SQUARE_SEPARATOR + facilityId); String facilityDummyId = getInstance().m_managerFacilityIdDummyNameMap .get(managerName + SQUARE_SEPARATOR + facilityId); String managerDummyName = getInstance().m_managerDummyNameMap.get(managerName); String itemName2 = itemName; if (!displayName.equals("") && !itemName2.endsWith("[" + displayName + "]")) { itemName2 += "[" + displayName + "]"; } // groupIdexecuteJavascriptForFirstDrawGraphs?????(id)????????????? String groupId = itemName2 + "_" + monitorId; if (!getInstance().totalFlg) { groupId = facilityDummyId + "_" + managerDummyName + "_" + itemName2 + "_" + monitorId; } String param = "{" + "\'data\':" + plot + ", " + "\'realfacilityid\':\'" + facilityId + "\', " + "\'facilityid\':\'" + facilityDummyId + "\', " // DUMMY + "\'facilityname\':\'" + facilityName + "\', " + "\'monitorid\':\'" + monitorId + "\', " + "\'displayname\':\'" + displayName + "\', " + "\'collectid\':\'" + collectId + "\', " + "\'realmanagername\':\'" + managerName + "\', " + "\'managername\':\'" + managerDummyName + "\', " // DUMMY + "\'itemname\':\'" + itemName2 + "\', " + "\'groupid\':\'" + groupId + "\', " // ?????????? + "\'measure\':\'" + measure + "\', " + "\'pluginid\':\'" + pluginId + "\', " + "\'graphrange\':" + graphRange + ", " + "\'ishttpsce\':" + isHttpSce + ", " + "\'summarytype\':" + getInstance().m_summaryType + ", " + "\'startdate\':\'" + selectStartDate + "\', " + "\'enddate\':\'" + selectEndDate + "\', " + "\'sliderstartdate\':\'" + getInstance().m_sliderStart + "\', " + "\'sliderenddate\':\'" + getInstance().m_sliderEnd + "\', " + "\'thresholdinfomin\':\'" + thresholdInfoMin + "\', " + "\'thresholdinfomax\':\'" + thresholdInfoMax + "\', " + "\'thresholdwarnmin\':\'" + thresholdWarnMin + "\', " + "\'thresholdwarnmax\':\'" + thresholdWarnMax + "\' " + "}"; sb.append(param); sb.append(","); count++; if (count == ClusterControlPlugin.getDefault().getPreferenceStore() .getInt(PerformancePreferencePage.P_GRAPH_MAX)) { allbreak = true; break; } } if (allbreak) { break; } } if (allbreak) { break; } } if (sb.length() == 0) { m_log.debug("getAddGraphPlotJson() plot data 0."); return null; } String appendfirst = "{\'all\':["; sb.insert(0, appendfirst); sb.deleteCharAt(sb.length() - 1); sb.append("],"); sb.append("\'eventflaginfo\':[" + getEventFlagInfo() + "], "); sb.append(orderItemInfoSelection()); sb.append("}"); return sb; }
From source file:HtmlEncoder.java
/** * Do "smart" encodging on a string. This means that valid HTML entities and tags, * Helma macros and HTML comments are passed through unescaped, while * other occurrences of '<', '>' and '&' are encoded to HTML entities. * * @param str the string to encode/* w w w. j ava2s . co m*/ * @param ret the string buffer to encode to * @param paragraphs if true use p tags for paragraphs, otherwise just use br's * @param allowedTags a set containing the names of allowed tags as strings. All other * tags will be escaped */ public final static void encode(String str, StringBuffer ret, boolean paragraphs, Set allowedTags) { if (str == null) { return; } int l = str.length(); // where to insert the <p> tag in case we want to create a paragraph later on int paragraphStart = ret.length(); // what kind of element/text are we leaving and entering? // this is one of TEXT|SEMIBLOCK|BLOCK|INTERNAL // depending on this information, we decide whether and how to insert // paragraphs and line breaks. "entering" a tag means we're at the '<' // and exiting means we're at the '>', not that it's a start or close tag. byte entering = TEXT; byte exiting = TEXT; Stack openTags = new Stack(); // are we currently within a < and a > that consitute some kind of tag? // we use tag balancing to know whether we are inside a tag (and should // pass things through unchanged) or outside (and should encode stuff). boolean insideTag = false; // are we inside an HTML tag? boolean insideHtmlTag = false; boolean insideCloseTag = false; byte htmlTagMode = TAG_NAME; // if we are inside a <code> tag, we encode everything to make // documentation work easier boolean insideCodeTag = false; boolean insidePreTag = false; // are we within a Helma <% macro %> tag? We treat macro tags and // comments specially, since we can't rely on tag balancing // to know when we leave a macro tag or comment. boolean insideMacroTag = false; // are we inside an HTML comment? boolean insideComment = false; // the quotation mark we are in within an HTML or Macro tag, if any char htmlQuoteChar = '\u0000'; char macroQuoteChar = '\u0000'; // number of newlines met since the last non-whitespace character int linebreaks = 0; // did we meet a backslash escape? boolean escape = false; boolean triggerBreak = false; for (int i = 0; i < l; i++) { char c = str.charAt(i); // step one: check if this is the beginning of an HTML tag, comment or // Helma macro. if (c == '<') { if (i < (l - 2)) { if (!insideMacroTag && ('%' == str.charAt(i + 1))) { // this is the beginning of a Helma macro tag if (!insideCodeTag) { insideMacroTag = insideTag = true; macroQuoteChar = '\u0000'; } } else if (('!' == str.charAt(i + 1)) && ('-' == str.charAt(i + 2))) { // the beginning of an HTML comment? if (!insideCodeTag) { insideComment = insideTag = ((i < (l - 3)) && ('-' == str.charAt(i + 3))); } } else if (!insideTag) { // check if this is a HTML tag. insideCloseTag = ('/' == str.charAt(i + 1)); int tagStart = insideCloseTag ? (i + 2) : (i + 1); int j = tagStart; while ((j < l) && Character.isLetterOrDigit(str.charAt(j))) j++; if ((j > tagStart) && (j < l)) { String tagName = str.substring(tagStart, j).toLowerCase(); if ("code".equals(tagName) && insideCloseTag && insideCodeTag) { insideCodeTag = false; } if (((allowedTags == null) || allowedTags.contains(tagName)) && allTags.contains(tagName) && !insideCodeTag) { insideHtmlTag = insideTag = true; htmlQuoteChar = '\u0000'; htmlTagMode = TAG_NAME; exiting = entering; entering = TEXT; if (internalTags.contains(tagName)) { entering = INTERNAL; } else if (blockTags.contains(tagName)) { entering = BLOCK; } else if (semiBlockTags.contains(tagName)) { entering = paragraphs ? BLOCK : SEMIBLOCK; } if (entering > 0) { triggerBreak = !insidePreTag; } if (insideCloseTag) { int t = openTags.search(tagName); if (t == -1) { i = j; insideHtmlTag = insideTag = false; continue; } else if (t > 1) { for (int k = 1; k < t; k++) { Object tag = openTags.pop(); if (!emptyTags.contains(tag)) { ret.append("</"); ret.append(tag); ret.append(">"); } } } openTags.pop(); } else { openTags.push(tagName); } if ("code".equals(tagName) && !insideCloseTag) { insideCodeTag = true; } if ("pre".equals(tagName)) { insidePreTag = !insideCloseTag; } } } } } // if (i < l-2) } if ((triggerBreak || linebreaks > 0) && !Character.isWhitespace(c)) { if (!insideTag) { exiting = entering; entering = TEXT; if (exiting >= SEMIBLOCK) { paragraphStart = ret.length(); } } if (entering != INTERNAL && exiting != INTERNAL) { int swallowBreaks = 0; if (paragraphs && (entering != BLOCK || exiting != BLOCK) && (exiting < BLOCK) && (linebreaks > 1) && paragraphStart < ret.length()) { ret.insert(paragraphStart, "<p>"); ret.append("</p>"); swallowBreaks = 2; } // treat entering a SEMIBLOCK as entering a TEXT int _entering = entering == SEMIBLOCK ? TEXT : entering; for (int k = linebreaks - 1; k >= 0; k--) { if (k >= swallowBreaks && k >= _entering && k >= exiting) { ret.append("<br />"); } ret.append(newLine); } if (exiting >= SEMIBLOCK || linebreaks > 1) { paragraphStart = ret.length(); } } linebreaks = 0; triggerBreak = false; } switch (c) { case '<': if (insideTag) { ret.append('<'); } else { ret.append("<"); } break; case '&': // check if this is an HTML entity already, // in which case we pass it though unchanged if ((i < (l - 3)) && !insideCodeTag) { // is this a numeric entity? if (str.charAt(i + 1) == '#') { int j = i + 2; while ((j < l) && Character.isDigit(str.charAt(j))) j++; if ((j < l) && (str.charAt(j) == ';')) { ret.append("&"); break; } } else { int j = i + 1; while ((j < l) && Character.isLetterOrDigit(str.charAt(j))) j++; if ((j < l) && (str.charAt(j) == ';')) { ret.append("&"); break; } } } // we didn't reach a break, so encode the ampersand as HTML entity ret.append("&"); break; case '\\': ret.append(c); if (insideTag && !insideComment) { escape = !escape; } break; case '"': case '\'': ret.append(c); if (!insideComment) { // check if the quote is escaped if (insideMacroTag) { if (escape) { escape = false; } else if (macroQuoteChar == c) { macroQuoteChar = '\u0000'; } else if (macroQuoteChar == '\u0000') { macroQuoteChar = c; } } else if (insideHtmlTag) { if (escape) { escape = false; } else if (htmlQuoteChar == c) { htmlQuoteChar = '\u0000'; htmlTagMode = TAG_SPACE; } else if (htmlQuoteChar == '\u0000') { htmlQuoteChar = c; } } } break; case '\n': if (insideTag || insidePreTag) { ret.append('\n'); } else { linebreaks++; } break; case '\r': if (insideTag || insidePreTag) { ret.append('\r'); } break; case '>': // For Helma macro tags and comments, we overrule tag balancing, // i.e. we don't require that '<' and '>' be balanced within // macros and comments. Rather, we check for the matching closing tag. if (insideComment) { ret.append('>'); insideComment = !((str.charAt(i - 2) == '-') && (str.charAt(i - 1) == '-')); } else if (insideMacroTag) { ret.append('>'); insideMacroTag = !((str.charAt(i - 1) == '%') && (macroQuoteChar == '\u0000')); } else if (insideHtmlTag) { ret.append('>'); // only leave HTML tag if quotation marks are balanced // within that tag. insideHtmlTag = htmlQuoteChar != '\u0000'; // Check if this is an empty tag so we don't generate an // additional </close> tag. if (str.charAt(i - 1) == '/') { // this is to avoid misinterpreting tags like // <a href=http://foo/> as empty if (htmlTagMode != TAG_ATT_VAL && htmlTagMode != TAG_ATT_NAME) { openTags.pop(); } } exiting = entering; if (exiting > 0) { triggerBreak = !insidePreTag; } } else { ret.append(">"); } // check if we still are inside any kind of tag insideTag = insideComment || insideMacroTag || insideHtmlTag; insideCloseTag = insideTag; break; default: if (insideHtmlTag && !insideCloseTag) { switch (htmlTagMode) { case TAG_NAME: if (!Character.isLetterOrDigit(c)) { htmlTagMode = TAG_SPACE; } break; case TAG_SPACE: if (Character.isLetterOrDigit(c)) { htmlTagMode = TAG_ATT_NAME; } break; case TAG_ATT_NAME: if (c == '=') { htmlTagMode = TAG_ATT_VAL; } else if (c == ' ') { htmlTagMode = TAG_SPACE; } break; case TAG_ATT_VAL: if (Character.isWhitespace(c) && htmlQuoteChar == '\u0000') { htmlTagMode = TAG_SPACE; } break; } } if (c < 128) { ret.append(c); } else if ((c >= 128) && (c < 256)) { ret.append(transform[c - 128]); } else { ret.append("&#"); ret.append((int) c); ret.append(";"); } escape = false; } } // if tags were opened but not closed, close them. int o = openTags.size(); if (o > 0) { for (int k = 0; k < o; k++) { Object tag = openTags.pop(); if (!emptyTags.contains(tag)) { ret.append("</"); ret.append(tag); ret.append(">"); } } } // add remaining newlines we may have collected int swallowBreaks = 0; if (paragraphs && entering < BLOCK) { ret.insert(paragraphStart, "<p>"); ret.append("</p>"); swallowBreaks = 2; } if (linebreaks > 0) { for (int i = linebreaks - 1; i >= 0; i--) { if (i >= swallowBreaks && i > exiting) { ret.append("<br />"); } ret.append(newLine); } } }
From source file:com.github.gekoh.yagen.ddl.CreateDDL.java
public String updateCreateConstraint(Dialect dialect, StringBuffer buf, String name, Table table, Constraint constraint) {//from ww w . j a va 2s . c o m NamingStrategy namingStrategy = getProfile().getNamingStrategy(); String newName = namingStrategy.constraintName(constraint, getEntityClassName(namingStrategy.tableName(table.getName()))); if (!name.equals(newName)) { String sqlCreate = buf.toString(); Matcher matcher = CONSTRAINT_PATTERN.matcher(sqlCreate); if (matcher.find()) { buf = new StringBuffer(); buf.append(sqlCreate.substring(0, matcher.start(1))); buf.append(newName); buf.append(sqlCreate.substring(matcher.end(1))); } name = newName; } String tableNameLC = getProfile().getNamingStrategy().tableName(table.getName()).toLowerCase(); if (!renderTable(tableNameLC) || externalViews.contains(tableNameLC)) { return "-- skipped creation of constraint '" + name + "' for table '" + table.getName() + "' as the mapped entity was not chosen to be processed or is a view"; } TableConfig tableConfig = tblNameToConfig.get(tableNameLC); String refTblNameLC = null; if (constraint instanceof ForeignKey) { if (tableConfig.getColumnNamesIsNoFK().contains(constraint.getColumn(0).getName().toLowerCase())) { return "-- skipped creation of foreign key constraint '" + name + "' for table '" + table.getName() + "' according to annotation of type " + NoForeignKeyConstraint.class.getSimpleName(); } refTblNameLC = getProfile().getNamingStrategy() .tableName(((ForeignKey) constraint).getReferencedTable().getName()).toLowerCase(); } checkObjectName(dialect, name); String i18nFK = tableConfig.getI18nBaseEntityFkCol(); if (i18nFK != null) { StringBuilder sql = new StringBuilder(); tableNameLC = getI18NDetailTableName(tableNameLC); Matcher matcher = TBL_ALTER_PATTERN.matcher(buf.toString()); if (matcher.find()) { sql.append(buf.substring(0, matcher.start(1))).append(tableNameLC) .append(buf.substring(matcher.end(1))); } buf = new StringBuffer(sql.toString()); } if (constraint instanceof ForeignKey) { StringBuilder colList = new StringBuilder(); org.hibernate.mapping.Column singleColumn = null; TableConfig refTableConfig = tblNameToConfig.get(refTblNameLC); IntervalPartitioning refTblPart = refTableConfig != null ? refTableConfig.getTableAnnotationOfType(IntervalPartitioning.class) : null; for (org.hibernate.mapping.Column column : (Iterable<? extends org.hibernate.mapping.Column>) constraint .getColumns()) { if (colList.length() > 0) { colList.append(", "); } colList.append(column.getName().toLowerCase()); singleColumn = singleColumn == null ? column : null; } if (externalViews.contains(refTblNameLC)) { buf = new StringBuffer("-- skipped creation of constraint '" + name + "' on table '" + tableNameLC + "' since a view will be referenced"); } else if (refTblPart != null && refTblPart.useLocalPK() && supportsPartitioning(dialect)) { buf = new StringBuffer(); buf.append("-- skipped creation of foreign key constraint '").append(name).append("' on table '") .append(tableNameLC).append("' to table '").append(refTblNameLC) .append("' as the partitioned target table has a local PK (see @IntervalPartitioning on ") .append(((ForeignKey) constraint).getReferencedEntityName()).append(")"); } else { if (singleColumn != null) { if (tableConfig.getColumnNamesIsCascadeNullable() .contains(singleColumn.getName().toLowerCase())) { buf.append(" on delete set null"); } else if (tableConfig.getColumnNamesIsCascadeDelete() .contains(singleColumn.getName().toLowerCase()) && buf.indexOf("on delete") < 0) { buf.append(" on delete cascade"); } } Map<String, Deferrable> col2Deferrable = tableConfig.getColumnNameToDeferrable(); Deferrable deferrable; if (supportsDeferrable(dialect) && col2Deferrable != null && (deferrable = col2Deferrable.get(colList.toString())) != null) { buf.append(" deferrable"); if (deferrable.initiallyDeferred()) { buf.append(" initially deferred"); } } if (getProfile().isDisableFKs()) { buf.insert(0, "-- creating FK constraint initially disabled since we do not need it for profile '" + getProfile() + "'\n"); buf.append(" disable"); } } getProfile().duplex(ObjectType.CONSTRAINT, name, buf.toString()); if (constraint.getColumnSpan() == 1 && hasIndex(table, tableNameLC, singleColumn)) { LOG.debug("not creating foreign key index as there is already an index on table " + tableNameLC + " and column " + colList.toString()); } else { String fkIndexName = getProfile().getNamingStrategy().indexName(getEntityClassName(tableNameLC), tableNameLC, DefaultNamingStrategy.concatColumnNames(colList.toString())); StringBuilder objDdl = new StringBuilder(); objDdl.append("create index ").append(fkIndexName).append(" on ").append(tableNameLC).append(" (") .append(colList.toString()).append(")"); if (constraint.getColumnSpan() == 1) { tblColNameHasSingleColIndex.add(tableNameLC + "." + colList.toString()); } buf.append(STATEMENT_SEPARATOR).append(objDdl); getProfile().duplex(ObjectType.INDEX, fkIndexName, objDdl.toString()); } } return buf.toString(); }