Example usage for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext

List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext

Introduction

In this page you can find the example usage for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext.

Prototype

public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc)
        throws IllegalStateException 

Source Link

Document

Find the root WebApplicationContext for this web app, typically loaded via org.springframework.web.context.ContextLoaderListener .

Usage

From source file:org.fao.fenix.maps.web.rest.MapsRESTService.java

private String htmlCloseLeaflet(HttpServletRequest request, Boolean tiny, String width) {
    StringBuilder sb = new StringBuilder();
    if (tiny) {//from  ww  w  .  j a  v  a 2  s.  com
        String fullURL = request.getRequestURL().toString() + "?" + request.getQueryString().toString();
        fullURL += "&shared=false";
        String tinyURL = null;
        try {
            ServletContext servletContext = this.getServletConfig().getServletContext();
            WebApplicationContext wac = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(servletContext);
            TinyClient tinyClient = (TinyClient) wac.getBean("tinyClient");
            tinyURL = tinyClient.register(fullURL);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (tiny && tinyURL != null) {
            sb.append("<table width='").append(width).append("'><tr>");
            sb.append("<td align='right' style='color: #3E576F; font-family: verdana; font-size: 16px;'>");
            sb.append("Share This Map: <INPUT SIZE='27' TYPE='TEXT' VALUE='" + tinyURL + "'></td>");
            sb.append("</tr></table>");
        }
    }
    sb.append("</body></html>");
    return sb.toString();
}

From source file:com.edgenius.wiki.webapp.servlet.InstallServlet.java

private UpgradeService getUpgradeService() {

    ApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    return (UpgradeService) ctx.getBean(UpgradeService.SERVICE_NAME);
}

From source file:no.kantega.publishing.admin.content.InputScreenRenderer.java

public InputScreenRenderer(PageContext pageContext, Content content, AttributeDataType attributeDataType) {
    this.pageContext = pageContext;
    this.content = content;
    this.attributeType = attributeDataType;
    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(pageContext.getServletContext());
    contentTemplateAO = context.getBean(ContentTemplateAO.class);
}

From source file:no.kantega.publishing.api.taglibs.util.BylineTag.java

private static Content content(PageContext pageContext) throws NotAuthorizedException {
    try {/*from  w ww .jav a2 s.co m*/
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        Content content = (Content) request.getAttribute("aksess_this");
        if (content == null) {
            if (contentIdHelper == null) {
                contentIdHelper = WebApplicationContextUtils
                        .getRequiredWebApplicationContext(pageContext.getServletContext())
                        .getBean(ContentIdHelper.class);
            }
            ContentIdentifier ci = contentIdHelper.fromRequest(request);
            content = new ContentManagementService(request).getContent(ci, true);
            RequestHelper.setRequestAttributes(request, content);
        }
        return content;
    } catch (ContentNotFoundException e) {
        return null; // Not an error
    }
}

From source file:no.kantega.publishing.api.taglibs.util.GetOrgUnitTag.java

@Override
public void setPageContext(PageContext pageContext) {
    super.setPageContext(pageContext);
    Map<String, OrganizationManager> organizationManagerMap = WebApplicationContextUtils
            .getRequiredWebApplicationContext(pageContext.getServletContext())
            .getBeansOfType(OrganizationManager.class);
    organizationManagers = organizationManagerMap.values();
}

From source file:no.kantega.publishing.api.taglibs.util.GetUrlTag.java

private void addSiteIdIfInAdminMode(StringBuilder urlBuilder, HttpServletRequest request) {
    if (HttpHelper.isAdminMode(request)) {
        try {/*from  w ww . j a  v a2 s  . c  o m*/
            if (contentIdHelper == null) {
                contentIdHelper = WebApplicationContextUtils
                        .getRequiredWebApplicationContext(pageContext.getServletContext())
                        .getBean(ContentIdHelper.class);
            }
            ContentIdentifier cid = contentIdHelper.fromRequestAndUrl(request, getUrlWithLeadingSlash(url));
            if (!url.contains("?")) {
                urlBuilder.append("?siteId=").append(cid.getSiteId());
            } else {
                urlBuilder.append("&siteId=").append(cid.getSiteId());
            }

        } catch (ContentNotFoundException e) {
            log.debug(e.getMessage());
        }
    }
}

From source file:no.kantega.publishing.api.taglibs.util.GetUrlTag.java

private void initUrlPlaceholderResolverIfNull() {
    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(pageContext.getServletContext());
    urlPlaceholderResolver = context.getBean(UrlPlaceholderResolver.class);
}

From source file:org.agnitas.web.MailingBaseAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//from   w  w w.  j a va  2  s . c  om
 * <br>
* ACTION_LIST: Initializes columns width list for the mailings-list-table, forwards to "list"
* <br><br>
* ACTION_SAVE: validates character encoding in mailing subject, mailing components and content blocks;
 *     saves mailing in database;
 *     if the current mailing is template - updates all mailings using this template with dynamic-template
 *     property set and saves these mailings to database;
 *     loads saved mailing into form;
 *     if the mailing was cloned and the original mailing has cms data, clones cms data for the saved mailing;
 *     forwards to "view".
* <br><br>
 * ACTION_VIEW: loads mailing data from database into a form, forwards to "view". Also resets showTemplate property
 *     of form which indicates if new need to show the template-section of a mailing.
 * <br><br>
 * ACTION_NEW: checks if there is at least one mailinglist in database: shows error message if no mailing list was found,
 *     if the mailinglist exists - clears the form and forwards to "view".
 * <br><br>
 * ACTION_REMOVE_TARGET: removes given target group from the list of chosen target groups; forwards to "view".
 * <br><br>
 * ACTION_SELECT_TEMPLATE: loads the settings of chosen template into current form (mailing type, mailinglist,
 *     target-groups etc.); doesn't save mailing to database; forwards to "view".
 * <br><br>
 * ACTION_CLONE_AS_MAILING: clears the form; sets the properties of original mailing to form (original mailing
 *     is mailing used as source for cloning); names the new mailing as "Copy of " + name of original; stores
 *     the id of original mailing in form as templateID; forwards to mailing view page.
 * <br><br>
 * ACTION_USED_ACTIONS: loads map of emm actions used by current mailing into form; forwards to mailing actions
 *     page (forward is "action").
 * <br><br>
 * ACTION_VIEW_WITHOUT_LOAD: just forwards to "view" without reloading form data (is used after failing form
 *     validation).
 * <br><br>
* ACTION_CONFIRM_DELETE: loads mailing into form; forwards to jsp with question to confirm deletion (forward
 *     is "delete").
* <br><br>
* ACITON_DELETE: marks the mailing as deleted in database; forwards to "list".
* <br><br>
* Any other ACTION_* would cause a forward to "list"
 * <br><br>
 * If destination is "list" - calls a FutureHolder to get the list of mailings/templates according to selected
 * mailing types and isTemplate form-property (indicates if we we work with templates or mailings). <br>
 * If the Future object is not ready, increases the page refresh time by 50ms until it reaches 1 second.
 * (The page refresh time - is the wait-time before calling the action again while the FutureHolder is
 * running; the initial value is 250ms). While the FutureHolder is running - destination is "loading".<br>
 * When the FutureHolder is finished - the list of mailings/templates is set to request, the destination is "list".
 * <br><br>
 * If destination is "view": updates oldMailFormat property with the current value;<br>
 * loads list of templates and template name to form;<br>
 * loads mailinglists, campaigns, target groups and selected target groups into form.
 * <br><br>
 * If destination is null and there are errors found - forwards to "list"
 * @param form  ActionForm object
 * @param req   request
 * @param res   response
 * @param mapping The ActionMapping used to select this instance
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 * @return destination
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws IOException, ServletException {

    // Validate the request parameters specified by the user
    MailingBaseForm aForm = null;
    ActionMessages errors = new ActionMessages();
    ActionMessages messages = new ActionMessages();
    ActionForward destination = null;
    boolean showTemplates = false;
    ApplicationContext aContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(req.getSession().getServletContext());

    if (!AgnUtils.isUserLoggedIn(req)) {
        return mapping.findForward("logon");
    }

    aForm = (MailingBaseForm) form;

    AgnUtils.logger().info("execute: action " + aForm.getAction());

    boolean hasAnyPermission = true;

    if (aForm.isIsTemplate()) {
        if (!allowed("template.show", req)) {
            errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
            saveErrors(req, errors);
            hasAnyPermission = false;
            //return null;
        }
    } else {
        if (!allowed("mailing.show", req)) {
            errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
            saveErrors(req, errors);
            hasAnyPermission = false;
            //return null;
        }
    }

    req.setAttribute("hasPermission", hasAnyPermission);

    if (hasAnyPermission) {

        if (aForm.getAction() != MailingBaseAction.ACTION_SAVE) {
            aForm.setOriginalMailingId(0);
        }

        try {
            switch (aForm.getAction()) {
            case MailingBaseAction.ACTION_LIST:
                if (aForm.getColumnwidthsList() == null) {
                    aForm.setColumnwidthsList(getInitializedColumnWidthList(5));
                }
                destination = mapping.findForward("list");
                break;
            case MailingBaseAction.ACTION_NEW:
                if (allowed("mailing.new", req)) {
                    List mlists = mailinglistDao.getMailinglists(getCompanyID(req));

                    if (mlists.size() > 0) {
                        aForm.setAction(MailingBaseAction.ACTION_SAVE);
                        int campaignID = aForm.getCampaignID();
                        aForm.clearData(getCompanyID(req), getDefaultMediaType(req));
                        aForm.setMailingID(0);
                        aForm.setCampaignID(campaignID);
                        destination = mapping.findForward("view");
                    } else {
                        errors.add(ActionErrors.GLOBAL_MESSAGE,
                                new ActionMessage("error.mailing.noMailinglist"));
                    }
                } else {
                    errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
                }
                break;

            case MailingBaseAction.ACTION_VIEW:
                aForm.setAction(MailingBaseAction.ACTION_SAVE);
                resetShowTemplate(req, aForm);
                loadMailing(aForm, req);
                destination = mapping.findForward("view");
                break;

            case MailingBaseAction.ACTION_VIEW_WITHOUT_LOAD:
                aForm.setAction(MailingBaseAction.ACTION_SAVE);
                destination = mapping.findForward("view");
                break;

            case MailingBaseAction.ACTION_REMOVE_TARGET:
                removeTarget(aForm, req);
                aForm.setAction(MailingBaseAction.ACTION_SAVE);
                destination = mapping.findForward("view");
                break;

            case MailingBaseAction.ACTION_SAVE:
                if (allowed("mailing.change", req)) {
                    destination = mapping.findForward("view");

                    try {
                        validateMailing(aForm, req);
                    } catch (CharacterEncodingValidationException e) {
                        if (!e.isSubjectValid())
                            errors.add(ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage("error.charset.subject"));
                        for (String mailingComponent : e.getFailedMailingComponents())
                            errors.add(ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage("error.charset.component", mailingComponent));
                        for (String dynTag : e.getFailedDynamicTags())
                            errors.add(ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage("error.charset.content", dynTag));
                    }

                    try {
                        saveMailing(aForm, req, messages);
                        loadMailing(aForm, req);
                        // Show "changes saved"
                        messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("default.changes_saved"));
                    } catch (AgnTagException e) {
                        req.setAttribute("errorReport", e.getReport());
                        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.template.dyntags"));
                    } catch (TransientDataAccessResourceException e) {
                        AgnUtils.logger().error("execute: " + e + "\n" + AgnUtils.getStackTrace(e));
                        errors.add(ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage("error.hibernate.attachmentTooLarge"));
                    }

                    showTemplates = aForm.isShowTemplate();
                    aForm.setShowTemplate(showTemplates);

                    // copy CMS data of cloned mailing if the original
                    // mailing included CMS content
                    if (aForm.getOriginalMailingId() != 0) {
                        if (CmsUtils.mailingHasCmsData(aForm.getOriginalMailingId(), aContext)) {
                            CmsUtils.cloneMailingCmsData(aForm.getOriginalMailingId(), aForm.getMailingID(),
                                    aContext);
                        }
                        aForm.setOriginalMailingId(0);
                    }

                } else {
                    errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
                }
                break;

            case MailingBaseAction.ACTION_SELECT_TEMPLATE:
                loadTemplateSettings(aForm, req);
                aForm.setAction(MailingBaseAction.ACTION_SAVE);
                destination = mapping.findForward("view");
                break;

            case MailingBaseAction.ACTION_CLONE_AS_MAILING:
                if (allowed("mailing.copy", req)) {
                    aForm.setOriginalMailingId(aForm.getMailingID());
                    int tmpTemplateID = aForm.getMailingID();
                    int tmpMlId = aForm.getMailinglistID();
                    String sname = aForm.getShortname();
                    int tmpFormat = aForm.getMediaEmail().getMailFormat();
                    boolean tmpl = aForm.isIsTemplate();
                    String tempDescription = aForm.getDescription();
                    aForm.clearData(this.getCompanyID(req), this.getDefaultMediaType(req));
                    aForm.setTemplateID(tmpTemplateID);
                    aForm.setIsTemplate(tmpl);
                    loadTemplateSettings(aForm, req);
                    aForm.setMailinglistID(tmpMlId);
                    aForm.getMediaEmail().setMailFormat(tmpFormat);
                    aForm.setMailingID(0);
                    aForm.setAction(MailingBaseAction.ACTION_SAVE);
                    aForm.setShortname(SafeString.getLocaleString("mailing.CopyOf",
                            (Locale) req.getSession().getAttribute(Globals.LOCALE_KEY)) + " " + sname);
                    //                        aForm.setDescription(SafeString.getLocaleString("default.description", (Locale)req.getSession().getAttribute(Globals.LOCALE_KEY)));
                    aForm.setDescription(tempDescription);
                    aForm.setCopyFlag(true);
                    destination = mapping.findForward("view");
                } else {
                    errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
                }
                break;

            case MailingBaseAction.ACTION_CONFIRM_DELETE:
                if (allowed("mailing.delete", req)) {
                    aForm.setAction(MailingBaseAction.ACTION_DELETE);
                    loadMailing(aForm, req);
                    destination = mapping.findForward("delete");
                } else {
                    errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
                }
                break;

            case MailingBaseAction.ACTION_DELETE:
                if (allowed("mailing.delete", req)) {
                    aForm.setAction(MailingBaseAction.ACTION_LIST);
                    deleteMailing(aForm, req);
                    destination = mapping.findForward("list");

                    messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("default.changes_saved"));
                    aForm.setMessages(messages);
                } else {
                    errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
                }
                break;

            case MailingBaseAction.ACTION_USED_ACTIONS:
                loadActions(aForm, req);
                destination = mapping.findForward("action");
                break;

            default:
                aForm.setAction(MailingBaseAction.ACTION_LIST);
                destination = mapping.findForward("list");
            }

        } catch (Exception e) {
            AgnUtils.logger().error("execute: " + e + "\n" + AgnUtils.getStackTrace(e));
            errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.exception"));
        }

        if (destination != null && "list".equals(destination.getName())) {
            try {
                setNumberOfRows(req, aForm);
                destination = mapping.findForward("loading");
                String key = FUTURE_TASK + "@" + req.getSession(false).getId();

                if (!futureHolder.containsKey(key)) {
                    Future mailingListFuture = getMailingListFuture(req, aForm.getTypes(), aForm.isIsTemplate(),
                            aForm);
                    futureHolder.put(key, mailingListFuture);
                }

                if (futureHolder.containsKey(key) && futureHolder.get(key).isDone()) {
                    req.setAttribute("mailinglist", futureHolder.get(key).get());
                    destination = mapping.findForward("list");
                    futureHolder.remove(key);
                    aForm.setRefreshMillis(RecipientForm.DEFAULT_REFRESH_MILLIS);
                    saveMessages(req, aForm.getMessages());
                    saveErrors(req, aForm.getErrors());
                    aForm.setMessages(null);
                    aForm.setErrors(null);
                } else {
                    if (aForm.getRefreshMillis() < 1000) { // raise the refresh time
                        aForm.setRefreshMillis(aForm.getRefreshMillis() + 50);
                    }
                    aForm.setError(false);
                }

            } catch (Exception e) {
                AgnUtils.logger().error("getMailingList: " + e + "\n" + AgnUtils.getStackTrace(e));
                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.exception"));
                aForm.setError(true); // do not refresh when an error has been occurred
            }
        }

        checkShowDynamicTemplateCheckbox(aForm, req);

        if (destination != null && "view".equals(destination.getName())) {
            if (aForm.getMediaEmail() != null) {
                aForm.setOldMailFormat(aForm.getMediaEmail().getMailFormat());
            }
            aForm.setTemplateMailingBases(mailingDao.getTemplateMailingsByCompanyID(getCompanyID(req)));
            if (aForm.getTemplateID() != 0) {
                MailingBase mb = mailingDao.getMailingForTemplateID(aForm.getTemplateID(), getCompanyID(req));
                aForm.setTemplateShortname(mb.getShortname().compareTo("") != 0 ? mb.getShortname()
                        : SafeString.getLocaleString("mailing.No_Template",
                                (Locale) req.getSession().getAttribute(Globals.LOCALE_KEY)));
            } else
                aForm.setTemplateShortname(SafeString.getLocaleString("mailing.No_Template",
                        (Locale) req.getSession().getAttribute(Globals.LOCALE_KEY)));

            aForm.setMailingLists(mailinglistDao.getMailinglists(getCompanyID(req)));
            aForm.setCampaigns(campaignDao.getCampaignList(getCompanyID(req), "lower(shortname)", 1));
            aForm.setTargetGroupsList(targetDao.getTargetGroup(getCompanyID(req), aForm.getTargetGroups()));
            aForm.setTargets(targetDao.getUnchoosenTargets(getCompanyID(req), aForm.getTargetGroups()));
        }
    }

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        saveErrors(req, errors);
        if (destination == null) {
            destination = mapping.findForward("list");
        }
    }

    // Report any message (non-errors) we have discovered
    if (!messages.isEmpty()) {
        saveMessages(req, messages);
    }

    return destination;
}

