001/* 002 * Copyright 2024 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.web; 017 018import java.util.Set; 019import java.util.regex.Matcher; 020import java.util.regex.Pattern; 021 022/** 023 * Helper for contexts. 024 */ 025public class AmetysContextHelper extends org.ametys.core.AmetysContextHelper 026{ 027 private static final Pattern _SITES_CONTEXT_PATTERN = Pattern.compile("^/sites/(.+)$"); 028 private static final Pattern _SITES_FO_CONTEXT_PATTERN = Pattern.compile("^/sites-fo/(.+)$"); 029 030 private static final String _SITES_CONTEXT_PREFIX = "/sites/"; 031 private static final String _SITES_FO_CONTEXT_PREFIX = "/sites-fo/"; 032 033 @Override 034 public boolean areRelated(Set<String> contextsSet1, Set<String> contextsSet2) 035 { 036 // The two sets are acquainted if at least one context, or its complementary, is in both sets 037 return contextsSet1.stream() 038 .anyMatch(context -> contextsSet2.contains(context) 039 || contextsSet2.contains(getSiteComplementaryContext(context))); 040 } 041 042 @Override 043 public boolean isRelatedWithContext(Set<String> setOfContexts, String contextToCheck) 044 { 045 return setOfContexts != null 046 // True if the set contains the context or its complementary context 047 && (setOfContexts.contains(contextToCheck) 048 || setOfContexts.contains(getSiteComplementaryContext(contextToCheck))); 049 } 050 051 /** 052 * Get the complementary context of a context 053 * @param context The context 054 * @return The site complementary context 055 */ 056 public static String getSiteComplementaryContext(String context) 057 { 058 Matcher matcher = _SITES_CONTEXT_PATTERN.matcher(context); 059 if (matcher.matches()) 060 { 061 String siteName = matcher.group(1); 062 return _SITES_FO_CONTEXT_PREFIX + siteName; 063 } 064 else 065 { 066 matcher = _SITES_FO_CONTEXT_PATTERN.matcher(context); 067 if (matcher.matches()) 068 { 069 String siteName = matcher.group(1); 070 return _SITES_CONTEXT_PREFIX + siteName; 071 } 072 } 073 074 return null; 075 } 076}