/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.eagle.security.auditlog;

import com.typesafe.config.Config;
import org.apache.eagle.security.service.ISecurityDataEnrichServiceClient;
import org.apache.eagle.security.service.IPZoneEntity;
import org.apache.eagle.security.enrich.AbstractDataEnrichLCM;

import java.util.Collection;

/**
 * Since 8/16/16.
 */
public class IPZoneDataEnrichLCM extends AbstractDataEnrichLCM<IPZoneEntity, String> {
    public IPZoneDataEnrichLCM(Config config){
        super(config);
    }
    @Override
    protected Collection<IPZoneEntity> loadFromService(ISecurityDataEnrichServiceClient client) {
        return client.listIPZones();
    }

    @Override
    public String getCacheKey(IPZoneEntity entity) {
        return entity.getIphost();
    }
}


/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.knox.gateway.filter.rewrite.impl;

import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
import org.apache.knox.gateway.i18n.messages.MessagesFactory;
import org.apache.knox.gateway.util.urltemplate.Evaluator;
import org.apache.knox.gateway.util.urltemplate.Params;
import org.apache.knox.gateway.util.urltemplate.Resolver;
import org.apache.knox.gateway.util.urltemplate.Template;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class UrlRewriteContextImpl implements UrlRewriteContext {

  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );

  private UrlRewriteEnvironment environment;
  private Resolver resolver;
  private Evaluator evaluator;
  private Map<String,UrlRewriteFunctionProcessor> functions;
  private ContextParameters params;
  private UrlRewriter.Direction direction;
  private Template originalUrl;
  private Template currentUrl;

  public UrlRewriteContextImpl(
      UrlRewriteEnvironment environment,
      Resolver resolver,
      Map<String,UrlRewriteFunctionProcessor> functions,
      UrlRewriter.Direction direction,
      Template url ) {
    this.environment = environment;
    this.resolver = resolver;
    this.functions = functions;
    this.params = new ContextParameters();
    this.evaluator = new ContextEvaluator();
    this.direction = direction;
    this.originalUrl = url;
    this.currentUrl = url;
  }

  @Override
  public UrlRewriter.Direction getDirection() {
    return direction;
  }

  @Override
  public Template getOriginalUrl() {
    return originalUrl;
  }

  @Override
  public Template getCurrentUrl() {
    return currentUrl;
  }

  @Override
  public void setCurrentUrl( Template url ) {
    currentUrl = url;
  }

  @Override
  public void addParameters( Params parameters ) {
    params.add( parameters );
  }

  @Override
  public Params getParameters() {
    return params;
  }

  @Override
  public Evaluator getEvaluator() {
    return evaluator;
  }

  private class ContextParameters implements Params {
    Map<String,List<String>> map = new LinkedHashMap<>();

    @Override
    public Set<String> getNames() {
      return map.keySet();
    }

    @Override
    public List<String> resolve( String name ) {
      List<String> values = map.get( name ); // Try to find the name in the context map.
      if( values == null ) {
        try {
          values = resolver.resolve( name );
          if( values == null ) {
            values = environment.resolve( name ); // Try to find the name in the environment.
          }
        } catch( Exception e ) {
          LOG.failedToFindValuesByParameter( name, e );
          // Ignore it and return null.
        }
      }
      return values;
    }

    public void add( Params params ) {
      for( String name : params.getNames() ) {
        map.put( name, params.resolve( name ) );
      }
    }

  }

  private class ContextEvaluator implements Evaluator {

    @Override
    public List<String> evaluate( String function, List<String> parameters ) {
      List<String> results = null;
      UrlRewriteFunctionProcessor processor = functions.get( function );
      if( processor != null ) {
        try {
          results = processor.resolve( UrlRewriteContextImpl.this, parameters );
        } catch( Exception e ) {
          LOG.failedToInvokeRewriteFunction( function, e );
          results = null;
        }
      }
      return results;
    }
  }

}


/**
 * Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package com.amazon.pay.response.model;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * This can parse two different variations of <IdList> nodes.
 * In most cases, the individual members are instead <member>..</member> tags,
 * but some IPN messages put them inside <Id>..</Id> tags.
 * The class was modified to handle both cases and let the
 * SDK client retrieve either case by a single getMember() call.
 *
 * Valid example 1:
 *   <IdList>
 *     <member>S01-9228170-9681927-C035172</member>
 *     <member>S01-9228170-9681927-C039558</member>
 *  </IdList>
 *
 * Valid example 2:
 *   <IdList>
 *     <Id>S01-9228170-9681927-C035172</Id>
 *     <Id>S01-9228170-9681927-C039558</Id>
 *  </IdList>
 *
 * Invalid example (cannot mix Id and member tags in same group):
 *   <IdList>
 *     <member>S01-9228170-9681927-C035172</member>
 *     <Id>S01-9228170-9681927-C039558</Id>
 *  </IdList>
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IdList", propOrder = {
    "member",
    "id"
})
public class IdList {

    @XmlElement(name = "member")
    protected List<String> member;
    @XmlElement(name = "Id")
    protected List<String> id;

    /**
     * Default constructor
     *
     */
    public IdList() {
        super();
    }

    public IdList(final List<String> member) {
        this.member = member;
    }

    /**
     * @return the members of the List
     */
    public List<String> getMember() {
        if ((member == null) && (id == null)) {
            return new ArrayList<String>();
        }
        return (member != null) ? member : id;
    }

    /**
     * @return the ID of the members of the List
     */
    public List<String> getId() {
        return getMember();
    }

    /**
     * Returns the string representation of GetServiceStatusResult
     */
    @Override
    public String toString() {
        return "IdList{" + "member=" + getMember() + '}';
    }
}


