org.apache.wicket.request.http.WebResponse Java Examples

The following examples show how to use org.apache.wicket.request.http.WebResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedirectRequestHandler.java    From onedev with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
public void respond(final IRequestCycle requestCycle)
{
	String location = requestCycle.getUrlRenderer().renderRelativeUrl(Url.parse(getRedirectUrl()));
	
	WebResponse response = (WebResponse)requestCycle.getResponse();

	if (status == HttpServletResponse.SC_MOVED_TEMPORARILY)
	{
		response.sendRedirect(location);
	}
	else
	{
		response.setStatus(status);

		if (((WebRequest)requestCycle.getRequest()).isAjax())
		{
			response.setHeader("Ajax-Location", location);
		}
		else
		{
			response.setHeader("Location", location);
		}
	}
}
 
Example #2
Source File: LoginPage.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public static void logout(final MySession mySession, final WebRequest request, final WebResponse response,
    final UserXmlPreferencesCache userXmlPreferencesCache, final MenuBuilder menuBuilder)
{
  final PFUserDO user = mySession.getUser();
  if (user != null) {
    userXmlPreferencesCache.flushToDB(user.getId());
    userXmlPreferencesCache.clear(user.getId());
    if (menuBuilder != null) {
      menuBuilder.expireMenu(user.getId());
    }
  }
  mySession.logout();
  final Cookie stayLoggedInCookie = UserFilter.getStayLoggedInCookie(WicketUtils.getHttpServletRequest(request));
  if (stayLoggedInCookie != null) {
    stayLoggedInCookie.setMaxAge(0);
    stayLoggedInCookie.setValue(null);
    stayLoggedInCookie.setPath("/");
    response.addCookie(stayLoggedInCookie);
  }
}
 
Example #3
Source File: HelloJsonResponse.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
 public void respond(Attributes attributes) 
 {
try
  {
    final WebResponse webResponse = (WebResponse) attributes.getResponse();
    webResponse.setContentLength(27);
    webResponse.setContentType(APPLICATION_JSON);
    JsonMessage message = new JsonMessage(HELLO_WORLD);
    byte[] json = MAPPER.writeValueAsBytes(message);
    webResponse.write(json);
  }
  catch (IOException ex)
  {
   // do nothing
  }
}
 
Example #4
Source File: SyncopeWebApplication.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected void setSecurityHeaders(final Properties props, final WebResponse response) {
    @SuppressWarnings("unchecked")
    Enumeration<String> propNames = (Enumeration<String>) props.propertyNames();
    while (propNames.hasMoreElements()) {
        String name = propNames.nextElement();
        if (name.startsWith("security.headers.")) {
            response.setHeader(StringUtils.substringAfter(name, "security.headers."), props.getProperty(name));
        }
    }
}
 
Example #5
Source File: ScriptingPage.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
private void jFreeChartExport()
{
  try {
    final ExportJFreeChart exportJFreeChart = (ExportJFreeChart) groovyResult.getResult();
    final StringBuilder sb = new StringBuilder();
    sb.append("pf_chart_");
    sb.append(DateHelper.getTimestampAsFilenameSuffix(new Date()));
    final Response response = getResponse();
    final String extension = exportJFreeChart.write(response.getOutputStream());
    sb.append('.').append(extension);
    final String filename = sb.toString();
    final int width = exportJFreeChart.getWidth();
    final int height = exportJFreeChart.getHeight();
    final JFreeChartImage image = new JFreeChartImage("image", exportJFreeChart.getJFreeChart(), exportJFreeChart.getImageType(), width,
        height);
    image.add(AttributeModifier.replace("width", String.valueOf(width)));
    image.add(AttributeModifier.replace("height", String.valueOf(height)));
    imageResultContainer.removeAll();
    imageResultContainer.add(image).setVisible(true);
    ((WebResponse) response).setAttachmentHeader(filename);
    ((WebResponse) response).setContentType(DownloadUtils.getContentType(filename));
    log.info("Starting download for file. filename:" + filename + ", content-type:" + DownloadUtils.getContentType(filename));
    response.getOutputStream().flush();
  } catch (final Exception ex) {
    error(getLocalizedMessage("error", ex.getMessage()));
    log.error(ex.getMessage(), ex);
  }
}
 
