Example usage for javax.servlet.http HttpServletResponse setDateHeader

List of usage examples for javax.servlet.http HttpServletResponse setDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setDateHeader.

Prototype

public void setDateHeader(String name, long date);

Source Link

Document

Sets a response header with the given name and date-value.

Usage

From source file:com.liferay.portal.events.ServicePreAction.java

public ThemeDisplay initThemeDisplay(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    HttpSession session = request.getSession();

    // Company//  www . ja  v a2  s.c o m

    Company company = PortalUtil.getCompany(request);

    long companyId = company.getCompanyId();

    // CDN host

    String cdnHost = PortalUtil.getCDNHost(request);

    String dynamicResourcesCDNHost = StringPool.BLANK;

    boolean cdnDynamicResourceEnabled = PortalUtil.isCDNDynamicResourcesEnabled(request);

    if (cdnDynamicResourceEnabled) {
        dynamicResourcesCDNHost = cdnHost;
    }

    // Portal URL

    String portalURL = PortalUtil.getPortalURL(request);

    // Paths

    String contextPath = PortalUtil.getPathContext();
    String friendlyURLPrivateGroupPath = PortalUtil.getPathFriendlyURLPrivateGroup();
    String friendlyURLPrivateUserPath = PortalUtil.getPathFriendlyURLPrivateUser();
    String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
    String imagePath = dynamicResourcesCDNHost.concat(PortalUtil.getPathImage());
    String mainPath = PortalUtil.getPathMain();

    String i18nPath = (String) request.getAttribute(WebKeys.I18N_PATH);

    if (Validator.isNotNull(i18nPath)) {
        if (Validator.isNotNull(contextPath)) {
            String i18nContextPath = contextPath.concat(i18nPath);

            friendlyURLPrivateGroupPath = StringUtil.replaceFirst(friendlyURLPrivateGroupPath, contextPath,
                    i18nContextPath);
            friendlyURLPrivateUserPath = StringUtil.replaceFirst(friendlyURLPrivateUserPath, contextPath,
                    i18nContextPath);
            friendlyURLPublicPath = StringUtil.replaceFirst(friendlyURLPublicPath, contextPath,
                    i18nContextPath);
            mainPath = StringUtil.replaceFirst(mainPath, contextPath, i18nContextPath);
        } else {
            friendlyURLPrivateGroupPath = i18nPath.concat(friendlyURLPrivateGroupPath);
            friendlyURLPrivateUserPath = i18nPath.concat(friendlyURLPrivateUserPath);
            friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath);
            mainPath = i18nPath.concat(mainPath);
        }
    }

    // Company logo

    StringBundler sb = new StringBundler(5);

    sb.append(imagePath);
    sb.append("/company_logo?img_id=");
    sb.append(company.getLogoId());
    sb.append("&t=");
    sb.append(WebServerServletTokenUtil.getToken(company.getLogoId()));

    String companyLogo = sb.toString();

    int companyLogoHeight = 0;
    int companyLogoWidth = 0;

    Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(company.getLogoId());

    if (companyLogoImage != null) {
        companyLogoHeight = companyLogoImage.getHeight();
        companyLogoWidth = companyLogoImage.getWidth();
    }

    String realCompanyLogo = companyLogo;
    int realCompanyLogoHeight = companyLogoHeight;
    int realCompanyLogoWidth = companyLogoWidth;

    // User

    User user = null;

    try {
        user = PortalUtil.getUser(request);
    } catch (NoSuchUserException nsue) {
        if (_log.isWarnEnabled()) {
            _log.warn(nsue.getMessage());
        }

        long userId = PortalUtil.getUserId(request);

        if (userId > 0) {
            session.invalidate();
        }

        return null;
    }

    boolean signedIn = false;

    if (user == null) {
        user = company.getDefaultUser();
    } else if (!user.isDefaultUser()) {
        signedIn = true;
    }

    if (PropsValues.BROWSER_CACHE_DISABLED || (PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) {

        response.setDateHeader(HttpHeaders.EXPIRES, 0);
        response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
        response.setHeader(HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE);
    }

    User realUser = user;

    Long realUserId = (Long) session.getAttribute(WebKeys.USER_ID);

    if (realUserId != null) {
        if (user.getUserId() != realUserId.longValue()) {
            realUser = UserLocalServiceUtil.getUserById(realUserId.longValue());
        }
    }

    String doAsUserId = ParamUtil.getString(request, "doAsUserId");
    String doAsUserLanguageId = ParamUtil.getString(request, "doAsUserLanguageId");
    long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId");

    long refererPlid = ParamUtil.getLong(request, "refererPlid");

    if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) {
        refererPlid = 0;
    }

    String controlPanelCategory = ParamUtil.getString(request, "controlPanelCategory");

    // Permission checker

    PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);
    //Modification start (code changed and moved to the bottom)
    // Locale
    /*
        Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY);
            
        if (Validator.isNotNull(doAsUserLanguageId)) {
          locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
        }
            
        String i18nLanguageId = (String)request.getAttribute(
              WebKeys.I18N_LANGUAGE_ID);
            
        if (Validator.isNotNull(i18nLanguageId)) {
          locale = LocaleUtil.fromLanguageId(i18nLanguageId);
        }
        else if (locale == null) {
          if (signedIn) {
              locale = user.getLocale();
          }
          else {
            
              // User previously set their preferred language
            
              String languageId = CookieKeys.getCookie(
          request, CookieKeys.GUEST_LANGUAGE_ID, false);
            
              if (Validator.isNotNull(languageId)) {
      locale = LocaleUtil.fromLanguageId(languageId);
              }
            
              // Get locale from the request
            
              if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
      Enumeration<Locale> locales = request.getLocales();
            
      while (locales.hasMoreElements()) {
          Locale requestLocale = locales.nextElement();
            
          if (Validator.isNull(requestLocale.getCountry())) {
            
              // Locales must contain a country code
            
              requestLocale = LanguageUtil.getLocale(
                      requestLocale.getLanguage());
          }
            
          if (LanguageUtil.isAvailableLocale(requestLocale)) {
              locale = requestLocale;
            
              break;
          }
      }
              }
            
              // Get locale from the default user
            
              if (locale == null) {
      locale = user.getLocale();
              }
            
              if (Validator.isNull(locale.getCountry())) {
            
      // Locales must contain a country code
            
      locale = LanguageUtil.getLocale(locale.getLanguage());
              }
            
              if (!LanguageUtil.isAvailableLocale(locale)) {
      locale = user.getLocale();
              }
          }
            
          session.setAttribute(Globals.LOCALE_KEY, locale);
            
          LanguageUtil.updateCookie(request, response, locale);
        }*/
    //Modification end
    // Cookie support

    try {

        // LEP-4069

        CookieKeys.validateSupportCookie(request);
    } catch (Exception e) {
        CookieKeys.addSupportCookie(request, response);
    }

    // Time zone

    TimeZone timeZone = user.getTimeZone();

    if (timeZone == null) {
        timeZone = company.getTimeZone();
    }

    // Layouts

    if (signedIn) {
        updateUserLayouts(user);
    }

    Layout layout = null;
    List<Layout> layouts = null;

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

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

        long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id");

        if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) {
            Group sourceGroup = GroupLocalServiceUtil.getGroup(sourceGroupId);

            if (layout.isPublicLayout()
                    || SitesUtil.isUserGroupLayoutSetViewable(permissionChecker, layout.getGroup())) {

                layout = new VirtualLayout(layout, sourceGroup);
            } else {
                layout = null;
            }
        }
    } else {
        long groupId = ParamUtil.getLong(request, "groupId");
        boolean privateLayout = ParamUtil.getBoolean(request, "privateLayout");
        long layoutId = ParamUtil.getLong(request, "layoutId");

        if ((groupId > 0) && (layoutId > 0)) {
            layout = LayoutLocalServiceUtil.getLayout(groupId, privateLayout, layoutId);
        }
    }

    Boolean redirectToDefaultLayout = (Boolean) request.getAttribute(WebKeys.REDIRECT_TO_DEFAULT_LAYOUT);

    if (redirectToDefaultLayout == null) {
        redirectToDefaultLayout = Boolean.FALSE;
    }

    if (layout != null) {
        Group group = layout.getGroup();

        if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
            request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
        }

        String ppid = ParamUtil.getString(request, "p_p_id");

        if (Validator.isNull(controlPanelCategory) && Validator.isNotNull(ppid)
                && (LiferayWindowState.isPopUp(request) || LiferayWindowState.isExclusive(request))) {

            controlPanelCategory = _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + ppid;
        }

        boolean viewableGroup = LayoutPermissionUtil.contains(permissionChecker, layout, controlPanelCategory,
                true, ActionKeys.VIEW);
        boolean viewableStaging = GroupPermissionUtil.contains(permissionChecker, group.getGroupId(),
                ActionKeys.VIEW_STAGING);

        if (viewableStaging) {
            layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
        } else if (!viewableGroup && group.isStagingGroup()) {
            layout = null;
        } else
        /* Permissions are managed by Mobile Portlet
        if (!isLoginRequest(request) &&
            (!viewableGroup ||
                (!redirectToDefaultLayout &&
          !LayoutPermissionUtil.contains(
              permissionChecker, layout, false,
              ActionKeys.VIEW)))) {
                
          if (user.isDefaultUser() &&
              PropsValues.AUTH_LOGIN_PROMPT_ENABLED) {
                
            throw new PrincipalException("User is not authenticated");
          }
                
          sb = new StringBundler(6);
                
          sb.append("User ");
          sb.append(user.getUserId());
          sb.append(" is not allowed to access the ");
          sb.append(layout.isPrivateLayout() ? "private" : "public");
          sb.append(" pages of group ");
          sb.append(layout.getGroupId());
                
          if (_log.isWarnEnabled()) {
            _log.warn(sb.toString());
          }
                
          throw new NoSuchLayoutException(sb.toString());
        } else*/ if (isLoginRequest(request) && !viewableGroup) {
            layout = null;
        } else if (group.isLayoutPrototype()) {
            layouts = new ArrayList<Layout>();
        } else {
            layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);

            if (!group.isControlPanel()) {
                doAsGroupId = 0;
            }
        }
    }

    List<Layout> unfilteredLayouts = layouts;

    if (layout == null) {
        Object[] defaultLayout = getDefaultLayout(request, user, signedIn);

        layout = (Layout) defaultLayout[0];
        layouts = (List<Layout>) defaultLayout[1];

        request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
    }

    Object[] viewableLayouts = getViewableLayouts(request, user, permissionChecker, layout, layouts);

    String layoutSetLogo = null;

    layout = (Layout) viewableLayouts[0];
    layouts = (List<Layout>) viewableLayouts[1];

    Group group = null;

    if (layout != null) {
        group = layout.getGroup();

        if (!group.isControlPanel()) {
            rememberVisitedGroupIds(request, group.getGroupId());
        }
    }

    LayoutTypePortlet layoutTypePortlet = null;

    layouts = mergeAdditionalLayouts(request, user, permissionChecker, layout, layouts);

    LayoutSet layoutSet = null;

    boolean hasCustomizeLayoutPermission = false;
    boolean hasUpdateLayoutPermission = false;

    boolean customizedView = SessionParamUtil.getBoolean(request, "customized_view", true);

    if (layout != null) {
        hasCustomizeLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                ActionKeys.CUSTOMIZE);
        hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE);

        layoutSet = layout.getLayoutSet();

        if (company.isSiteLogo()) {
            long logoId = 0;

            if (layoutSet.isLogo()) {
                logoId = layoutSet.getLogoId();

                if (logoId == 0) {
                    logoId = layoutSet.getLiveLogoId();
                }
            } else {
                LayoutSet siblingLayoutSet = LayoutSetLocalServiceUtil.getLayoutSet(layout.getGroupId(),
                        !layout.isPrivateLayout());

                if (siblingLayoutSet.isLogo()) {
                    logoId = siblingLayoutSet.getLogoId();
                }
            }

            if (logoId > 0) {
                sb = new StringBundler(5);

                sb.append(imagePath);
                sb.append("/layout_set_logo?img_id=");
                sb.append(logoId);
                sb.append("&t=");
                sb.append(WebServerServletTokenUtil.getToken(logoId));

                layoutSetLogo = sb.toString();

                Image layoutSetLogoImage = ImageLocalServiceUtil.getCompanyLogo(logoId);

                companyLogo = layoutSetLogo;
                companyLogoHeight = layoutSetLogoImage.getHeight();
                companyLogoWidth = layoutSetLogoImage.getWidth();
            }
        }

        plid = layout.getPlid();

        // Updates to shared layouts are not reflected until the next time
        // the user logs in because group layouts are cached in the session

        layout = (Layout) layout.clone();

        layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

        boolean customizable = layoutTypePortlet.isCustomizable();

        if (!customizable || (group.isLayoutPrototype() || group.isLayoutSetPrototype())) {

            customizedView = false;
        }

        layoutTypePortlet.setCustomizedView(customizedView);
        layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission);

        if (signedIn && customizable && customizedView && hasCustomizeLayoutPermission) {

            PortalPreferences portalPreferences = PortletPreferencesFactoryUtil.getPortalPreferences(companyId,
                    user.getUserId(), true);

            layoutTypePortlet.setPortalPreferences(portalPreferences);
        }

        LayoutClone layoutClone = LayoutCloneFactory.getInstance();

        if (layoutClone != null) {
            String typeSettings = layoutClone.get(request, plid);

            if (typeSettings != null) {
                UnicodeProperties typeSettingsProperties = new UnicodeProperties(true);

                typeSettingsProperties.load(typeSettings);

                String stateMax = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MAX);
                String stateMin = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MIN);
                String modeAbout = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_ABOUT);
                String modeConfig = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_CONFIG);
                String modeEdit = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_EDIT);
                String modeEditDefaults = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
                String modeEditGuest = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST);
                String modeHelp = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_HELP);
                String modePreview = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_PREVIEW);
                String modePrint = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_PRINT);

                layoutTypePortlet.setStateMax(stateMax);
                layoutTypePortlet.setStateMin(stateMin);
                layoutTypePortlet.setModeAbout(modeAbout);
                layoutTypePortlet.setModeConfig(modeConfig);
                layoutTypePortlet.setModeEdit(modeEdit);
                layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
                layoutTypePortlet.setModeEditGuest(modeEditGuest);
                layoutTypePortlet.setModeHelp(modeHelp);
                layoutTypePortlet.setModePreview(modePreview);
                layoutTypePortlet.setModePrint(modePrint);
            }
        }

        request.setAttribute(WebKeys.LAYOUT, layout);
        request.setAttribute(WebKeys.LAYOUTS, layouts);
    }

    // Scope

    long scopeGroupId = PortalUtil.getScopeGroupId(request);

    if ((scopeGroupId <= 0) && (doAsGroupId > 0)) {
        scopeGroupId = doAsGroupId;
    }

    long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId);

    // Theme and color scheme

    Theme theme = null;
    ColorScheme colorScheme = null;

    boolean wapTheme = BrowserSnifferUtil.isWap(request);

    if ((layout != null) && group.isControlPanel()) {
        String themeId = PrefsPropsUtil.getString(companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID);
        String colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();

        theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme);
        colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                wapTheme);

        if (!wapTheme && theme.isWapTheme()) {
            theme = ThemeLocalServiceUtil.getTheme(companyId, PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID,
                    false);
            colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                    false);
        }

        request.setAttribute(WebKeys.THEME, theme);
        request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
    }

    boolean themeCssFastLoad = SessionParamUtil.getBoolean(request, "css_fast_load",
            PropsValues.THEME_CSS_FAST_LOAD);
    boolean themeImagesFastLoad = SessionParamUtil.getBoolean(request, "images_fast_load",
            PropsValues.THEME_IMAGES_FAST_LOAD);

    boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;

    if (themeJsBarebone) {
        if (signedIn) {
            themeJsBarebone = false;
        }
    }

    boolean themeJsFastLoad = SessionParamUtil.getBoolean(request, "js_fast_load",
            PropsValues.JAVASCRIPT_FAST_LOAD);

    String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0");

    lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle);

    boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated");

    String facebookCanvasPageURL = (String) request.getAttribute(WebKeys.FACEBOOK_CANVAS_PAGE_URL);

    boolean widget = false;

    Boolean widgetObj = (Boolean) request.getAttribute(WebKeys.WIDGET);

    if (widgetObj != null) {
        widget = widgetObj.booleanValue();
    }

    ////////// Modification start //////////

    // Locale
    Locale locale = null;
    String[] languageIds = request.getParameterMap().get("languageId");
    if (languageIds != null && languageIds.length > 0 && StringUtils.isNotEmpty(languageIds[0])) {
        Locale localeFromLanguageId = LocaleUtil.fromLanguageId(languageIds[0]);
        session.setAttribute(Globals.LOCALE_KEY, localeFromLanguageId);
    }
    try {
        locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
    } catch (IllegalStateException e) {
        _log.warn("Can't get locale from session, session is invalidated");
    }
    if (Validator.isNotNull(doAsUserLanguageId)) {
        locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
    }

    String i18nLanguageId = (String) request.getAttribute(WebKeys.I18N_LANGUAGE_ID);
    if (Validator.isNotNull(i18nLanguageId)) {
        locale = LocaleUtil.fromLanguageId(i18nLanguageId);
    }

    if (locale == null) {
        locale = LanguageDetectionUtil.detectLocale(request);
    }

    ////////// Modification end //////////

    // Theme display

    ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
    //Modification start
    //    themeDisplay.setHttpServletRequest(request);
    //Modification end

    // Set the CDN host, portal URL, and Facebook application ID first
    // because other methods (setLookAndFeel) depend on them being set

    themeDisplay.setCDNHost(cdnHost);
    themeDisplay.setCDNDynamicResourcesHost(dynamicResourcesCDNHost);
    themeDisplay.setPortalURL(portalURL);
    themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
    themeDisplay.setWidget(widget);

    themeDisplay.setCompany(company);
    themeDisplay.setCompanyLogo(companyLogo);
    themeDisplay.setCompanyLogoHeight(companyLogoHeight);
    themeDisplay.setCompanyLogoWidth(companyLogoWidth);
    themeDisplay.setRealCompanyLogo(realCompanyLogo);
    themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
    themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
    themeDisplay.setUser(user);
    themeDisplay.setRealUser(realUser);
    themeDisplay.setDoAsUserId(doAsUserId);
    themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId);
    themeDisplay.setDoAsGroupId(doAsGroupId);
    themeDisplay.setRefererPlid(refererPlid);
    themeDisplay.setControlPanelCategory(controlPanelCategory);
    themeDisplay.setLayoutSet(layoutSet);
    themeDisplay.setLayoutSetLogo(layoutSetLogo);
    themeDisplay.setLayout(layout);
    themeDisplay.setLayouts(layouts);
    themeDisplay.setUnfilteredLayouts(unfilteredLayouts);
    themeDisplay.setPlid(plid);
    themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
    themeDisplay.setScopeGroupId(scopeGroupId);
    themeDisplay.setParentGroupId(parentGroupId);
    themeDisplay.setSignedIn(signedIn);
    themeDisplay.setPermissionChecker(permissionChecker);
    themeDisplay.setLocale(locale);
    themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
    themeDisplay.setI18nLanguageId(i18nLanguageId);
    themeDisplay.setI18nPath(i18nPath);
    themeDisplay.setTimeZone(timeZone);
    themeDisplay.setLookAndFeel(theme, colorScheme);
    themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
    themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad);
    themeDisplay.setThemeJsBarebone(themeJsBarebone);
    themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
    themeDisplay.setServerName(request.getServerName());
    themeDisplay.setServerPort(request.getServerPort());
    themeDisplay.setSecure(request.isSecure());
    themeDisplay.setLifecycle(lifecycle);
    themeDisplay.setLifecycleAction(lifecycle.equals("1"));
    themeDisplay.setLifecycleRender(lifecycle.equals("0"));
    themeDisplay.setLifecycleResource(lifecycle.equals("2"));
    themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
    themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
    themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
    themeDisplay.setIsolated(isolated);
    themeDisplay.setPathApplet(contextPath.concat("/applets"));
    themeDisplay.setPathCms(contextPath.concat("/cms"));
    themeDisplay.setPathContext(contextPath);
    themeDisplay.setPathFlash(contextPath.concat("/flash"));
    themeDisplay.setPathFriendlyURLPrivateGroup(friendlyURLPrivateGroupPath);
    themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
    themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
    themeDisplay.setPathImage(imagePath);
    themeDisplay.setPathJavaScript(contextPath.concat("/html/js"));
    themeDisplay.setPathMain(mainPath);
    themeDisplay.setPathSound(contextPath.concat("/html/sound"));

    // Icons

    themeDisplay.setShowAddContentIcon(false);
    themeDisplay.setShowControlPanelIcon(signedIn);
    themeDisplay.setShowHomeIcon(true);
    themeDisplay.setShowMyAccountIcon(signedIn);
    themeDisplay.setShowPageSettingsIcon(false);
    themeDisplay.setShowPortalIcon(true);
    themeDisplay.setShowSignInIcon(!signedIn);
    themeDisplay.setShowSignOutIcon(signedIn);

    boolean showSiteContentIcon = false;

    long controlPanelPlid = 0;

    if (signedIn) {
        Group controlPanelGroup = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL);

        controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(controlPanelGroup.getGroupId(), true);

        List<Portlet> siteContentPortlets = PortalUtil.getControlPanelPortlets(PortletCategoryKeys.CONTENT,
                themeDisplay);

        Portlet groupPagesPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.GROUP_PAGES);

        siteContentPortlets.remove(groupPagesPortlet);

        Portlet siteMembershipsAdminPortlet = PortletLocalServiceUtil
                .getPortletById(PortletKeys.SITE_MEMBERSHIPS_ADMIN);

        siteContentPortlets.remove(siteMembershipsAdminPortlet);

        Portlet siteSettingsPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.SITE_SETTINGS);

        siteContentPortlets.remove(siteSettingsPortlet);

        showSiteContentIcon = PortletPermissionUtil.contains(permissionChecker, scopeGroupId, controlPanelPlid,
                siteContentPortlets, ActionKeys.VIEW);
    }

    themeDisplay.setShowSiteContentIcon(showSiteContentIcon);

    themeDisplay.setShowStagingIcon(false);

    // Session

    if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID && !CookieKeys.hasSessionId(request)) {

        themeDisplay.setAddSessionIdToURL(true);
        themeDisplay.setSessionId(session.getId());
    }

    // URLs

    String urlControlPanel = friendlyURLPrivateGroupPath.concat(GroupConstants.CONTROL_PANEL_FRIENDLY_URL);

    if (Validator.isNotNull(doAsUserId)) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsUserId", doAsUserId);
    }

    if (scopeGroupId > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsGroupId", scopeGroupId);
    }

    if (refererPlid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", refererPlid);
    } else if (plid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", plid);
    }

    if (themeDisplay.isAddSessionIdToURL()) {
        urlControlPanel = PortalUtil.getURLWithSessionId(urlControlPanel, session.getId());
    }

    themeDisplay.setURLControlPanel(urlControlPanel);

    String siteContentURL = urlControlPanel;

    siteContentURL = HttpUtil.addParameter(siteContentURL, "controlPanelCategory", PortletCategoryKeys.CONTENT);

    themeDisplay.setURLSiteContent(siteContentURL);

    String currentURL = PortalUtil.getCurrentURL(request);

    themeDisplay.setURLCurrent(currentURL);

    String urlHome = PortalUtil.getHomeURL(request);

    themeDisplay.setURLHome(urlHome);

    if (layout != null) {
        if (layout.isTypePortlet()) {
            boolean freeformLayout = layoutTypePortlet.getLayoutTemplateId().equals("freeform");

            themeDisplay.setFreeformLayout(freeformLayout);

            if (hasUpdateLayoutPermission) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setShowLayoutTemplatesIcon(true);

                if (!group.isUser()) {
                    themeDisplay.setShowPageCustomizationIcon(true);
                }

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));

                themeDisplay.setURLLayoutTemplates("Liferay.LayoutConfiguration.showTemplates();");
            }

            if (hasCustomizeLayoutPermission && customizedView) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));
            }
        }

        if (hasUpdateLayoutPermission) {
            themeDisplay.setShowPageSettingsIcon(true);

            LiferayPortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            pageSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN);
            pageSettingsURL.setDoAsGroupId(scopeGroupId);
            pageSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts");

            if (layout.isPrivateLayout()) {
                pageSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                pageSettingsURL.setParameter("tabs1", "public-pages");
            }

            pageSettingsURL.setParameter("closeRedirect", currentURL);
            pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            pageSettingsURL.setParameter("selPlid", String.valueOf(plid));
            pageSettingsURL.setPortletMode(PortletMode.VIEW);
            pageSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLPageSettings(pageSettingsURL);

            boolean site = group.isSite();

            if (!site && group.isStagingGroup()) {
                Group liveGroup = group.getLiveGroup();

                site = liveGroup.isSite();
            }

            if (site && GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                    ActionKeys.ASSIGN_MEMBERS)) {

                themeDisplay.setShowManageSiteMembershipsIcon(true);

                LiferayPortletURL manageSiteMembershipsURL = new PortletURLImpl(request,
                        PortletKeys.SITE_MEMBERSHIPS_ADMIN, controlPanelPlid, PortletRequest.RENDER_PHASE);

                manageSiteMembershipsURL.setControlPanelCategory(
                        _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_MEMBERSHIPS_ADMIN);
                manageSiteMembershipsURL.setDoAsGroupId(scopeGroupId);
                manageSiteMembershipsURL.setParameter("struts_action", "/sites_admin/edit_site_assignments");
                manageSiteMembershipsURL.setParameter("groupId", String.valueOf(scopeGroupId));
                manageSiteMembershipsURL.setParameter("selPlid", String.valueOf(plid));
                manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW);
                manageSiteMembershipsURL.setWindowState(LiferayWindowState.POP_UP);

                themeDisplay.setURLManageSiteMemberships(manageSiteMembershipsURL);
            } else {
                themeDisplay.setShowManageSiteMembershipsIcon(false);
            }
        }

        boolean hasAddLayoutGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.ADD_LAYOUT);
        boolean hasAddLayoutLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                ActionKeys.ADD_LAYOUT);
        boolean hasManageLayoutsGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_LAYOUTS);
        boolean hasManageStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_STAGING);
        boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.PUBLISH_STAGING);
        boolean hasUpdateGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.UPDATE);
        boolean hasViewStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.VIEW_STAGING);

        if (!group.isControlPanel() && !group.isUser() && !group.isUserGroup() && hasUpdateGroupPermission) {

            themeDisplay.setShowSiteSettingsIcon(true);

            LiferayPortletURL siteSettingsURL = new PortletURLImpl(request, PortletKeys.SITE_SETTINGS,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            siteSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_SETTINGS);
            siteSettingsURL.setDoAsGroupId(scopeGroupId);
            siteSettingsURL.setParameter("struts_action", "/sites_admin/edit_site");
            siteSettingsURL.setParameter("closeRedirect", currentURL);
            siteSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            siteSettingsURL.setPortletMode(PortletMode.VIEW);
            siteSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLSiteSettings(siteSettingsURL);
        }

        if (!group.isLayoutPrototype() && (hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission
                || hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) {

            themeDisplay.setShowSiteMapSettingsIcon(true);

            LiferayPortletURL siteMapSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            siteMapSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN);
            siteMapSettingsURL.setDoAsGroupId(scopeGroupId);
            siteMapSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts");

            if (layout.isPrivateLayout()) {
                siteMapSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                siteMapSettingsURL.setParameter("tabs1", "public-pages");
            }

            siteMapSettingsURL.setParameter("closeRedirect", currentURL);
            siteMapSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            siteMapSettingsURL.setPortletMode(PortletMode.VIEW);
            siteMapSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLSiteMapSettings(siteMapSettingsURL);
        }

        if (group.hasStagingGroup() && !group.isStagingGroup()) {
            themeDisplay.setShowAddContentIcon(false);
            themeDisplay.setShowLayoutTemplatesIcon(false);
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        if (group.isControlPanel()) {
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        // LEP-4987

        if (group.isStaged() || group.isStagingGroup()) {
            if (hasManageStagingPermission || hasPublishStagingPermission || hasUpdateLayoutPermission
                    || hasViewStagingPermission) {

                themeDisplay.setShowStagingIcon(true);
            }

            if (hasPublishStagingPermission) {
                PortletURL publishToLiveURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN, plid,
                        PortletRequest.RENDER_PHASE);

                publishToLiveURL.setParameter("struts_action", "/layouts_admin/publish_layouts");

                if (layout.isPrivateLayout()) {
                    publishToLiveURL.setParameter("tabs1", "private-pages");
                } else {
                    publishToLiveURL.setParameter("tabs1", "public-pages");
                }

                publishToLiveURL.setParameter("pagesRedirect", currentURL);
                publishToLiveURL.setParameter("groupId", String.valueOf(scopeGroupId));
                publishToLiveURL.setParameter("selPlid", String.valueOf(plid));
                publishToLiveURL.setPortletMode(PortletMode.VIEW);
                publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE);

                themeDisplay.setURLPublishToLive(publishToLiveURL);
            }
        }

        PortletURLImpl myAccountURL = new PortletURLImpl(request, PortletKeys.MY_ACCOUNT, controlPanelPlid,
                PortletRequest.RENDER_PHASE);

        if (scopeGroupId > 0) {
            myAccountURL.setDoAsGroupId(scopeGroupId);
        }

        myAccountURL.setParameter("struts_action", "/my_account/edit_user");
        myAccountURL.setPortletMode(PortletMode.VIEW);

        if (refererPlid > 0) {
            myAccountURL.setRefererPlid(refererPlid);
        } else {
            myAccountURL.setRefererPlid(plid);
        }

        myAccountURL.setWindowState(WindowState.MAXIMIZED);

        themeDisplay.setURLMyAccount(myAccountURL);
    }

    if (!user.isActive() || (PrefsPropsUtil.getBoolean(companyId, PropsKeys.TERMS_OF_USE_REQUIRED)
            && !user.isAgreedToTermsOfUse())) {

        themeDisplay.setShowAddContentIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
    }

    if (layout.isLayoutPrototypeLinkActive()) {
        themeDisplay.setShowPageCustomizationIcon(false);
    }

    if (group.isLayoutPrototype()) {
        themeDisplay.setShowControlPanelIcon(false);
        themeDisplay.setShowHomeIcon(false);
        themeDisplay.setShowManageSiteMembershipsIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowPageSettingsIcon(true);
        themeDisplay.setShowPortalIcon(false);
        themeDisplay.setShowSignInIcon(false);
        themeDisplay.setShowSignOutIcon(false);
        themeDisplay.setShowSiteContentIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
        themeDisplay.setShowStagingIcon(false);
    }

    if (group.isLayoutSetPrototype()) {
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
    }

    if (group.hasStagingGroup() && !group.isStagingGroup()) {
        themeDisplay.setShowLayoutTemplatesIcon(false);
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
        themeDisplay.setShowSiteContentIcon(false);
        themeDisplay.setShowSiteMapSettingsIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
    }

    themeDisplay.setURLPortal(portalURL.concat(contextPath));

    String urlSignIn = mainPath.concat("/portal/login");

    urlSignIn = HttpUtil.addParameter(urlSignIn, "p_l_id", layout.getPlid());

    themeDisplay.setURLSignIn(urlSignIn);

    themeDisplay.setURLSignOut(mainPath.concat("/portal/logout"));

    PortletURL updateManagerURL = new PortletURLImpl(request, PortletKeys.UPDATE_MANAGER, plid,
            PortletRequest.RENDER_PHASE);

    updateManagerURL.setParameter("struts_action", "/update_manager/view");
    updateManagerURL.setPortletMode(PortletMode.VIEW);
    updateManagerURL.setWindowState(WindowState.MAXIMIZED);

    themeDisplay.setURLUpdateManager(updateManagerURL);

    return themeDisplay;
}

