protected List<String> getPortletMimeTypeActions(String name) {
    List<String> actions = new UniqueList<String>();

    Portlet portlet = portletLocalService.getPortletById(name);

    if (portlet != null) {
      Map<String, Set<String>> portletModes = portlet.getPortletModes();

      Set<String> mimeTypePortletModes = portletModes.get(ContentTypes.TEXT_HTML);

      if (mimeTypePortletModes != null) {
        for (String actionId : mimeTypePortletModes) {
          if (StringUtil.equalsIgnoreCase(actionId, "edit")) {
            actions.add(ActionKeys.PREFERENCES);
          } else if (StringUtil.equalsIgnoreCase(actionId, "edit_guest")) {

            actions.add(ActionKeys.GUEST_PREFERENCES);
          } else {
            actions.add(StringUtil.toUpperCase(actionId));
          }
        }
      }
    } else {
      if (_log.isDebugEnabled()) {
        _log.debug("Unable to obtain resource actions for unknown portlet " + name);
      }
    }

    return actions;
  }
  protected void testCanonicalURL(
      String virtualHostname,
      String portalDomain,
      Group group,
      Layout layout,
      Locale[] groupAvailableLocales,
      Locale groupDefaultLocale,
      String i18nPath,
      String expectedLayoutFriendlyURL,
      boolean forceLayoutFriendlyURL)
      throws Exception {

    if (!group.isGuest()) {
      group =
          GroupTestUtil.updateDisplaySettings(
              group.getGroupId(), groupAvailableLocales, groupDefaultLocale);
    }

    String completeURL =
        generateURL(portalDomain, i18nPath, group.getFriendlyURL(), layout.getFriendlyURL());

    setVirtualHost(layout.getCompanyId(), virtualHostname);

    ThemeDisplay themeDisplay = getThemeDisplay(group);

    themeDisplay.setPortalURL("http://" + portalDomain + ":8080/");

    String actualCanonicalURL =
        PortalUtil.getCanonicalURL(completeURL, themeDisplay, layout, forceLayoutFriendlyURL);

    String expectedGroupFriendlyURL = StringPool.BLANK;

    if (!group.isGuest()) {
      expectedGroupFriendlyURL = group.getFriendlyURL();
    }

    String expectedPortalDomain = virtualHostname;

    if (StringUtil.equalsIgnoreCase(virtualHostname, "localhost")
        && !StringUtil.equalsIgnoreCase(portalDomain, "localhost")) {

      expectedPortalDomain = portalDomain;
    }

    String expectedCanonicalURL =
        generateURL(
            expectedPortalDomain,
            StringPool.BLANK,
            expectedGroupFriendlyURL,
            expectedLayoutFriendlyURL);

    Assert.assertEquals(expectedCanonicalURL, actualCanonicalURL);
  }
  protected boolean tableHasColumn(String tableName, String columnName) throws Exception {

    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      ps = connection.prepareStatement("select * from " + tableName);

      rs = ps.executeQuery();

      ResultSetMetaData rsmd = rs.getMetaData();

      for (int i = 0; i < rsmd.getColumnCount(); i++) {
        String curColumnName = rsmd.getColumnName(i + 1);

        if (StringUtil.equalsIgnoreCase(curColumnName, columnName)) {
          return true;
        }
      }
    } catch (Exception e) {
      _log.error(e, e);
    } finally {
      DataAccess.cleanUp(ps, rs);
    }

    return false;
  }
  protected void validate(long entryId, long userId, String fullName, String emailAddress)
      throws PortalException {

    if (Validator.isNull(fullName)) {
      throw new ContactFullNameException();
    }

    if (Validator.isNull(emailAddress)) {
      throw new RequiredEntryEmailAddressException();
    }

    if (!Validator.isEmailAddress(emailAddress)) {
      throw new EntryEmailAddressException();
    }

    if (entryId > 0) {
      Entry entry = entryPersistence.findByPrimaryKey(entryId);

      if (!StringUtil.equalsIgnoreCase(emailAddress, entry.getEmailAddress())) {

        validateEmailAddress(userId, emailAddress);
      }
    } else {
      validateEmailAddress(userId, emailAddress);
    }
  }
  @Override
  public boolean hasCompanyMx(String emailAddress) throws SystemException {
    emailAddress = StringUtil.toLowerCase(emailAddress.trim());

    int pos = emailAddress.indexOf(CharPool.AT);

    if (pos == -1) {
      return false;
    }

    String mx = emailAddress.substring(pos + 1);

    if (mx.equals(getMx())) {
      return true;
    }

    String[] mailHostNames =
        PrefsPropsUtil.getStringArray(
            getCompanyId(),
            PropsKeys.ADMIN_MAIL_HOST_NAMES,
            StringPool.NEW_LINE,
            PropsValues.ADMIN_MAIL_HOST_NAMES);

    for (int i = 0; i < mailHostNames.length; i++) {
      if (StringUtil.equalsIgnoreCase(mx, mailHostNames[i])) {
        return true;
      }
    }

    return false;
  }
  public static String checkOrderByType(String orderByType) {
    if ((orderByType == null) || StringUtil.equalsIgnoreCase(orderByType, "DESC")) {

      return "DESC";
    } else {
      return "ASC";
    }
  }
Example #7
0
  private boolean _isOverwrite(HttpServletRequest request) {
    String value = GetterUtil.getString(request.getHeader("Overwrite"));

    if (StringUtil.equalsIgnoreCase(value, "F") || !GetterUtil.getBoolean(value)) {

      return false;
    } else {
      return true;
    }
  }
    public static boolean containsIgnoreCase(Collection<String> columnNames, String columnName) {

      for (String curColumnName : columnNames) {
        if (StringUtil.equalsIgnoreCase(curColumnName, columnName)) {
          return true;
        }
      }

      return false;
    }
  @Override
  public void processAction(ActionRequest actionRequest, ActionResponse actionResponse)
      throws IOException, PortletException {

    super.processAction(actionRequest, actionResponse);

    String actionName = ParamUtil.getString(actionRequest, ActionRequest.ACTION_NAME);

    if (StringUtil.equalsIgnoreCase(actionName, "invokeTaglibDiscussion")) {
      hideDefaultSuccessMessage(actionRequest);
    }
  }
