private void sendResults(
      HashMap<String, List<String>> results,
      String reportEmail,
      String subject,
      String logPath,
      String fileName) {
    StringBuilder message = new StringBuilder(1024);
    message.ensureCapacity(256);

    List<String> messages = ((List<String>) results.get("errors"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nError Found:\n\n");
      Logger.info(ContentImporterThread.class, "\nError Found:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    messages = ((List<String>) results.get("warnings"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nWarnings Found:\n\n");
      Logger.info(ContentImporterThread.class, "\nWarnings Found:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    messages = ((List<String>) results.get("results"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nResults:\n\n");
      Logger.info(ContentImporterThread.class, "\nResults:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    Company company = PublicCompanyFactory.getDefaultCompany();

    contentImporterLogger(logPath, fileName, message.toString());
    if (UtilMethods.isSet(reportEmail)) {
      Mailer m = new Mailer();
      m.setToEmail(reportEmail);
      m.setFromEmail(company.getEmailAddress());
      m.setCc(null);
      m.setBcc(null);
      m.setSubject(subject);
      m.setTextBody(message.toString());

      if (!m.sendMessage()) {
        Logger.info(ContentImporterThread.class, "Email couldn't be sent.");
      }
    }
  }
コード例 #2
0
ファイル: TrustFactory.java プロジェクト: 4DvAnCeBoY/dotCMS
  public SSLContext getSSLContext() {
    TrustManager mytm[] = null;
    KeyManager mykm[] = null;

    try {
      if (UtilMethods.isSet(truststore_path) && UtilMethods.isSet(truststore_password)) {
        mytm =
            new TrustManager[] {
              new MyX509TrustManager(truststore_path, truststore_password.toCharArray())
            };
      }

      if (UtilMethods.isSet(keystore_path) && UtilMethods.isSet(keystore_password)) {
        mykm =
            new KeyManager[] {new MyX509KeyManager(keystore_path, keystore_password.toCharArray())};
      }
    } catch (Exception ex) {
      Logger.error(this.getClass(), ex.toString());
      Logger.debug(this.getClass(), ex.getMessage(), ex);
    }

    SSLContext ctx = null;
    try {
      ctx = SSLContext.getInstance("SSL");
      ctx.init(mykm, mytm, null);
    } catch (java.security.GeneralSecurityException ex) {
      Logger.error(this.getClass(), ex.getMessage(), ex);
    }
    return ctx;
  }
コード例 #3
0
  /**
   * Save the file uploaded
   *
   * @param user the user that save the file
   * @param host Current host
   * @param uploadedFile
   * @param folder The folder where the file is going to be save
   * @param title The filename
   * @return File
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  private static FileAsset saveFile(
      User user, Host host, java.io.File uploadedFile, String folderPath, String title)
      throws Exception {

    Folder folder = APILocator.getFolderAPI().findFolderByPath(folderPath, host, user, false);
    if (!UtilMethods.isSet(folder.getInode())) {
      User systemUser = APILocator.getUserAPI().getSystemUser();
      folder =
          APILocator.getFolderAPI()
              .createFolders(folderPath, host, APILocator.getUserAPI().getSystemUser(), false);
    }

    byte[] bytes = FileUtil.getBytes(uploadedFile);

    if (bytes != null) {
      String newFileName = "";
      String name = UtilMethods.getFileName(title);
      int counter = 1;
      String fileName = name + "." + UtilMethods.getFileExtension(title);
      while (APILocator.getFileAPI().fileNameExists(folder, fileName)) {
        newFileName = name + "(" + counter + ")";
        fileName = newFileName + "." + UtilMethods.getFileExtension(title);
        counter++;
      }
      while (APILocator.getFileAssetAPI().fileNameExists(host, folder, name, "")) {
        newFileName = name + "(" + counter + ")";
        fileName = newFileName + "." + UtilMethods.getFileExtension(title);
        counter++;
      }
      if (UtilMethods.isSet(newFileName)) {
        name = newFileName;
      }
      Contentlet cont = new Contentlet();
      cont.setStructureInode(folder.getDefaultFileType());
      cont.setStringProperty(FileAssetAPI.TITLE_FIELD, UtilMethods.getFileName(name));
      cont.setFolder(folder.getInode());
      cont.setHost(host.getIdentifier());
      cont.setBinary(FileAssetAPI.BINARY_FIELD, uploadedFile);
      if (StructureCache.getStructureByInode(cont.getStructureInode()).getStructureType()
          == Structure.STRUCTURE_TYPE_FILEASSET) cont.setStringProperty("fileName", title);
      cont = APILocator.getContentletAPI().checkin(cont, user, false);
      if (APILocator.getPermissionAPI()
          .doesUserHavePermission(cont, PermissionAPI.PERMISSION_PUBLISH, user))
        APILocator.getVersionableAPI().setLive(cont);
      return APILocator.getFileAssetAPI().fromContentlet(cont);
    }

    return null;
  }
コード例 #4
0
  @SuppressWarnings("deprecation")
  private void _loadForm(ActionForm form, ActionRequest req, ActionResponse res) {
    try {
      StructureForm structureForm = (StructureForm) form;
      Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE);
      BeanUtils.copyProperties(structureForm, structure);
      structureForm.setFields(structure.getFields());

      if (structure.getReviewInterval() != null) {
        String interval = structure.getReviewInterval();
        Pattern p = Pattern.compile("(\\d+)([dmy])");
        Matcher m = p.matcher(interval);
        boolean b = m.matches();
        if (b) {
          structureForm.setReviewContent(true);
          String g1 = m.group(1);
          String g2 = m.group(2);
          structureForm.setReviewIntervalNum(g1);
          structureForm.setReviewIntervalSelect(g2);
        }
      }
      if (UtilMethods.isSet(structure.getDetailPage())) {
        Identifier ident = APILocator.getIdentifierAPI().find(structure.getDetailPage());
        HTMLPage page = HTMLPageFactory.getLiveHTMLPageByIdentifier(ident);
        if (InodeUtils.isSet(page.getInode())) {
          structureForm.setDetailPage(page.getIdentifier());
        }
      }

    } catch (Exception ex) {
      Logger.debug(EditStructureAction.class, ex.toString());
    }
  }
コード例 #5
0
ファイル: TemplateAjax.java プロジェクト: 4DvAnCeBoY/dotCMS
  /**
   * Method that will verify if a given template title is already used by another template
   *
   * @param title template title to verify
   * @param templateInode template inode in case we are editing a template, null or empty in case of
   *     a new template
   * @param hostIdentifier current host identifier
   * @return
   * @throws DotDataException
   * @throws SystemException
   * @throws PortalException
   * @throws DotSecurityException
   */
  public boolean duplicatedTitle(String title, String templateInode, String hostIdentifier)
      throws DotDataException, SystemException, PortalException, DotSecurityException {

    HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
    User user = userWebAPI.getLoggedInUser(req);
    boolean respectFrontendRoles = userWebAPI.isLoggedToFrontend(req);

    // Getting the current host
    Host host = hostAPI.find(hostIdentifier, user, respectFrontendRoles);

    // The template name must be unique
    Template foundTemplate =
        FactoryLocator.getTemplateFactory().findWorkingTemplateByName(title, host);
    boolean duplicatedTitle = false;
    if (foundTemplate != null && InodeUtils.isSet(foundTemplate.getInode())) {
      if (!UtilMethods.isSet(templateInode)) {
        duplicatedTitle = true;
      } else {
        if (!foundTemplate.getInode().equals(templateInode)) {
          duplicatedTitle = true;
        }
      }
    }

    return duplicatedTitle;
  }
  private void loadEveryDayForm(ActionForm form, ActionRequest req) {
    String[] everyDay = req.getParameterValues("everyDay");

    ContentImporterForm contentImporterForm = (ContentImporterForm) form;
    if (UtilMethods.isSet(everyDay) && contentImporterForm.isEveryInfo()) {
      for (String dayOfWeek : everyDay) {
        if (dayOfWeek.equals("MON")) contentImporterForm.setMonday(true);
        else if (dayOfWeek.equals("TUE")) contentImporterForm.setTuesday(true);
        else if (dayOfWeek.equals("WED")) contentImporterForm.setWednesday(true);
        else if (dayOfWeek.equals("THU")) contentImporterForm.setThusday(true);
        else if (dayOfWeek.equals("FRI")) contentImporterForm.setFriday(true);
        else if (dayOfWeek.equals("SAT")) contentImporterForm.setSaturday(true);
        else if (dayOfWeek.equals("SUN")) contentImporterForm.setSunday(true);
      }

      contentImporterForm.setEveryInfo(true);
      contentImporterForm.setEvery("isDays");
    } else {
      contentImporterForm.setEvery("");
      contentImporterForm.setMonday(false);
      contentImporterForm.setTuesday(false);
      contentImporterForm.setWednesday(false);
      contentImporterForm.setThusday(false);
      contentImporterForm.setFriday(false);
      contentImporterForm.setSaturday(false);
      contentImporterForm.setSunday(false);
    }
  }
コード例 #7
0
  /**
   * This method trys to build a cache key based on the information given in the request - if the
   * page can't be cached, or caching is not availbale then return null
   *
   * @param request
   * @return
   */
  private String getPageCacheKey(HttpServletRequest request) {
    // no license
    if (LicenseUtil.getLevel() < 100) {
      return null;
    }
    // don't cache posts
    if (!"GET".equalsIgnoreCase(request.getMethod())) {
      return null;
    }
    // nocache passed either as a session var, as a request var or as a
    // request attribute
    if ("no".equals(request.getParameter("dotcache"))
        || "no".equals(request.getAttribute("dotcache"))
        || "no".equals(request.getSession().getAttribute("dotcache"))) {
      return null;
    }

    String idInode = (String) request.getAttribute("idInode");

    User user =
        (com.liferay.portal.model.User)
            request.getSession().getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);

    HTMLPage page = null;
    try {
      page = APILocator.getHTMLPageAPI().loadLivePageById(idInode, user, true);
    } catch (Exception e) {
      Logger.error(
          HTMLPageWebAPI.class,
          "unable to load live version of page: " + idInode + " because " + e.getMessage());
      return null;
    }
    if (page == null || page.getCacheTTL() < 1) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(page.getInode());
    sb.append("_" + page.getModDate().getTime());

    String userId = (user != null) ? user.getUserId() : "PUBLIC";
    sb.append("_" + userId);

    String language =
        (String) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE);
    sb.append("_" + language);

    String urlMap = (String) request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE);
    if (urlMap != null) {
      sb.append("_" + urlMap);
    }

    if (UtilMethods.isSet(request.getQueryString())) {
      sb.append("_" + request.getQueryString());
    }

    return sb.toString();
  }