From source file:com.jpeterson.littles3.StorageEngine.java

/**
 * Process HTTP HEAD and GET// ww w  .j a v a2s. c  om
 * 
 * @param req
 *            an HttpServletRequest object that contains the request the
 *            client has made of the servlet
 * @param resp
 *            an HttpServletResponse object that contains the response the
 *            servlet sends to the client
 * @throws IOException
 *             if an input or output error is detected when the servlet
 *             handles the GET request
 * @throws ServletException
 *             if the request for the GET could not be handled
 */
@SuppressWarnings("unchecked")
public void processHeadGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Context path: " + req.getContextPath());
        logger.debug("Path info: " + req.getPathInfo());
        logger.debug("Path translated: " + req.getPathTranslated());
        logger.debug("Query string: " + req.getQueryString());
        logger.debug("Request URI: " + req.getRequestURI());
        logger.debug("Request URL: " + req.getRequestURL());
        logger.debug("Servlet path: " + req.getServletPath());
        logger.debug("Servlet name: " + this.getServletName());

        for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
            String headerName = (String) headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            logger.debug("Header- " + headerName + ": " + headerValue);
        }
    }

    try {
        S3ObjectRequest or;

        try {
            or = S3ObjectRequest.create(req, resolvedHost(),
                    (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR));
        } catch (InvalidAccessKeyIdException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId");
            return;
        } catch (InvalidSecurityException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        } catch (RequestTimeTooSkewedException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed");
            return;
        } catch (SignatureDoesNotMatchException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch");
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        }

        if (or.getKey() != null) {
            S3Object s3Object;
            StorageService storageService;

            try {
                storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);
                s3Object = storageService.load(or.getBucket(), or.getKey());

                if (s3Object == null) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                    return;
                }
            } catch (DataAccessException e) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                return;
            }

            if (req.getParameter(PARAMETER_ACL) != null) {
                // retrieve access control policy
                String response;
                Acp acp = s3Object.getAcp();

                try {
                    acp.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = Acp.encode(acp);
                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                out.flush(); // commit response
                out.close();
                out = null;
            } else {
                // retrieve object
                InputStream in = null;
                OutputStream out = null;
                byte[] buffer = new byte[4096];
                int count;
                String value;

                try {
                    s3Object.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // headers
                resp.setContentType(s3Object.getContentType());
                if ((value = s3Object.getContentDisposition()) != null) {
                    resp.setHeader("Content-Disposition", value);
                }
                // TODO: set the Content-Range, if request includes Range
                // TODO: add "x-amz-missing-meta", if any

                // add the "x-amz-meta-" headers
                for (Iterator<String> names = s3Object.getMetadataNames(); names.hasNext();) {
                    String name = names.next();
                    String headerName = HEADER_PREFIX_USER_META + name;
                    String prefix = "";
                    StringBuffer buf = new StringBuffer();
                    for (Iterator<String> values = s3Object.getMetadataValues(name); values.hasNext();) {
                        buf.append(values.next()).append(prefix);
                        prefix = ",";
                    }
                    resp.setHeader(headerName, buf.toString());
                }

                resp.setDateHeader("Last-Modified", s3Object.getLastModified());
                if ((value = s3Object.getETag()) != null) {
                    resp.setHeader("ETag", value);
                }
                if ((value = s3Object.getContentMD5()) != null) {
                    resp.setHeader("Content-MD5", value);
                }
                if ((value = s3Object.getContentDisposition()) != null) {
                    resp.setHeader("Content-Disposition", value);
                }
                resp.setHeader("Accept-Ranges", "bytes");

                String rangeRequest = req.getHeader("Range");

                if (rangeRequest != null) {
                    // request for a range
                    RangeSet rangeSet = RangeFactory.processRangeHeader(rangeRequest);

                    // set content length
                    rangeSet.resolve(s3Object.getContentLength());

                    if (rangeSet.size() > 1) {
                        // requires multi-part response
                        // TODO: implement
                        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
                    }

                    Range[] ranges = (Range[]) rangeSet.toArray(new Range[0]);

                    resp.setHeader("Content-Range",
                            formatRangeHeaderValue(ranges[0], s3Object.getContentLength()));
                    resp.setHeader("Content-Length", Long.toString(rangeSet.getLength()));

                    in = new RangeInputStream(s3Object.getInputStream(), ranges[0]);
                    resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                } else {
                    // request for entire content
                    // Used instead of resp.setContentLength((int)); because
                    // Amazon
                    // limit is 5 gig, which is bigger than an int
                    resp.setHeader("Content-Length", Long.toString(s3Object.getContentLength()));

                    in = s3Object.getInputStream();
                    resp.setStatus(HttpServletResponse.SC_OK);
                }

                // body
                out = resp.getOutputStream();

                while ((count = in.read(buffer, 0, buffer.length)) > 0) {
                    out.write(buffer, 0, count);
                }

                out.flush(); // commit response
                out.close();
                out = null;
            }
            return;
        } else if (or.getBucket() != null) {
            // operation on a bucket
            StorageService storageService;
            String prefix;
            String marker;
            int maxKeys = Integer.MAX_VALUE;
            String delimiter;
            String response;
            String value;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // retrieve access control policy
                Acp acp;

                try {
                    acp = storageService.loadBucket(or.getBucket()).getAcp();
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    acp.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = Acp.encode(acp);
                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                out.flush(); // commit response
                out.close();
                out = null;
            } else {
                Bucket bucket;

                prefix = req.getParameter("prefix");
                if (prefix == null) {
                    prefix = "";
                }
                marker = req.getParameter("marker");
                value = req.getParameter("max-keys");
                if (value != null) {
                    try {
                        maxKeys = Integer.parseInt(value);
                    } catch (NumberFormatException e) {
                        logger.info("max-keys must be numeric: " + value);
                    }
                }

                delimiter = req.getParameter("delimiter");

                try {
                    bucket = storageService.loadBucket(or.getBucket());
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    bucket.canRead(or.getRequestor());
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                response = storageService.listKeys(bucket, prefix, marker, delimiter, maxKeys);

                resp.setContentLength(response.length());
                resp.setContentType("application/xml");
                resp.setStatus(HttpServletResponse.SC_OK);

                Writer out = resp.getWriter();
                out.write(response);
                if (logger.isTraceEnabled()) {
                    logger.trace("Response: " + response);
                }
            }
            return;
        } else {
            // operation on the service
            StorageService storageService;
            List buckets;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            buckets = storageService.findBuckets("");

            StringBuffer buffer = new StringBuffer();

            buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            buffer.append("<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
            buffer.append("<Owner>");
            buffer.append("<ID/>"); // TODO: implement
            buffer.append("<DisplayName/>"); // TODO: implementF
            buffer.append("</Owner>");
            buffer.append("<Buckets>");
            for (Iterator iter = buckets.iterator(); iter.hasNext();) {
                Bucket bucket = (Bucket) iter.next();
                buffer.append("<Bucket>");
                buffer.append("<Name>").append(bucket.getName()).append("</Name>");
                buffer.append("<CreationDate>").append(iso8601.format(bucket.getCreated()))
                        .append("</CreationDate>");
                buffer.append("</Bucket>");
            }
            buffer.append("</Buckets>");
            buffer.append("</ListAllMyBucketsResult>");

            resp.setContentLength(buffer.length());
            resp.setContentType("application/xml");
            resp.setStatus(HttpServletResponse.SC_OK);

            Writer out = resp.getWriter();
            out.write(buffer.toString());
            return;
        }
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidURI");
        return;
    }
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void dispatchPublishingFile(PublishingFile publishingFile, HttpServletRequest request,
        HttpServletResponse response, String textOutputEncoding, FileCache fileCache, WGPRequestPath path)
        throws WGException, HttpErrorException, IOException {

    // Collect HTTP client hints (if enabled)
    ClientHints clientHints = new ClientHints();
    boolean useHttpClientHints = false;
    if (publishingFile.getDatabase() != null) {
        Database database = WGA.get(request, response, getCore()).database(publishingFile.getDatabase());
        if (database instanceof App
                && ((Boolean) database.getPublisherOption(WGACore.DBATTRIB_USE_NONFINAL_HT_FEATURES)) == true) {
            useHttpClientHints = true;//from   www. j av  a 2s. c o m
        }
    }

    if (useHttpClientHints) {
        String dprStr = request.getHeader("CH-DPR");
        if (dprStr != null) {
            try {
                clientHints.setDevicePixelRatio(Float.valueOf(dprStr));
            } catch (NumberFormatException e) {
                getCore().getLog().warn("Client uses unparseable device pixel ratio: " + dprStr);
            }
        }
    }

    // Optionally select derivate
    Float usedDevicePixelRatio = null;
    try {

        String derivate = request.getParameter(URLPARAM_DERIVATE);
        if (derivate != null) {
            DerivateQuery derivateQuery = getCore().getFileDerivateManager().parseDerivateQuery(derivate);
            if (publishingFile instanceof DocumentPublishingFile) {
                DocumentPublishingFile docPublishingFile = (DocumentPublishingFile) publishingFile;
                WGFileDerivateMetaData derivateMd = docPublishingFile.queryDerivate(derivateQuery, clientHints);
                if (derivateMd != null) {
                    usedDevicePixelRatio = docPublishingFile.getUsedDevicePixelRatio();
                    publishingFile = new DerivatePublishingFile(this, docPublishingFile.getContainer(),
                            derivateMd);

                }
            } else if (!isFallbackToOriginalOnDerivateQuery(derivateQuery, publishingFile)) {
                throw new WGNotSupportedException("Derivate queries are not supported on this file type");
            }

        }

    } catch (WGNotSupportedException e) {
        throw new HttpErrorException(412, e.getMessage(), path.getDatabaseKey());
    } catch (WGInvalidDerivateQueryException e) {
        throw new HttpErrorException(400, "Invalid derivate query: " + e.getMessage(), path.getDatabaseKey());
    } catch (WGFailedDerivateQueryException e) {
        throw new HttpErrorException(412,
                "No derivate of file '" + publishingFile.getFileName() + "' matches the derivate query",
                path.getDatabaseKey());
    }

    // Put out the used device pixel ratio, if any
    if (usedDevicePixelRatio != null) {
        response.setHeader("Vary", "CH-DPR");
        response.setHeader("DPR", usedDevicePixelRatio.toString());
    }

    // Handle browser cache
    long lastModified = determinePublishingFileLastModified(publishingFile, request, response);

    if (browserCacheIsValid(request, lastModified, publishingFile.getETag())) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    } else {
        response.setDateHeader("Last-Modified", lastModified);
        response.setHeader("ETag", '"' + publishingFile.getETag() + '"');
    }

    // Optionally inject online scaling information to file object
    String maxHeightStr = request.getParameter(URLPARAM_MAXHEIGHT);
    String maxWidthStr = request.getParameter(URLPARAM_MAXWIDTH);
    if (maxHeightStr != null || maxWidthStr != null) {
        try {
            int maxHeight = -1;
            if (maxHeightStr != null) {
                maxHeight = Integer.parseInt(maxHeightStr);
            }
            int maxWidth = -1;
            if (maxWidthStr != null) {
                maxWidth = Integer.parseInt(maxWidthStr);
            }
            publishingFile.setOnlineScaling(maxWidth, maxHeight, clientHints);
        } catch (NumberFormatException e) {
            getCore().getLog().error("Unparseable online scaling metrics", e);
        } catch (Exception e) {
            getCore().getLog().error("Exception setting online scaling information", e);
        }
    }

    // Put out content type
    String contentType = publishingFile.getContentType();
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    response.setContentType(contentType);

    // Content Disposition Header - Either if download forced or a disposition filename has been specified
    Boolean forceDownload = Boolean.parseBoolean(request.getParameter("forcedownload"));
    if (forceDownload) {
        response.setHeader("Content-disposition",
                "attachment" + (publishingFile.getDispositionFileName() != null
                        ? ";filename=" + publishingFile.getDispositionFileName()
                        : ""));
    } else if (publishingFile.getDispositionFileName() != null) {
        response.setHeader("Content-disposition", "inline;filename=" + publishingFile.getDispositionFileName());
    }

    // Allow accept ranges on all CS with optimized file handling and binary responses
    if (publishingFile.isAllowAcceptRanges() && isBinary(request, response)) {
        response.setHeader("Accept-Ranges", "bytes");
    }

    try {
        // Look if file is cached - If so, send it and exit
        if (fileCache != null) {
            boolean outputHandled = dispatchFileWithCache(publishingFile, request, response, fileCache,
                    lastModified, textOutputEncoding, contentType, path);
            if (outputHandled) {
                return;
            }
        }

        // We serve from cache so must retrieve the file. Test for availability now which may load the document.
        if (!publishingFile.isAvailable()) {
            throw new HttpErrorException(404, "File not found: " + publishingFile.getName(),
                    path.getDatabaseKey());
        }

        // File is above threshold and not in cache - serve from database
        writeData(publishingFile, request, response, publishingFile.getTextEncoding(),
                publishingFile.getFileSize(), publishingFile.getSourceHint(),
                publishingFile.isAllowAcceptRanges() && isBinary(request, response));
    } catch (java.net.SocketException exc) {
        _log.warn("Dispatch of file request failed bc. of socket error: " + exc.getMessage());
    } catch (java.io.IOException exc) {
        if (!exc.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
            _log.warn("Dispatch of file request failed bc. of IO error: " + exc.getMessage());
        }
    } catch (HttpErrorException exc) {
        throw exc;
    } catch (Exception exc) {
        _log.error("Exception dispatching file " + publishingFile.getName(), exc);
    }
}

From source file:net.dorokhov.pony.web.server.common.StreamingViewRenderer.java

@Override
protected void renderMergedOutputModel(Map objectMap, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    InputStream dataStream = (InputStream) objectMap.get(DownloadConstants.INPUT_STREAM);

    if (dataStream == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from ww  w  .  j  a v a  2  s  .  co m
    }
    long length = (Long) objectMap.get(DownloadConstants.CONTENT_LENGTH);
    String fileName = (String) objectMap.get(DownloadConstants.FILENAME);
    Date lastModifiedObj = (Date) objectMap.get(DownloadConstants.LAST_MODIFIED);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = lastModifiedObj.getTime();
    String contentType = (String) objectMap.get(DownloadConstants.CONTENT_TYPE);

    // Validate request headers for caching ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, fileName)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(dataStream);
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total);
            response.setHeader("Content-Length", String.valueOf(full.length));
            copy(input, output, length, full.start, full.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        close(dataStream);
    }

}