Example #10
0
  public static void collectPartContent(Part part, MBMailMessage mbMailMessage) throws Exception {

    Object partContent = part.getContent();

    String contentType = StringUtil.toLowerCase(part.getContentType());

    if ((part.getDisposition() != null)
        && StringUtil.equalsIgnoreCase(part.getDisposition(), MimeMessage.ATTACHMENT)) {

      if (_log.isDebugEnabled()) {
        _log.debug("Processing attachment");
      }

      byte[] bytes = null;

      if (partContent instanceof String) {
        bytes = ((String) partContent).getBytes();
      } else if (partContent instanceof InputStream) {
        bytes = JavaMailUtil.getBytes(part);
      }

      mbMailMessage.addBytes(part.getFileName(), bytes);
    } else {
      if (partContent instanceof MimeMultipart) {
        MimeMultipart mimeMultipart = (MimeMultipart) partContent;

        collectMultipartContent(mimeMultipart, mbMailMessage);
      } else if (partContent instanceof String) {
        Map<String, Object> options = new HashMap<String, Object>();

        options.put("emailPartToMBMessageBody", Boolean.TRUE);

        String messageBody =
            SanitizerUtil.sanitize(
                0,
                0,
                0,
                MBMessage.class.getName(),
                0,
                contentType,
                Sanitizer.MODE_ALL,
                (String) partContent,
                options);

        if (contentType.startsWith(ContentTypes.TEXT_HTML)) {
          mbMailMessage.setHtmlBody(messageBody);
        } else {
          mbMailMessage.setPlainBody(messageBody);
        }
      }
    }
  }
  /**
   * See {@link com.liferay.portal.service.BaseServiceImpl#getUserId()}
   *
   * @deprecated As of 7.0.0, with no direct replacement
   */
  @Deprecated
  public static long getUserId() throws PrincipalException {
    String name = PrincipalThreadLocal.getName();

    if (Validator.isNull(name)) {
      throw new PrincipalException("Principal is null");
    } else {
      for (int i = 0; i < BaseServiceImpl.ANONYMOUS_NAMES.length; i++) {
        if (StringUtil.equalsIgnoreCase(name, BaseServiceImpl.ANONYMOUS_NAMES[i])) {

          throw new PrincipalException("Principal cannot be " + BaseServiceImpl.ANONYMOUS_NAMES[i]);
        }
      }
    }

    return GetterUtil.getLong(name);
  }
Example #12
0
  @Override
  public boolean isOfficeExtension(String extension) {
    if (StringUtil.equalsIgnoreCase(extension, "doc")
        || StringUtil.equalsIgnoreCase(extension, "docx")
        || StringUtil.equalsIgnoreCase(extension, "dot")
        || StringUtil.equalsIgnoreCase(extension, "ppt")
        || StringUtil.equalsIgnoreCase(extension, "pptx")
        || StringUtil.equalsIgnoreCase(extension, "xls")
        || StringUtil.equalsIgnoreCase(extension, "xlsx")) {

      return true;
    }

    return false;
  }
  @Override
  public boolean evaluate(
      HttpServletRequest request, RuleInstance ruleInstance, AnonymousUser anonymousUser)
      throws Exception {

    JSONObject typeSettings = JSONFactoryUtil.createJSONObject(anonymousUser.getTypeSettings());

    User user = FacebookUtil.getFacebookUser(typeSettings.getString(WebKeys.FACEBOOK_ACCESS_TOKEN));

    String gender = ruleInstance.getTypeSettings();

    if (gender.equals("custom") && Validator.isNull(user.getGender())) {
      return true;
    }

    if (StringUtil.equalsIgnoreCase(gender, user.getGender())) {
      return true;
    }

    return false;
  }
  private LuceneHelperImpl() {
    if (PropsValues.INDEX_ON_STARTUP && PropsValues.INDEX_WITH_THREAD) {
      _luceneIndexThreadPoolExecutor =
          PortalExecutorManagerUtil.getPortalExecutor(LuceneHelperImpl.class.getName());
    }

    if (isLoadIndexFromClusterEnabled()) {
      _loadIndexClusterEventListener = new LoadIndexClusterEventListener();

      ClusterExecutorUtil.addClusterEventListener(_loadIndexClusterEventListener);
    }

    BooleanQuery.setMaxClauseCount(_LUCENE_BOOLEAN_QUERY_CLAUSE_MAX_SIZE);

    if (StringUtil.equalsIgnoreCase(Http.HTTPS, PropsValues.WEB_SERVER_PROTOCOL)) {

      _protocol = Http.HTTPS;
    } else {
      _protocol = Http.HTTP;
    }
  }
Example #15
0
/**
 * @author Brian Wing Shun Chan
 * @author Jorge Ferrer
 * @author Brian Myunghun Kim
 */
public class MainServlet extends ActionServlet {

  @Override
  public void destroy() {
    if (_log.isDebugEnabled()) {
      _log.debug("Destroy plugins");
    }

    PortalLifecycleUtil.flushDestroys();

    List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();

    if (_log.isDebugEnabled()) {
      _log.debug("Destroy portlets");
    }

    try {
      destroyPortlets(portlets);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Destroy companies");
    }

    try {
      destroyCompanies();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Process global shutdown events");
    }

    try {
      processGlobalShutdownEvents();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Destroy");
    }

    callParentDestroy();
  }

  @Override
  public void init() throws ServletException {
    if (_log.isDebugEnabled()) {
      _log.debug("Initialize");
    }

    ServletContext servletContext = getServletContext();

    servletContext.setAttribute(MainServlet.class.getName(), Boolean.TRUE);

    callParentInit();

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize servlet context pool");
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Process startup events");
    }

    try {
      processStartupEvents();
    } catch (Exception e) {
      _log.error(e, e);

      System.out.println("Stopping the server due to unexpected startup errors");

      System.exit(0);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize server detector");
    }

