001/* 002 * oauth2-oidc-sdk 003 * 004 * Copyright 2012-2020, Connect2id Ltd and contributors. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.openid.connect.sdk.federation.policy.language; 019 020 021import java.util.List; 022 023import com.nimbusds.oauth2.sdk.ParseException; 024import com.nimbusds.oauth2.sdk.util.JSONUtils; 025 026 027/** 028 * Utility for applying a policy operation to a metadata parameter value. 029 */ 030public class PolicyOperationApplication { 031 032 033 /** 034 * Applies a policy operation to a metadata parameter value. 035 * 036 * @param op The policy operation. Must not be {@code null}. 037 * @param value The parameter value. Must be a boolean, string, string 038 * list or {@code null}. 039 * 040 * @return The new parameter value, potentially modified. 041 * 042 * @throws PolicyViolationException On a policy violation. 043 */ 044 public static Object apply(final PolicyOperation op, final Object value) 045 throws PolicyViolationException { 046 047 if (op instanceof UntypedOperation) { 048 049 return ((UntypedOperation)op).apply(value); 050 } 051 052 if (op instanceof BooleanOperation) { 053 054 if (! (value instanceof Boolean)) { 055 throw new PolicyViolationException("The value must be a boolean"); 056 } 057 return ((BooleanOperation)op).apply((Boolean)value); 058 } 059 060 if (op instanceof StringOperation) { 061 062 StringOperation stringOperation = (StringOperation)op; 063 064 if (value == null) { 065 return stringOperation.apply(null); 066 } else if (value instanceof String) { 067 return stringOperation.apply((String)value); 068 } else { 069 throw new PolicyViolationException("The value must be a string"); 070 } 071 } 072 073 if (op instanceof StringListOperation) { 074 075 StringListOperation stringListOperation = (StringListOperation)op; 076 077 if (value == null) { 078 return stringListOperation.apply(null); 079 } else if (value instanceof List) { 080 try { 081 return stringListOperation.apply(JSONUtils.toStringList(value)); 082 } catch (ParseException e) { 083 throw new PolicyViolationException("The value must be a string list", e); 084 } 085 } else { 086 throw new PolicyViolationException("The value must be a string list"); 087 } 088 } 089 090 throw new PolicyViolationException("Unsupported policy operation: " + op.getClass().getName()); 091 } 092 093 094 /** 095 * Prevents public instantiation. 096 */ 097 private PolicyOperationApplication() {} 098}