From source file:com.swingtech.apps.filemgmt.controller.StreamingViewRenderer.java

@Override
protected void renderMergedOutputModel(Map objectMap, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    InputStream dataStream = (InputStream) objectMap.get(DownloadConstants.INPUT_STREAM);

    if (dataStream == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//  w ww.ja v a2s .  c om
    }
    long length = (Long) objectMap.get(DownloadConstants.CONTENT_LENGTH);
    String fileName = (String) objectMap.get(DownloadConstants.FILENAME);
    Date lastModifiedObj = (Date) objectMap.get(DownloadConstants.LAST_MODIFIED);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = lastModifiedObj.getTime();
    String contentType = (String) objectMap.get(DownloadConstants.CONTENT_TYPE);

    // Validate request headers for caching
    // ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return
    // 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume
    // ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If
    // not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range
    // -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not,
        // then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required
            // in
            // 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws
                // IAE
                // if
                // invalid.
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte
        // range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = StringUtils.sublong(part, 0, part.indexOf("-"));
                long end = StringUtils.sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required
                    // in
                    // 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response
    // --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If
        // content type is supported by
        // the browser, then set to inline, else attachment which will pop a
        // 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(dataStream);
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            copy(input, output, length, r.start, r.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println
            // methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        close(dataStream);
    }

}