    try {
      initServerDetector();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize plugin package");
    }

    PluginPackage pluginPackage = null;

    try {
      pluginPackage = initPluginPackage();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize portlets");
    }

    List<Portlet> portlets = new ArrayList<Portlet>();

    try {
      portlets.addAll(initPortlets(pluginPackage));
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize layout templates");
    }

    try {
      initLayoutTemplates(pluginPackage, portlets);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize social");
    }

    try {
      initSocial(pluginPackage);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize themes");
    }

    try {
      initThemes(pluginPackage, portlets);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize web settings");
    }

    try {
      initWebSettings();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize extension environment");
    }

    try {
      initExt();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Process global startup events");
    }

    try {
      processGlobalStartupEvents();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize resource actions");
    }

    try {
      initResourceActions(portlets);
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize companies");
    }

    try {
      initCompanies();
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Initialize plugins");
    }

    try {
      initPlugins();
    } catch (Exception e) {
      _log.error(e, e);
    }

    servletContext.setAttribute(WebKeys.STARTUP_FINISHED, true);

    StartupHelperUtil.setStartupFinished(true);

    ThreadLocalCacheManager.clearAll(Lifecycle.REQUEST);
  }

  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (_log.isDebugEnabled()) {
      _log.debug("Process service request");
    }

    if (processShutdownRequest(request, response)) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processed shutdown request");
      }

      return;
    }

    if (processMaintenanceRequest(request, response)) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processed maintenance request");
      }

      return;
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Get company id");
    }

    long companyId = getCompanyId(request);

    if (processCompanyInactiveRequest(request, response, companyId)) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processed company inactive request");
      }

      return;
    }

    try {
      if (processGroupInactiveRequest(request, response)) {
        if (_log.isDebugEnabled()) {
          _log.debug("Processed site inactive request");
        }

        return;
      }
    } catch (Exception e) {
      if (e instanceof NoSuchLayoutException) {
        if (_log.isDebugEnabled()) {
          _log.debug(e, e);
        }
      } else {
        _log.error(e, e);
      }
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Set portal port");
    }

    setPortalPort(request);

    if (_log.isDebugEnabled()) {
      _log.debug("Check variables");
    }

    checkServletContext(request);
    checkPortletRequestProcessor(request);
    checkTilesDefinitionsFactory();

    if (_log.isDebugEnabled()) {
      _log.debug("Handle non-serializable request");
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Encrypt request");
    }

    request = encryptRequest(request, companyId);

    long userId = getUserId(request);

    String remoteUser = getRemoteUser(request, userId);

    if (_log.isDebugEnabled()) {
      _log.debug("Protect request");
    }

    request = protectRequest(request, remoteUser);

    if (_log.isDebugEnabled()) {
      _log.debug("Set principal");
    }

    String password = getPassword(request);

    setPrincipal(companyId, userId, remoteUser, password);

    try {
      if (_log.isDebugEnabled()) {
        _log.debug("Authenticate user id " + userId + " and remote user " + remoteUser);
      }

      userId = loginUser(request, response, companyId, userId, remoteUser);

      if (_log.isDebugEnabled()) {
        _log.debug("Authenticated user id " + userId);
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (_log.isDebugEnabled()) {
      _log.debug("Set session thread local");
    }

    PortalSessionThreadLocal.setHttpSession(request.getSession());

    if (_log.isDebugEnabled()) {
      _log.debug("Process service pre events");
    }

    if (processServicePre(request, response, userId)) {
      if (_log.isDebugEnabled()) {
        _log.debug("Processing service pre events has errors");
      }

      return;
    }

    if (hasAbsoluteRedirect(request)) {
      if (_log.isDebugEnabled()) {
        String currentURL = PortalUtil.getCurrentURL(request);

        _log.debug("Current URL " + currentURL + " has absolute redirect");
      }

      return;
    }

    if (!hasThemeDisplay(request)) {
      if (_log.isDebugEnabled()) {
        String currentURL = PortalUtil.getCurrentURL(request);

        _log.debug("Current URL " + currentURL + " does not have a theme display");
      }

      return;
    }

    try {
      if (_log.isDebugEnabled()) {
        _log.debug("Call parent service");
      }

      callParentService(request, response);
    } finally {
      if (_log.isDebugEnabled()) {
        _log.debug("Process service post events");
      }

      processServicePost(request, response);
    }
  }

  protected void callParentDestroy() {
    super.destroy();
  }

  protected void callParentInit() throws ServletException {
    super.init();
  }

  protected void callParentService(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    super.service(request, response);
  }

  protected void checkPortletRequestProcessor(HttpServletRequest request) throws ServletException {

    ServletContext servletContext = getServletContext();

    PortletRequestProcessor portletReqProcessor =
        (PortletRequestProcessor) servletContext.getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR);

    if (portletReqProcessor == null) {
      ModuleConfig moduleConfig = getModuleConfig(request);

      portletReqProcessor = PortletRequestProcessor.getInstance(this, moduleConfig);

      servletContext.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
    }
  }

  protected void checkServletContext(HttpServletRequest request) {
    ServletContext servletContext = getServletContext();

    request.setAttribute(WebKeys.CTX, servletContext);

    String contextPath = request.getContextPath();

    servletContext.setAttribute(WebKeys.CTX_PATH, contextPath);
  }

  protected void checkTilesDefinitionsFactory() {
    ServletContext servletContext = getServletContext();

    if (servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) != null) {

      return;
    }

    servletContext.setAttribute(
        TilesUtilImpl.DEFINITIONS_FACTORY,
        servletContext.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
  }

  protected void checkWebSettings(String xml) throws DocumentException {
    Document doc = SAXReaderUtil.read(xml);

    Element root = doc.getRootElement();

    int timeout = PropsValues.SESSION_TIMEOUT;

    Element sessionConfig = root.element("session-config");

    if (sessionConfig != null) {
      String sessionTimeout = sessionConfig.elementText("session-timeout");

      timeout = GetterUtil.getInteger(sessionTimeout, timeout);
    }

    PropsUtil.set(PropsKeys.SESSION_TIMEOUT, String.valueOf(timeout));

    PropsValues.SESSION_TIMEOUT = timeout;

    I18nServlet.setLanguageIds(root);
    I18nFilter.setLanguageIds(I18nServlet.getLanguageIds());
  }

  protected void destroyCompanies() throws Exception {
    long[] companyIds = PortalInstances.getCompanyIds();

    for (long companyId : companyIds) {
      destroyCompany(companyId);
    }
  }

  protected void destroyCompany(long companyId) {
    if (_log.isDebugEnabled()) {
      _log.debug("Process shutdown events");
    }

    try {
      EventsProcessorUtil.process(
          PropsKeys.APPLICATION_SHUTDOWN_EVENTS,
          PropsValues.APPLICATION_SHUTDOWN_EVENTS,
          new String[] {String.valueOf(companyId)});
    } catch (Exception e) {
      _log.error(e, e);
    }
  }

  protected void destroyPortlets(List<Portlet> portlets) throws Exception {
    for (Portlet portlet : portlets) {
      PortletInstanceFactoryUtil.destroy(portlet);
    }
  }

  protected HttpServletRequest encryptRequest(HttpServletRequest request, long companyId) {

    boolean encryptRequest = ParamUtil.getBoolean(request, WebKeys.ENCRYPT);

    if (!encryptRequest) {
      return request;
    }

    try {
      Company company = CompanyLocalServiceUtil.getCompanyById(companyId);

      request = new EncryptedServletRequest(request, company.getKeyObj());
    } catch (Exception e) {
    }

    return request;
  }

  protected long getCompanyId(HttpServletRequest request) {
    return PortalInstances.getCompanyId(request);
  }

  protected String getPassword(HttpServletRequest request) {
    return PortalUtil.getUserPassword(request);
  }

  protected String getRemoteUser(HttpServletRequest request, long userId) {
    String remoteUser = request.getRemoteUser();

    if (!PropsValues.PORTAL_JAAS_ENABLE) {
      HttpSession session = request.getSession();

      String jRemoteUser = (String) session.getAttribute("j_remoteuser");

      if (jRemoteUser != null) {
        remoteUser = jRemoteUser;

        session.removeAttribute("j_remoteuser");
      }
    }

    if ((userId > 0) && (remoteUser == null)) {
      remoteUser = String.valueOf(userId);
    }

    return remoteUser;
  }

  @Override
  protected synchronized RequestProcessor getRequestProcessor(ModuleConfig moduleConfig)
      throws ServletException {

    ServletContext servletContext = getServletContext();

    String key = Globals.REQUEST_PROCESSOR_KEY + moduleConfig.getPrefix();

    RequestProcessor requestProcessor = (RequestProcessor) servletContext.getAttribute(key);

    if (requestProcessor == null) {
      ControllerConfig controllerConfig = moduleConfig.getControllerConfig();

      try {
        requestProcessor =
            (RequestProcessor)
                InstanceFactory.newInstance(
                    ClassLoaderUtil.getPortalClassLoader(), controllerConfig.getProcessorClass());
      } catch (Exception e) {
        throw new ServletException(e);
      }

      requestProcessor.init(this, moduleConfig);

      servletContext.setAttribute(key, requestProcessor);
    }

    return requestProcessor;
  }

  protected long getUserId(HttpServletRequest request) {
    return PortalUtil.getUserId(request);
  }

  protected boolean hasAbsoluteRedirect(HttpServletRequest request) {
    if (request.getAttribute(AbsoluteRedirectsResponse.class.getName()) == null) {

      return false;
    } else {
      return true;
    }
  }

  protected boolean hasThemeDisplay(HttpServletRequest request) {
    if (request.getAttribute(WebKeys.THEME_DISPLAY) == null) {
      return false;
    } else {
      return true;
    }
  }

  protected void initCompanies() throws Exception {
    ServletContext servletContext = getServletContext();

    try {
      String[] webIds = PortalInstances.getWebIds();

      for (String webId : webIds) {
        PortalInstances.initCompany(servletContext, webId);
      }
    } finally {
      CompanyThreadLocal.setCompanyId(PortalInstances.getDefaultCompanyId());

      ShardDataSourceTargetSource shardDataSourceTargetSource =
          (ShardDataSourceTargetSource) InfrastructureUtil.getShardDataSourceTargetSource();

      if (shardDataSourceTargetSource != null) {
        shardDataSourceTargetSource.resetDataSource();
      }
    }
  }

  protected void initExt() throws Exception {
    ServletContext servletContext = getServletContext();

    ExtRegistry.registerPortal(servletContext);
  }

  protected void initLayoutTemplates(PluginPackage pluginPackage, List<Portlet> portlets)
      throws Exception {

    ServletContext servletContext = getServletContext();

    String[] xmls =
        new String[] {
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-layout-templates.xml")),
          HttpUtil.URLtoString(
              servletContext.getResource("/WEB-INF/liferay-layout-templates-ext.xml"))
        };

    List<LayoutTemplate> layoutTemplates =
        LayoutTemplateLocalServiceUtil.init(servletContext, xmls, pluginPackage);

    servletContext.setAttribute(WebKeys.PLUGIN_LAYOUT_TEMPLATES, layoutTemplates);
  }

  protected PluginPackage initPluginPackage() throws Exception {
    ServletContext servletContext = getServletContext();

    return PluginPackageUtil.readPluginPackageServletContext(servletContext);
  }

  /** @see SetupWizardUtil#_initPlugins */
  protected void initPlugins() throws Exception {

    // See LEP-2885. Don't flush hot deploy events until after the portal
    // has initialized.

    if (SetupWizardUtil.isSetupFinished()) {
      HotDeployUtil.setCapturePrematureEvents(false);

      PortalLifecycleUtil.flushInits();
    }
  }

  protected void initPortletApp(Portlet portlet, ServletContext servletContext)
      throws PortletException {

    PortletApp portletApp = portlet.getPortletApp();

    PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, servletContext);

    PortletContext portletContext = portletConfig.getPortletContext();

    Set<PortletFilter> portletFilters = portletApp.getPortletFilters();

    for (PortletFilter portletFilter : portletFilters) {
      PortletFilterFactory.create(portletFilter, portletContext);
    }

    Set<PortletURLListener> portletURLListeners = portletApp.getPortletURLListeners();

    for (PortletURLListener portletURLListener : portletURLListeners) {
      PortletURLListenerFactory.create(portletURLListener);
    }
  }

  protected List<Portlet> initPortlets(PluginPackage pluginPackage) throws Exception {

    ServletContext servletContext = getServletContext();

    String[] xmls =
        new String[] {
          HttpUtil.URLtoString(
              servletContext.getResource("/WEB-INF/" + Portal.PORTLET_XML_FILE_NAME_CUSTOM)),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/portlet-ext.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-portlet.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-portlet-ext.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/web.xml"))
        };

    PortletLocalServiceUtil.initEAR(servletContext, xmls, pluginPackage);

    PortletBagFactory portletBagFactory = new PortletBagFactory();

    portletBagFactory.setClassLoader(ClassLoaderUtil.getPortalClassLoader());
    portletBagFactory.setServletContext(servletContext);
    portletBagFactory.setWARFile(false);

    List<Portlet> portlets = PortletLocalServiceUtil.getPortlets();

    for (int i = 0; i < portlets.size(); i++) {
      Portlet portlet = portlets.get(i);

      portletBagFactory.create(portlet);

      if (i == 0) {
        initPortletApp(portlet, servletContext);
      }
    }

    servletContext.setAttribute(WebKeys.PLUGIN_PORTLETS, portlets);

    return portlets;
  }

  protected void initResourceActions(List<Portlet> portlets) throws Exception {

    for (Portlet portlet : portlets) {
      List<String> portletActions = ResourceActionsUtil.getPortletResourceActions(portlet);

      ResourceActionLocalServiceUtil.checkResourceActions(portlet.getPortletId(), portletActions);

      List<String> modelNames =
          ResourceActionsUtil.getPortletModelResources(portlet.getPortletId());

      for (String modelName : modelNames) {
        List<String> modelActions = ResourceActionsUtil.getModelResourceActions(modelName);

        ResourceActionLocalServiceUtil.checkResourceActions(modelName, modelActions);
      }
    }
  }

  protected void initServerDetector() throws Exception {
    ServerCapabilitiesUtil.determineServerCapabilities(getServletContext());
  }

  protected void initSocial(PluginPackage pluginPackage) throws Exception {
    ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader();

    ServletContext servletContext = getServletContext();

    String[] xmls =
        new String[] {
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-social.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-social-ext.xml"))
        };

    SocialConfigurationUtil.read(classLoader, xmls);
  }

  protected void initThemes(PluginPackage pluginPackage, List<Portlet> portlets) throws Exception {

    ServletContext servletContext = getServletContext();

    String[] xmls =
        new String[] {
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-look-and-feel.xml")),
          HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-look-and-feel-ext.xml"))
        };

    List<Theme> themes =
        ThemeLocalServiceUtil.init(servletContext, null, true, xmls, pluginPackage);

    servletContext.setAttribute(WebKeys.PLUGIN_THEMES, themes);
  }

  protected void initWebSettings() throws Exception {
    ServletContext servletContext = getServletContext();

    String xml = HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/web.xml"));

    checkWebSettings(xml);
  }

  protected long loginUser(
      HttpServletRequest request,
      HttpServletResponse response,
      long companyId,
      long userId,
      String remoteUser)
      throws PortalException, SystemException {

    if ((userId > 0) || (remoteUser == null)) {
      return userId;
    }

    if (PropsValues.PORTAL_JAAS_ENABLE) {
      userId = JAASHelper.getJaasUserId(companyId, remoteUser);
    } else {
      userId = GetterUtil.getLong(remoteUser);
    }

    EventsProcessorUtil.process(
        PropsKeys.LOGIN_EVENTS_PRE, PropsValues.LOGIN_EVENTS_PRE, request, response);

    User user = UserLocalServiceUtil.getUserById(userId);

    if (PropsValues.USERS_UPDATE_LAST_LOGIN) {
      UserLocalServiceUtil.updateLastLogin(userId, request.getRemoteAddr());
    }

    HttpSession session = request.getSession();

    session.setAttribute(WebKeys.USER, user);
    session.setAttribute(WebKeys.USER_ID, new Long(userId));
    session.setAttribute(Globals.LOCALE_KEY, user.getLocale());

    EventsProcessorUtil.process(
        PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST, request, response);

    return userId;
  }

  protected boolean processCompanyInactiveRequest(
      HttpServletRequest request, HttpServletResponse response, long companyId) throws IOException {

    if (PortalInstances.isCompanyActive(companyId)) {
      return false;
    }

    processInactiveRequest(
        request, response, "this-instance-is-inactive-please-contact-the-administrator");

    return true;
  }

  protected void processGlobalShutdownEvents() throws Exception {
    EventsProcessorUtil.process(
        PropsKeys.GLOBAL_SHUTDOWN_EVENTS, PropsValues.GLOBAL_SHUTDOWN_EVENTS);

    super.destroy();
  }

  protected void processGlobalStartupEvents() throws Exception {
    EventsProcessorUtil.process(PropsKeys.GLOBAL_STARTUP_EVENTS, PropsValues.GLOBAL_STARTUP_EVENTS);
  }

  protected boolean processGroupInactiveRequest(
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, PortalException, SystemException {

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (plid <= 0) {
      return false;
    }

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

    Group group = layout.getGroup();

    if (group.isActive()) {
      return false;
    }

    processInactiveRequest(
        request, response, "this-site-is-inactive-please-contact-the-administrator");

    return true;
  }

  protected void processInactiveRequest(
      HttpServletRequest request, HttpServletResponse response, String messageKey)
      throws IOException {

    response.setContentType(ContentTypes.TEXT_HTML_UTF8);

    Locale locale = LocaleUtil.getDefault();

    String message = LanguageUtil.get(locale, messageKey);

    String html = ContentUtil.get("com/liferay/portal/dependencies/inactive.html");

    html = StringUtil.replace(html, "[$MESSAGE$]", message);

    PrintWriter printWriter = response.getWriter();

    printWriter.print(html);
  }

  protected boolean processMaintenanceRequest(
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (!MaintenanceUtil.isMaintaining()) {
      return false;
    }

    RequestDispatcher requestDispatcher =
        request.getRequestDispatcher("/html/portal/maintenance.jsp");

    requestDispatcher.include(request, response);

    return true;
  }

  protected void processServicePost(HttpServletRequest request, HttpServletResponse response) {

    try {
      EventsProcessorUtil.process(
          PropsKeys.SERVLET_SERVICE_EVENTS_POST,
          PropsValues.SERVLET_SERVICE_EVENTS_POST,
          request,
          response);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }

  protected boolean processServicePre(
      HttpServletRequest request, HttpServletResponse response, long userId)
      throws IOException, ServletException {

    try {
      EventsProcessorUtil.process(
          PropsKeys.SERVLET_SERVICE_EVENTS_PRE,
          PropsValues.SERVLET_SERVICE_EVENTS_PRE,
          request,
          response);
    } catch (Exception e) {
      Throwable cause = e.getCause();

      if (cause instanceof NoSuchLayoutException) {
        sendError(HttpServletResponse.SC_NOT_FOUND, cause, request, response);

        return true;
      } else if (cause instanceof PrincipalException) {
        processServicePrePrincipalException(cause, userId, request, response);

        return true;
      }

      _log.error(e, e);

      request.setAttribute(PageContext.EXCEPTION, e);

      ServletContext servletContext = getServletContext();

      StrutsUtil.forward(
          PropsValues.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE, servletContext, request, response);

      return true;
    }

    if (_HTTP_HEADER_VERSION_VERBOSITY_DEFAULT) {
    } else if (_HTTP_HEADER_VERSION_VERBOSITY_PARTIAL) {
      response.addHeader(_LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getName());
    } else {
      response.addHeader(_LIFERAY_PORTAL_REQUEST_HEADER, ReleaseInfo.getReleaseInfo());
    }

    return false;
  }

  protected void processServicePrePrincipalException(
      Throwable t, long userId, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    if (userId > 0) {
      sendError(HttpServletResponse.SC_UNAUTHORIZED, t, request, response);

      return;
    }

    String redirect = PortalUtil.getPathMain().concat("/portal/login");

    String currentURL = PortalUtil.getCurrentURL(request);

    redirect = HttpUtil.addParameter(redirect, "redirect", currentURL);

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (plid > 0) {
      try {
        Layout layout = LayoutLocalServiceUtil.getLayout(plid);

        Group group = layout.getGroup();

        plid = group.getDefaultPublicPlid();

        if ((plid == LayoutConstants.DEFAULT_PLID) || group.isStagingGroup()) {

          Group guestGroup =
              GroupLocalServiceUtil.getGroup(layout.getCompanyId(), GroupConstants.GUEST);

          plid = guestGroup.getDefaultPublicPlid();
        }

        redirect = HttpUtil.addParameter(redirect, "p_l_id", plid);
      } catch (Exception e) {
      }
    }

    response.sendRedirect(redirect);
  }

  protected boolean processShutdownRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    if (!ShutdownUtil.isShutdown()) {
      return false;
    }

    String messageKey = ShutdownUtil.getMessage();

    if (Validator.isNull(messageKey)) {
      messageKey = "the-system-is-shutdown-please-try-again-later";
    }

    processInactiveRequest(request, response, messageKey);

    return true;
  }

  protected void processStartupEvents() throws Exception {
    StartupAction startupAction = new StartupAction();

    startupAction.run(null);
  }

  protected HttpServletRequest protectRequest(HttpServletRequest request, String remoteUser) {

    // WebSphere will not return the remote user unless you are
    // authenticated AND accessing a protected path. Other servers will
    // return the remote user for all threads associated with an
    // authenticated user. We use ProtectedServletRequest to ensure we get
    // similar behavior across all servers.

    return new ProtectedServletRequest(request, remoteUser);
  }

  protected void sendError(
      int status, Throwable t, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    DynamicServletRequest dynamicRequest = new DynamicServletRequest(request);

    // Reset layout params or there will be an infinite loop

    dynamicRequest.setParameter("p_l_id", StringPool.BLANK);

    dynamicRequest.setParameter("groupId", StringPool.BLANK);
    dynamicRequest.setParameter("layoutId", StringPool.BLANK);
    dynamicRequest.setParameter("privateLayout", StringPool.BLANK);

    PortalUtil.sendError(status, (Exception) t, dynamicRequest, response);
  }

  protected void setPortalPort(HttpServletRequest request) {
    PortalUtil.setPortalPort(request);
  }

  protected void setPrincipal(long companyId, long userId, String remoteUser, String password) {

    if ((userId == 0) && (remoteUser == null)) {
      return;
    }

    String name = String.valueOf(userId);

    if (PropsValues.PORTAL_JAAS_ENABLE) {
      long remoteUserId = 0;

      try {
        remoteUserId = JAASHelper.getJaasUserId(companyId, remoteUser);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(e);
        }
      }

      if (remoteUserId > 0) {
        name = String.valueOf(remoteUserId);
      }
    } else if (remoteUser != null) {
      name = remoteUser;
    }

    PrincipalThreadLocal.setName(name);

    PrincipalThreadLocal.setPassword(password);
  }

  private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_DEFAULT =
      StringUtil.equalsIgnoreCase(PropsValues.HTTP_HEADER_VERSION_VERBOSITY, ReleaseInfo.getName());

  private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_PARTIAL =
      StringUtil.equalsIgnoreCase(PropsValues.HTTP_HEADER_VERSION_VERBOSITY, "partial");

  private static final String _LIFERAY_PORTAL_REQUEST_HEADER = "Liferay-Portal";

  private static Log _log = LogFactoryUtil.getLog(MainServlet.class);
}
/**
 * @author Shuyang Zhou
 * @author Raymond Augé
 */