Example #6
Source File: HelloDbResponse.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void respond(Attributes attributes) 
{
 final StringValue queriesParam = attributes.getRequest().getQueryParameters().getParameterValue("queries");
 int qs = queriesParam.toInt(1);
 if (qs < 1)
 {
  qs = 1;
 }
 else if (qs > 500)
 {
  qs = 500;
 }
 final int queries = qs;

 try 
 {
byte[] data = getDataFromDatabase(queriesParam, queries);

final WebResponse webResponse = (WebResponse) attributes.getResponse();
webResponse.setContentLength(data.length);
webResponse.setContentType(HelloJsonResponse.APPLICATION_JSON);
webResponse.write(data);
 } 
 catch (Exception ex)
 {
WebResponse response = (WebResponse) attributes.getResponse();

response.setContentType(TEXT_PLAIN);
response.setStatus(500);
response.write(ex.getClass().getSimpleName() + ": " + ex.getMessage());

ex.printStackTrace();
 }
}
 
Example #7
Source File: HelloTextResource.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void respond(Attributes attributes)
{

  final WebResponse webResponse = (WebResponse) attributes.getResponse();
  webResponse.setContentType(CONTENT_TYPE);
  webResponse.setContentLength(DATA.length);
  webResponse.write(DATA);
}
 
Example #8
Source File: SyncopeWebApplication.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected void setSecurityHeaders(final Properties props, final WebResponse response) {
    @SuppressWarnings("unchecked")
    Enumeration<String> propNames = (Enumeration<String>) props.propertyNames();
    while (propNames.hasMoreElements()) {
        String name = propNames.nextElement();
        if (name.startsWith("security.headers.")) {
            response.setHeader(StringUtils.substringAfter(name, "security.headers."), props.getProperty(name));
        }
    }
}
 
Example #9
Source File: AbstractPlainTextPage.java    From AppStash with Apache License 2.0 5 votes vote down vote up
private WebResponse newStringResponse() {
    WebResponse response = (WebResponse) getResponse();
    response.setContentType("text/plain");
    response.write(responseText());
    response.flush();
    response.setStatus(HttpStatus.OK.value());
    return response;
}
 
Example #10
Source File: DirectBuyRequestCycleListener.java    From AppStash with Apache License 2.0 5 votes vote down vote up
private void redirectTo(RequestCycle cycle, Url urlWithoutDirectBuy) {
    Url requestUrl = cycle.getRequest().getUrl();
    if (!requestUrl.equals(urlWithoutDirectBuy)) {
        WebResponse response = (WebResponse) cycle.getResponse();
        response.reset();
        response.sendRedirect(urlWithoutDirectBuy.toString(Url.StringMode.FULL));
    }
}
 
Example #11
Source File: AbstractPlainTextPage.java    From the-app with Apache License 2.0 5 votes vote down vote up
private WebResponse newStringResponse() {
    WebResponse response = (WebResponse) getResponse();
    response.setContentType("text/plain");
    response.write(responseText());
    response.flush();
    response.setStatus(HttpStatus.OK.value());
    return response;
}
 
Example #12
Source File: DirectBuyRequestCycleListener.java    From the-app with Apache License 2.0 5 votes vote down vote up
private void redirectTo(RequestCycle cycle, Url urlWithoutDirectBuy) {
    Url requestUrl = cycle.getRequest().getUrl();
    if (!requestUrl.equals(urlWithoutDirectBuy)) {
        WebResponse response = (WebResponse) cycle.getResponse();
        response.reset();
        response.sendRedirect(urlWithoutDirectBuy.toString(Url.StringMode.FULL));
    }
}
 
Example #13
Source File: SavedQueriesPanel.java    From onedev with MIT License 5 votes vote down vote up
private void toggle(IPartialPageRequestHandler handler) {
	WebResponse response = (WebResponse) RequestCycle.get().getResponse();
	
	Cookie cookie = new Cookie(getCookieName(), closed?"no":"yes");
	cookie.setPath("/");
	cookie.setMaxAge(Integer.MAX_VALUE);
	response.addCookie(cookie);
	closed = !closed;
	handler.add(this);
}
 