コード例 #8
0
  @SuppressWarnings({"unchecked", "deprecation"})
  public boolean renameFile(File file, String newName)
      throws DotStateException, DotDataException, DotSecurityException {

    // getting old file properties
    String oldFileName = file.getFileName();
    String ext = UtilMethods.getFileExtension(oldFileName);
    Folder folder =
        APILocator.getFolderAPI()
            .findParentFolder(file, APILocator.getUserAPI().getSystemUser(), false);

    Identifier ident = APILocator.getIdentifierAPI().find(file);

    String newFileName = newName;
    if (UtilMethods.isSet(ext)) {
      newFileName = newFileName + "." + ext;
    }

    if (fileNameExists(folder, newFileName) || file.isLocked()) return false;

    List<Versionable> versions = APILocator.getVersionableAPI().findAllVersions(ident);

    boolean islive = false;

    for (Versionable version : versions) {
      File f = (File) version;

      // sets filename for this new file
      f.setFileName(newFileName);

      HibernateUtil.saveOrUpdate(f);

      if (f.isLive()) islive = true;
    }

    LiveCache.removeAssetFromCache(file);
    WorkingCache.removeAssetFromCache(file);
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);

    ident.setURI(APILocator.getIdentifierAPI().find(folder).getPath() + newFileName);
    // HibernateUtil.saveOrUpdate(ident);
    APILocator.getIdentifierAPI().save(ident);

    if (islive) {
      LiveCache.removeAssetFromCache(file);
      LiveCache.addToLiveAssetToCache(file);
    }
    WorkingCache.removeAssetFromCache(file);
    WorkingCache.addToWorkingAssetToCache(file);
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);

    // RefreshMenus.deleteMenus();
    RefreshMenus.deleteMenu(file);
    CacheLocator.getNavToolCache().removeNav(folder.getHostId(), folder.getInode());

    return true;
  }