public class PortletContainerUtil {

  public static List<LayoutTypePortlet> getLayoutTypePortlets(Layout layout)
      throws PortletContainerException {

    if (_PORTLET_EVENT_DISTRIBUTION_LAYOUT_SET) {
      List<Layout> layouts = null;

      try {
        layouts =
            LayoutLocalServiceUtil.getLayouts(
                layout.getGroupId(), layout.isPrivateLayout(), LayoutConstants.TYPE_PORTLET);
      } catch (SystemException se) {
        throw new PortletContainerException(se);
      }

      List<LayoutTypePortlet> layoutTypePortlets = new ArrayList<LayoutTypePortlet>(layouts.size());

      for (Layout curLayout : layouts) {
        LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) curLayout.getLayoutType();

        layoutTypePortlets.add(layoutTypePortlet);
      }

      return layoutTypePortlets;
    }

    if (layout.isTypePortlet()) {
      List<LayoutTypePortlet> layoutTypePortlets = new ArrayList<LayoutTypePortlet>(1);

      LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

      layoutTypePortlets.add(layoutTypePortlet);

      return layoutTypePortlets;
    }

    return Collections.emptyList();
  }

  public static PortletContainer getPortletContainer() {
    PortalRuntimePermission.checkGetBeanProperty(PortletContainerUtil.class);

    return _portletContainer;
  }

  public static void preparePortlet(HttpServletRequest request, Portlet portlet)
      throws PortletContainerException {

    getPortletContainer().preparePortlet(request, portlet);
  }

  public static void processAction(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet)
      throws PortletContainerException {

    PortletContainer portletContainer = getPortletContainer();

    ActionResult actionResult = portletContainer.processAction(request, response, portlet);

    List<Event> events = actionResult.getEvents();

    if (!events.isEmpty()) {
      _processEvents(request, response, events);
    }

    String location = actionResult.getLocation();

    if (Validator.isNotNull(location)) {
      try {
        response.sendRedirect(location);
      } catch (IOException ioe) {
        throw new PortletContainerException(ioe);
      }
    }
  }

  public static void processEvent(
      HttpServletRequest request,
      HttpServletResponse response,
      Portlet portlet,
      Layout layout,
      Event event)
      throws PortletContainerException {

    PortletContainer portletContainer = getPortletContainer();

    List<Event> events = portletContainer.processEvent(request, response, portlet, layout, event);

    if (!events.isEmpty()) {
      _processEvents(request, response, events);
    }
  }

  public static void render(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet)
      throws PortletContainerException {

    getPortletContainer().render(request, response, portlet);
  }

  public static void serveResource(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet)
      throws PortletContainerException {

    getPortletContainer().serveResource(request, response, portlet);
  }

  public static HttpServletRequest setupOptionalRenderParameters(
      HttpServletRequest request,
      String renderPath,
      String columnId,
      Integer columnPos,
      Integer columnCount) {

    return setupOptionalRenderParameters(
        request, renderPath, columnId, columnPos, columnCount, null, null);
  }

  public static HttpServletRequest setupOptionalRenderParameters(
      HttpServletRequest request,
      String renderPath,
      String columnId,
      Integer columnPos,
      Integer columnCount,
      Boolean boundary,
      Boolean decorate) {

    if ((_LAYOUT_PARALLEL_RENDER_ENABLE && ServerDetector.isTomcat())
        || _PORTLET_CONTAINER_RESTRICT) {

      RestrictPortletServletRequest restrictPortletServletRequest =
          new RestrictPortletServletRequest(request);

      if (renderPath != null) {
        restrictPortletServletRequest.setAttribute(WebKeys.RENDER_PATH, renderPath);
      }

      if (columnId != null) {
        restrictPortletServletRequest.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId);
      }

      if (columnPos != null) {
        restrictPortletServletRequest.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos);
      }

      if (columnCount != null) {
        restrictPortletServletRequest.setAttribute(
            WebKeys.RENDER_PORTLET_COLUMN_COUNT, columnCount);
      }

      if (boundary != null) {
        restrictPortletServletRequest.setAttribute(WebKeys.RENDER_PORTLET_BOUNDARY, boundary);
      }

      if (decorate != null) {
        restrictPortletServletRequest.setAttribute(WebKeys.PORTLET_DECORATE, decorate);
      }

      return restrictPortletServletRequest;
    }

    TempAttributesServletRequest tempAttributesServletRequest =
        new TempAttributesServletRequest(request);

    if (renderPath != null) {
      tempAttributesServletRequest.setTempAttribute(WebKeys.RENDER_PATH, renderPath);
    }

    if (columnId != null) {
      tempAttributesServletRequest.setTempAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId);
    }

    if (columnPos != null) {
      tempAttributesServletRequest.setTempAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos);
    }

    if (columnCount != null) {
      tempAttributesServletRequest.setTempAttribute(
          WebKeys.RENDER_PORTLET_COLUMN_COUNT, columnCount);
    }

    return tempAttributesServletRequest;
  }

  public void setPortletContainer(PortletContainer portletContainer) {
    PortalRuntimePermission.checkSetBeanProperty(getClass());

    _portletContainer = portletContainer;
  }

  private static void _processEvents(
      HttpServletRequest request, HttpServletResponse response, List<Event> events)
      throws PortletContainerException {

    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    List<LayoutTypePortlet> layoutTypePortlets = getLayoutTypePortlets(layout);

    for (LayoutTypePortlet layoutTypePortlet : layoutTypePortlets) {
      List<Portlet> portlets = null;

      try {
        portlets = layoutTypePortlet.getAllPortlets();
      } catch (Exception e) {
        throw new PortletContainerException(e);
      }

      for (Portlet portlet : portlets) {
        for (Event event : events) {
          javax.xml.namespace.QName qName = event.getQName();

          QName processingQName =
              portlet.getProcessingEvent(qName.getNamespaceURI(), qName.getLocalPart());

          if (processingQName == null) {
            continue;
          }

          processEvent(request, response, portlet, layoutTypePortlet.getLayout(), event);
        }
      }
    }
  }

  private static final boolean _LAYOUT_PARALLEL_RENDER_ENABLE =
      GetterUtil.getBoolean(PropsUtil.get(PropsKeys.LAYOUT_PARALLEL_RENDER_ENABLE));

  private static final boolean _PORTLET_CONTAINER_RESTRICT =
      GetterUtil.getBoolean(PropsUtil.get(PropsKeys.PORTLET_CONTAINER_RESTRICT));

  private static final boolean _PORTLET_EVENT_DISTRIBUTION_LAYOUT_SET =
      !StringUtil.equalsIgnoreCase(PropsUtil.get(PropsKeys.PORTLET_EVENT_DISTRIBUTION), "layout");

  private static PortletContainer _portletContainer;
}
Example #17
0
/**
 * @author Alexander Chow
 * @author Brian Wing Shun Chan
 */
