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.mock; 018 019import java.io.Serializable; 020import java.util.HashMap; 021import java.util.Map; 022import java.util.function.Supplier; 023 024import org.apache.wicket.MetaDataEntry; 025import org.apache.wicket.MetaDataKey; 026import org.apache.wicket.pageStore.IPageContext; 027 028/** 029 * Mock implementation of a page context - suitable for a single session only. 030 */ 031public class MockPageContext implements IPageContext 032{ 033 034 final String sessionId; 035 036 MetaDataEntry<?>[] requestData; 037 038 MetaDataEntry<?>[] sessionData; 039 040 Map<String, Object> sessionAttributes = new HashMap<>(); 041 042 public MockPageContext() 043 { 044 this("dummy_id"); 045 } 046 047 public MockPageContext(String sessionId) 048 { 049 this.sessionId = sessionId; 050 } 051 052 @Override 053 public <T> T getRequestData(MetaDataKey<T> key, Supplier<T> defaultValue) 054 { 055 T value = key.get(requestData); 056 if (value == null) { 057 value = defaultValue.get(); 058 if (value != null) { 059 requestData = key.set(requestData, value); 060 } 061 } 062 063 return value; 064 } 065 066 @Override 067 public <T extends Serializable> T getSessionAttribute(String key, Supplier<T> defaultValue) 068 { 069 @SuppressWarnings("unchecked") 070 T value = (T)sessionAttributes.get(key); 071 if (value == null && defaultValue != null) { 072 value = defaultValue.get(); 073 sessionAttributes.put(key, value); 074 } 075 076 return value; 077 } 078 079 @Override 080 public <T extends Serializable> T getSessionData(MetaDataKey<T> key, Supplier<T> defaultValue) 081 { 082 T value = key.get(sessionData); 083 if (value == null && defaultValue != null) { 084 value = defaultValue.get(); 085 sessionData = key.set(sessionData, value); 086 } 087 088 return value; 089 } 090 091 @Override 092 public String getSessionId(boolean bind) 093 { 094 return sessionId; 095 } 096 097 public void clearRequest() 098 { 099 requestData = null; 100 } 101 102 public void clearSession() { 103 sessionAttributes.clear(); 104 sessionData = null; 105 } 106}