コード例 #9
0
  /**
   * Check if a para is tupe file or image
   *
   * @param structure
   * @param paramName
   * @return boolean
   */
  public static boolean imageOrFileParam(Structure structure, String paramName) {

    Field field = structure.getFieldVar(paramName);
    if (UtilMethods.isSet(field)
        && (field.getFieldType().equals(Field.FieldType.FILE.toString())
            || field.getFieldType().equals(Field.FieldType.IMAGE.toString()))) {
      return true;
    }
    return false;
  }
コード例 #10
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public Map<String, Object> getEvent(String id, boolean live)
      throws DotDataException, DotSecurityException, PortalException, SystemException {

    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(id, live, user, respectFrontendRoles);

    Map<String, Object> eventMap = ev.getMap();

    // Loading categories
    List<Map<String, Object>> categoryMaps = new ArrayList<Map<String, Object>>();
    List<Category> eventCategories = categoryAPI.getParents(ev, user, respectFrontendRoles);
    for (Category cat : eventCategories) {
      categoryMaps.add(cat.getMap());
    }
    eventMap.put("categories", categoryMaps);
    eventMap.put("rating", RatingAPI.getAverageRating(ev.getIdentifier()));
    eventMap.put("votes", RatingAPI.getRatingVotesNumber(ev.getIdentifier()));
    eventMap.put(
        "hasReadPermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles));
    eventMap.put(
        "hasWritePermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles));
    eventMap.put(
        "hasPublishPermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles));
    eventMap.put(
        "readPermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles));
    eventMap.put(
        "writePermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles));
    eventMap.put(
        "publishPermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles));
    eventMap.put("isDisconnected", UtilMethods.isSet(ev.getDisconnectedFrom()));
    CommentsWebAPI cAPI = new CommentsWebAPI();
    cAPI.setUser(user);
    cAPI.setRespectFrontendRoles(respectFrontendRoles);
    eventMap.put("commentsCount", cAPI.getCommentsCount(ev.getInode()));

    return eventMap;
  }
  private void _deleteScheduler(
      ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
      throws Exception {
    ContentImporterForm contentImporterForm = (ContentImporterForm) form;

    if (UtilMethods.isSet(contentImporterForm.getJobGroup()))
      QuartzUtils.removeJob(contentImporterForm.getJobName(), contentImporterForm.getJobGroup());
    else QuartzUtils.removeJob(req.getParameter("name"), req.getParameter("group"));

    SessionMessages.add(req, "message", "message.Scheduler.delete");
  }
コード例 #12
0
  public void init() {
    String file = getInitParameter("log4j-init-file");
    String path = null;
    try {
      path = new ClassPathResource("log4j.xml").getFile().getPath();
    } catch (IOException e) {
      Logger.error(Log4JInitializationServlet.class, e.getMessage(), e);
    }

    // if the log4j-init-file is not set, then no point in trying
    if (file != null && UtilMethods.isSet(path)) {
      PropertyConfigurator.configure(path);
    }
  }
コード例 #13
0
  @SuppressWarnings("unchecked")
  public File saveFile(
      File newFile, java.io.File dataFile, Folder parentFolder, Identifier identifier)
      throws DotDataException {

    boolean localTransation = false;

    try {
      localTransation = DbConnectionFactory.getConnection().getAutoCommit();
      if (localTransation) {
        HibernateUtil.startTransaction();
      }
      // old working file
      File oldFile = null;
      // if new identifier
      if (identifier == null || !InodeUtils.isSet(identifier.getInode())) {
        identifier = APILocator.getIdentifierAPI().createNew(newFile, parentFolder);
        newFile.setIdentifier(identifier.getInode());
        HibernateUtil.save(newFile);
        APILocator.getVersionableAPI().setWorking(newFile);
        saveFileData(newFile, null, dataFile);
      } else {
        APILocator.getVersionableAPI().removeLive(identifier.getId());
      }
      if (UtilMethods.isSet(dataFile)) {
        HibernateUtil.save(newFile);
        saveFileData(newFile, null, dataFile);
      }
      if (oldFile != null && InodeUtils.isSet(oldFile.getInode())) {
        APILocator.getFileAPI().invalidateCache(oldFile);
        fileCache.remove(oldFile);
        WorkingCache.removeAssetFromCache(oldFile);
      }
      LiveCache.removeAssetFromCache(newFile);
      if (newFile.isLive()) {
        LiveCache.addToLiveAssetToCache(newFile);
      }
      WorkingCache.addToWorkingAssetToCache(newFile);

      if (localTransation) {
        HibernateUtil.commitTransaction();
      }
    } catch (Exception e) {
      if (localTransation) {
        HibernateUtil.rollbackTransaction();
      }
      throw new DotDataException(e.getMessage(), e);
    }
    return newFile;
  }
コード例 #14
0
  /**
   * Set the field value, to a content according the content structure
   *
   * @param structure The content structure
   * @param contentlet The content
   * @param fieldName The field name
   * @param value The field value
   * @throws DotDataException
   */
  private static void setField(
      Structure structure, Contentlet contentlet, String fieldName, String[] values)
      throws DotDataException {

    Field field = structure.getFieldVar(fieldName);
    String value = "";
    if (UtilMethods.isSet(field) && APILocator.getFieldAPI().valueSettable(field)) {
      try {
        if (field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())) {
          value = VelocityUtil.cleanVelocity(values[0]);
          Host host =
              APILocator.getHostAPI().find(value, APILocator.getUserAPI().getSystemUser(), false);
          if (host != null && InodeUtils.isSet(host.getIdentifier())) {
            contentlet.setHost(host.getIdentifier());
            contentlet.setFolder(FolderAPI.SYSTEM_FOLDER);
          } else {
            Folder folder =
                APILocator.getFolderAPI()
                    .find(value, APILocator.getUserAPI().getSystemUser(), false);
            if (folder != null && InodeUtils.isSet(folder.getInode())) {
              contentlet.setHost(folder.getHostId());
              contentlet.setFolder(folder.getInode());
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.MULTI_SELECT.toString())
            || field.getFieldType().equals(Field.FieldType.CHECKBOX.toString())) {
          if (field.getFieldContentlet().startsWith("float")
              || field.getFieldContentlet().startsWith("integer")) {
            value = values[0];
          } else {
            for (String temp : values) {
              value = temp + "," + value;
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.DATE.toString())) {
          value = VelocityUtil.cleanVelocity(values[0]);
          if (value instanceof String) {
            value = value + " 00:00:00";
          }
        } else {

          value = VelocityUtil.cleanVelocity(values[0]);
        }
        conAPI.setContentletProperty(contentlet, field, value);

      } catch (Exception e) {
        Logger.debug(SubmitContentUtil.class, e.getMessage());
      }
    }
  }
コード例 #15
0
ファイル: CampaignForm.java プロジェクト: AppChecker/core
  public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    if (request.getParameter("cmd") != null && request.getParameter("cmd").equals(Constants.ADD)) {

      ActionErrors ae = super.validate(mapping, request);

      if (!UtilMethods.isSet(mailingList) && !UtilMethods.isSet(userFilterInode)) {
        ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Please-select-a-Mailing-List"));
      }

      if ((UtilMethods.isSet(webExpirationDate)) && (expirationDate == null)) {
        ae.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("message.campaign.error.expiration.date.incomplete"));
      }
      if (expirationDate != null && (expirationDate.before(new Date()))) {
        ae.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("message.campaign.error.wrong.expiration.date"));
      }

      return ae;
    }
    return null;
  }
  private Map<String, String> getSchedulerProperties(
      ActionRequest req, ContentImporterForm contentImporterForm) {
    Map<String, String> properties = new HashMap<String, String>(5);
    Enumeration<String> propertiesNames = req.getParameterNames();

    if (UtilMethods.isSet(contentImporterForm.getMap())) {
      properties = contentImporterForm.getMap();
    } else {
      String propertyName;
      String propertyValue;

      for (; propertiesNames.hasMoreElements(); ) {
        propertyName = propertiesNames.nextElement();
        if (propertyName.startsWith("propertyName")) {
          propertyValue = req.getParameter("propertyValue" + propertyName.substring(12));

          if (UtilMethods.isSet(req.getParameter(propertyName)) && UtilMethods.isSet(propertyValue))
            properties.put(req.getParameter(propertyName), propertyValue);
        }
      }
    }

    return properties;
  }
コード例 #17
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public List<Map<String, Object>> findEventsForDay(
      String hostId,
      String dateStr,
      String[] tags,
      String[] keywords,
      String[] categoriesInodes,
      boolean live,
      boolean includeArchived,
      int offset,
      int limit)
      throws DotDataException, DotSecurityException, PortalException, SystemException,
          java.text.ParseException {

    Date fromDate = null;
    Date toDate = null;
    if (UtilMethods.isSet(dateStr)) {
      String date = dateFormat.format(dateFormat2.parse(dateStr));
      fromDate = dateFormat.parse(date);
    }

    Calendar fromDateCal = Calendar.getInstance();
    Calendar toDateCal = Calendar.getInstance();
    fromDateCal.setTime(fromDate);
    toDateCal.setTime(fromDate);

    fromDateCal.set(Calendar.HOUR, 0);
    fromDateCal.set(Calendar.MINUTE, 0);
    fromDateCal.set(Calendar.SECOND, 0);

    toDateCal.set(Calendar.HOUR, 23);
    toDateCal.set(Calendar.MINUTE, 59);
    toDateCal.set(Calendar.SECOND, 59);

    fromDate = fromDateCal.getTime();
    toDate = toDateCal.getTime();

    return findEventsByHostId(
        hostId,
        fromDate,
        toDate,
        tags,
        keywords,
        categoriesInodes,
        live,
        includeArchived,
        offset,
        limit);
  }
コード例 #18
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public void unarchiveEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    try {

      if (UtilMethods.isSet(ev.getDisconnectedFrom())) {
        Event baseEvent = null;
        try {
          baseEvent = eventAPI.find(ev.getDisconnectedFrom(), false, user, respectFrontendRoles);
        } catch (Exception e) {
          Logger.error(this, "Base event not found");
        }
        if (baseEvent != null) {
          try {
            Date originalStartDate = ev.getOriginalStartDate();
            baseEvent.addDateToIgnore(originalStartDate);
            APILocator.getContentletAPI()
                .checkin(
                    baseEvent,
                    categoryAPI.getParents(baseEvent, user, true),
                    perAPI.getPermissions(baseEvent),
                    user,
                    false);
          } catch (Exception e) {
            Logger.error(this, "Could not delete event from recurrence");
          }
        }
      }
      contAPI.unarchive(ev, user, respectFrontendRoles);

    } catch (Exception e) {
      Logger.error(this, e.getMessage());
    }

    HibernateUtil.commitTransaction();
    if (!contAPI.isInodeIndexed(ev.getInode())) {
      Logger.error(this, "Timed out while waiting for index to return");
    }
  }
コード例 #19
0
ファイル: LanguageWebAPI.java プロジェクト: helloyy/dotCMS
  public String get(String key, String languageId) {
    String value = null;
    try {
      Language lang = langAPI.getLanguage(languageId);
      value = langAPI.getStringKey(lang, key);

      if ((!UtilMethods.isSet(value) || value.equals(key))
          && Config.getBooleanProperty("DEFAULT_CONTENT_TO_DEFAULT_LANGUAGE")) {
        lang = langAPI.getDefaultLanguage();
        value = langAPI.getStringKey(lang, key);
      }
    } catch (Exception e) {
      Logger.error(this, e.toString());
    }

    return (value == null) ? "" : value;
  }
コード例 #20
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  public List<Map<String, Object>> findLocations(String filter)
      throws DotDataException, DotSecurityException, PortalException, SystemException {

    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    // Searching for buildings
    Structure buildingStructure = eventAPI.getBuildingStructure();
    Field titleField = buildingStructure.getFieldVar("title");
    String luceneQuery = "+structureInode:" + buildingStructure.getInode();
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    List<Contentlet> matches =
        contAPI.search(
            luceneQuery, -1, 0, titleField.getFieldContentlet(), user, respectFrontendRoles);
    List<Map<String, Object>> facilitiesList =
        findChildFacilities(matches, filter, user, respectFrontendRoles);

    for (Contentlet cont : matches) {
      List<Map<String, Object>> facilitiesListCont = new ArrayList<Map<String, Object>>();
      Map<String, Object> contMap = cont.getMap();
      if (!UtilMethods.isSet(filter)
          || facilitiesList.size() > 0
          || ((String) contMap.get("title")).contains(filter)) {
        for (Map<String, Object> facility : facilitiesList) {
          for (Contentlet building : (ArrayList<Contentlet>) facility.get("buildings")) {
            if (building.getIdentifier().equals(cont.getIdentifier())
                && !facilitiesListCont.contains(facility)) {
              Map<String, Object> facilityMap = new HashMap<String, Object>();
              facilityMap.putAll(facility);
              facilityMap.put("buildings", null);
              facilitiesListCont.add(facilityMap);
              break;
            }
          }
        }
        contMap.put("facilities", facilitiesListCont);
        results.add(contMap);
      }
    }
    return results;
  }
コード例 #21
0
  /**
   * Get the user if the user is not logged return default AnonymousUser
   *
   * @param userId The userId
   * @return User
   * @exception DotDataException
   */
  public static User getUserFromId(String userId) throws DotDataException {
    User user = null;
    try {
      if (UtilMethods.isSet(userId)) {

        user =
            APILocator.getUserAPI()
                .loadUserById(userId, APILocator.getUserAPI().getSystemUser(), true);

      } else {
        user = APILocator.getUserAPI().getAnonymousUser();
      }
    } catch (NoSuchUserException e) {
      Logger.error(SubmitContentUtil.class, e.getMessage(), e);
    } catch (DotSecurityException e) {
      Logger.error(SubmitContentUtil.class, e.getMessage(), e);
    }
    return user;
  }
  private CronScheduledTask _retrieveScheduler(
      ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form)
      throws Exception {
    ContentImporterForm contentImporterForm = (ContentImporterForm) form;
    List<ScheduledTask> results = null;
    if (UtilMethods.isSet(contentImporterForm.getJobGroup())) {
      results =
          (List<ScheduledTask>)
              QuartzUtils.getStandardScheduledTask(
                  contentImporterForm.getJobName(), contentImporterForm.getJobGroup());
    } else {
      results =
          (List<ScheduledTask>)
              QuartzUtils.getStandardScheduledTask(
                  req.getParameter("name"), req.getParameter("group"));
    }

    if (results.size() > 0) return (CronScheduledTask) results.get(0);
    else return null;
  }
コード例 #23
0
ファイル: CalendarAjax.java プロジェクト: rmundy/dotCMS
  private List<Map<String, Object>> findChildFacilities(
      List<Contentlet> buildingConts, String filter, User user, boolean respectFrontendRoles)
      throws DotDataException, DotSecurityException {
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();

    // Searching for children facilities
    Structure facilityStructure = eventAPI.getFacilityStructure();
    // Facility Structure might be absent http://jira.dotmarketing.net/browse/DOTCMS-6275
    if (facilityStructure.getName() != null) {
      Field titleField = facilityStructure.getFieldVar("title");
      String luceneQuery = "+structureInode:" + facilityStructure.getInode() + " +(";
      for (Contentlet cont : buildingConts) {
        luceneQuery += " Building-Facility:" + cont.getIdentifier() + " ";
      }
      luceneQuery += ") ";
      if (UtilMethods.isSet(filter))
        luceneQuery += " +" + titleField.getFieldContentlet() + ":" + filter.trim() + "*";

      List<Contentlet> matches =
          contAPI.search(
              luceneQuery, -1, 0, titleField.getFieldContentlet(), user, respectFrontendRoles);
      List<Relationship> rels =
          RelationshipFactory.getAllRelationshipsByStructure(eventAPI.getBuildingStructure());
      for (Contentlet cont : matches) {
        List<Contentlet> relCont = new ArrayList<Contentlet>();
        for (Relationship rel : rels) {
          if (rel.getChildStructure().equals(eventAPI.getFacilityStructure())
              && rel.getParentStructure().equals(eventAPI.getBuildingStructure())) {
            relCont.addAll(
                APILocator.getContentletAPI()
                    .getRelatedContent(cont, rel, user, respectFrontendRoles));
          }
        }
        Map<String, Object> contMap = cont.getMap();
        contMap.put("buildings", relCont);
        results.add(contMap);
      }
    }
    return results;
  }
コード例 #24
0
  private void addUserComments(String userid, WebForm webForm, HttpServletRequest request)
      throws Exception {

    Date now = new Date();
    String webFormType = webForm.getFormType();
    String webFormId = webForm.getWebFormId();

    UserComment userComments = new UserComment();
    userComments.setUserId(userid);
    userComments.setCommentUserId(userid);
    userComments.setDate(now);
    if (request.getParameter("comments") != null) {
      userComments.setComment(request.getParameter("comments"));
    } else if (UtilMethods.isSet(webForm.getFormType())) {
      userComments.setSubject("User submitted: " + webFormType);
      userComments.setComment("Web Form: " + webFormType + " - ID: " + webFormId);
    } else {
      userComments.setSubject("User submitted Form: Open Entry ");
      StringBuffer buffy = new StringBuffer();
      Enumeration x = request.getParameterNames();
      while (x.hasMoreElements()) {
        String key = (String) x.nextElement();
        buffy.append(key);
        buffy.append(":\t");
        buffy.append(request.getParameter(key));
        buffy.append("\n");
        if (buffy.length() > 65000) {
          break;
        }
      }
      userComments.setComment(buffy.toString());
    }

    userComments.setTypeComment(UserComment.TYPE_INCOMING);
    userComments.setMethod(UserComment.METHOD_WEB);
    userComments.setCommunicationId(null);
    UserCommentsFactory.saveUserComment(userComments);
  }
コード例 #25
0
  /**
   * Verifies what we were doing to the current bundle, it was received for this server?, or this
   * server is trying to send it...., we don't want to retry bundles we received.
   *
   * @param request
   * @param config
   * @return
   */
  private Boolean sendingBundle(
      HttpServletRequest request, PushPublisherConfig config, String bundleId)
      throws DotDataException {

    // Get the local address
    String remoteIP = request.getRemoteHost();
    int port = request.getLocalPort();
    if (!UtilMethods.isSet(remoteIP)) {
      remoteIP = request.getRemoteAddr();
    }

    /*
    Getting the bundle end points in order to compare if this current server it is an end point or not.
    If it is is because we received this bundle as we were a targeted end point server.
    */

    List<Environment> environments =
        APILocator.getEnvironmentAPI().findEnvironmentsByBundleId(bundleId);

    for (Environment environment : environments) {

      List<PublishingEndPoint> endPoints =
          APILocator.getPublisherEndPointAPI()
              .findSendingEndPointsByEnvironment(environment.getId());
      for (PublishingEndPoint endPoint : endPoints) {

        // Getting the end point details
        String endPointAddress = endPoint.getAddress();
        String endPointPort = endPoint.getPort();

        if (endPointAddress.equals(remoteIP) && endPointPort.equals(String.valueOf(port))) {
          return false;
        }
      }
    }

    return true;
  }
コード例 #26
0
  public ActionForward render(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig config,
      RenderRequest req,
      RenderResponse res)
      throws Exception {

    String orderBy = req.getParameter("orderBy");
    User user = _getUser(req);
    orderBy = (UtilMethods.isSet(orderBy) ? orderBy : "name");
    _loadStructures(
        req,
        user,
        WebKeys.STRUCTURES_VIEW_COUNT,
        WebKeys.Structure.STRUCTURES,
        WebKeys.STRUCTURE_QUERY);
    if (req.getWindowState().equals(WindowState.NORMAL)) {
      return mapping.findForward("portlet.ext.formhandler.view");
    } else {
      return mapping.findForward("portlet.ext.formhandler.view_form");
    }
  }
コード例 #27
0
ファイル: TemplateAjax.java プロジェクト: 4DvAnCeBoY/dotCMS
 public Map<String, Object> fetchTemplateImage(String id)
     throws DotDataException, DotSecurityException {
   Map<String, Object> toReturn = new HashMap<String, Object>();
   Template template = null;
   try {
     template =
         templateAPI.findWorkingTemplate(id, APILocator.getUserAPI().getSystemUser(), false);
   } catch (DotSecurityException e) {
     Logger.error(this, e.getMessage());
   }
   if (template != null) {
     Identifier imageIdentifier = APILocator.getIdentifierAPI().find(template.getImage());
     if (UtilMethods.isSet(imageIdentifier.getAssetType())
         && imageIdentifier.getAssetType().equals("contentlet")) {
       Contentlet imageContentlet = TemplateFactory.getImageContentlet(template);
       if (imageContentlet != null) {
         toReturn.put("inode", imageContentlet.getInode());
         toReturn.put("name", imageContentlet.getTitle());
         toReturn.put("identifier", imageContentlet.getIdentifier());
         toReturn.put(
             "extension",
             com.dotmarketing.util.UtilMethods.getFileExtension(imageContentlet.getTitle()));
       }
     } else {
       File imgFile = TemplateFactory.getImageFile(template);
       if (imgFile != null) {
         toReturn.put("inode", imgFile.getInode());
         toReturn.put("name", imgFile.getFileName());
         toReturn.put("identifier", imgFile.getIdentifier());
         toReturn.put(
             "extension",
             com.dotmarketing.util.UtilMethods.getFileExtension(imgFile.getFileName()));
       }
     }
   }
   return toReturn;
 }
コード例 #28
0
ファイル: PushPublisher.java プロジェクト: xxg2/dotCMS
  @Override
  public PublisherConfig process(final PublishStatus status) throws DotPublishingException {
    if (LicenseUtil.getLevel() < 400)
      throw new RuntimeException("need an enterprise prime license to run this bundler");

    PublishAuditHistory currentStatusHistory = null;
    try {
      // Compressing bundle
      File bundleRoot = BundlerUtil.getBundleRoot(config);

      ArrayList<File> list = new ArrayList<File>(1);
      list.add(bundleRoot);
      File bundle =
          new File(
              bundleRoot + File.separator + ".." + File.separator + config.getId() + ".tar.gz");
      PushUtils.compressFiles(list, bundle, bundleRoot.getAbsolutePath());

      // Retriving enpoints and init client
      List<PublishingEndPoint> endpoints = ((PushPublisherConfig) config).getEndpoints();
      Map<String, List<PublishingEndPoint>> endpointsMap =
          new HashMap<String, List<PublishingEndPoint>>();
      List<PublishingEndPoint> buffer = null;
      // Organize the endpoints grouping them by groupId
      for (PublishingEndPoint pEndPoint : endpoints) {

        String gid =
            UtilMethods.isSet(pEndPoint.getGroupId()) ? pEndPoint.getGroupId() : pEndPoint.getId();

        if (endpointsMap.get(gid) == null) buffer = new ArrayList<PublishingEndPoint>();
        else buffer = endpointsMap.get(gid);

        buffer.add(pEndPoint);

        // put in map with either the group key or the id if no group is set
        endpointsMap.put(gid, buffer);
      }

      ClientConfig cc = new DefaultClientConfig();

      if (Config.getStringProperty("TRUSTSTORE_PATH") != null
          && !Config.getStringProperty("TRUSTSTORE_PATH").trim().equals(""))
        cc.getProperties()
            .put(
                HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(tFactory.getHostnameVerifier(), tFactory.getSSLContext()));
      Client client = Client.create(cc);

      // Updating audit table
      currentStatusHistory = pubAuditAPI.getPublishAuditStatus(config.getId()).getStatusPojo();

      currentStatusHistory.setPublishStart(new Date());
      pubAuditAPI.updatePublishAuditStatus(
          config.getId(), PublishAuditStatus.Status.SENDING_TO_ENDPOINTS, currentStatusHistory);
      // Increment numTries
      currentStatusHistory.addNumTries();

      boolean hasError = false;
      int errorCounter = 0;

      for (String group : endpointsMap.keySet()) {
        List<PublishingEndPoint> groupList = endpointsMap.get(group);

        boolean sent = false;
        for (PublishingEndPoint endpoint : groupList) {
          EndpointDetail detail = new EndpointDetail();
          try {
            FormDataMultiPart form = new FormDataMultiPart();
            form.field(
                "AUTH_TOKEN",
                retriveKeyString(
                    PublicEncryptionFactory.decryptString(endpoint.getAuthKey().toString())));

            form.field(
                "GROUP_ID",
                UtilMethods.isSet(endpoint.getGroupId())
                    ? endpoint.getGroupId()
                    : endpoint.getId());

            form.field("ENDPOINT_ID", endpoint.getId());
            form.bodyPart(
                new FileDataBodyPart("bundle", bundle, MediaType.MULTIPART_FORM_DATA_TYPE));

            // Sending bundle to endpoint
            WebResource resource =
                client.resource(endpoint.toURL() + "/api/bundlePublisher/publish");

            ClientResponse response =
                resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);

            if (response.getClientResponseStatus().getStatusCode() == HttpStatus.SC_OK) {
              detail.setStatus(PublishAuditStatus.Status.BUNDLE_SENT_SUCCESSFULLY.getCode());
              detail.setInfo("Everything ok");
              sent = true;
            } else {
              detail.setStatus(PublishAuditStatus.Status.FAILED_TO_SENT.getCode());
              detail.setInfo(
                  "Returned "
                      + response.getClientResponseStatus().getStatusCode()
                      + " status code "
                      + "for the endpoint "
                      + endpoint.getId()
                      + "with address "
                      + endpoint.getAddress());
            }
          } catch (Exception e) {
            hasError = true;
            detail.setStatus(PublishAuditStatus.Status.FAILED_TO_SENT.getCode());

            String error =
                "An error occured for the endpoint "
                    + endpoint.getId()
                    + " with address "
                    + endpoint.getAddress()
                    + ".  Error: "
                    + e.getMessage();

            detail.setInfo(error);

            Logger.error(this.getClass(), error);
          }

          currentStatusHistory.addOrUpdateEndpoint(group, endpoint.getId(), detail);

          if (sent) break;
        }

        if (!sent) {
          hasError = true;
          errorCounter++;
        }
      }

      if (!hasError) {
        // Updating audit table
        currentStatusHistory.setPublishEnd(new Date());
        pubAuditAPI.updatePublishAuditStatus(
            config.getId(),
            PublishAuditStatus.Status.BUNDLE_SENT_SUCCESSFULLY,
            currentStatusHistory);

        // Deleting queue records
        // pubAPI.deleteElementsFromPublishQueueTable(config.getId());
      } else {
        if (errorCounter == endpointsMap.size()) {
          pubAuditAPI.updatePublishAuditStatus(
              config.getId(),
              PublishAuditStatus.Status.FAILED_TO_SEND_TO_ALL_GROUPS,
              currentStatusHistory);
        } else {
          pubAuditAPI.updatePublishAuditStatus(
              config.getId(),
              PublishAuditStatus.Status.FAILED_TO_SEND_TO_SOME_GROUPS,
              currentStatusHistory);
        }
      }

      return config;

    } catch (Exception e) {
      // Updating audit table
      try {
        pubAuditAPI.updatePublishAuditStatus(
            config.getId(), PublishAuditStatus.Status.FAILED_TO_PUBLISH, currentStatusHistory);
      } catch (DotPublisherException e1) {
        throw new DotPublishingException(e.getMessage());
      }

      Logger.error(this.getClass(), e.getMessage(), e);
      throw new DotPublishingException(e.getMessage());
    }
  }
コード例 #29
0
  protected void _loadStructures(
      RenderRequest req, User user, String countWebKey, String viewWebKey, String queryWebKey)
      throws Exception {

    com.liferay.portlet.RenderRequestImpl reqImpl = (com.liferay.portlet.RenderRequestImpl) req;
    HttpServletRequest httpReq = reqImpl.getHttpServletRequest();
    // gets the session object for the messages
    HttpSession session = httpReq.getSession();

    Integer structureType =
        (Integer) session.getAttribute(com.dotmarketing.util.WebKeys.Structure.STRUCTURE_EDIT_TYPE);
    if (req.getParameter("structureType") != null)
      structureType = Integer.parseInt(req.getParameter("structureType"));
    if (structureType != null)
      session.setAttribute(
          com.dotmarketing.util.WebKeys.Structure.STRUCTURE_EDIT_TYPE, structureType);

    String query = req.getParameter("query");
    String resetQuery = req.getParameter("resetQuery");

    List<Structure> structures = new java.util.ArrayList<Structure>();

    try {
      String orderby = req.getParameter("orderBy");
      if (!UtilMethods.isSet(orderby)) {
        orderby = "upper(name)";
      }
      String direction = req.getParameter("direction");
      if (!UtilMethods.isSet(direction)) {
        direction = "asc";
      }

      int pageNumber = 1;

      if (UtilMethods.isSet(req.getParameter("pageNumber"))) {
        pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
      }

      int limit = com.dotmarketing.util.Config.getIntProperty("PER_PAGE");

      int offset = (pageNumber - 1) * limit;

      if ((query == null) && (resetQuery == null)) {
        query = (String) session.getAttribute(queryWebKey);
      }
      session.setAttribute(queryWebKey, query);

      int count = 0;
      String queryCondition = "";

      if (((query != null) && (query.length() != 0)) || (structureType != null)) {

        if (query == null) query = "";
        query = query.trim();
        if (UtilMethods.isSet(query)) {
          queryCondition +=
              "(lower(name) "
                  + "like '%"
                  + query.toLowerCase().replace("\'", "\\\'")
                  + "%' or inode='"
                  + query
                  + "')";
        }

      } else {
        Logger.debug(this, "Getting all Forms Structures");
      }

      if (UtilMethods.isSet(queryCondition)) {
        queryCondition += " and structuretype=" + Structure.STRUCTURE_TYPE_FORM;
      } else {
        queryCondition += " structuretype=" + Structure.STRUCTURE_TYPE_FORM;
      }

      structures =
          StructureFactory.getStructuresByUser(
              user, queryCondition, orderby, limit, offset, direction);
      count = (int) ((PaginatedArrayList<Structure>) structures).getTotalResults();
      req.setAttribute(countWebKey, new Integer(count));
      req.setAttribute(viewWebKey, structures);
    } catch (Exception e) {
      req.setAttribute(viewWebKey, structures);
      Logger.error(this, "Exception e =" + e.getMessage(), e);
      throw new Exception(e.getMessage());
    }
  }
コード例 #30
0
  private String getParseErrorMessage(ParseErrorException pee) {
    String msg = pee.toString().replaceAll("at " + pee.getTemplateName(), "");
    msg = msg.replaceAll("org.apache.velocity.exception.ParseErrorException:", "");
    msg = msg.replaceAll("\\.\\.\\.", ",");
    if (pee.getLineNumber() > -1) {
      msg = msg.replaceAll("\\[.*\\]", "");
    } else {
      msg = msg.replaceAll("\\[", "\n\\[");
    }
    msg = UtilMethods.replace(msg, "\"<EOF>\"", "end of file");
    msg = UtilMethods.htmlifyString(msg);

    msg = UtilMethods.htmlLineBreak(msg);
    while (msg.endsWith(",")) {
      msg = msg.substring(0, msg.length() - 1);
    }

    int showLines = 2;
    List<Map<String, String>> badCode = new ArrayList<Map<String, String>>();
    if (pee.getLineNumber() > -1) {
      BufferedReader buff = null;
      try {
        buff =
            new BufferedReader(
                new InputStreamReader(
                    DotResourceLoader.getInstance().getResourceStream(pee.getTemplateName())));

        String x;
        int here = 1;
        while ((x = buff.readLine()) != null) {
          Map m = new HashMap<String, String>();
          if (pee.getLineNumber() == here) {
            m.put("code", UtilMethods.htmlifyString(x));
            m.put("lineNumber", here);
            m.put("badLine", "true");
            badCode.add(m);
          } else if (here >= pee.getLineNumber() - showLines
              && here <= pee.getLineNumber() + showLines) {
            if (UtilMethods.isSet(x)) {
              m.put("code", UtilMethods.htmlifyString(x));
              m.put("lineNumber", here);
              badCode.add(m);
            } else {
              m.put("code", "&nbsp;");
              m.put("lineNumber", here);
              badCode.add(m);
            }

          } else if (here - showLines > pee.getLineNumber()) {
            break;
          }

          here++;
        }

      } catch (IOException e1) {
        Logger.error(this.getClass(), "Unable to open buffy!" + e1);
      } finally {
        try {
          buff.close();
        } catch (Exception die) {
          Logger.error(this.getClass(), "Unable to close buffy!" + die);
        }
      }
    }

    java.io.StringWriter sw = new StringWriter();
    VelocityEngine ve = VelocityUtil.getEngine();
    VelocityContext context = new VelocityContext();

    context.put("veloError", pee);
    context.put("subErrorTemplate", "/static/preview_mode/error_template_parseexception.vtl");
    context.put("badCode", badCode);
    context.put("prettyError", msg);
    org.apache.velocity.Template template;
    try {
      template = ve.getTemplate(errorTemplate);
      context.put("error", this);
      template.merge(context, sw);
    } catch (Exception ex) {
      Logger.error(this.getClass(), "Unable to show velocityError", ex);
    }
    return sw.toString();
  }