public class XmlRpcImpl implements XmlRpc {

  @Override
  public Fault createFault(int code, String description) {
    return new FaultImpl(code, description);
  }

  @Override
  public Success createSuccess(String description) {
    return new SuccessImpl(description);
  }

  @Override
  public Response executeMethod(String url, String methodName, Object[] arguments)
      throws XmlRpcException {

    try {
      return doExecuteMethod(url, methodName, arguments);
    } catch (Exception e) {
      throw new XmlRpcException(e);
    }
  }

  protected Response doExecuteMethod(String url, String methodName, Object[] arguments)
      throws Exception {

    if (_log.isDebugEnabled()) {
      StringBundler sb = new StringBundler();

      sb.append("XML-RPC invoking ");
      sb.append(methodName);
      sb.append(" ");

      if (arguments != null) {
        for (int i = 0; i < arguments.length; i++) {
          sb.append(arguments[i]);

          if (i < (arguments.length - 1)) {
            sb.append(", ");
          }
        }
      }

      _log.debug(sb.toString());
    }

    String requestXML = XmlRpcParser.buildMethod(methodName, arguments);

    Http.Options options = new Http.Options();

    if (_HTTP_HEADER_VERSION_VERBOSITY_DEFAULT) {
    } else if (_HTTP_HEADER_VERSION_VERBOSITY_PARTIAL) {
      options.addHeader(HttpHeaders.USER_AGENT, ReleaseInfo.getName());
    } else {
      options.addHeader(HttpHeaders.USER_AGENT, ReleaseInfo.getServerInfo());
    }

    options.setBody(requestXML, ContentTypes.TEXT_XML, StringPool.UTF8);
    options.setLocation(url);
    options.setPost(true);

    String responseXML = HttpUtil.URLtoString(options);

    return XmlRpcParser.parseResponse(responseXML);
  }