From source file:org.jpublish.servlet.JPublishServlet.java

/**
 * Called when the HTTP request method is POST.  This method provides the
 * main control logic./*from  w w w.j  a va2s.  c o  m*/
 *
 * @param request  The HTTP request
 * @param response The HTTP response
 * @throws ServletException
 * @throws IOException
 */

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletContext servletContext = getServletContext();

    String pathInfo = request.getPathInfo();
    if (log.isDebugEnabled())
        log.debug("Path info: " + pathInfo);

    //OLAT: PATCH BEGIN
    if (pathInfo == null) {
        // we have a direct mapping rule in web.xml like /kurs/bridge.html -> jpublish servlet
        // so we use servletPath
        //String servletPath = request.getServletPath();
        pathInfo = request.getServletPath();
    } //TODO: make more generic (use JPublish with other servlets..) and post it.

    if (log.isDebugEnabled())
        log.debug("calculated Path info: " + pathInfo);
    //OLAT: PATCH END

    String contextPath = request.getContextPath();

    if (log.isDebugEnabled())
        log.debug("Context path: " + contextPath);

    // get the real path
    String path = getRealPath(pathInfo);

    if (siteContext.getPathDispatcherManager().canDispatch(path)) {

        //only one from below ones should react
        String dispatcherName = siteContext.getPathDispatcherManager().canForwardDispatch(path);

        if (dispatcherName != null) {
            siteContext.getPathDispatcherManager().forward(request, response, dispatcherName);
        }

        dispatcherName = siteContext.getPathDispatcherManager().canIncludeDispatch(path);
        if (dispatcherName != null) {
            siteContext.getPathDispatcherManager().include(request, response, dispatcherName);
        }

        return;
    }

    if (log.isDebugEnabled())
        log.debug("Real path: " + path);

    // create the session if enabled
    HttpSession session = null;

    if (isSessionEnabled(path)) {
        session = request.getSession(true);
    }

    // get the character encoding map
    CharacterEncodingMap characterEncodingMap = siteContext.getCharacterEncodingManager().getMap(path);

    // set the request character encoding for parameter data
    if (requireVersion(2, 3)) {
        request.setCharacterEncoding(characterEncodingMap.getRequestEncoding());
    }

    // put standard servlet stuff into the context
    JPublishContext context = new JPublishContext(this);
    context.put("request", request);
    context.put("response", response);
    context.put("session", session);
    context.put("application", servletContext);

    // add the character encoding map to the context
    context.put("characterEncodingMap", characterEncodingMap);

    // add the URLUtilities to the context
    URLUtilities urlUtilities = new URLUtilities(request, response);
    context.put("urlUtilities", urlUtilities);
    // deprecated
    context.put("url_util", urlUtilities);
    context.put("url_utils", urlUtilities);

    // add the DateUtilities to the context
    context.put("dateUtilities", DateUtilities.getInstance());

    // add the NumberUtilities to the context
    context.put("numberUtilities", NumberUtilities.getInstance());

    // add the messages log to the context
    context.put("syslog", SiteContext.syslog);

    // expose the SiteContext
    context.put("site", siteContext);

    // expose the context itself for debugging purposes
    if (siteContext.isDebug()) {
        context.put("context", context);
    }

    // switch from merge to eval, while rendering Velocity templates [hack for utf8]
    if (siteContext.isEval()) {
        context.put("evaluateVelocityTemplates", "true");
    }

    if (siteContext.isProtectReservedNames()) {
        context.enableCheckReservedNames(this);
    }

    // add the repositories to the context
    Iterator repositories = siteContext.getRepositories().iterator();
    while (repositories.hasNext()) {
        Repository repository = (Repository) repositories.next();
        if (log.isDebugEnabled())
            log.debug("Adding " + repository.getClass().getName() + " as " + repository.getName());

        context.put(repository.getName(), new RepositoryWrapper(repository, context));
    }

    Writer out = null;
    try {

        if (executePreEvaluationActions(request, response, context, path))
            return;

        if (context.getStopProcessing() != null) {
            return;
        }

        // if the page is static
        StaticResourceManager staticResourceManager = siteContext.getStaticResourceManager();

        if (staticResourceManager.resourceExists(path)) {

            long ifModifiedSince = request.getDateHeader(HEADER_IF_MODIFIED);
            // will round the file's lastModified down to the nearest second by dividing by 1000 and then
            // multiplying it by 1000; florin
            long lastUpdatedTime = -1;
            try {
                lastUpdatedTime = (staticResourceManager.getLastModified(path) / 1000) * 1000;
            } catch (Exception e) {
                log.warn("Cannot read the LastModified for: " + path);
            }
            //log.info(String.format("%s: if modified since: %d, file time:%d, modified? %s", path, ifModifiedSince, lastUpdatedTime, (ifModifiedSince < lastUpdatedTime)));

            if (ifModifiedSince < lastUpdatedTime) {
                // execute the global actions
                if (executeGlobalActions(request, response, context, path))
                    return;

                if (context.getStopProcessing() != null)
                    return;

                // execute path actions
                if (executePathActions(request, response, context, path))
                    return;
                if (context.getStopProcessing() != null)
                    return;

                // execute parameter actions
                if (executeParameterActions(request, response, context, path))
                    return;
                if (context.getStopProcessing() != null)
                    return;

                // load and return the static resource
                setResponseContentType(request, response, path, characterEncodingMap);
                response.setDateHeader(HEADER_LAST_MODIFIED, lastUpdatedTime);
                response.setContentLength((int) staticResourceManager.getContentLength(path));
                try {
                    staticResourceManager.load(path, response.getOutputStream());
                } catch (SocketException e) {
                    log.warn("Error writing to output stream: " + e.getMessage());
                }
                // OLAT: PATCH: Ignore org.apache.catalina.connector.ClientAbortException
                // that is produced by InternetExplorer (6.0) browser caching.
                catch (IOException e) {
                    if (e instanceof FileNotFoundException) {
                        throw e;
                    }
                }
            } else {
                //If the browser has current version of the file, don't send it. Just say it has not changed
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            }
            return;
        } else {
            if (log.isDebugEnabled())
                log.debug("Static resource '" + path + "' not found");
        }

        // load the page
        if (log.isDebugEnabled())
            log.debug("Loading the page.");

        PageInstance pageInstance = siteContext.getPageManager().getPage(path);
        Page page = new Page(pageInstance);

        context.disableCheckReservedNames(this);

        // expose the page in the context
        context.put("page", page);

        // expose components in the context
        context.put("components", new ComponentMap(context));

        if (siteContext.isProtectReservedNames()) {
            context.enableCheckReservedNames(this);
        }

        request.setAttribute(JPUBLISH_CONTEXT, context);

        // execute the global actions
        if (executeGlobalActions(request, response, context, path))
            return;
        if (context.getStopProcessing() != null)
            return;

        // execute path actions
        if (executePathActions(request, response, context, path))
            return;
        if (context.getStopProcessing() != null)
            return;

        // execute parameter actions
        if (executeParameterActions(request, response, context, path))
            return;
        if (context.getStopProcessing() != null)
            return;

        // execute the page actions
        if (log.isDebugEnabled())
            log.debug("Executing page actions.");

        if (optionalRedirect(page.executeActions(context), path, response))
            return;
        if (context.getStopProcessing() != null) {
            return;
        }
        setResponseContentType(request, response, path, characterEncodingMap);

        // get the template
        // OLAT: PATCH using context.getPage() instead of page object
        // since page can be changed in internal forward and page points
        // still to the original page
        Template template = siteContext.getTemplateManager()
                .getTemplate(context.getPage().getFullTemplateName());

        // get the Servlet writer
        out = response.getWriter();

        // merge the template
        if (log.isDebugEnabled())
            log.debug("Merging with template " + template.getPath());
        // OLAT: PATCH using context.getPage() instead of page object
        // since page can be changed in internal forward and page points
        // still to the original page
        template.merge(context, context.getPage(), out);

    } catch (FileNotFoundException e) {
        log.error("[404] " + path);
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        }
    } catch (Exception e) {
        // Allow Jetty RequestRetry exception to propogate to container!
        if ("org.mortbay.jetty.RetryRequest".equals(e.getClass().getName())) {
            throw (RuntimeException) e;
        }

        JPublishError error = new JPublishError(e, context);
        Iterator errorHandlers = siteContext.getErrorHandlers(path).iterator();
        while (errorHandlers.hasNext()) {
            ((ErrorHandler) errorHandlers.next()).handleError(error);
        }

        if (!error.isConsumed()) {
            log.error("Execution error: " + MessageUtilities.format(e.getMessage()));
            if (!response.isCommitted()) {
                throw new ServletException(e);
            }
        }
    } finally {
        try {
            executePostEvaluationActions(request, response, context, path);
        } catch (Exception e) {
            log.error("Error executing post evaluation actions: " + MessageUtilities.format(e.getMessage()));
        }
    }
}

