001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket.pageStore; 018 019import java.io.Serializable; 020import java.util.function.Supplier; 021 022import org.apache.wicket.MetaDataKey; 023import org.apache.wicket.Session; 024import org.apache.wicket.request.cycle.RequestCycle; 025 026/** 027 * Default page context using {@link RequestCycle#getRequest()} and {@link Session#get()}. 028 * 029 * @author Juergen Donnerstag 030 * @author svenmeier 031 */ 032public class DefaultPageContext implements IPageContext 033{ 034 035 /** 036 * @see org.apache.wicket.pageStore.IPageContext#getSessionId(boolean) 037 */ 038 @Override 039 public String getSessionId(boolean bind) 040 { 041 Session session = Session.get(); 042 043 if (bind) { 044 session.bind(); 045 } 046 047 return session.getId(); 048 } 049 050 @SuppressWarnings("unchecked") 051 @Override 052 public <T extends Serializable> T getSessionAttribute(String key, Supplier<T> defaultValue) 053 { 054 Session session = Session.get(); 055 056 synchronized (session) 057 { 058 T value = (T)session.getAttribute(key); 059 if (defaultValue != null) { 060 if (value == null) { 061 value = defaultValue.get(); 062 session.bind(); 063 } 064 065 session.setAttribute(key, value); 066 } 067 068 return value; 069 } 070 } 071 072 @Override 073 public <T extends Serializable> T getSessionData(MetaDataKey<T> key, Supplier<T> defaultValue) 074 { 075 Session session = Session.get(); 076 077 synchronized (session) 078 { 079 T value = session.getMetaData(key); 080 if (defaultValue != null) { 081 if (value == null) { 082 value = defaultValue.get(); 083 session.bind(); 084 } 085 086 session.setMetaData(key, value); 087 } 088 089 return value; 090 } 091 } 092 093 @Override 094 public <T> T getRequestData(MetaDataKey<T> key, Supplier<T> defaultValue) 095 { 096 RequestCycle requestCycle = RequestCycle.get(); 097 if (requestCycle == null) 098 { 099 throw new IllegalStateException("Not a request thread."); 100 } 101 T value = requestCycle.getMetaData(key); 102 if (value == null) { 103 value = defaultValue.get(); 104 if (value != null) { 105 requestCycle.setMetaData(key, value); 106 } 107 } 108 return value; 109 } 110}