From source file:org.agnitas.web.MailingBaseAction.java

/**
 * Loads mailing data from db./*from  w  ww  .  j  a  v a  2 s . co  m*/
 *
 * @param aForm  MailingBaseForm object
 * @param req request
 * @throws Exception
 */
protected void loadMailing(MailingBaseForm aForm, HttpServletRequest req) throws Exception {
    MediatypeEmail type = null;
    MailingComponent comp = null;
    Mailing aMailing = mailingDao.getMailing(aForm.getMailingID(), getCompanyID(req));
    ApplicationContext aContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(req.getSession().getServletContext());
    if (aMailing == null) {
        aMailing = mailingFactory.newMailing();
        aMailing.init(getCompanyID(req), aContext);
        aMailing.setId(0);
        aForm.setMailingID(0);
    }

    aForm.setShortname(aMailing.getShortname());
    aForm.setDescription(aMailing.getDescription());
    aForm.setMailingType(aMailing.getMailingType());
    aForm.setMailinglistID(aMailing.getMailinglistID());
    aForm.setTemplateID(aMailing.getMailTemplateID());
    aForm.setTargetGroups(aMailing.getTargetGroups());
    aForm.setMediatypes(aMailing.getMediatypes());
    aForm.setArchived(aMailing.getArchived() != 0);
    aForm.setCampaignID(aMailing.getCampaignID());
    aForm.setTargetMode(aMailing.getTargetMode());
    aForm.setWorldMailingSend(aMailing.isWorldMailingSend());
    aForm.setUseDynamicTemplate(aMailing.getUseDynamicTemplate());

    type = aMailing.getEmailParam();
    if (type != null) {
        aForm.setEmailSubject(type.getSubject());
        aForm.setEmailOnepixel(type.getOnepixel());
        try {
            aForm.setEmailReplytoEmail(new InternetAddress(type.getReplyAdr()).getAddress());
        } catch (Exception e) {
            // do nothing
        }
        try {
            aForm.setEmailReplytoFullname(new InternetAddress(type.getReplyAdr()).getPersonal());
        } catch (Exception e) {
            // do nothing
        }
        aForm.setEmailLinefeed(type.getLinefeed());
        aForm.setEmailCharset(type.getCharset());
    }

    comp = aMailing.getTextTemplate();
    if (comp != null) {
        aForm.setTextTemplate(comp.getEmmBlock());
    }

    comp = aMailing.getHtmlTemplate();
    if (comp != null) {
        aForm.setHtmlTemplate(comp.getEmmBlock());
    }

    String entityName = aMailing.isIsTemplate() ? "template" : "mailing";
    AgnUtils.userlogger().info(
            AgnUtils.getAdmin(req).getUsername() + ": do load " + entityName + " " + aMailing.getShortname());

    AgnUtils.logger().info("loadMailing: mailing loaded");
}