From source file:com.harrywu.springweb.common.StreamingViewRenderer.java

@Override
public void renderMergedOutputModel(Map<String, Object> objectMap, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    InputStream dataStream = (InputStream) objectMap.get(INPUT_STREAM);

    if (dataStream == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*from   ww w  .  ja  v  a2  s.  c o m*/
    }
    long length = (Long) objectMap.get(CONTENT_LENGTH);
    String fileName = (String) objectMap.get(FILENAME);
    Date lastModifiedObj = (Date) objectMap.get(LAST_MODIFIED);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = lastModifiedObj.getTime();
    String contentType = (String) objectMap.get(CONTENT_TYPE);

    // Validate request headers for caching
    // ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return
    // 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", fileName); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume
    // ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, fileName)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If
    // not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range
    // -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not,
        // then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required
                                                                      // in
                                                                      // 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws
                                                                      // IAE
                                                                      // if
                                                                      // invalid.
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte
        // range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required
                                                                              // in
                                                                              // 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response
    // --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If
        // content type is supported by
        // the browser, then set to inline, else attachment which will pop a
        // 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    InputStream input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(dataStream);
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            copy(input, output, length, r.start, r.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println
            // methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        close(dataStream);
    }

}

From source file:net.wastl.webmail.server.WebMailServlet.java

