public String getFromSessionLanguage(String key) throws LanguageException { String language = null; if (language == null) language = request.getParameter("languageId"); if (language == null) language = (String) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE); if (language == null) language = String.valueOf(langAPI.getDefaultLanguage().getId()); Language lang = APILocator.getLanguageAPI().getLanguage(language); return LanguageUtil.get(LanguageUtil.getLocale(lang.getLanguageCode()), key); }
/** * Appends info messages to a main StringBuilder message for an easier display to the user * * @param responseMessage Response message to return to the user * @param messageKey i18 key * @param bundleId Current bundle * @param failure True for failures, false otherwise * @throws LanguageException If fails using the i18 massage key */ private void appendMessage( StringBuilder responseMessage, String messageKey, String bundleId, Boolean failure) throws LanguageException { String message = LanguageUtil.format(getUser().getLocale(), messageKey, new String[] {bundleId}, false); if (responseMessage.length() > 0) { responseMessage.append("<br>"); } if (failure) { responseMessage.append("FAILURE: ").append(message); } else { responseMessage.append(message); } }
@Override public List<WorkflowActionletParameter> getParameters() { try { if (null == paramList) { paramList = new ArrayList<WorkflowActionletParameter>(); paramList.add( new WorkflowActionletParameter( "fieldList", LanguageUtil.get(APILocator.getUserAPI().getSystemUser(), "checkURL.fieldList"), "", true)); } } catch (Exception e) { } return paramList; }
public String getFromUserLanguage(String key) { User user1 = null; try { user1 = com.liferay.portal.util.PortalUtil.getUser(this.request); } catch (PortalException e) { Logger.error(this, e.toString()); } catch (SystemException e) { Logger.error(this, e.toString()); } String message = null; try { message = LanguageUtil.get(user1, key); } catch (LanguageException e) { Logger.error(this, e.toString()); } return message; }
@Override public void executeAction( WorkflowProcessor processor, Map<String, WorkflowActionClassParameter> params) throws WorkflowActionFailureException { if (LicenseUtil.getLevel() < 200) return; // the apis will do nothing anyway WebContext ctx = WebContextFactory.get(); HttpServletRequest request = ctx.getHttpServletRequest(); User user = null; try { user = uWebAPI.getLoggedInUser(request); } catch (Exception exx) { throw new WorkflowActionFailureException(exx.getMessage()); } Contentlet con = processor.getContentlet(); List<InvalidLink> httpResponse = null; try { httpResponse = APILocator.getLinkCheckerAPI().findInvalidLinks(con); } catch (Exception e1) { Logger.error(this, e1.getMessage(), e1); throw new WorkflowActionFailureException(e1.getMessage()); } // if there are unreachable URL... if (httpResponse.size() > 0) { String msg = ""; try { msg = LanguageUtil.get(user, "checkURL.errorBrokenLinks"); } catch (Exception e) { } throw new WorkflowActionFailureException( LinkCheckerUtil.buildPopupMsgWithLinksList(msg, httpResponse)); } }
public Map<String, Object> fetchTemplates( Map<String, String> query, Map<String, String> queryOptions, int start, int count, List<String> sort) throws PortalException, SystemException, DotDataException, DotSecurityException { HttpServletRequest req = WebContextFactory.get().getHttpServletRequest(); User user = userWebAPI.getLoggedInUser(req); boolean respectFrontendRoles = userWebAPI.isLoggedToFrontend(req); if (count <= 0) count = 10; List<Template> fullListTemplates = new ArrayList<Template>(); List<Template> totalTemplates = new ArrayList<Template>(); Host host = hostAPI.find(query.get("hostId"), user, respectFrontendRoles); try { String filter = query.get("fullTitle"); if (UtilMethods.isSet(filter)) { filter = filter.replaceAll("\\*", ""); filter = filter.replaceAll("\\?", ""); } if (UtilMethods.isSet(query.get("hostId"))) { int startF = start; int countF = count; if (start == 0) { Template t = new Template(); t.setOwner(user.getUserId()); t.setModUser(user.getUserId()); t.setInode("0"); t.setTitle("--- " + LanguageUtil.get(user, "All-Hosts") + " ---"); t.setIdentifier("0"); fullListTemplates.add(t); totalTemplates.add(t); countF = count - 1; } else { startF = start - 1; } fullListTemplates.addAll( templateAPI.findTemplatesUserCanUse( user, host.getHostname(), filter, true, startF, countF)); totalTemplates.addAll( templateAPI.findTemplatesUserCanUse(user, host.getHostname(), filter, true, 0, 1000)); } // doesn't currently respect archived if (fullListTemplates.size() == 0) { fullListTemplates.addAll( templateAPI.findTemplatesUserCanUse( user, "", filter, true, start, start > 0 ? count : count + 1)); totalTemplates.addAll(templateAPI.findTemplatesUserCanUse(user, "", filter, true, 0, 1000)); } } catch (DotDataException e) { Logger.error(this, e.getMessage(), e); throw new DotDataException(e.getMessage(), e); } // Collections.sort(fullListTemplates, new TemplateComparator(baseHostId)); Map<String, Object> results = new HashMap<String, Object>(); List<Map<String, Object>> list = new LinkedList<Map<String, Object>>(); boolean shouldIncludeTemplate = true; String toInclude = queryOptions.get("includeTemplate"); for (Template template : fullListTemplates) { Map<String, Object> contMap = buildTemplateMap(template); list.add(contMap); } if (toInclude != null && shouldIncludeTemplate) { Template template = templateAPI.findWorkingTemplate( toInclude, APILocator.getUserAPI().getSystemUser(), false); if (template != null) { list.add(buildTemplateMap(template)); } } // totalTemplates = templateAPI.findTemplatesAssignedTo(host); // if(start >= list.size()) start = list.size() - 1; // if(start < 0) start = 0; // if(start + count >= list.size()) count = list.size() - start; // List<Map<String, Object>> templates = list.subList(start, start + count); results.put("totalResults", totalTemplates.size()); results.put("list", list); return results; }
@SuppressWarnings("unchecked") protected void doEditMode(HttpServletRequest request, HttpServletResponse response) throws Exception { String uri = request.getRequestURI(); uri = UtilMethods.cleanURI(uri); Host host = hostWebAPI.getCurrentHost(request); StringBuilder preExecuteCode = new StringBuilder(); Boolean widgetPreExecute = false; // Getting the user to check the permissions com.liferay.portal.model.User backendUser = null; try { backendUser = com.liferay.portal.util.PortalUtil.getUser(request); } catch (Exception nsue) { Logger.warn(this, "Exception trying getUser: "******"idInode", String.valueOf(id.getInode())); Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode()); Template template = null; Template hostVariablesTemplate = null; // creates the context where to place the variables response.setContentType(CHARSET); Context context = VelocityUtil.getWebContext(request, response); HTMLPage htmlPage = (HTMLPage) APILocator.getVersionableAPI() .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false); HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI(); // to check user has permission to write on this page boolean hasAddChildrenPermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, backendUser); boolean hasWritePermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, backendUser); boolean hasPublishPermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, backendUser); context.put("ADD_CHILDREN_HTMLPAGE_PERMISSION", new Boolean(hasAddChildrenPermOverHTMLPage)); context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage)); context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage)); context.put("canAddForm", new Boolean(LicenseUtil.getLevel() > 199 ? true : false)); context.put("canViewDiff", new Boolean(LicenseUtil.getLevel() > 199 ? true : false)); boolean canUserWriteOnTemplate = permissionAPI.doesUserHavePermission( htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, backendUser) && portletAPI.hasTemplateManagerRights(backendUser); context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate); com.dotmarketing.portlets.templates.model.Template cmsTemplate = com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate( htmlPage, true); if (cmsTemplate == null) { // DOTCMS-4051 cmsTemplate = new com.dotmarketing.portlets.templates.model.Template(); Logger.debug(VelocityServlet.class, "HTMLPAGE TEMPLATE NOT FOUND"); } Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate); Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode()); VelocityUtil.makeBackendContext( context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, true, false, host); // added to show tabs context.put("previewPage", "1"); // get the containers for the page and stick them in context List<Container> containers = APILocator.getTemplateAPI() .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false); for (Container c : containers) { context.put( String.valueOf("container" + c.getIdentifier()), "/working/" + c.getIdentifier() + "." + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION")); boolean hasWritePermissionOnContainer = permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, backendUser, false) && portletAPI.hasContainerManagerRights(backendUser); boolean hasReadPermissionOnContainer = permissionAPI.doesUserHavePermission(c, PERMISSION_READ, backendUser, false); context.put("EDIT_CONTAINER_PERMISSION" + c.getIdentifier(), hasWritePermissionOnContainer); if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true)) context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), true); else context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), hasReadPermissionOnContainer); // to check user has permission to write this container Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class); boolean hasWritePermOverTheStructure = permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, backendUser); context.put( "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure)); Logger.debug( VelocityServlet.class, String.valueOf("container" + c.getIdentifier()) + "=/working/" + c.getIdentifier() + "." + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION")); String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy(); List<Contentlet> contentlets = null; boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery()); // get contentlets only for main frame if (request.getParameter("mainFrame") != null) { if (staticContainer) { Logger.debug(VelocityServlet.class, "Static Container!!!!"); Logger.debug( VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode()); // The container doesn't have categories Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage); Identifier idenContainer = APILocator.getIdentifierAPI().find(c); contentlets = conAPI.findPageContentlets( idenHtmlPage.getInode(), idenContainer.getInode(), sort, true, -1, backendUser, true); Logger.debug( VelocityServlet.class, "Getting contentlets for language=" + (String) request .getSession() .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE) + " contentlets =" + contentlets.size()); } else { String luceneQuery = c.getLuceneQuery(); int limit = c.getMaxContentlets(); String sortBy = c.getSortContentletsBy(); int offset = 0; contentlets = conAPI.search(luceneQuery, limit, offset, sortBy, backendUser, true); } if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) { Set<String> contentletIdentList = new HashSet<String>(); List<Contentlet> contentletsFilter = new ArrayList<Contentlet>(); for (Contentlet cont : contentlets) { if (!contentletIdentList.contains(cont.getIdentifier())) { contentletIdentList.add(cont.getIdentifier()); contentletsFilter.add(cont); } } contentlets = contentletsFilter; } List<String> contentletList = new ArrayList<String>(); if (contentlets != null) { Iterator<Contentlet> iter = contentlets.iterator(); int count = 0; while (iter.hasNext() && (count < c.getMaxContentlets())) { count++; Contentlet contentlet = (Contentlet) iter.next(); Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet); boolean hasWritePermOverContentlet = permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, backendUser); context.put( "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(), new Boolean(hasWritePermOverContentlet)); contentletList.add(String.valueOf(contentletIdentifier.getInode())); Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode()); Structure contStructure = contentlet.getStructure(); if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) { Field field = contStructure.getFieldVar("widgetPreexecute"); if (field != null && UtilMethods.isSet(field.getValues())) { preExecuteCode.append(field.getValues().trim() + "\n"); widgetPreExecute = true; } } } } // sets contentletlist with all the files to load per // container context.put("contentletList" + c.getIdentifier(), contentletList); context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size())); // ### Add the structure fake contentlet ### if (contentletList.size() == 0) { Structure structure = ContainerFactory.getContainerStructure(c); contentletList.add(structure.getInode() + ""); // sets contentletlist with all the files to load per // container context.remove("contentletList" + c.getIdentifier()); context.remove("totalSize" + c.getIdentifier()); // http://jira.dotmarketing.net/browse/DOTCMS-2876 context.put("contentletList" + c.getIdentifier(), new long[0]); context.put("totalSize" + c.getIdentifier(), 0); } // ### END Add the structure fake contentlet ### } } Logger.debug( VelocityServlet.class, "Before finding template: /working/" + templateIdentifier.getInode() + "." + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION")); Logger.debug( VelocityServlet.class, "Velocity directory:" + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH)); if (request.getParameter("leftMenu") != null) { /* * try to get the messages from the session */ List<String> list = new ArrayList<String>(); if (SessionMessages.contains(request, "message")) { list.add((String) SessionMessages.get(request, "message")); SessionMessages.clear(request); } if (SessionMessages.contains(request, "custommessage")) { list.add((String) SessionMessages.get(request, "custommessage")); SessionMessages.clear(request); } if (list.size() > 0) { ArrayList<String> mymessages = new ArrayList<String>(); Iterator<String> it = list.iterator(); while (it.hasNext()) { try { String message = (String) it.next(); Company comp = PublicCompanyFactory.getDefaultCompany(); mymessages.add(LanguageUtil.get(comp.getCompanyId(), backendUser.getLocale(), message)); } catch (Exception e) { } } context.put("vmessages", mymessages); } template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl"); } else if (request.getParameter("mainFrame") != null) { hostVariablesTemplate = VelocityUtil.getEngine() .getTemplate( "/working/" + host.getIdentifier() + "." + Config.getStringProperty("VELOCITY_HOST_EXTENSION")); template = VelocityUtil.getEngine() .getTemplate( "/working/" + templateIdentifier.getInode() + "." + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION")); } else { // Return a resource not found right away if the page is not found, // not try to load the frames if (!InodeUtils.isSet(templateIdentifier.getInode())) throw new ResourceNotFoundException(""); template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl"); } PrintWriter out = response.getWriter(); request.setAttribute("velocityContext", context); try { if (widgetPreExecute) { VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString()); } if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out); template.merge(context, out); } catch (ParseErrorException e) { out.append(e.getMessage()); } }
@SuppressWarnings("unchecked") public void doPreviewMode(HttpServletRequest request, HttpServletResponse response) throws Exception { String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration()); uri = UtilMethods.cleanURI(uri); Host host = hostWebAPI.getCurrentHost(request); StringBuilder preExecuteCode = new StringBuilder(); Boolean widgetPreExecute = false; // Getting the user to check the permissions com.liferay.portal.model.User user = null; HttpSession session = request.getSession(false); try { if (session != null) user = (com.liferay.portal.model.User) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER); } catch (Exception nsue) { Logger.warn(this, "Exception trying getUser: "******"idInode", id.getInode()); Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode()); Template template = null; Template hostVariablesTemplate = null; // creates the context where to place the variables response.setContentType(CHARSET); Context context = VelocityUtil.getWebContext(request, response); HTMLPage htmlPage = (HTMLPage) APILocator.getVersionableAPI().findWorkingVersion(id, user, true); HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI(); // to check user has permission to write on this page boolean hasWritePermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, user); boolean hasPublishPermOverHTMLPage = permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, user); context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage)); context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage)); boolean canUserWriteOnTemplate = permissionAPI.doesUserHavePermission( htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, user, true); context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate); com.dotmarketing.portlets.templates.model.Template cmsTemplate = com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate( htmlPage, true); Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate); Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode()); VelocityUtil.makeBackendContext( context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, false, true, host); context.put("previewPage", "2"); context.put("livePage", "0"); // get the containers for the page and stick them in context List<Container> containers = APILocator.getTemplateAPI() .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false); for (Container c : containers) { context.put( String.valueOf("container" + c.getIdentifier()), "/working/" + c.getIdentifier() + "." + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION")); context.put( "EDIT_CONTAINER_PERMISSION" + c.getIdentifier(), permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, user, true)); // to check user has permission to write this container Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class); boolean hasWritePermOverTheStructure = permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, user, true); context.put( "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure)); Logger.debug( VelocityServlet.class, String.valueOf("container" + c.getIdentifier()) + "=/working/" + c.getIdentifier() + "." + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION")); String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy(); boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery()); List<Contentlet> contentlets = null; // get contentlets only for main frame if (request.getParameter("mainFrame") != null) { if (staticContainer) { Logger.debug(VelocityServlet.class, "Static Container!!!!"); Logger.debug( VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode()); // The container doesn't have categories Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage); Identifier idenContainer = APILocator.getIdentifierAPI().find(c); contentlets = conAPI.findPageContentlets( idenHtmlPage.getInode(), idenContainer.getInode(), sort, true, -1, user, true); Logger.debug( VelocityServlet.class, "Getting contentlets for language=" + (String) request .getSession() .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE) + " contentlets =" + contentlets.size()); } if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) { Set<String> contentletIdentList = new HashSet<String>(); List<Contentlet> contentletsFilter = new ArrayList<Contentlet>(); for (Contentlet cont : contentlets) { if (!contentletIdentList.contains(cont.getIdentifier())) { contentletIdentList.add(cont.getIdentifier()); contentletsFilter.add(cont); } } contentlets = contentletsFilter; } List<String> contentletList = new ArrayList<String>(); if (contentlets != null && contentlets.size() > 0) { Iterator<Contentlet> iter = contentlets.iterator(); int count = 0; while (iter.hasNext() && (count < c.getMaxContentlets())) { count++; Contentlet contentlet = (Contentlet) iter.next(); Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet); boolean hasWritePermOverContentlet = permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, user, true); context.put( "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(), new Boolean(hasWritePermOverContentlet)); contentletList.add(String.valueOf(contentletIdentifier.getInode())); Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode()); Structure contStructure = contentlet.getStructure(); if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) { Field field = contStructure.getFieldVar("widgetPreexecute"); if (field != null && UtilMethods.isSet(field.getValues())) { preExecuteCode.append(field.getValues().trim() + "\n"); widgetPreExecute = true; } } } } // sets contentletlist with all the files to load per // container context.put("contentletList" + c.getIdentifier(), contentletList); context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size())); } } Logger.debug( VelocityServlet.class, "Before finding template: /working/" + templateIdentifier.getInode() + "." + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION")); Logger.debug( VelocityServlet.class, "Velocity directory:" + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH)); if (request.getParameter("leftMenu") != null) { /* * try to get the messages from the session */ List<String> list = new ArrayList<String>(); if (SessionMessages.contains(request, "message")) { list.add((String) SessionMessages.get(request, "message")); SessionMessages.clear(request); } if (SessionMessages.contains(request, "custommessage")) { list.add((String) SessionMessages.get(request, "custommessage")); SessionMessages.clear(request); } if (list.size() > 0) { ArrayList<String> mymessages = new ArrayList<String>(); Iterator<String> it = list.iterator(); while (it.hasNext()) { try { String message = (String) it.next(); Company comp = PublicCompanyFactory.getDefaultCompany(); mymessages.add(LanguageUtil.get(comp.getCompanyId(), user.getLocale(), message)); } catch (Exception e) { } } context.put("vmessages", mymessages); } template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl"); } else if (request.getParameter("mainFrame") != null) { hostVariablesTemplate = VelocityUtil.getEngine() .getTemplate( "/working/" + host.getIdentifier() + "." + Config.getStringProperty("VELOCITY_HOST_EXTENSION")); template = VelocityUtil.getEngine() .getTemplate( "/working/" + templateIdentifier.getInode() + "." + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION")); } else { template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl"); } PrintWriter out = response.getWriter(); request.setAttribute("velocityContext", context); try { if (widgetPreExecute) { VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString()); } if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out); template.merge(context, out); } catch (ParseErrorException e) { out.append(e.getMessage()); } }
private void _saveStructure(ActionForm form, ActionRequest req, ActionResponse res) { try { boolean newStructure = false; StructureForm structureForm = (StructureForm) form; Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE); User user = _getUser(req); HttpServletRequest httpReq = ((ActionRequestImpl) req).getHttpServletRequest(); if (!UtilMethods.isSet(structureForm.getHost()) && (!UtilMethods.isSet(structureForm.getFolder()) || structureForm.getFolder().equals("SYSTEM_FOLDER"))) { throw new DotDataException(LanguageUtil.get(user, "Host-or-folder-is-required")); } // Checking permissions _checkWritePermissions(structure, user, httpReq); // Check if another structure with the same name exist String auxStructureName = structureForm.getName(); auxStructureName = (auxStructureName != null ? auxStructureName.trim() : ""); @SuppressWarnings("deprecation") Structure auxStructure = StructureCache.getStructureByType(auxStructureName); if (InodeUtils.isSet(auxStructure.getInode()) && !auxStructure.getInode().equalsIgnoreCase(structure.getInode())) { throw new DotDataException( LanguageUtil.get(user, "There-is-another-structure-with-the-same-name")); } Arrays.sort(reservedStructureNames); if (!InodeUtils.isSet(structureForm.getInode()) && (Arrays.binarySearch(reservedStructureNames, auxStructureName) >= 0)) { throw new DotDataException("Invalid Reserved Structure Name : " + auxStructureName); } // Validate if is a new structure and if the name hasn't change if (!InodeUtils.isSet(structure.getInode())) { newStructure = true; } else { String structureName = structure.getName(); String structureFormName = structureForm.getName(); if (UtilMethods.isSet(structureName) && UtilMethods.isSet(structureFormName) && !structureName.equals(structureFormName) && !structure.isFixed()) { StructureCache.removeStructure(structure); } } // If the structure is fixed the name cannot be changed if (structure.isFixed()) { structureForm.setName(structure.getName()); } // if I'm editing a structure the structureType couldn't not be // change if (UtilMethods.isSet(structure.getInode()) && InodeUtils.isSet(structure.getInode())) { // reset the structure type to it's original value structureForm.setStructureType(structure.getStructureType()); } if (UtilMethods.isSet(structure.getVelocityVarName())) { structureForm.setVelocityVarName(structure.getVelocityVarName()); } if (UtilMethods.isSet(structureForm.getHost())) { if (!structureForm.getHost().equals(Host.SYSTEM_HOST) && hostAPI.findSystemHost().getIdentifier().equals(structureForm.getHost())) { structureForm.setHost(Host.SYSTEM_HOST); } structureForm.setFolder("SYSTEM_FOLDER"); } else if (UtilMethods.isSet(structureForm.getFolder())) { structureForm.setHost(folderAPI.find(structureForm.getFolder(), user, false).getHostId()); } if (UtilMethods.isSet(structureForm.getHost()) && (!UtilMethods.isSet(structureForm.getFolder()) || structureForm.getFolder().equals("SYSTEM_FOLDER"))) { Host host = hostAPI.find(structureForm.getHost(), user, false); if (host != null) { if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { if (!perAPI.doesUserHavePermissions( host, "PARENT:" + PermissionAPI.PERMISSION_CAN_ADD_CHILDREN + ", STRUCTURES:" + PermissionAPI.PERMISSION_PUBLISH, user)) { throw new DotDataException( LanguageUtil.get( user, "User-does-not-have-add-children-permission-on-host-folder")); } } else { if (!perAPI.doesUserHavePermission( host, PermissionAPI.PERMISSION_CAN_ADD_CHILDREN, user)) { throw new DotDataException( LanguageUtil.get( user, "User-does-not-have-add-children-permission-on-host-folder")); } } } } if (UtilMethods.isSet(structureForm.getFolder()) && !structureForm.getFolder().equals("SYSTEM_FOLDER")) { Folder folder = folderAPI.find(structureForm.getFolder(), user, false); if (folder != null) { if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { if (!perAPI.doesUserHavePermissions( folder, "PARENT:" + PermissionAPI.PERMISSION_CAN_ADD_CHILDREN + ", STRUCTURES:" + PermissionAPI.PERMISSION_PUBLISH, user)) { throw new DotDataException( LanguageUtil.get( user, "User-does-not-have-add-children-permission-on-host-folder")); } } else { if (!perAPI.doesUserHavePermission( folder, PermissionAPI.PERMISSION_CAN_ADD_CHILDREN, user)) { throw new DotDataException( LanguageUtil.get( user, "User-does-not-have-add-children-permission-on-host-folder")); } } } } BeanUtils.copyProperties(structure, structureForm); // if htmlpage doesn't exist page id should be an identifier. Should // be refactored once we get identifierAPI/HTMLPage API done String pageDetail = structureForm.getDetailPage(); if (newStructure) { String structureVelocityName = VelocityUtil.convertToVelocityVariable(structure.getName(), true); List<String> velocityvarnames = StructureFactory.getAllVelocityVariablesNames(); int found = 0; if (VelocityUtil.isNotAllowedVelocityVariableName(structureVelocityName)) { found++; } for (String velvar : velocityvarnames) { if (velvar != null) { if (structureVelocityName.equalsIgnoreCase(velvar)) { found++; } else if (velvar.toLowerCase().contains(structureVelocityName.toLowerCase())) { String number = velvar.substring(structureVelocityName.length()); if (RegEX.contains(number, "^[0-9]+$")) { found++; } } } } if (found > 0) { structureVelocityName = structureVelocityName + Integer.toString(found); } structure.setVelocityVarName(structureVelocityName); } if (UtilMethods.isSet(pageDetail)) { structure.setDetailPage(pageDetail); } // Saving interval review properties if (structureForm.isReviewContent()) { structure.setReviewInterval( structureForm.getReviewIntervalNum() + structureForm.getReviewIntervalSelect()); } else { structure.setReviewInterval(null); structure.setReviewerRole(null); } // If there is no default structure this would be Structure defaultStructure = StructureFactory.getDefaultStructure(); if (!InodeUtils.isSet(defaultStructure.getInode())) { structure.setDefaultStructure(true); } if (newStructure) { structure.setFixed(false); structure.setOwner(user.getUserId()); } // validate iit is a form structure set it as system by default if (structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { structure.setSystem(true); } StructureFactory.saveStructure(structure); structureForm.setUrlMapPattern(structure.getUrlMapPattern()); WorkflowScheme scheme = APILocator.getWorkflowAPI().findSchemeForStruct(structure); String schemeId = req.getParameter("workflowScheme"); if (scheme != null && UtilMethods.isSet(schemeId) && !schemeId.equals(scheme.getId())) { scheme = APILocator.getWorkflowAPI().findScheme(schemeId); APILocator.getWorkflowAPI().saveSchemeForStruct(structure, scheme); } // if the structure is a widget we need to add the base fields. if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) { wAPI.createBaseWidgetFields(structure); } // if the structure is a form we need to add the base fields. if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FORM) { fAPI.createBaseFormFields(structure); } // if the structure is a form we need to add the base fields. if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FILEASSET) { APILocator.getFileAssetAPI().createBaseFileAssetFields(structure); } if (!newStructure) { perAPI.resetPermissionReferences(structure); } // Saving the structure in cache StructureCache.removeStructure(structure); StructureCache.addStructure(structure); StructureServices.removeStructureFile(structure); String message = "message.structure.savestructure"; if (structure.getStructureType() == 3) { message = "message.form.saveform"; } SessionMessages.add(req, "message", message); AdminLogger.log( EditStructureAction.class, "_saveStructure", "Structure saved : " + structure.getName(), user); } catch (Exception ex) { Logger.error(this.getClass(), ex.toString()); String message = ex.toString(); SessionMessages.add(req, "error", message); } }
public Map<String, Object> saveEvent(List<String> formData, boolean isAutoSave, boolean isCheckin) throws LanguageException, PortalException, SystemException, DotDataException, DotSecurityException, java.text.ParseException { HibernateUtil.startTransaction(); ContentletWebAPI contentletWebAPI = WebAPILocator.getContentletWebAPI(); int tempCount = 0; // To store multiple values opposite to a name. Ex: selected permissions & categories String newInode = ""; String referer = ""; String language = ""; String strutsAction = ""; String recurrenceDaysOfWeek = ""; Map<String, Object> contentletFormData = new HashMap<String, Object>(); Map<String, Object> callbackData = new HashMap<String, Object>(); List<String> saveContentErrors = new ArrayList<String>(); HttpServletRequest req = WebContextFactory.get().getHttpServletRequest(); User user = com.liferay.portal.util.PortalUtil.getUser((HttpServletRequest) req); List<Field> fields = com.dotmarketing.cache.FieldsCache.getFieldsByStructureInode( eventAPI.getEventStructure().getInode()); String titleField = ""; String urlTitleField = ""; String urlTitleFieldValue = ""; String titleFieldValue = ""; for (Field field : fields) { if (field.getVelocityVarName().equals("urlTitle")) { urlTitleField = field.getFieldContentlet(); } if (field.getVelocityVarName().equals("title")) { titleField = field.getFieldContentlet(); } if (UtilMethods.isSet(titleField) && UtilMethods.isSet(urlTitleField)) { break; } } // get the struts_action from the form data for (Iterator<String> iterator = formData.iterator(); iterator.hasNext(); ) { String element = iterator.next(); if (element != null) { String elementName = element.substring(0, element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR)); if (elementName.startsWith("_EXT") && elementName.endsWith("cmd")) { strutsAction = elementName.substring(0, elementName.indexOf("cmd")); break; } } } // Storing form data into map. for (Iterator<String> iterator = formData.iterator(); iterator.hasNext(); ) { String element = iterator.next(); if (!com.dotmarketing.util.UtilMethods.isSet(element)) continue; String elementName = element.substring(0, element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR)); Object elementValue = element.substring( element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR) + WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR.length()); if (element.startsWith(strutsAction)) elementName = elementName.substring(elementName.indexOf(strutsAction) + strutsAction.length()); // Placed increments as Map holds unique keys. if (elementName.equals("read") || elementName.equals("write") || elementName.equals("publish")) { tempCount++; elementName = "selected_permission_" + tempCount + elementName; } if (elementName.equals(titleField)) { titleFieldValue = (String) elementValue; } if (elementName.equals(urlTitleField)) { urlTitleFieldValue = (String) elementValue; } if (elementName.equals("categories")) { tempCount++; elementName = elementName + tempCount + "_"; } // http://jira.dotmarketing.net/browse/DOTCMS-3232 if (elementName.equalsIgnoreCase("hostId")) { callbackData.put("hostOrFolder", true); } if (elementName.startsWith("binary")) { String binaryFileValue = (String) elementValue; if (UtilMethods.isSet(binaryFileValue) && !binaryFileValue.equals("---removed---")) { binaryFileValue = ContentletUtil.sanitizeFileName(binaryFileValue); File binaryFile = new File( APILocator.getFileAPI().getRealAssetPathTmpBinary() + File.separator + user.getUserId() + File.separator + elementName + File.separator + binaryFileValue); if (binaryFile.exists()) binaryFile.delete(); elementValue = binaryFile; } else { elementValue = null; } } if (!UtilMethods.isSet(elementName)) continue; if (elementValue == null) elementValue = ""; if (elementName.equals("referer")) referer = (String) elementValue; if (elementName.equals("languageId")) language = (String) elementValue; if (elementName.equals("recurrenceDaysOfWeek")) { recurrenceDaysOfWeek = recurrenceDaysOfWeek + elementValue + ","; } contentletFormData.put(elementName, elementValue); } contentletFormData.put("recurrenceDaysOfWeek", recurrenceDaysOfWeek); if (!UtilMethods.isSet(urlTitleFieldValue) && UtilMethods.isSet(titleFieldValue)) { urlTitleFieldValue = titleFieldValue.toLowerCase(); urlTitleFieldValue = urlTitleFieldValue.replace("/^\\s+|\\s+$/g", ""); urlTitleFieldValue = urlTitleFieldValue.replace("/[^a-zA-Z 0-9]+/g", " "); urlTitleFieldValue = urlTitleFieldValue.replace("/\\s/g", "-"); while (urlTitleFieldValue.indexOf("--") > -1) { urlTitleFieldValue = urlTitleFieldValue.replace("--", "-"); } contentletFormData.put(urlTitleField, urlTitleFieldValue); } String d1 = (String) contentletFormData.get("date1"); String d2 = (String) contentletFormData.get("date2"); String d3 = (String) contentletFormData.get("recurrenceEnds"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd"); Date eventStartDate = null; Date eventEndDate = null; Date recurrenceEndDate = null; try { eventStartDate = df.parse(d1); eventEndDate = df.parse(d2); if (UtilMethods.isSet(d3)) { recurrenceEndDate = df2.parse(d3); } } catch (java.text.ParseException e1) { } Boolean cont = true; if (eventEndDate.before(eventStartDate)) { String errorString = LanguageUtil.get(user, "message.event.endate.before.stardate"); saveContentErrors.add(errorString); } if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) { if (contentletFormData.get("noEndDate") == null || !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString())) { if (recurrenceEndDate != null && recurrenceEndDate.before(eventStartDate)) { String errorString = LanguageUtil.get(user, "message.event.recurrence.endate.before.stardate"); saveContentErrors.add(errorString); } } } Calendar start = Calendar.getInstance(); start.setTime(eventStartDate); Calendar end = Calendar.getInstance(); end.setTime(eventEndDate); if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) { if (end.after(start) && (end.get(Calendar.DAY_OF_MONTH) > start.get(Calendar.DAY_OF_MONTH) || end.get(Calendar.MONTH) > start.get(Calendar.MONTH) || end.get(Calendar.YEAR) > start.get(Calendar.YEAR))) { contentletFormData.put("recurrenceOccurs", "never"); } } if (Boolean.parseBoolean(contentletFormData.get("recurrenceChanged").toString())) { if (!UtilMethods.isSet(contentletFormData.get("recurrenceInterval"))) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.interval"); saveContentErrors.add(errorString); } else { try { Long.valueOf((String) contentletFormData.get("recurrenceInterval")); } catch (NumberFormatException nfe) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.interval"); saveContentErrors.add(errorString); } } if (contentletFormData.get("recurrenceOccurs").toString().equals("monthly")) { if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString()) && !UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth"))) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth"); saveContentErrors.add(errorString); } if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString()) && UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth"))) { try { Long.valueOf((String) contentletFormData.get("recurrenceDayOfMonth")); } catch (Exception e) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth"); saveContentErrors.add(errorString); } } else { contentletFormData.put("recurrenceDayOfMonth", "0"); } } if (contentletFormData.get("recurrenceOccurs").toString().equals("annually")) { if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString()) && !UtilMethods.isSet((String) contentletFormData.get("specificDayOfMonthRecY")) && !UtilMethods.isSet((String) contentletFormData.get("specificMonthOfYearRecY"))) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.date"); saveContentErrors.add(errorString); } if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString()) && UtilMethods.isSet((String) contentletFormData.get("specificDayOfMonthRecY")) && UtilMethods.isSet((String) contentletFormData.get("specificMonthOfYearRecY"))) { try { Long.valueOf((String) contentletFormData.get("specificDayOfMonthRecY")); contentletFormData.put( "recurrenceDayOfMonth", (String) contentletFormData.get("specificDayOfMonthRecY")); } catch (Exception e) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth"); saveContentErrors.add(errorString); } try { Long.valueOf((String) contentletFormData.get("specificMonthOfYearRecY")); contentletFormData.put( "recurrenceMonthOfYear", (String) contentletFormData.get("specificMonthOfYearRecY")); } catch (Exception e) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.monthofyear"); saveContentErrors.add(errorString); } } else { contentletFormData.put("recurrenceDayOfMonth", "0"); } } } if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) { if (contentletFormData.get("noEndDate") == null || (contentletFormData.get("noEndDate") != null && !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString()))) { if (!UtilMethods.isSet((String) contentletFormData.get("recurrenceEnds"))) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.enddate"); saveContentErrors.add(errorString); } else { try { eventRecurrenceEndDateF.parse((String) contentletFormData.get("recurrenceEnds")); } catch (Exception e) { String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.enddate"); saveContentErrors.add(errorString); } } } } // http://jira.dotmarketing.net/browse/DOTCMS-6327 if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) { if (contentletFormData.get("noEndDate") == null || !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString())) { Integer interval = UtilMethods.isSet((String) contentletFormData.get("recurrenceInterval")) ? Integer.valueOf((String) contentletFormData.get("recurrenceInterval")) : null; Integer recurrenceWeekOfMonth = UtilMethods.isSet((String) contentletFormData.get("recurrenceWeekOfMonth")) ? Integer.valueOf((String) contentletFormData.get("recurrenceWeekOfMonth")) : null; Integer recurrenceDayOfWeek = UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfWeek")) ? Integer.valueOf((String) contentletFormData.get("recurrenceDayOfWeek")) : null; Integer recurrenceMonthOfYear = UtilMethods.isSet((String) contentletFormData.get("recurrenceMonthOfYear")) ? Integer.valueOf((String) contentletFormData.get("recurrenceMonthOfYear")) : null; Integer recurrenceDayOfMonth = UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth")) ? Integer.valueOf((String) contentletFormData.get("recurrenceDayOfMonth")) : null; Occurrency occurency = Occurrency.findOcurrency((String) contentletFormData.get("recurrenceOccurs")); if (occurency != null) { Calendar firstOccurence = RecurrenceUtil.calculateFirstOccurence( eventStartDate, interval, occurency, recurrenceDaysOfWeek, recurrenceWeekOfMonth, recurrenceDayOfWeek, recurrenceMonthOfYear, recurrenceDayOfMonth); if (recurrenceEndDate.before(firstOccurence.getTime())) { String errorString = LanguageUtil.get(user, "message.event.recurrence.before.occurence"); saveContentErrors.add(errorString); } } } } try { if (cont && (saveContentErrors == null || saveContentErrors.isEmpty())) { newInode = contentletWebAPI.saveContent(contentletFormData, isAutoSave, isCheckin, user); } } catch (DotContentletValidationException ve) { if (ve.hasRequiredErrors()) { List<Field> reqs = ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_REQUIRED); for (Field field : reqs) { String errorString = LanguageUtil.get(user, "message.contentlet.required"); errorString = errorString.replace("{0}", field.getFieldName()); saveContentErrors.add(errorString); } } if (ve.hasLengthErrors()) { List<Field> reqs = ve.getNotValidFields() .get(DotContentletValidationException.VALIDATION_FAILED_MAXLENGTH); for (Field field : reqs) { String errorString = LanguageUtil.get(user, "message.contentlet.maxlength"); errorString = errorString.replace("{0}", field.getFieldName()); errorString = errorString.replace("{1}", "225"); saveContentErrors.add(errorString); } } if (ve.hasPatternErrors()) { List<Field> reqs = ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_PATTERN); for (Field field : reqs) { String errorString = LanguageUtil.get(user, "message.contentlet.format"); errorString = errorString.replace("{0}", field.getFieldName()); saveContentErrors.add(errorString); } } if (ve.hasRelationshipErrors()) { StringBuffer sb = new StringBuffer("<br>"); Map<String, Map<Relationship, List<Contentlet>>> notValidRelationships = ve.getNotValidRelationship(); Set<String> auxKeys = notValidRelationships.keySet(); for (String key : auxKeys) { String errorMessage = ""; if (key.equals(DotContentletValidationException.VALIDATION_FAILED_REQUIRED_REL)) { errorMessage = "<b>Required Relationship</b>"; } else if (key.equals( DotContentletValidationException.VALIDATION_FAILED_INVALID_REL_CONTENT)) { errorMessage = "<b>Invalid Relationship-Contentlet</b>"; } else if (key.equals(DotContentletValidationException.VALIDATION_FAILED_BAD_REL)) { errorMessage = "<b>Bad Relationship</b>"; } sb.append(errorMessage + ":<br>"); Map<Relationship, List<Contentlet>> relationshipContentlets = notValidRelationships.get(key); for (Entry<Relationship, List<Contentlet>> relationship : relationshipContentlets.entrySet()) { sb.append(relationship.getKey().getRelationTypeValue() + ", "); } sb.append("<br>"); } sb.append("<br>"); // need to update message to support multiple relationship validation errors String errorString = LanguageUtil.get(user, "message.relationship.required_ext"); errorString = errorString.replace("{0}", sb.toString()); saveContentErrors.add(errorString); } if (ve.hasUniqueErrors()) { List<Field> reqs = ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_UNIQUE); for (Field field : reqs) { String errorString = LanguageUtil.get(user, "message.contentlet.unique"); errorString = errorString.replace("{0}", field.getFieldName()); saveContentErrors.add(errorString); } } if (ve.getMessage() .contains( "The content form submission data id different from the content which is trying to be edited")) { String errorString = LanguageUtil.get(user, "message.contentlet.invalid.form"); saveContentErrors.add(errorString); } } catch (DotSecurityException dse) { String errorString = LanguageUtil.get(user, "message.insufficient.permissions.to.save"); saveContentErrors.add(errorString); } catch (Exception e) { if (e.getMessage().equals(Constants.COMMON_ERROR)) { String errorString = LanguageUtil.get(user, "message.contentlet.save.error"); saveContentErrors.add(errorString); SessionMessages.clear(req.getSession()); } else { saveContentErrors.add(e.getLocalizedMessage()); } } finally { if (!isAutoSave && (saveContentErrors != null && saveContentErrors.size() > 0)) { callbackData.put("saveContentErrors", saveContentErrors); SessionMessages.clear(req.getSession()); } } if (InodeUtils.isSet(newInode)) callbackData.put("contentletInode", newInode); if (!isAutoSave && (saveContentErrors == null || saveContentErrors.size() == 0)) { Logger.debug(this, "AFTER PUBLISH LANGUAGE=" + language); if (UtilMethods.isSet(language) && referer.indexOf("language") > -1) { Logger.debug(this, "Replacing referer language=" + referer); referer = referer.replaceAll( "language=([0-9])*", com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE + "=" + language); Logger.debug(this, "Referer after being replaced=" + referer); } } boolean savingRecurrence = false; callbackData.put("referer", referer); HibernateUtil.commitTransaction(); if (UtilMethods.isSet(newInode) && !savingRecurrence) { if (!contAPI.isInodeIndexed(newInode)) { Logger.error(this, "Timed out while waiting for index to return"); } } return callbackData; }
public void executeAction( WorkflowProcessor processor, Map<String, WorkflowActionClassParameter> params) throws WorkflowActionFailureException { String tweatThis = null; try { tweatThis = processor.getWorkflowMessage(); if (!UtilMethods.isSet(tweatThis) && UtilMethods.isSet(params.get("fieldVar").getValue())) { tweatThis = processor.getContentlet().getStringProperty(params.get("fieldVar").getValue()); } if (UtilMethods.isSet(tweatThis)) { if (tweatThis.length() > 140) { String error = LanguageUtil.get( PublicCompanyFactory.getDefaultCompanyId(), PublicCompanyFactory.getDefaultCompany().getLocale(), "Tweet-too-long"); if (error.equals("Tweet-too-long")) { error = error.replaceAll("-", " "); } throw new DotValidationException(error); } String consumerKey = null, consumerSecret = null, password = null, userName = null, accessToken = null, accessTokenSecret = null; consumerKey = params.get("consumerKey").getValue(); consumerSecret = params.get("consumerSecret").getValue(); accessToken = params.get("accessToken").getValue(); accessTokenSecret = params.get("accessTokenSecret").getValue(); String path = APILocator.getContentletAPI() .getUrlMapForContentlet( processor.getContentlet(), APILocator.getUserAPI().getSystemUser(), false); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); Status stat = twitter.updateStatus(tweatThis); WorkflowComment comment = new WorkflowComment(); comment.setPostedBy(processor.getUser().getUserId()); comment.setComment("Tweeted: " + tweatThis + " twitterId:" + stat.getId()); comment.setWorkflowtaskId(processor.getTask().getId()); try { APILocator.getWorkflowAPI().saveComment(comment); } catch (DotDataException e) { Logger.error(CommentOnWorkflowActionlet.class, e.getMessage(), e); } } } catch (Exception e) { Logger.error(TwitterActionlet.class, e.getMessage()); throw new WorkflowActionFailureException(e.getMessage()); } }