  private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_DEFAULT =
      StringUtil.equalsIgnoreCase(PropsValues.HTTP_HEADER_VERSION_VERBOSITY, ReleaseInfo.getName());

  private static final boolean _HTTP_HEADER_VERSION_VERBOSITY_PARTIAL =
      StringUtil.equalsIgnoreCase(PropsValues.HTTP_HEADER_VERSION_VERBOSITY, "partial");

  private static Log _log = LogFactoryUtil.getLog(XmlRpcImpl.class);
}
  protected User updateUser(User user, Userinfo userinfo) throws Exception {
    String emailAddress = userinfo.getEmail();
    String firstName = userinfo.getGivenName();
    String lastName = userinfo.getFamilyName();
    boolean male = Validator.equals(userinfo.getGender(), "male");

    if (emailAddress.equals(user.getEmailAddress())
        && firstName.equals(user.getFirstName())
        && lastName.equals(user.getLastName())
        && (male == user.isMale())) {

      return user;
    }

    Contact contact = user.getContact();

    Calendar birthdayCal = CalendarFactoryUtil.getCalendar();

    birthdayCal.setTime(contact.getBirthday());

    int birthdayMonth = birthdayCal.get(Calendar.MONTH);
    int birthdayDay = birthdayCal.get(Calendar.DAY_OF_MONTH);
    int birthdayYear = birthdayCal.get(Calendar.YEAR);

    long[] groupIds = null;
    long[] organizationIds = null;
    long[] roleIds = null;
    List<UserGroupRole> userGroupRoles = null;
    long[] userGroupIds = null;

    ServiceContext serviceContext = new ServiceContext();

    if (!StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {

      UserLocalServiceUtil.updateEmailAddress(
          user.getUserId(), StringPool.BLANK, emailAddress, emailAddress);
    }

    UserLocalServiceUtil.updateEmailAddressVerified(user.getUserId(), true);

    return UserLocalServiceUtil.updateUser(
        user.getUserId(),
        StringPool.BLANK,
        StringPool.BLANK,
        StringPool.BLANK,
        false,
        user.getReminderQueryQuestion(),
        user.getReminderQueryAnswer(),
        user.getScreenName(),
        emailAddress,
        0,
        user.getOpenId(),
        user.getLanguageId(),
        user.getTimeZoneId(),
        user.getGreeting(),
        user.getComments(),
        firstName,
        user.getMiddleName(),
        lastName,
        contact.getPrefixId(),
        contact.getSuffixId(),
        male,
        birthdayMonth,
        birthdayDay,
        birthdayYear,
        contact.getSmsSn(),
        contact.getAimSn(),
        contact.getFacebookSn(),
        contact.getIcqSn(),
        contact.getJabberSn(),
        contact.getMsnSn(),
        contact.getMySpaceSn(),
        contact.getSkypeSn(),
        contact.getTwitterSn(),
        contact.getYmSn(),
        contact.getJobTitle(),
        groupIds,
        organizationIds,
        roleIds,
        userGroupRoles,
        userGroupIds,
        serviceContext);
  }