/**
 * Handle a request to the WebMail servlet. This is the central method of
 * the WebMailServlet. It first gathers all of the necessary information
 * from the client, then either creates or gets a Session and executes the
 * URL handler for the given path./* w  w w.ja  v  a 2  s.  c  o  m*/
 */
public void service(ServletRequest req1, ServletResponse res1) throws ServletException {
    final HttpServletRequest req = (HttpServletRequest) req1;
    final HttpServletResponse res = (HttpServletResponse) res1;
    final HTTPRequestHeader http_header = new HTTPRequestHeader();

    if (req.getServletPath().equals("/admin"))
        try {
            log.debug("Forwarding /admin request back to self");
            req.getRequestDispatcher("WebMail/admin").forward(req1, res1);
            return;
        } catch (IOException ioe) {
            log.fatal("Forward from '/admin' failed", ioe);
            throw new ServletException(ioe.getMessage());
        }

    final Enumeration en = req.getHeaderNames();
    while (en.hasMoreElements()) {
        final String s = (String) en.nextElement();
        http_header.setHeader(s, req.getHeader(s));
    }

    http_header.setPath(req.getPathInfo() == null ? "/" : req.getPathInfo());

    InetAddress addr;
    try {
        addr = InetAddress.getByName(req.getRemoteHost());
    } catch (final UnknownHostException e) {
        try {
            addr = InetAddress.getByName(req.getRemoteAddr());
        } catch (final Exception ex) {
            throw new ServletException("Remote host must identify!");
        }
    }

    HTMLDocument content = null;
    final int err_code = 400;
    HTTPSession sess = null;

    /*
     * Here we try to parse the MIME content that the Client sent in his
     * POST since the JServ doesn't do that for us:-( At least we can use
     * the functionality provided by the standalone server where we need to
     * parse the content ourself anyway.
     */
    try {
        final BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());

        /*
         * First we try to use the Servlet API's methods to parse the
         * parameters. Unfortunately, it doesn't know how to handle MIME
         * multipart POSTs, so we will have to handle that ourselves
         */

        /*
         * First get all the parameters and set their values into
         * http_header
         */
        Enumeration enum2 = req.getParameterNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setContent(s, req.getParameter(s));
            // log.info("Parameter "+s);
        }

        /* Then we set all the headers in http_header */
        enum2 = req.getHeaderNames();
        while (enum2.hasMoreElements()) {
            final String s = (String) enum2.nextElement();
            http_header.setHeader(s, req.getHeader(s));
        }

        /*
         * In Servlet API 2.2 we might want to fetch the attributes also,
         * but this doesn't work in API 2.0, so we leave it commented out
         */
        // enum2=req.getAttributeNames();
        // while(enum2.hasMoreElements()) {
        // String s=(String)enum2.nextElement();
        // log.info("Attribute "+s);
        // }

        /* Now let's try to handle multipart/form-data posts */

        if (req.getContentType() != null
                && req.getContentType().toUpperCase().startsWith("MULTIPART/FORM-DATA")) {
            final int size = Integer.parseInt(WebMailServer.getStorage().getConfig("max attach size"));
            final MultipartParser mparser = new MultipartParser(req, size);
            Part p;
            while ((p = mparser.readNextPart()) != null) {
                if (p.isFile()) {
                    final ByteStore bs = ByteStore.getBinaryFromIS(((FilePart) p).getInputStream(), size);
                    bs.setName(((FilePart) p).getFileName());
                    bs.setContentType(getStorage().getMimeType(((FilePart) p).getFileName()));
                    http_header.setContent(p.getName(), bs);
                    log.info("File name " + bs.getName());
                    log.info("Type      " + bs.getContentType());

                } else if (p.isParam()) {
                    http_header.setContent(p.getName(), ((ParamPart) p).getStringValue());
                }

                // log.info("Parameter "+p.getName());
            }
        }

        try {
            final String url = http_header.getPath();

            try {
                /* Find out about the session id */
                sess = req.getSession(false) == null ? null
                        : (HTTPSession) req.getSession(false).getAttribute("webmail.session");

                /*
                 * If the user was logging on, he doesn't have a session id,
                 * so generate one. If he already had one, all the better,
                 * we will take the old one
                 */
                if (sess == null && url.startsWith("/login")) {
                    sess = newSession(req, http_header);
                } else if (sess == null && url.startsWith("/admin/login")) {
                    http_header.setHeader("LOGIN", "Administrator");
                    sess = newAdminSession(req, http_header);
                }
                if (sess == null && !url.equals("/") && !url.startsWith("/passthrough")
                        && !url.startsWith("/admin")) {
                    content = getURLHandler().handleURL("/logout", sess, http_header);
                } else {
                    /* Ensure that the session state is up-to-date */
                    if (sess != null) {
                        sess.setEnv();
                    }

                    /* Let the URLHandler determine the result of the query */
                    content = getURLHandler().handleURL(url, sess, http_header);
                }
            } catch (final InvalidPasswordException e) {
                log.error("Connection to " + addr.toString() + ": Authentication failed!");
                if (url.startsWith("/admin/login")) {
                    content = getURLHandler().handleURL("/admin", null, http_header);
                } else if (url.startsWith("/login")) {
                    content = getURLHandler().handleURL("/", null, http_header);
                } else
                    // content=new
                    // HTMLErrorMessage(getStorage(),e.getMessage());
                    throw new ServletException("Invalid URL called!");
            } catch (final Exception ex) {
                content = getURLHandler().handleException(ex, sess, http_header);
                log.debug("Some strange error while handling request", ex);
            }

            /*
             * Set some HTTP headers: Date is now, the document should
             * expire in 5 minutes, proxies and clients shouldn't cache it
             * and all WebMail documents must be revalidated when they think
             * they don't have to follow the "no-cache".
             */
            res.setDateHeader("Date:", System.currentTimeMillis());
            res.setDateHeader("Expires", System.currentTimeMillis() + 300000);
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Cache-Control", "must-revalidate");

            synchronized (out) {
                res.setStatus(content.getReturnCode());

                if (content.hasHTTPHeader()) {
                    final Enumeration enumVar = content.getHTTPHeaderKeys();
                    while (enumVar.hasMoreElements()) {
                        final String s = (String) enumVar.nextElement();
                        res.setHeader(s, content.getHTTPHeader(s));
                    }
                }

                /*
                 * What we will send is an image or some other sort of
                 * binary
                 */
                if (content instanceof HTMLImage) {
                    final HTMLImage img = (HTMLImage) content;
                    /*
                     * the HTMLImage class provides us with most of the
                     * necessary information that we want to send
                     */
                    res.setHeader("Content-Type", img.getContentType());
                    res.setHeader("Content-Transfer-Encoding", img.getContentEncoding());
                    res.setHeader("Content-Length", "" + img.size());
                    res.setHeader("Connection", "Keep-Alive");

                    /* Send 8k junks */
                    int offset = 0;
                    while (offset + chunk_size < img.size()) {
                        out.write(img.toBinary(), offset, chunk_size);
                        offset += chunk_size;
                    }
                    out.write(img.toBinary(), offset, img.size() - offset);
                    out.flush();

                    out.close();
                } else {
                    final byte[] encoded_content = content.toString().getBytes("UTF-8");

                    /*
                     * We are sending HTML text. Set the encoding to UTF-8
                     * for Unicode messages
                     */
                    res.setHeader("Content-Length", "" + (encoded_content.length + 2));
                    res.setHeader("Connection", "Keep-Alive");
                    res.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");

                    out.write(encoded_content);
                    out.write("\r\n".getBytes());

                    out.flush();

                    out.close();
                }
            }
        } catch (final DocumentNotFoundException e) {
            log.info("Connection to " + addr.toString() + ": Could not handle request (" + err_code
                    + ") (Reason: " + e.getMessage() + ")");
            throw new ServletException("Error: " + e.getMessage(), e);
            // res.setStatus(err_code);
            // res.setHeader("Content-type","text/html");
            // res.setHeader("Connection","close");

            // content=new HTMLErrorMessage(getStorage(),e.getMessage());
            // out.write((content+"\r\n").getBytes("UTF-8"));
            // out.write("</HTML>\r\n".getBytes());
            // out.flush();
            // out.close();
        }
    } catch (final Exception e) {
        log.info("Connection to " + addr.toString() + " closed unexpectedly", e);
        throw new ServletException(e.getMessage());
    }
}

