001/* 002 * Copyright 2017 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.plugins.odfweb.restrictions.rules; 017 018import java.util.Set; 019 020import org.apache.commons.lang.StringUtils; 021 022import org.ametys.odf.ProgramItem; 023import org.ametys.odf.orgunit.RootOrgUnitProvider; 024import org.ametys.odf.program.Program; 025import org.ametys.plugins.repository.query.expression.Expression; 026import org.ametys.plugins.repository.query.expression.Expression.Operator; 027import org.ametys.plugins.repository.query.expression.OrExpression; 028import org.ametys.plugins.repository.query.expression.StringExpression; 029 030/** 031 * This implementation of {@link OdfRestrictionRule} restricts ODF to a orgunit and their child orgunits 032 */ 033public class OdfOrgunitRestrictionRule implements OdfRestrictionRule 034{ 035 private final RootOrgUnitProvider _ouProvider; 036 private final String _rootOrgUnitId; 037 038 /** 039 * Constructor for ODF rule restriction on a orgunit 040 * @param ouProvider The orgunits provider 041 * @param orgUnitId The id of orgunit 042 */ 043 public OdfOrgunitRestrictionRule(RootOrgUnitProvider ouProvider, String orgUnitId) 044 { 045 _ouProvider = ouProvider; 046 _rootOrgUnitId = orgUnitId; 047 048 if (StringUtils.isEmpty(_rootOrgUnitId)) 049 { 050 throw new IllegalArgumentException("At least one non-null rule is required."); 051 } 052 } 053 054 @Override 055 public Expression getExpression() 056 { 057 Set<String> validOrgUnits = _ouProvider.getChildOrgUnitIds(_rootOrgUnitId, true); 058 validOrgUnits.add(_rootOrgUnitId); 059 060 Expression[] orgUnitExprs = validOrgUnits.stream() 061 .map(ou -> new StringExpression(ProgramItem.ORG_UNITS_REFERENCES, Operator.EQ, ou)) 062 .toArray(Expression[]::new); 063 064 return new OrExpression(orgUnitExprs); 065 } 066 067 @Override 068 public boolean contains(Program program) 069 { 070 Set<String> validOrgUnits = _ouProvider.getChildOrgUnitIds(_rootOrgUnitId, true); 071 validOrgUnits.add(_rootOrgUnitId); 072 073 return program.getOrgUnits().stream() 074 .filter(StringUtils::isNotEmpty) 075 .anyMatch(orgUnitId -> validOrgUnits.contains(orgUnitId)); 076 } 077 078 @Override 079 public boolean hasOrgunitRestrictions() 080 { 081 return true; 082 } 083}