/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.apex.malhar.contrib.parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.simple.parser.ContentHandler;

import com.google.protobuf.TextFormat.ParseException;

/**
 * A concrete implementation of Json ContentHandler<br>
 * Matches JSON keys set from the {@link StreamingJsonParser }
 *
 * @since 3.5.0
 */
public class JsonKeyFinder implements ContentHandler
{
  public JsonKeyFinder()
  {
    keyValMap = new HashMap<>();
  }

  public int getKeyCount()
  {
    return keyCount;
  }

  public void setKeyCount(int keyCount)
  {
    this.keyCount = keyCount;
  }

  private Object value;
  private HashMap<Object, Object> keyValMap;
  private int keyCount = 0;

  public HashMap<Object, Object> getKeyValMap()
  {
    return keyValMap;
  }

  public void setKeyValMap(HashMap<Object, Object> keyValMap)
  {
    this.keyValMap = keyValMap;
  }

  private boolean found = false;
  private boolean end = false;
  private String key;

  private ArrayList<String> matchKeyList;

  public void setMatchKeyList(ArrayList<String> matchKeyList)
  {
    this.matchKeyList = matchKeyList;
  }

  public ArrayList<String> getMatchKeyList()
  {
    return matchKeyList;
  }

  public Object getValue()
  {
    return value;
  }

  public boolean isEnd()
  {
    return end;
  }

  public void setFound(boolean found)
  {
    this.found = found;
  }

  public boolean isFound()
  {
    return found;
  }

  public void startJSON() throws ParseException, IOException
  {
    found = false;
    end = false;
  }

  public void endJSON() throws ParseException, IOException
  {
    end = true;
  }

  public boolean primitive(Object value) throws ParseException, IOException
  {
    if (getMatchKeyList().contains(key)) {
      found = true;
      this.value = value;
      keyValMap.put(key, value);
      key = null;
      keyCount++;
      return false;
    }
    return true;
  }

  public boolean startArray() throws ParseException, IOException
  {
    return true;
  }

  public boolean startObject() throws ParseException, IOException
  {
    return true;
  }

  public boolean startObjectEntry(String key) throws ParseException, IOException
  {
    this.key = key;
    return true;
  }

  public boolean endArray() throws ParseException, IOException
  {
    return false;
  }

  public boolean endObject() throws ParseException, IOException
  {
    return true;
  }

  public boolean endObjectEntry() throws ParseException, IOException
  {
    return true;
  }
}


/*
 * Copyright 2006-2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package org.springframework.security.oauth2.provider.expression;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;

/**
 * A convenience object for security expressions in OAuth2 protected resources, providing public methods that act on the
 * current authentication.
 *
 * @author Dave Syer
 * @author Rob Winch
 * @author Radek Ostrowski
 *
 */
public class OAuth2SecurityExpressionMethods {

	private final Authentication authentication;

	private Set<String> missingScopes = new LinkedHashSet<String>();

	public OAuth2SecurityExpressionMethods(Authentication authentication) {
		this.authentication = authentication;
	}

	/**
	 * Check if any scope decisions have been denied in the current context and throw an exception if so. This method
	 * automatically wraps any expressions when using {@link OAuth2MethodSecurityExpressionHandler} or
	 * {@link OAuth2WebSecurityExpressionHandler}.
	 *
	 * OAuth2Example usage:
	 *
	 *

	 * access = "#oauth2.hasScope('read') or (#oauth2.hasScope('other') and hasRole('ROLE_USER'))"
	 *

	 *
	 * Will automatically be wrapped to ensure that explicit errors are propagated rather than a generic error when
	 * returning false:
	 *
	 *

	 * access = "#oauth2.throwOnError(#oauth2.hasScope('read') or (#oauth2.hasScope('other') and hasRole('ROLE_USER'))"
	 *

	 *
	 * N.B. normally this method will be automatically wrapped around all your access expressions. You could use it
	 * explicitly to get more control, or if you have registered your own ExpressionParser you might need
	 * it.
	 *
	 * @param decision the existing access decision
	 * @return true if the OAuth2 token has one of these scopes
	 * @throws InsufficientScopeException if the scope is invalid and we the flag is set to throw the exception
	 */
	public boolean throwOnError(boolean decision) {
		if (!decision && !missingScopes.isEmpty()) {
			Throwable failure = new InsufficientScopeException("Insufficient scope for this resource", missingScopes);
			throw new AccessDeniedException(failure.getMessage(), failure);
		}
		return decision;
	}