Example #14
Source File: AbstractPlainTextPage.java    From AppStash with Apache License 2.0 4 votes vote down vote up
@Override
public void renderPage() {
    WebResponse response = newStringResponse();
    getRequestCycle().setResponse(response);
}
 
Example #15
Source File: ExpiredPage.java    From wicket-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
protected void setHeaders(final WebResponse response)
{
	response.setStatus(HttpServletResponse.SC_GONE);
}
 
Example #16
Source File: AbstractWebSocketProcessor.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Exports the Wicket thread locals and broadcasts the received message from the client to all
 * interested components and behaviors in the page with id {@code #pageId}
 * <p>
 *     Note: ConnectedMessage and ClosedMessage messages are notification-only. I.e. whatever the
 *     components/behaviors write in the WebSocketRequestHandler will be ignored because the protocol
 *     doesn't expect response from the user.
 * </p>
 *
 * @param message
 *      the message to broadcast
 */
public final void broadcastMessage(final IWebSocketMessage message)
{
	IKey key = getRegistryKey();
	IWebSocketConnection connection = connectionRegistry.getConnection(application, sessionId, key);

	if (connection != null && connection.isOpen())
	{
		Application oldApplication = ThreadContext.getApplication();
		Session oldSession = ThreadContext.getSession();
		RequestCycle oldRequestCycle = ThreadContext.getRequestCycle();

		WebResponse webResponse = webSocketSettings.newWebSocketResponse(connection);
		try
		{
			WebSocketRequestMapper requestMapper = new WebSocketRequestMapper(application.getRootRequestMapper());
			RequestCycle requestCycle = createRequestCycle(requestMapper, webResponse);
			ThreadContext.setRequestCycle(requestCycle);

			ThreadContext.setApplication(application);

			Session session;
			if (oldSession == null || message instanceof IWebSocketPushMessage)
			{
				ISessionStore sessionStore = application.getSessionStore();
				session = sessionStore.lookup(webRequest);
				ThreadContext.setSession(session);
			}
			else
			{
				session = oldSession;
			}

			// Session is null if we copy the url with jsessionid to a new browser window 
			if (session != null) {
				IPageManager pageManager = session.getPageManager();
				Page page = getPage(pageManager);

				if (page != null) {
					WebSocketRequestHandler requestHandler = webSocketSettings.newWebSocketRequestHandler(page, connection);

					@SuppressWarnings("rawtypes")
					WebSocketPayload payload = createEventPayload(message, requestHandler);

					if (!(message instanceof ConnectedMessage || message instanceof ClosedMessage))
					{
						requestCycle.scheduleRequestHandlerAfterCurrent(requestHandler);
					}

					IRequestHandler broadcastingHandler = new WebSocketMessageBroadcastHandler(pageId, resourceName, payload);
					requestMapper.setHandler(broadcastingHandler);
					requestCycle.processRequestAndDetach();
				}
			}
		}
		catch (Exception x)
		{
			try {
				connection.sendMessage(WebSocketManager.ERROR_MESSAGE);
			} catch (IOException e1) {
			}
			LOG.error("An error occurred during processing of a WebSocket message", x);
		}
		finally
		{
			try
			{
				webResponse.close();
			}
			finally
			{
				ThreadContext.setApplication(oldApplication);
				ThreadContext.setRequestCycle(oldRequestCycle);
				ThreadContext.setSession(oldSession);
			}
		}
	}
	else
	{
		LOG.debug("Either there is no connection({}) or it is closed.", connection);
	}
}
 
Example #17
Source File: NotFoundPage.java    From Orienteer with Apache License 2.0 4 votes vote down vote up
@Override
protected void setHeaders(WebResponse response) {
	response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
 
Example #18
Source File: AccessDeniedPage.java    From wicket-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
protected void setHeaders(final WebResponse response)
{
	response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
 
Example #19
Source File: HelloDbUpdatesResource.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void respond(Attributes attributes)
{
  int _queries = attributes.getRequest().getQueryParameters().getParameterValue("queries").toInt(1);
  if (_queries < 1)
  {
    _queries = 1;
  }
  else if (_queries > 500)
  {
    _queries = 500;
  }
  final int queries = _queries;

  try
  {
    final ThreadLocalRandom random = ThreadLocalRandom.current();
    DataSource dataSource = WicketApplication.get().getDataSource();

    World[] worlds = new World[queries];
    try (Connection connection = dataSource.getConnection();
         PreparedStatement query = connection.prepareStatement(
                 "SELECT * FROM World WHERE id = ?",
                 ResultSet.TYPE_FORWARD_ONLY,
                 ResultSet.CONCUR_READ_ONLY);
         PreparedStatement update = connection.prepareStatement(
                 "UPDATE World SET randomNumber = ? WHERE id= ?"))
    {
      for (int i = 0; i < queries; i++)
      {
        query.setInt(1, random.nextInt(DB_ROWS) + 1);
        World world;
        try (ResultSet resultSet = query.executeQuery())
        {
          resultSet.next();
          world = new World(
              resultSet.getInt("id"),
              resultSet.getInt("randomNumber"));
        }
        world.randomNumber = random.nextInt(DB_ROWS) + 1;
        update.setInt(1, world.randomNumber);
        update.setInt(2, world.id);
        update.executeUpdate();
        worlds[i] = world;
      }
    }

    byte[] data = HelloJsonResponse.MAPPER.writeValueAsBytes(worlds);
    final WebResponse webResponse = (WebResponse) attributes.getResponse();
    webResponse.setContentLength(data.length);
    webResponse.setContentType(HelloJsonResponse.APPLICATION_JSON);
    webResponse.write(data);
  }
  catch (Exception ex)
  {
    // do nothing
  }
}
 
Example #20
Source File: AbstractPlainTextPage.java    From the-app with Apache License 2.0 4 votes vote down vote up
@Override
public void renderPage() {
    WebResponse response = newStringResponse();
    getRequestCycle().setResponse(response);
}
 
Example #21
Source File: FortunePage.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void configureResponse(final WebResponse response) {
	response.setContentType(TEXT_HTML);
}
 
Example #22
Source File: LoginPage.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public static void logout(final MySession mySession, final WebRequest request, final WebResponse response,
    final UserXmlPreferencesCache userXmlPreferencesCache)
{
  logout(mySession, request, response, userXmlPreferencesCache, null);
}
 
Example #23
Source File: MenuMobilePage.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("serial")
public MenuMobilePage(final PageParameters parameters)
{
  super(parameters);
  if (getUser().getAttribute(UserFilter.USER_ATTR_STAY_LOGGED_IN) != null) {
    getUser().removeAttribute(UserFilter.USER_ATTR_STAY_LOGGED_IN);
    if (WicketUtils.contains(parameters, PARAM_HOME_KEY) == false) {
      final RecentMobilePageInfo pageInfo = (RecentMobilePageInfo) UserPreferencesHelper
          .getEntry(AbstractSecuredMobilePage.USER_PREF_RECENT_PAGE);
      if (pageInfo != null && pageInfo.getPageClass() != null) {
        throw new RestartResponseException((Class< ? extends Page>) pageInfo.getPageClass(), pageInfo.restorePageParameters());
      }
    }
  }
  setNoBackButton();
  final ListViewPanel listViewPanel = new ListViewPanel("menu");
  pageContainer.add(listViewPanel);
  listViewPanel.add(new ListViewItemPanel(listViewPanel.newChildId(), getString("menu.main.title")).setListDivider());
  final Menu menu = menuBuilder.getMobileMenu(PFUserContext.getUser());
  if (menu.getMenuEntries() != null) {
    for (final MenuEntry menuEntry : menu.getMenuEntries()) {
      if (menuEntry.isVisible() == true) {
        listViewPanel.add(new ListViewItemPanel(listViewPanel.newChildId(), menuEntry.getMobilePageClass(), getString(menuEntry
            .getI18nKey())));
      }
    }
  }
  listViewPanel.add(new ListViewItemPanel(listViewPanel.newChildId(), new BookmarkablePageLink<String>(ListViewItemPanel.LINK_ID,
      WicketUtils.getDefaultPage()), getString("menu.mobile.fullWebVersion")).setAsExternalLink());

  listViewPanel.add(new ListViewItemPanel(listViewPanel.newChildId(), new Link<String>(ListViewItemPanel.LINK_ID) {
    @Override
    public void onClick()
    {
      LoginPage.logout((MySession) getSession(), (WebRequest) getRequest(), (WebResponse) getResponse(), userXmlPreferencesCache,
          menuBuilder);
      setResponsePage(LoginMobilePage.class);
    }

  }, getString("menu.logout")) {
  });
  if (getMySession().isIOSDevice() == true) {
    pageContainer.add(new Label("iOSHint", getString("mobile.iOS.startScreenInfo")));
  } else {
    pageContainer.add(new Label("iOSHint", getString("mobile.others.startScreenInfo")));
  }
}
 
Example #24
Source File: NavTopPanel.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public void init(final AbstractSecuredPage page)
{
  getMenu();
  this.favoritesMenu = FavoritesMenu.get();
  final WebMarkupContainer goMobile = new WebMarkupContainer("goMobile");
  add(goMobile);
  if (page.getMySession().isMobileUserAgent() == true) {
    goMobile.add(new BookmarkablePageLink<Void>("link", MenuMobilePage.class));
  } else {
    goMobile.setVisible(false);
  }
  add(new MenuConfig("menuconfig", getMenu(), favoritesMenu));
  @SuppressWarnings("serial")
  final Form<String> searchForm = new Form<String>("searchForm") {
    private String searchString;

    /**
     * @see org.apache.wicket.markup.html.form.Form#onSubmit()
     */
    @Override
    protected void onSubmit()
    {
      csrfTokenHandler.onSubmit();
      if (StringUtils.isNotBlank(searchString) == true) {
        final SearchPage searchPage = new SearchPage(new PageParameters(), searchString);
        setResponsePage(searchPage);
      }
      super.onSubmit();
    }
  };
  csrfTokenHandler = new CsrfTokenHandler(searchForm);
  add(searchForm);
  final TextField<String> searchField = new TextField<String>("searchField", new PropertyModel<String>(searchForm, "searchString"));
  WicketUtils.setPlaceHolderAttribute(searchField, getString("search.search"));
  searchForm.add(searchField);
  add(new BookmarkablePageLink<Void>("feedbackLink", FeedbackPage.class));
  {
    @SuppressWarnings("serial")
    final AjaxLink<Void> showBookmarkLink = new AjaxLink<Void>("showBookmarkLink") {
      /**
       * @see org.apache.wicket.ajax.markup.html.AjaxLink#onClick(org.apache.wicket.ajax.AjaxRequestTarget)
       */
      @Override
      public void onClick(final AjaxRequestTarget target)
      {
        bookmarkDialog.open(target);
        // Redraw the content:
        bookmarkDialog.redraw().addContent(target);
      }
    };
    add(showBookmarkLink);
    addBookmarkDialog();
  }
  {
    add(new Label("user", PFUserContext.getUser().getFullname()));
    if (accessChecker.isRestrictedUser() == true) {
      // Show ChangePaswordPage as my account for restricted users.
      final BookmarkablePageLink<Void> changePasswordLink = new BookmarkablePageLink<Void>("myAccountLink", ChangePasswordPage.class);
      add(changePasswordLink);
    } else {
      final BookmarkablePageLink<Void> myAccountLink = new BookmarkablePageLink<Void>("myAccountLink", MyAccountEditPage.class);
      add(myAccountLink);
    }
    final BookmarkablePageLink<Void> documentationLink = new BookmarkablePageLink<Void>("documentationLink", DocumentationPage.class);
    add(documentationLink);

    @SuppressWarnings("serial")
    final Link<String> logoutLink = new Link<String>("logoutLink") {
      @Override
      public void onClick()
      {
        LoginPage.logout((MySession) getSession(), (WebRequest) getRequest(), (WebResponse) getResponse(), userXmlPreferencesCache);
        setResponsePage(LoginPage.class);
      };
    };
    add(logoutLink);
  }
  addCompleteMenu();
  addFavoriteMenu();
}
 
Example #25
Source File: WidgetWebPage.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
@Override
protected void setHeaders(WebResponse response) {
	response.disableCaching();		
	super.setHeaders(response);
}