package com.ctrip.framework.apollo.common.condition;

import com.google.common.collect.Sets;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author Jason Song(song_s@ctrip.com)
 */
public class OnProfileCondition implements Condition {
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    Set<String> activeProfiles = Sets.newHashSet(context.getEnvironment().getActiveProfiles());

    Set<String> requiredActiveProfiles = retrieveAnnotatedProfiles(metadata, ConditionalOnProfile.class.getName());
    Set<String> requiredInactiveProfiles = retrieveAnnotatedProfiles(metadata, ConditionalOnMissingProfile.class
        .getName());

    return Sets.difference(requiredActiveProfiles, activeProfiles).isEmpty()
        && Sets.intersection(requiredInactiveProfiles, activeProfiles).isEmpty();
  }

  private Set<String> retrieveAnnotatedProfiles(AnnotatedTypeMetadata metadata, String annotationType) {
    if (!metadata.isAnnotated(annotationType)) {
      return Collections.emptySet();
    }

    Set<String> profiles = Sets.newHashSet();
    MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(annotationType);

    List<?> values = attributes.get("value");
    if (values != null) {
      for (Object value : values) {
        if (value instanceof String[]) {
          Collections.addAll(profiles, (String[]) value);
        }
        else {
          profiles.add((String) value);
        }
      }
    }

    return profiles;
  }
}

@@ -1306,54 +1306,8 @@
  %7D%0A%0A
-    Set%3CString%3E profiles = Sets.newHashSet();%0A
     
@@ -1399,24 +1399,144 @@
 tionType);%0A%0A
+    if (attributes == null) %7B%0A      return Collections.emptySet();%0A    %7D%0A%0A    Set%3CString%3E profiles = Sets.newHashSet();%0A
     List%3C?%3E 
@@ -1569,16 +1569,17 @@
 alue%22);%0A
+%0A
     if (

fix potential conditional npe