	/**
	 * Check if the OAuth2 client (not the user) has the role specified. To check the user's roles see
	 * {@link #clientHasRole(String)}.
	 *
	 * @param role the role to check
	 * @return true if the OAuth2 client has this role
	 */
	public boolean clientHasRole(String role) {
		return clientHasAnyRole(role);
	}

	/**
	 * Check if the OAuth2 client (not the user) has one of the roles specified. To check the user's roles see
	 * {@link #clientHasAnyRole(String...)}.
	 *
	 * @param roles the roles to check
	 * @return true if the OAuth2 client has one of these roles
	 */
	public boolean clientHasAnyRole(String... roles) {
		return OAuth2ExpressionUtils.clientHasAnyRole(authentication, roles);
	}

	/**
	 * Check if the current OAuth2 authentication has the scope specified.
	 *
	 * @param scope the scope to check
	 * @return true if the OAuth2 authentication has the required scope
	 */
	public boolean hasScope(String scope) {
		return hasAnyScope(scope);
	}

	/**
	 * Check if the current OAuth2 authentication has one of the scopes specified.
	 *
	 * @param scopes the scopes to check
	 * @return true if the OAuth2 token has one of these scopes
	 * @throws AccessDeniedException if the scope is invalid and we the flag is set to throw the exception
	 */
	public boolean hasAnyScope(String... scopes) {
		boolean result = OAuth2ExpressionUtils.hasAnyScope(authentication, scopes);
		if (!result) {
			missingScopes.addAll(Arrays.asList(scopes));
		}
		return result;
	}

	/**
	 * Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression.
	 *
	 *

	 * access = "#oauth2.hasScopeMatching('.*_admin:manage_scopes')))"
	 *

	 *
	 * @param scopeRegex the scope regex to match
	 * @return true if the OAuth2 authentication has the required scope
	 */
	public boolean hasScopeMatching(String scopeRegex) {
		return hasAnyScopeMatching(scopeRegex);
	}

	/**
	 * Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression.
	 *
	 *

	 * access = "#oauth2.hasAnyScopeMatching('admin:manage_scopes','.*_admin:manage_scopes','.*_admin:read_scopes')))"
	 *

	 *
	 * @param scopesRegex the scopes regex to match
	 * @return true if the OAuth2 token has one of these scopes
	 * @throws AccessDeniedException if the scope is invalid and we the flag is set to throw the exception
	 */
	public boolean hasAnyScopeMatching(String... scopesRegex) {

		boolean result = OAuth2ExpressionUtils.hasAnyScopeMatching(authentication, scopesRegex);
		if (!result) {
			missingScopes.addAll(Arrays.asList(scopesRegex));
		}
		return result;
	}

	/**
	 * Deny access to oauth requests, so used for example to only allow web UI users to access a resource.
	 *
	 * @return true if the current authentication is not an OAuth2 type
	 */
	public boolean denyOAuthClient() {
		return !OAuth2ExpressionUtils.isOAuth(authentication);
	}

	/**
	 * Permit access to oauth requests, so used for example to only allow machine clients to access a resource.
	 *
	 * @return true if the current authentication is not an OAuth2 type
	 */
	public boolean isOAuth() {
		return OAuth2ExpressionUtils.isOAuth(authentication);
	}

	/**
	 * Check if the current authentication is acting on behalf of an authenticated user.
	 *
	 * @return true if the current authentication represents a user
	 */
	public boolean isUser() {
		return OAuth2ExpressionUtils.isOAuthUserAuth(authentication);
	}

	/**
	 * Check if the current authentication is acting as an authenticated client application not on behalf of a user.
	 *
	 * @return true if the current authentication represents a client application
	 */
	public boolean isClient() {
		return OAuth2ExpressionUtils.isOAuthClientAuth(authentication);
	}
}


/*******************************************************************************
 * Copyright (c) 2004, 2005 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

package org.eclipse.birt.report.data.adapter.group;

import java.util.Date;

import org.eclipse.birt.core.exception.BirtException;

import com.ibm.icu.util.TimeZone;
import com.ibm.icu.util.ULocale;

/**
 * This calculator is used to calculate a year group key basing group interval.
 */
class YearGroupCalculator extends DateGroupCalculator
{

	public YearGroupCalculator( Object intervalStart, double intervalRange,
			ULocale locale, TimeZone timeZone ) throws BirtException
	{
		super( intervalStart, intervalRange, locale, timeZone );
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.birt.data.engine.impl.group.DateGroupCalculator#calculate(java.lang.Object)
	 */
	public Object calculate( Object value )
	{
		if ( value == null )
		{
			return new Double( -1 );
		}

		if ( intervalStart == null )
		{
			return new Double( Math.floor( this.dateTimeUtil.diffYear( defaultStart,
					(Date) value )
					/ getDateIntervalRange( ) ) );
		}
		else
		{
			if ( this.dateTimeUtil.diffYear( (Date) intervalStart, (Date) value ) < 0 )
			{
				return new Double( -1 );
			}
			else
			{
				return new Double( Math.floor( this.dateTimeUtil.diffYear( (Date) intervalStart,
						(Date) value )
						/ getDateIntervalRange( ) ) );
			}
		}
	}
}