From source file:org.agnitas.web.MailingBaseAction.java

/**
 * Saves current mailing in DB (including mailing components, content blocks, dynamic tags, dynamic tags contents
 * and trackable links)//  w ww .j  a v  a 2 s  . co  m
 *
 * @param aForm MailingBaseForm object
 * @param req  request
 * @param messages  not in use
 * @throws Exception
 */
protected void saveMailing(MailingBaseForm aForm, HttpServletRequest req, ActionMessages messages)
        throws Exception {
    Mailing aMailing = null;
    Mailing aTemplate = null;
    MediatypeEmail paramEmail = null;
    boolean newMail = false;
    ApplicationContext aContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(req.getSession().getServletContext());

    if (aForm.getMailingID() != 0) {
        aMailing = mailingDao.getMailing(aForm.getMailingID(), this.getCompanyID(req));
    } else {
        newMail = true;
        if (aForm.getTemplateID() != 0) {
            aTemplate = mailingDao.getMailing(aForm.getTemplateID(), this.getCompanyID(req));
            aMailing = (Mailing) aTemplate.clone(aContext);
            aMailing.setId(0);
            aMailing.setMailTemplateID(aForm.getTemplateID());
            aMailing.setCompanyID(this.getCompanyID(req));
        }
    }

    if (aMailing == null) {
        aMailing = mailingFactory.newMailing();
        aMailing.init(this.getCompanyID(req), aContext);
        aMailing.setId(0);
        aForm.setMailingID(0);
    }

    if (aForm.getMediaEmail().getMailFormat() == 0) {
        aForm.getMediaEmail().setHtmlTemplate("");
    } else if (aForm.getOldMailFormat() == 0) {
        if (aForm.getMediaEmail() != null && StringUtils.isEmpty(aForm.getMediaEmail().getHtmlTemplate())) {
            aForm.getMediaEmail().setHtmlTemplate("[agnDYN name=\"HTML-Version\"/]");
        }
    }

    aMailing.setIsTemplate(aForm.isIsTemplate());
    aMailing.setCampaignID(aForm.getCampaignID());
    aMailing.setDescription(aForm.getDescription());
    aMailing.setShortname(aForm.getShortname());
    aMailing.setMailinglistID(aForm.getMailinglistID());
    aMailing.setMailingType(aForm.getMailingType());
    aMailing.setArchived(aForm.isArchived() ? 1 : 0);
    aMailing.setTargetMode(aForm.getTargetMode());
    aMailing.setTargetGroups(aForm.getTargetGroups());
    aMailing.setMediatypes(aForm.getMediatypes());
    aMailing.setUseDynamicTemplate(aForm.getUseDynamicTemplate());

    try {
        paramEmail = aMailing.getEmailParam();

        paramEmail.setSubject(aForm.getEmailSubject());
        paramEmail.setLinefeed(aForm.getEmailLinefeed());
        paramEmail.setCharset(aForm.getEmailCharset());
        paramEmail.setOnepixel(aForm.getEmailOnepixel());

        aForm.getMediaEmail().syncTemplate(aMailing, aContext);

        aMailing.buildDependencies(true, aContext);
    } catch (Exception e) {
        AgnUtils.logger()
                .error("Error in save mailing id: " + aForm.getMailingID() + " msg: " + e.getMessage());
    }

    // validate the components
    if (!newMail) {
        Set<Entry<String, MailingComponent>> componentEntries = aMailing.getComponents().entrySet();
        List<String[]> errorReports = new ArrayList<String[]>();
        Vector<String> outFailures = new Vector<String>();
        TAGCheck tagCheck = tagCheckFactory.createTAGCheck(aMailing.getId());

        for (Entry<String, MailingComponent> mapEntry : componentEntries) {
            String tagName = mapEntry.getKey();
            MailingComponent component = mapEntry.getValue();
            String emmBlock = component.getEmmBlock();
            StringBuffer contentOutReport = new StringBuffer();
            if (!tagCheck.checkContent(emmBlock, contentOutReport, outFailures)) {
                appendErrorsToList(tagName, errorReports, contentOutReport);
            }

        }

        if (errorReports.size() > 0) {
            throw new AgnTagException("error.template.dyntags", errorReports);
        }

    }

    mailingDao.saveMailing(aMailing);
    aForm.setMailingID(aMailing.getId());
    String entityName = aMailing.isIsTemplate() ? "template" : "mailing";

    if (aMailing.isIsTemplate()) {
        updateMailingsWithDynamicTemplate(aMailing);
    }

    if (newMail) {
        AgnUtils.userlogger().info(AgnUtils.getAdmin(req).getUsername() + ": create " + entityName + " "
                + aMailing.getShortname());
    } else {
        AgnUtils.userlogger().info(
                AgnUtils.getAdmin(req).getUsername() + ": edit " + entityName + " " + aMailing.getShortname());
    }
}