From source file:hu.api.SivaPlayerVideoServlet.java

private void doAction(HttpServletRequest request, HttpServletResponse response, String requestType)
        throws ServletException, IOException {

    // Check if it's an AJAX request
    this.isAJAXRequest = (request.getParameter("ajax") != null && request.getParameter("ajax").equals("true"));

    // Allow Cross-Origin-Requests
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "1000");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");

    // URL pattern: /videoId
    // Get request parameter from URL and check if it has been set.
    // Show 400 if less or more parameters than allowed.
    String requestedVideo = request.getPathInfo();
    if (requestedVideo == null || requestedVideo.split("/").length < 2
            || requestedVideo.split("/")[1].equals("")) {
        this.sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "The video folder has to be specified for using this web service.");
        return;/*w  w  w .ja v  a  2  s.c o m*/
    }

    this.persistenceProvider = (IPersistenceProvider) getServletContext().getAttribute("PersistenceProvider");
    this.mailService = (MailService) getServletContext().getAttribute("mailService");
    this.brandingConfiguration = (BrandingConfiguration) getServletContext()
            .getAttribute("brandingConfiguration");

    // Check if it's a watching request
    if (request.getPathInfo().endsWith("/watch.html")) {
        this.providePlayer(request, response);
        return;
    }

    // Check if it's a log request and perform logging if so
    if (request.getPathInfo().endsWith("/log") && requestType.equals("POST")) {
        this.doLogging(request, response);
        return;
    }

    // Check if it's a checkSession request and provide session status if so
    if (requestedVideo.endsWith("/getStats.js")) {
        this.getStats(request, response);
        return;
    }

    // Check if user requests user secret and perform login
    if (request.getPathInfo().endsWith("/getSecret.js") && requestType.equals("POST")) {
        this.provideUserSecret(request, response, requestType);
        return;
    }

    // Check if current session exists and if it is allowed to access this
    // video, stop further execution, if so.
    boolean result = handleAccess(request, response, requestType);
    if (!result) {
        return;
    }

    // Check if it's collaboration request and provide data
    if (request.getPathInfo().endsWith("/getCollaboration.js")) {
        this.provideCollaboration(request, response);
        return;
    }

    // Check if it's a thread creation request
    if (request.getPathInfo().endsWith("/createCollaborationThread.js")) {
        this.createCollaborationThread(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/createCollaborationPost.js")) {
        this.createCollaborationPost(request, response);
        return;
    }

    // Check if it's a post activation request
    if (request.getPathInfo().endsWith("/activateCollaborationPost.js")) {
        this.activateCollaborationPost(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/deleteCollaborationThread.js")) {
        this.deleteCollaborationThread(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/deleteCollaborationPost.js")) {
        this.deleteCollaborationPost(request, response);
        return;
    }

    // Check if it's a checkSession request and provide session status if so
    if (requestedVideo.endsWith("/checkSession.js")) {
        this.provideSessionStatus(request, response);
        return;
    }

    // Decode the file name from the URL and check if file actually exists
    // in
    // file system, send 404 if not
    File file = new File(videoPath, URLDecoder.decode(requestedVideo, "UTF-8"));
    if (!file.exists()) {
        this.sendError(response, HttpServletResponse.SC_NOT_FOUND, "File not found");
        return;
    }

    // Create log entry for file request
    this.logFileRequest(requestedVideo);

    // Check if configuration is requested and do needed preparing and
    // stop standard file preparation
    if (file.getName().equals("export.js")) {
        this.provideConfigFile(request, response, file);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;

    // Validate request headers for caching
    // ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return
    // 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
        // week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
        // week.
        return;
    }

    // Validate request headers for resume
    // ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If
    // not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range
    // -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not,
        // then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required
            // in
            // 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then
        // LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws
                // IAE
                // if
                // invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte
        // range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required
                    // in
                    // 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response
    // --------------------------------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding
    // is supported by
    // the browser and expand content type with the one and right character
    // encoding.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by
    // the browser, then set to inline, else attachment which will pop a
    // 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (requestType.equals("GET")) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of
                    // GZIP.
                    // So only add it if there is no means of GZIP, else
                    // browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (requestType.equals("GET")) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (requestType.equals("GET")) {
                // Cast back to ServletOutputStream to get the easy println
                // methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every
                    // range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:eionet.gdem.web.FileDownloadServlet.java

/**
 * Process the actual request./*ww  w . j a v  a2  s  .c o m*/
 *
 * @param request
 *            The request to be processed.
 * @param response
 *            The response to be created.
 * @param content
 *            Whether the request body should be written (GET) or not (HEAD).
 * @throws IOException
 *             If something fails at I/O level.
 * @throws ServletException If an error occurs.
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException, ServletException {

    String urlPath = URLDecoder
            .decode(StringUtils.substringAfter(request.getRequestURI(), request.getContextPath()), "UTF-8");
    String filePath = Properties.appRootFolder + urlPath;

    String securityMessage = checkPermissions(request, urlPath);
    if (securityMessage != null) {
        handleNotAuthorised(securityMessage, request, response);
        return;
    }

    // Get the file object from the file store
    File file = new File(filePath);

    // If file was not found, send 404.
    if (file == null || !file.exists() || !file.isFile()) {
        handleFileNotFound("Could not find file by the following URI: " + request.getRequestURI(), request,
                response);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;

    // Validate request headers for caching ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "text/plain";
    }

    // If content type is text, then determine whether GZIP content encoding is supported by
    // the browser and expand content type with the one and right character encoding.
    // Else, expect for images, determine content disposition. If content type is supported by
    // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    } else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (content) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of GZIP.
                    // So only add it if there is no means of GZIP, else browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Cast back to ServletOutputStream to get the easy println methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}