@Override
  protected Object getMasterObject(String keyValue) throws Throwable {
    String managerNameValue = (String) super.findValue(keyValue, String.class);
    try {
      IEntityManager entityManager =
          (IEntityManager) ApsWebApplicationUtils.getBean(managerNameValue, this.pageContext);
      if (null != entityManager) {
        List<IApsEntity> entityTypes = new ArrayList<IApsEntity>();
        Map<String, IApsEntity> typeMap = entityManager.getEntityPrototypes();
        if (null != typeMap) {
          BeanComparator c = new BeanComparator(this.getOrderBy());
          entityTypes.addAll(typeMap.values());
          Collections.sort(entityTypes, c);
        }
        return entityTypes;
      } else {
        _logger.debug("Null entity manager : service name '{}'", managerNameValue);
      }
    } catch (Throwable t) {
      String message = "Error extracting entity types : entity manager '" + managerNameValue + "'";

      _logger.error("Error extracting entity types : entity manager '{}'", managerNameValue, t);
      // ApsSystemUtils.logThrowable(t, this, "getMasterObject", message);
      throw new ApsSystemException(message, t);
    }
    return null;
  }
 protected String extractTemplate(ApiMethod apiMethod) throws Exception {
   String template = null;
   InputStream is = null;
   try {
     StringBuffer path = new StringBuffer("classpath*:/api/");
     if (null != apiMethod.getPluginCode()) {
       path.append("plugins/" + apiMethod.getPluginCode() + "/");
     } else if (!apiMethod.getSource().equalsIgnoreCase("core")) {
       path.append(apiMethod.getSource() + "/");
     }
     path.append("aps/get/" + apiMethod.getResourceName() + "/description-item.vm");
     Resource[] resources =
         ApsWebApplicationUtils.getResources(path.toString(), this.getServletContext());
     if (null != resources && resources.length == 1) {
       Resource resource = resources[0];
       is = resource.getInputStream();
     }
     if (null == is) {
       ApsSystemUtils.getLogger()
           .info("Null Input Stream - template file path " + path.toString());
       return null;
     }
     template = FileTextReader.getText(is);
   } catch (Throwable t) {
     String message = "Error extracting template - " + this.buildApiSignature(apiMethod);
     ApsSystemUtils.logThrowable(t, this, "extractTemplate", message);
   } finally {
     if (null != is) {
       is.close();
     }
   }
   return template;
 }
 @Override
 public String intercept(ActionInvocation invocation) throws Exception {
   HttpServletRequest request = ServletActionContext.getRequest();
   Map<String, Object> params = invocation.getInvocationContext().getParameters();
   ILangManager langManager =
       (ILangManager) ApsWebApplicationUtils.getBean(SystemConstants.LANGUAGE_MANAGER, request);
   String langCode = (String) this.findParameter(params, "langCode");
   Lang currentLang = (null != langCode) ? langManager.getLang(langCode) : null;
   if (null == currentLang) {
     currentLang = langManager.getDefaultLang();
   }
   Locale locale = new Locale(currentLang.getCode(), "");
   invocation.getInvocationContext().setLocale(locale);
   return invocation.invoke();
 }
 private String extractTitle(Widget widget) {
   ServletRequest request = this.pageContext.getRequest();
   RequestContext reqCtx = (RequestContext) request.getAttribute(RequestContext.REQCTX);
   Lang currentLang = (Lang) reqCtx.getExtraParam(SystemConstants.EXTRAPAR_CURRENT_LANG);
   WidgetType type = widget.getType();
   String value = type.getTitles().getProperty(currentLang.getCode());
   if (null == value || value.trim().length() == 0) {
     ILangManager langManager =
         (ILangManager)
             ApsWebApplicationUtils.getBean(SystemConstants.LANGUAGE_MANAGER, this.pageContext);
     Lang defaultLang = langManager.getDefaultLang();
     value = type.getTitles().getProperty(defaultLang.getCode());
   }
   return value;
 }
 @Override
 public int doStartTag() throws JspException {
   IPageManager pageManager =
       (IPageManager)
           ApsWebApplicationUtils.getBean(SystemConstants.PAGE_MANAGER, this.pageContext);
   try {
     List<IPage> pages = pageManager.getWidgetUtilizers(this.getWidgetTypeCode());
     if (this.isListResult()) {
       this.pageContext.setAttribute(this.getVar(), pages);
     } else if (null != pages && pages.size() > 0) {
       this.pageContext.setAttribute(this.getVar(), pages.get(0));
     }
   } catch (Throwable t) {
     _logger.error("error in doStartTag", t);
     throw new JspException("Errore tag", t);
   }
   return super.doStartTag();
 }
 public int doEndTag() throws JspException {
   try {
     if (null == _root) {
       ConfigInterface configService =
           (ConfigInterface)
               ApsWebApplicationUtils.getBean(
                   SystemConstants.BASE_CONFIG_MANAGER, this.pageContext);
       _root = configService.getParam(SystemConstants.PAR_RESOURCES_ROOT_URL);
     }
     if (null == _folder) {
       _folder = "";
     }
     pageContext.getOut().print(_root + _folder);
   } catch (Throwable e) {
     ApsSystemUtils.logThrowable(e, this, "doEndTag");
     throw new JspException("Error closing the tag", e);
   }
   return EVAL_PAGE;
 }
  @Override
  public int doStartTag() throws JspException {

    IRssManager rssManager =
        (IRssManager)
            ApsWebApplicationUtils.getBean(JpRssSystemConstants.RSS_MANAGER, this.pageContext);

    try {

      List<Channel> activeChannels = rssManager.getChannels(Channel.STATUS_ACTIVE);

      this.pageContext.setAttribute(this.getListName(), activeChannels);

    } catch (Throwable t) {
      _logger.error("error in doStartTag", t);

      throw new JspException("Error in RssListTag - doStartTag", t);
    }

    return super.doStartTag();
  }
  public int doEndTag() throws JspException {
    try {
      IAvatarManager avatarManager =
          (IAvatarManager)
              ApsWebApplicationUtils.getBean(JpAvatarSystemConstants.AVATAR_MANAGER, pageContext);
      HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
      UserDetails currentUser =
          (UserDetails)
              request.getSession().getAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER);

      boolean isCurrentUserGuest =
          null == currentUser
              || currentUser.getUsername().trim().length() == 0
              || currentUser.getUsername().equalsIgnoreCase(SystemConstants.GUEST_USER_NAME);
      if (StringUtils.isBlank(this.getUsername()) && isCurrentUserGuest) {
        this.doOut(this.getNullAvatar(avatarManager));
      } else {
        String username = this.getUsername();
        if (StringUtils.isBlank(username)) {
          username = currentUser.getUsername();
        }
        String avatarName = avatarManager.getAvatarUrl(username);
        if (null != avatarName) {
          this.doOut(avatarName);
        } else {
          this.doOut(this.getNullAvatar(avatarManager));
        }
      }
      if (StringUtils.isNotBlank(this.getAvatarStyleVar())) {
        this.pageContext
            .getRequest()
            .setAttribute(this.getAvatarStyleVar(), avatarManager.getConfig().getStyle());
      }
    } catch (Throwable e) {
      ApsSystemUtils.logThrowable(e, this, "doEndTag");
      throw new JspException("Error in AvatarTag", e);
    }
    return EVAL_PAGE;
  }
  @Override
  public boolean uninstallComponent(Component component) throws ApsSystemException {
    ServletContext servletContext =
        ((ConfigurableWebApplicationContext) _applicationContext).getServletContext();
    ClassLoader cl = (ClassLoader) servletContext.getAttribute("componentInstallerClassLoader");
    List<ClassPathXmlApplicationContext> ctxList =
        (List<ClassPathXmlApplicationContext>) servletContext.getAttribute("pluginsContextsList");
    ClassPathXmlApplicationContext appCtx = null;
    if (ctxList != null) {
      for (ClassPathXmlApplicationContext ctx : ctxList) {
        if (component.getCode().equals(ctx.getDisplayName())) {
          appCtx = ctx;
        }
      }
    }
    String appRootPath = servletContext.getRealPath("/");
    String backupDirPath =
        appRootPath + "componentinstaller" + File.separator + component.getArtifactId() + "-backup";
    Map<File, File> resourcesMap = new HashMap<File, File>();
    try {
      ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
      try {
        if (cl != null) {
          Thread.currentThread().setContextClassLoader(cl);
        }
        if (null == component || null == component.getUninstallerInfo()) {
          return false;
        }
        this.getDatabaseManager().createBackup(); // backup database
        SystemInstallationReport report = super.extractReport();
        ComponentUninstallerInfo ui = component.getUninstallerInfo();
        // remove records from db
        String[] dataSourceNames = this.extractBeanNames(DataSource.class);
        for (int j = 0; j < dataSourceNames.length; j++) {
          String dataSourceName = dataSourceNames[j];
          Resource resource = (null != ui) ? ui.getSqlResources(dataSourceName) : null;
          String script = (null != resource) ? this.readFile(resource) : null;
          if (null != script && script.trim().length() > 0) {
            DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
            String[] queries = QueryExtractor.extractDeleteQueries(script);
            TableDataUtils.executeQueries(dataSource, queries, true);
          }
        }
        this.executePostProcesses(ui.getPostProcesses());

        // drop tables
        Map<String, List<String>> tableMapping = component.getTableMapping();
        if (tableMapping != null) {
          for (int j = 0; j < dataSourceNames.length; j++) {
            String dataSourceName = dataSourceNames[j];
            List<String> tableClasses = tableMapping.get(dataSourceName);
            if (null != tableClasses && tableClasses.size() > 0) {
              List<String> newList = new ArrayList<String>();
              newList.addAll(tableClasses);
              Collections.reverse(newList);
              DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
              IDatabaseManager.DatabaseType type =
                  this.getDatabaseManager().getDatabaseType(dataSource);
              TableFactory tableFactory = new TableFactory(dataSourceName, dataSource, type);
              tableFactory.dropTables(newList);
            }
          }
        }

        // move resources (jar, files and folders) on temp folder
        List<String> resourcesPaths = ui.getResourcesPaths();
        if (resourcesPaths != null) {
          for (String resourcePath : resourcesPaths) {
            try {
              String fullResourcePath = servletContext.getRealPath(resourcePath);
              File resFile = new File(fullResourcePath);
              String relResPath = FilenameUtils.getPath(resFile.getAbsolutePath());
              File newResFile =
                  new File(backupDirPath + File.separator + relResPath + resFile.getName());
              if (resFile.isDirectory()) {
                FileUtils.copyDirectory(resFile, newResFile);
                resourcesMap.put(resFile, newResFile);
                FileUtils.deleteDirectory(resFile);
              } else {
                FileUtils.copyFile(resFile, newResFile);
                resourcesMap.put(resFile, newResFile);
                FileUtils.forceDelete(resFile);
              }
            } catch (Exception e) {
            }
          }
        }

        // upgrade report
        ComponentInstallationReport cir = report.getComponentReport(component.getCode(), true);
        cir.getDataSourceReport()
            .upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
        cir.getDataReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
        this.saveReport(report);

        // remove plugin's xmlapplicationcontext if present
        if (appCtx != null) {
          appCtx.close();
          ctxList.remove(appCtx);
        }
        InitializerManager initializerManager =
            (InitializerManager) _applicationContext.getBean("InitializerManager");
        initializerManager.reloadCurrentReport();
        ComponentManager componentManager =
            (ComponentManager) _applicationContext.getBean("ComponentManager");
        componentManager.refresh();
      } catch (Exception e) {
        _logger.error("Unexpected error in component uninstallation process", e);
        throw new ApsSystemException("Unexpected error in component uninstallation process.", e);
      } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
        ApsWebApplicationUtils.executeSystemRefresh(servletContext);
      }
    } catch (Throwable t) {
      // restore files on temp folder
      try {
        for (Object object : resourcesMap.entrySet()) {
          File resFile = ((Map.Entry<File, File>) object).getKey();
          File newResFile = ((Map.Entry<File, File>) object).getValue();
          if (newResFile.isDirectory()) {
            FileUtils.copyDirectoryToDirectory(newResFile, resFile.getParentFile());
          } else {
            FileUtils.copyFile(newResFile, resFile.getParentFile());
          }
        }
      } catch (Exception e) {
      }
      _logger.error("Unexpected error in component uninstallation process", t);
      throw new ApsSystemException("Unexpected error in component uninstallation process.", t);
    } finally {
      // clean temp folder
    }
    return true;
  }