text:
package org.dasein.cloud.test;

import org.apache.log4j.Logger;
import org.dasein.cloud.Cloud;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.CloudProvider;
import org.dasein.cloud.ContextRequirements;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.compute.VmState;
import org.dasein.cloud.compute.VolumeFormat;
import org.dasein.cloud.network.Firewall;
import org.dasein.cloud.network.FirewallSupport;
import org.dasein.cloud.network.IPVersion;
import org.dasein.cloud.network.LbProtocol;
import org.dasein.cloud.network.LoadBalancerSupport;
import org.dasein.cloud.network.NetworkServices;
import org.dasein.cloud.platform.DatabaseEngine;
import org.dasein.cloud.storage.Blob;
import org.dasein.cloud.test.ci.CIResources;
import org.dasein.cloud.test.compute.ComputeResources;
import org.dasein.cloud.test.identity.IdentityResources;
import org.dasein.cloud.test.network.NetworkResources;
import org.dasein.cloud.test.platform.PlatformResources;
import org.dasein.cloud.test.storage.StorageResources;
import org.dasein.cloud.util.APITrace;
import org.dasein.util.CalendarWrapper;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Consolidates and manages cloud resources shared across many different tests.
 *
Created by George Reese: 2/17/13 3:23 PM

 * @author George Reese
 * @version 2013.04 initial version
 * @version 2013.07 Added MQ cloud services support (issue #6)
 * @since 2013.04
 */
public class DaseinTestManager {
    static public final String STATEFUL  = "stateful";
    static public final String STATELESS = "stateless";
    static public final String REMOVED   = "removed";

    static private Map<String,Integer> apiAudit = new HashMap<>();

    static private CIResources       ciResources;
    static private ComputeResources  computeResources;
    static private IdentityResources identityResources;
    static private NetworkResources  networkResources;
    static private PlatformResources platformResources;
    static private StorageResources  storageResources;

    static private Set<String>   exclusions;
    static private Set<String>   inclusions;

    static private int  skipCount;
    static private int  testCount;
    static private long testStart;
    static private boolean dirty = true;

    static public @Nonnull CloudProvider constructProvider() {
        return constructProvider(null, null, null);
    }

    static public @Nonnull CloudProvider constructProvider(@Nullable String overrideAccount, @Nullable String overrideShared, @Nullable String overrideSecret) {
        String cname = getSystemProperty("providerClass");
        if( cname == null ) {
            throw new RuntimeException("Provider class name (env.providerClass) is not set, make sure to specify it manually or via a Maven profile");
        }

        CloudProvider provider = null;

        try{
            String prop, account = "", cloudName = "", endpoint = "", regionId = "", providerName = "", userName = "";

            prop = overrideAccount == null ? System.getProperty("accountNumber") : overrideAccount;
            if( prop != null ) {
                account = prop;
            }
            prop = System.getProperty("cloudName");
            if( prop != null ) {
                cloudName = prop;
            }
            prop = System.getProperty("endpoint");
            if( prop != null ) {
                endpoint = prop;
            }
            prop = System.getProperty("providerName");
            if( prop != null ) {
                providerName = prop;
            }
            prop = System.getProperty("regionId");
            if( prop != null ) {
                regionId = prop;
            }

            Cloud cloud = Cloud.register(providerName, cloudName, endpoint, (Class<? extends CloudProvider>) Class.forName(cname));

            ContextRequirements requirements = cloud.buildProvider().getContextRequirements();
            List<ContextRequirements.Field> fields = requirements.getConfigurableValues();
            List<ProviderContext.Value> values = new ArrayList<ProviderContext.Value>(fields.size());

            for(ContextRequirements.Field f : fields ) {
                if( f.type.equals(ContextRequirements.FieldType.TOKEN) ) {
                    String token = System.getProperty(f.name);
                    // use either shared or secret override, doesn't really matter
                    if( overrideShared != null || overrideSecret != null ) {
                        token = overrideShared == null ? overrideSecret : overrideShared;
                    }
                    values.add(ProviderContext.Value.parseValue(f, token));
                }
                else if( f.type.equals(ContextRequirements.FieldType.KEYPAIR) ) {
                    String shared = overrideShared == null ? System.getProperty(f.name + "Shared") : overrideShared;
                    String secret = overrideSecret == null ? System.getProperty(f.name + "Secret") : overrideSecret;
                    if( shared != null || secret != null ) {

                        //I would rather not have this but its the only way to pass in the binary file from a path
                        boolean p12 = false;
                        byte[] p12Bytes = null;
                        if(f.name.contains("p12")){
                            String p12Path = shared;
                            File file = new File(p12Path);
                            p12Bytes = new byte[(int) file.length()];
                            InputStream ios = null;
                            try {
                                ios = new FileInputStream(file);
                                if ( ios.read(p12Bytes) == -1 ) {
                                    throw new IOException("EOF reached while trying to read p12 certificate");
                                }
                                p12 = true;
                            }
                            catch(IOException ex){
                                //Bummer
                            }
                            finally {
                                try {
                                    if ( ios != null )
                                        ios.close();
                                } catch ( IOException e) {}
                            }
                        }
                        if(p12) values.add(new ProviderContext.Value<byte[][]>("p12Certificate", new byte[][] { p12Bytes, secret.getBytes() }));
                        else values.add(ProviderContext.Value.parseValue(f, shared, secret));
                    } else {
                        String error = String.format("Keypair fields are not set up correctly: " +
                                "%sShared = %s, %sSecret = %s. Check the Maven profile and pom.xml.",
                                f.name, shared, f.name, secret);
                        Logger logger = Logger.getLogger(DaseinTestManager.class);
                        logger.fatal(error);
                        throw new RuntimeException(error);
                    }
                }
                else {
                    String value = System.getProperty(f.name);
                    if( value != null && value.trim().length() > 0 ) {
                        values.add(ProviderContext.Value.parseValue(f, value));
                    } else if( f.required ) {
                        String error = String.format("%s field is missing, but declared as REQUIRED. " +
                                        "Check the Maven profile and pom.xml.",
                                f.name);
                        Logger logger = Logger.getLogger(DaseinTestManager.class);
                        logger.fatal(error);
                        throw new RuntimeException(error);
                    }
                }
            }

            ProviderContext ctx = cloud.createContext(account, regionId, values.toArray(new ProviderContext.Value[0]));
            provider = ctx.connect();
        }
        catch( ClassNotFoundException e ) {
            throw new RuntimeException("No such class: " + e.getMessage());
        }
        catch( IllegalAccessException | InstantiationException | UnsupportedEncodingException
                | InternalException | CloudException ignore ) {
        }
        return provider;
    }

    static public @Nullable ComputeResources getComputeResources() {
        return computeResources;
    }

    static public @Nullable String getDefaultDataCenterId(boolean stateless) {
        return (computeResources == null ? null : computeResources.getTestDataCenterId(stateless));
    }

    static public @Nullable IdentityResources getIdentityResources() {
        return identityResources;
    }

    static public @Nullable NetworkResources getNetworkResources() {
        return networkResources;
    }

    static public @Nullable CIResources getCiResources() {
        return ciResources;
    }
    static public @Nullable PlatformResources getPlatformResources() {
        return platformResources;
    }

    static public @Nullable StorageResources getStorageResources() {
        return storageResources;
    }

    static private @Nullable Set<String> parseArrayProperty(String name) {
        String prop = System.getProperty(name);

        if( prop != null && !prop.equals("") ) {
            Set<String> values = new TreeSet<>();
            if( prop.contains(",") ) {
                for( String which : prop.split(",") ) {
                    values.add(which.toLowerCase());
                }
            }
            else {
                values.add(prop.toLowerCase());
            }
            return values;
        }
        return null;
    }

    static public void init() {
        Logger logger = Logger.getLogger(DaseinTestManager.class);
        logger.info("BEGIN Test Initialization ------------------------------------------------------------------------------");
        try {
            testStart = System.currentTimeMillis();

            CloudProvider cloudProvider = constructProvider();
            storageResources = new StorageResources(cloudProvider);
            platformResources = new PlatformResources(cloudProvider);
            networkResources = new NetworkResources(cloudProvider);
            identityResources = new IdentityResources(cloudProvider);
            ciResources = new CIResources(cloudProvider);
            computeResources = new ComputeResources(cloudProvider);

            computeResources.init();

            inclusions = parseArrayProperty("dasein.inclusions");
            exclusions = parseArrayProperty("dasein.exclusions");

            out(logger, null, "Included", (inclusions == null ? null : inclusions.toString()));
            out(logger, null, "Excluded", (exclusions == null ? null : exclusions.toString()));

            APITrace.report("Init");
            APITrace.reset();

            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    if( dirty ) {
                        cleanUp();
                    }
                }
            });
        }
        finally {
            logger.info("END Test Initialization ------------------------------------------------------------------------------");
            logger.info("");
        }
    }

    static public void cleanUp() {
        System.out.println("Cleaning up, please wait...");
        Logger logger = Logger.getLogger(DaseinTestManager.class);
        int provisioned = 0;
        int cleaned = 0;

        logger.info("");
        logger.info("BEGIN Test Clean Up ------------------------------------------------------------------------------");
        try {
            APITrace.report("Clean Up");
            if( ciResources != null ) {
                int count = ciResources.close();

                out(logger, null, "CI Resources", String.valueOf(count));
                cleaned += count;
            }
            if( computeResources != null ) {
                int count = computeResources.close();

                out(logger, null, "Compute Resources", String.valueOf(count));
                cleaned += count;
            }
            if( networkResources != null ) {
                int count = networkResources.close();

                out(logger, null, "Network Resources", String.valueOf(count));
                cleaned += count;
            }
            if( identityResources != null ) {
                int count = identityResources.close();

                out(logger, null, "Identity Resources", String.valueOf(count));
                cleaned += count;
            }
            if( platformResources != null ) {
                int count = platformResources.close();

                out(logger, null, "Platform Resources", String.valueOf(count));
                cleaned += count;
            }
            if( storageResources != null ) {
                int count = storageResources.close();

                out(logger, null, "Storage Resources", String.valueOf(count));
                cleaned += count;
            }
        }
        finally {
            logger.info("END Test Clean Up ------------------------------------------------------------------------------");
            logger.info("");
        }
        long duration = System.currentTimeMillis() - testStart;
        int minutes = (int)(duration/ CalendarWrapper.MINUTE);
        float seconds = ((float)(duration%CalendarWrapper.MINUTE))/1000f;
        logger.info("");
        logger.info("All Tests Complete ------------------------------------------------------------------------------");
        logger.info("--------------- API Log ---------------");
        int total = 0;

        for( Map.Entry<String,Integer> entry : apiAudit.entrySet() ) {
            out(logger, null, "---> " + entry.getKey(), String.valueOf(entry.getValue()));
            total += entry.getValue();
        }
        out(logger, null, "---> Total Calls", String.valueOf(total));
        logger.info("");

        logger.info("----------- Provisioning Log ----------");
        if( computeResources != null ) {
            provisioned += computeResources.report();
        }
        if( ciResources != null ) {
            provisioned += ciResources.report();
        }
        if( identityResources != null ) {
            provisioned += identityResources.report();
        }
        if( networkResources != null ) {
            provisioned += networkResources.report();
        }
        if( platformResources != null ) {
            provisioned += platformResources.report();
        }
        if( storageResources != null ) {
            provisioned += storageResources.report();
        }
        logger.info("");
        logger.info("--------------- Results ---------------");
        out(logger, null, "Tests", String.valueOf(testCount));
        out(logger, null, "Skipped", String.valueOf(skipCount));
        out(logger, null, "Run", String.valueOf(testCount - skipCount));
        out(logger, null, "Resources Provisioned", String.valueOf(provisioned));
        out(logger, null, "Resources De-provisioned", String.valueOf(cleaned));
        out(logger, null, "Duration", minutes + " minutes " + seconds + " seconds");
        logger.info("-------------------------------------------------------------------------------------------------");

        dirty = false;
    }

    static public void out(@Nonnull Logger logger, @Nullable String prefix, @Nonnull String key, @Nullable String value) {
        StringBuilder str = new StringBuilder();

        if( key.length() > 36 ) {
            str.append(key.substring(0, 36)).append(": ");
        }
        else {
            str.append(key).append(": ");
            while( str.length() < 38 ) {
                str.append(" ");
            }
        }
        if( prefix == null ) {
            logger.info(str.toString() + value);
        }
        else {
            logger.info( prefix + str.toString() + value);
        }
    }

    private Logger                  logger;
    private String                  name;
    private String                  prefix;
    private CloudProvider           provider;
    private long                    startTimestamp;
    private String                  suite;
    private String                  userName = "";

    public DaseinTestManager(@Nonnull Class<?> testClass) {
        logger = Logger.getLogger(testClass);
        suite = testClass.getSimpleName();
        provider = constructProvider();
        changePrefix();

        String prop = System.getProperty("user.name");
        if( prop != null ) {
            userName = prop;
        }
    }

    public void begin(@Nonnull String name) {
        this.name = name;
        APITrace.report("Setup");
        APITrace.reset();
        changePrefix();
        startTimestamp = System.currentTimeMillis();
        testCount++;
        out("");
        out(">>> BEGIN ---------------------------------------------------------------------------------------------->>>");
    }

    private void changePrefix() {
        StringBuilder str = new StringBuilder();
        String s;

        if( suite.endsWith("Test") ) {
            s = suite.substring(0, suite.length()-4);
        }
        else if( suite.endsWith("Tests") ) {
            s = suite.substring(0, suite.length()-5);
        }
        else {
            s = suite;
        }
        str.append(provider.getProviderName()).append("/").append(provider.getCloudName()).append(".").append(s);
        if( name != null ) {
            str.append(".").append(name);
        }
        if( str.length() > 44 ) {
            prefix = str.substring(str.length()-44) + "> ";
        }
        else {
            str.append("> ");
            while( str.length() < 46 ) {
                str.append(" ");
            }
            prefix = str.toString();
        }
    }

    public void close() {
        getProvider().close();
    }

    public void end() {
        String[] calls = APITrace.listApis(provider.getProviderName(), provider.getCloudName());

        if( calls.length > 0 ) {
            out("---------- API Log ----------");
            int total = 0;

            for( String call : calls ) {
                int count = (int)APITrace.getAPICountAcrossAccounts(provider.getProviderName(), provider.getCloudName(), call);

                if( apiAudit.containsKey(call) ) {
                    apiAudit.put(call, count + apiAudit.get(call));
                }
                else {
                    apiAudit.put(call, count);
                }
                out("---> " + call, count);
                total += count;
            }
            out("---> Total Calls", total);
        }
        out("Duration", (((float) (System.currentTimeMillis() - startTimestamp)) / 1000f) + " seconds");
        out("<<< END   ----------------------------------------------------------------------------------------------<<<");
        out("");
        APITrace.report(prefix);
        APITrace.reset();
        name = null;
        changePrefix();
    }

    public @Nonnull ProviderContext getContext() {
        ProviderContext ctx = provider.getContext();

        if( ctx == null ) {
            throw new RuntimeException("Provider context went away");
        }
        return ctx;
    }

    public @Nullable String getName() {
        return name;
    }

    public @Nullable String getTestDataCenterId(boolean stateless) {
        return (computeResources == null ? null : computeResources.getTestDataCenterId(stateless));
    }

    public @Nullable String getTestAnyFirewallId(@Nonnull String label, boolean provisionIfNull) {
        NetworkServices services = provider.getNetworkServices();

        if( services != null ) {
            FirewallSupport support = services.getFirewallSupport();

            try {
                if( support != null && support.isSubscribed() ) {
                    if( support.getCapabilities().supportsFirewallCreation(false) ) {
                        return getTestGeneralFirewallId(label, provisionIfNull);
                    }
                    else if( support.getCapabilities().supportsFirewallCreation(true) ) {
                        return getTestVLANFirewallId(DaseinTestManager.REMOVED, true, null);
                    }
                }
            }
            catch( Throwable ignore ) {
                // ignore
            }
        }
        return null;
    }

    public @Nullable Blob getTestBucket(@Nonnull String label, boolean root, boolean provisionIfNull) {
        if( root ) {
            return (storageResources == null ? null : storageResources.getTestRootBucket(label, provisionIfNull, null));
        }
        else {
            return (storageResources == null ? null : storageResources.getTestChildBucket(label, provisionIfNull, null, null));
        }
    }

    public @Nullable String getTestDistributionId(@Nonnull String label, boolean provisionIfNull, @Nullable String origin) {
        return (platformResources == null ? null : platformResources.getTestDistributionId(label, provisionIfNull, origin));
    }

    public @Nullable String getTestGeneralFirewallId(@Nonnull String label, boolean provisionIfNull) {
        return (networkResources == null ? null : networkResources.getTestFirewallId(label, provisionIfNull, null));
    }

    public @Nullable String getTestGroupId(@Nonnull String label, boolean provisionIfNull) {
        return (identityResources == null ? null : identityResources.getTestGroupId(label, provisionIfNull));
    }

    public @Nullable String getTestImageId(@Nonnull String label, boolean provisionIfNull) {
        return (computeResources == null ? null : computeResources.getTestImageId(label, provisionIfNull));
    }

    public @Nullable String getTestKeypairId(@Nonnull String label, boolean provisionIfNull) {
        return (identityResources == null ? null : identityResources.getTestKeypairId(label, provisionIfNull));
    }

    public @Nullable String getTestLoadBalancerId(@Nonnull String label, @Nonnull String lbNamePrefix, boolean provisionIfNull, boolean withHealthCheck) {
        return (networkResources == null ? null : networkResources.getTestLoadBalancerId(label, lbNamePrefix, provisionIfNull, withHealthCheck));
    }

    public @Nullable String getTestLoadBalancerId(@Nonnull String label, @Nonnull String lbNamePrefix, boolean provisionIfNull) {
    	return (networkResources == null ? null : networkResources.getTestLoadBalancerId(label, lbNamePrefix, provisionIfNull, false));
    }

    public @Nullable String getTestSSLCertificateName(@Nonnull String label, boolean provisionIfNull) {
        return (networkResources == null ? null : networkResources.getTestSSLCertificateName(label, provisionIfNull));
    }

    public @Nullable String getTestNetworkFirewallId(@Nonnull String label, boolean provisionIfNull, @Nullable String inVlanId) {
        return (networkResources == null ? null : networkResources.getTestNetworkFirewallId(label, provisionIfNull, inVlanId));
    }

    public @Nullable Blob getTestObject(@Nonnull String label, boolean root, boolean provisionIfNull) {
        if( root ) {
            return (storageResources == null ? null : storageResources.getTestRootObject(label, provisionIfNull, null));
        }
        else {
            return (storageResources == null ? null : storageResources.getTestChildObject(label, provisionIfNull, null, null));
        }
    }

    public @Nullable String getTestQueueId(@Nonnull String label, boolean provisionIfNull) {
        return (platformResources == null ? null : platformResources.getTestQueueId(label, provisionIfNull));
    }

    public @Nullable String getTestRDBMSId(@Nonnull String label, boolean provisionIfNull, @Nullable DatabaseEngine engine) {
        return (platformResources == null ? null : platformResources.getTestRDBMSId(label, provisionIfNull, engine));
    }

    public @Nullable String getTestSnapshotId(@Nonnull String label, boolean provisionIfNull) {
        return (computeResources == null ? null : computeResources.getTestSnapshotId(label, provisionIfNull));
    }

    public @Nullable String getTestStaticIpId(@Nonnull String label, boolean provisionIfNull, @Nullable IPVersion version, boolean forVLAN, @Nullable String vlanId) {
        return networkResources == null ? null : networkResources.getTestStaticIpId(label, provisionIfNull, version, forVLAN, vlanId);
    }

    public @Nullable String getTestSubnetId(@Nonnull String label, boolean provisionIfNull, @Nullable String vlanId, @Nullable String preferredDataCenterId) {
        return (networkResources == null ? null : networkResources.getTestSubnetId(label, provisionIfNull, vlanId, preferredDataCenterId));
    }

    public @Nullable String getTestInternetGatewayId(@Nonnull String label, boolean provisionIfNull, @Nullable String vlanId, @Nullable String preferredDataCenterId) {
      return (networkResources == null ? null : networkResources.getTestInternetGatewayId(label, provisionIfNull, vlanId, preferredDataCenterId));
    }

    public @Nullable String getTestTopicId(@Nonnull String label, boolean provisionIfNull) {
        return (platformResources == null ? null : platformResources.getTestTopicId(label, provisionIfNull));
    }

    public @Nullable String getTestTopologyId(@Nonnull String label, boolean provisionIfNull) {
        return (ciResources == null ? null : ciResources.getTestTopologyId(label, provisionIfNull));
    }

    public @Nullable String getTestCIId(@Nonnull String label, boolean provisionIfNull) {
        return (ciResources == null ? null : ciResources.getTestCIId(label, provisionIfNull));
    }

    public @Nullable String getTestHttpLoadBalancerId(@Nonnull String label, boolean provisionIfNull) {
        return (ciResources == null ? null : ciResources.getTestConvergedHttpLoadBalancerId(label, provisionIfNull));
    }

    public @Nullable String getTestUserId(@Nonnull String label, boolean provisionIfNull, @Nullable String preferredGroupId) {
        return (identityResources == null ? null : identityResources.getTestUserId(label, provisionIfNull, preferredGroupId));
    }

    public @Nullable String getTestVLANFirewallId(@Nonnull String label, boolean provisionIfNull, @Nullable String inVlanId) {
        if( inVlanId == null ) {
            if( label.equals(DaseinTestManager.STATELESS) ) {
                inVlanId = getTestVLANId(DaseinTestManager.STATELESS, false, null);
            }
            else {
                inVlanId = getTestVLANId(DaseinTestManager.STATEFUL, true, null);
            }
            if( inVlanId == null ) {
                return null;
            }
        }
        String id = (networkResources == null ? null : networkResources.getTestFirewallId(label, provisionIfNull, inVlanId));

        if( id != null ) {
            try {
                @SuppressWarnings("ConstantConditions") Firewall firewall = provider.getNetworkServices().getFirewallSupport().getFirewall(id);

                if( firewall == null ) {
                    return null;
                }
                if( !inVlanId.equals(firewall.getProviderVlanId()) ) {
                    return getTestVLANFirewallId(label + "a", provisionIfNull, inVlanId);
                }
            }
            catch( Throwable ignore ) {
                // ignore
            }
        }
        return id;
    }

    public @Nullable String getTestVLANId(@Nonnull String label, boolean provisionIfNull, @Nullable String preferredDataCenterId) {
        return (networkResources == null ? null : networkResources.getTestVLANId(label, provisionIfNull, preferredDataCenterId));
    }

    public @Nullable String getTestRoutingTableId(@Nonnull String label, boolean provisionIfNull, @Nullable String vlanId, @Nullable String preferredDataCenterId) {
      return (networkResources == null ? null : networkResources.getTestRoutingTableId(label, provisionIfNull, vlanId, preferredDataCenterId));
    }

    public @Nullable String getTestVMId(@Nonnull String label, @Nullable VmState desiredState, boolean provisionIfNull, @Nullable String preferredDataCenterId) {
    	return getTestVMId(label, "dsnvm", desiredState, provisionIfNull, preferredDataCenterId);
    }

    public @Nullable String getTestVMId(@Nonnull String label, @Nonnull String vmName, @Nullable VmState desiredState, boolean provisionIfNull, @Nullable String preferredDataCenterId) {
        if( computeResources == null ) {
            return null;
        }
        return computeResources.getTestVmId(label, vmName, desiredState, provisionIfNull, preferredDataCenterId);
    }

    public @Nullable String getTestVLANVMId(@Nonnull String label, @Nullable VmState desiredState, @Nullable String vlanId, boolean provisionIfNull, @Nullable String preferredDataCenterId) {
      if( computeResources == null ) {
        return null;
      }
      return computeResources.getTestVLANVmId(label, desiredState, vlanId, provisionIfNull, preferredDataCenterId);
    }

    public @Nullable String getTestVMProductId() {
        return (computeResources == null ? null : computeResources.getTestVMProductId());
    }

    public @Nullable String getTestVolumeId(@Nonnull String label, boolean provisionIfNull, @Nullable VolumeFormat preferredFormat, @Nullable String preferredDataCenterId) {
        if( computeResources == null ) {
            return null;
        }
        return computeResources.getTestVolumeId(label, provisionIfNull, preferredFormat, preferredDataCenterId);
    }

    public @Nullable String getTestVolumeProductId() {
        return (computeResources == null ? null : computeResources.getTestVolumeProductId());
    }

    public @Nullable String getTestZoneId(@Nonnull String label, boolean provisionIfNull) {
        return (networkResources == null ? null : networkResources.getTestZoneId(label, provisionIfNull));
    }

    public @Nullable String getTestVpnId(@Nonnull String label, boolean provisionIfNull, @Nullable String preferredDataCenterId) {
        return (networkResources == null ? null : networkResources.getTestVpnId(label, provisionIfNull, preferredDataCenterId));
    }

    public @Nonnull CloudProvider getProvider() {
        return provider;
    }

    /**
     * Checks to see if the test currently being executed is supposed to be skipped.
     * A test is assumed to be run unless there are a list of inclusions and the test is not
     * in the list or there is a list of exclusions and the test is in the list. If there are
     * inclusions and exclusions, any conflict is resolved in favor of executing the test.
     * Exclusions and inclusions are set as the {@link System} properties dasein.inclusions and
     * dasein.exclusions. You may specify an entire suite (e.g. "StatelessVMTests") or a specific
     * test (e.g. "StatelessVMTests.listVirtualMachines"). You may also specify multiple tests:
     *

     *     -Ddasein.inclusions=StatelessVMTests.listVirtualMachines,StatelessDCTests
     *

     * This will execute only the listVirtualMachines test from StatelessVMTests and all StatelessDCTests. All other
     * tests will be skipped.
     * @return true if the current test is to be skipped
     */
    public boolean isTestSkipped() {
        if( inclusions == null && exclusions == null ) {
            return false;
        }
        String s = suite.toLowerCase();
        String t = (name == null ? null : name.toLowerCase());

        Boolean suiteIncluded = null;
        Boolean testIncluded = null;

        if( inclusions != null ) {
            if( inclusions.contains(s) ) {
                suiteIncluded = true;
            }
            if( t != null && inclusions.contains(s + "." + t) ) {
                testIncluded = true;
            }
            if( suiteIncluded == null && testIncluded == null ) {
                skip();
                return true;
            }
        }
        if( exclusions != null ) {
            if( t != null && exclusions.contains(s + "." + t) ) {
                if( testIncluded == null || !testIncluded ) {
                    skip();
                    return true;
                }
                return false; // conflict goes to not skipping
            }
            if( exclusions.contains(s) ) {
                if( testIncluded != null && testIncluded ) {
                    return false; // specific test inclusion overrides suite exclusion
                }
                // suite included must be true to get this far
                if( suiteIncluded != null && suiteIncluded ) {
                    return false; // conflict goes to skipping
                }
            }
        }
        return false;
    }

    public void ok(@Nonnull String message) {
        logger.info(prefix + message + " (OK)");
    }

    public void out(@Nonnull String message) {
        logger.info(prefix + message);
    }

    public void out(@Nonnull String key, boolean value) {
        out(key, String.valueOf(value));
    }

    public void out(@Nonnull String key, int value) {
        out(key, String.valueOf(value));
    }

    public void out(@Nonnull String key, long value) {
        out(key, String.valueOf(value));
    }

    public void out(@Nonnull String key, double value) {
        out(key, String.valueOf(value));
    }

    public void out(@Nonnull String key, float value) {
        out(key, String.valueOf(value));
    }

    public void out(@Nonnull String key, Object value) {
        out(key, value == null ? "null" : value.toString());
    }

    public void out(@Nonnull String key, @Nullable String value) {
        out(logger, prefix, key, value);
    }

    public void skip() {
        skipCount++;
        out("SKIPPING");
    }

    public void warn(@Nonnull String message) {
        logger.warn(prefix + "WARNING: " + message);
    }

    public String getUserName() {
    	return userName;
    }

    /**
     * Get environment property
     * @param key the key to regrieve the property for
     * @return environment property, null if missing or empty
     */
    public static @Nullable String getSystemProperty(@Nonnull String key) {
        String value = System.getProperty(key);
        if( value != null && value.trim().isEmpty() ) {
            return null;
        }
        return value;
    }

    public static boolean supportsHttps(@Nonnull LoadBalancerSupport lbs) throws CloudException, InternalException {
        boolean sslSupported = false;
        for( LbProtocol proto : lbs.getCapabilities().listSupportedProtocols() ) {
            if( LbProtocol.HTTPS.equals(proto) ) {
                sslSupported = true;
            }
        }
        return sslSupported;
    }

}


text:
var irc = require('../api/index.js');

var moment = require('moment');

//var fs = require('fs');
//var obj = JSON.parse(fs.readFileSync(__dirname + '/bot/bot.json', 'utf8'));
var obj = require(__dirname + '/bot/bot.json', 'utf8');

var bot = new irc.irc(obj.settings.ip, obj.settings.port, obj.settings.nick);

var lastSeen = {};

if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str){
    return this.slice(0, str.length) == str;
  };
}

bot.on('raw', function(data){
	console.log('Data recived: ' + data);
});

bot.on('connect', function(){
	obj.channels.forEach(function(channel){
		bot.join(channel);
	});
});

var parseData = function(data,dataParser){
	var str = data;
	dataParser.forEach(function(bit){
		console.log(bit);
		str = str.replace('$$' +bit.id+ '$$', bit.val);
		console.log(str);
	});
	return str;
};

bot.on('chat', function(message,user,channel){
	console.log('chat: ' + message);
	lastSeen[user.nick] = new Date();
	console.log(lastSeen[user.nick]);
	if(message.startsWith(obj.settings.prefix)){
		var msg = message.slice(1).split(' ');
		var cmd = obj.commands[msg[0]];
		var dataParser = [
			{id: "NICK", val: user.nick},
			{id: "CHANNEL", val: channel}
		];
		if(cmd !== undefined){
			cmd.actions.forEach(function(action){
				console.log(cmd);
				cmd.args.params.forEach(function(bit,i){
					dataParser.push({id:bit, val:msg[i + 1]});
				});
				cmd.args.calc.forEach(function(bit,i){
					var val = '';

					switch (bit.type) {
						case 'lastseen':
							console.log(lastSeen[parseData(bit.params.user,dataParser)]);
							val = moment(lastSeen[parseData(bit.params.user,dataParser)]).fromNow();
							break;

						case 'concat':

							break;

						default:
							// code
					}

					dataParser.push({id:bit.id, val:val});
				});

				switch (action.perms) {
					case 'chanop':
						// code
						break;

					default:
						// code
				}

				switch (action.type) {
					case 'raw':
						bot.send(parseData(action.params.data,dataParser));
						break;
					case 'chat':
						bot.say(parseData(action.params.channel,dataParser), parseData(action.params.message,dataParser));
						break;
					case 'multiline-chat':
						action.params.message.forEach(function(bit){
							bot.say(parseData(action.params.channel,dataParser), parseData(bit,dataParser));
						});
						break;
					default:
						bot.say(channel, "Error in JSON file: Type " + cmd.type + " not found");
				}
			});
		}else{
			bot.say(channel, "Command does not exist");
		}
	}
});

bot.on('pm', function(message,user,channel){
	console.log('pm: ' + message);
	if(message == 'data sent'){
		bot.say(user.nick,'data recived from ' + user.nick);
	}
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sensio\Bundle\FrameworkExtraBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * HttpCacheListener handles HTTP cache headers.
 *
 * It can be configured via the Cache annotation.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class HttpCacheListener implements EventSubscriberInterface
{
    private $lastModifiedDates;
    private $etags;
    private $expressionLanguage;

    public function __construct()
    {
        $this->lastModifiedDates = new \SplObjectStorage();
        $this->etags = new \SplObjectStorage();
    }

    /**
     * Handles HTTP validation headers.
     */
    public function onKernelController(KernelEvent $event)
    {
        $request = $event->getRequest();
        if (!$configuration = $request->attributes->get('_cache')) {
            return;
        }

        $response = new Response();

        $lastModifiedDate = '';
        if ($configuration->getLastModified()) {
            $lastModifiedDate = $this->getExpressionLanguage()->evaluate($configuration->getLastModified(), $request->attributes->all());
            $response->setLastModified($lastModifiedDate);
        }

        $etag = '';
        if ($configuration->getEtag()) {
            $etag = hash('sha256', $this->getExpressionLanguage()->evaluate($configuration->getEtag(), $request->attributes->all()));
            $response->setEtag($etag);
        }

        if ($response->isNotModified($request)) {
            $event->setController(function () use ($response) {
                return $response;
            });
            $event->stopPropagation();
        } else {
            if ($etag) {
                $this->etags[$request] = $etag;
            }
            if ($lastModifiedDate) {
                $this->lastModifiedDates[$request] = $lastModifiedDate;
            }
        }
    }

    /**
     * Modifies the response to apply HTTP cache headers when needed.
     */
    public function onKernelResponse(KernelEvent $event)
    {
        $request = $event->getRequest();

        if (!$configuration = $request->attributes->get('_cache')) {
            return;
        }

        $response = $event->getResponse();

        // http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1
        if (!\in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 304, 404, 410])) {
            return;
        }

        if (!$response->headers->hasCacheControlDirective('s-maxage') && null !== $age = $configuration->getSMaxAge()) {
            $age = $this->convertToSecondsIfNeeded($age);

            $response->setSharedMaxAge($age);
        }

        if ($configuration->mustRevalidate()) {
            $response->headers->addCacheControlDirective('must-revalidate');
        }

        if (!$response->headers->hasCacheControlDirective('max-age') && null !== $age = $configuration->getMaxAge()) {
            $age = $this->convertToSecondsIfNeeded($age);

            $response->setMaxAge($age);
        }

        if (!$response->headers->hasCacheControlDirective('max-stale') && null !== $stale = $configuration->getMaxStale()) {
            $stale = $this->convertToSecondsIfNeeded($stale);

            $response->headers->addCacheControlDirective('max-stale', $stale);
        }

        if (!$response->headers->hasCacheControlDirective('stale-while-revalidate') && null !== $staleWhileRevalidate = $configuration->getStaleWhileRevalidate()) {
            $staleWhileRevalidate = $this->convertToSecondsIfNeeded($staleWhileRevalidate);

            $response->headers->addCacheControlDirective('stale-while-revalidate', $staleWhileRevalidate);
        }

        if (!$response->headers->hasCacheControlDirective('stale-if-error') && null !== $staleIfError = $configuration->getStaleIfError()) {
            $staleIfError = $this->convertToSecondsIfNeeded($staleIfError);

            $response->headers->addCacheControlDirective('stale-if-error', $staleIfError);
        }

        if (!$response->headers->has('Expires') && null !== $configuration->getExpires()) {
            $date = \DateTime::createFromFormat('U', strtotime($configuration->getExpires()), new \DateTimeZone('UTC'));
            $response->setExpires($date);
        }

        if (!$response->headers->has('Vary') && null !== $configuration->getVary()) {
            $response->setVary($configuration->getVary());
        }

        if ($configuration->isPublic()) {
            $response->setPublic();
        }

        if ($configuration->isPrivate()) {
            $response->setPrivate();
        }

        if (!$response->headers->has('Last-Modified') && isset($this->lastModifiedDates[$request])) {
            $response->setLastModified($this->lastModifiedDates[$request]);

            unset($this->lastModifiedDates[$request]);
        }

        if (!$response->headers->has('Etag') && isset($this->etags[$request])) {
            $response->setEtag($this->etags[$request]);

            unset($this->etags[$request]);
        }
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::CONTROLLER => 'onKernelController',
            KernelEvents::RESPONSE => 'onKernelResponse',
        ];
    }

    private function getExpressionLanguage()
    {
        if (null === $this->expressionLanguage) {
            if (!class_exists(ExpressionLanguage::class)) {
                throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
            }
            $this->expressionLanguage = new ExpressionLanguage();
        }

        return $this->expressionLanguage;
    }

    /**
     * @param int|string $time Time that can be either expressed in seconds or with relative time format (1 day, 2 weeks, ...)
     *
     * @return int
     */
    private function convertToSecondsIfNeeded($time)
    {
        if (!is_numeric($time)) {
            $now = microtime(true);

            $time = ceil(strtotime($time, $now) - $now);
        }

        return $time;
    }
}


text:
package org.deviceconnect.message.intent.params;

import org.apache.http.params.HttpParams;

import android.content.ComponentName;
import android.content.Context;

/**
 * Intentクライアントパラメータ管理.
 * @author NTT DOCOMO, INC.
 */
public class IntentConnectionParams {

    /**
     * コンストラクタ.
     */
    protected IntentConnectionParams() {
    }

    /**
     * コンテキストを取得する.
     * @param params HTTPパラメータ
     * @return コンテキスト
     */
    public static Context getContext(final HttpParams params) {
        return (Context) params.getParameter(IntentPNames.CONNECTION_CONTEXT);
    }

    /**
     * コンテキストを設定する.
     * @param params HTTPパラメータ
     * @param context コンテキスト
     */
    public static void setContext(
            final HttpParams params, final Context context) {
        params.setParameter(IntentPNames.CONNECTION_CONTEXT, context);
    }

    /**
     * コンテキストを取得する.
     * @param params HTTPパラメータ
     * @return コンテキスト
     */
    public static ComponentName getComponent(final HttpParams params) {
        return (ComponentName) params.getParameter(IntentPNames.CONNECTION_COMPONENT_NAME);
    }

    /**
     * コンポーネント名を設定する.
     * @param params HTTPパラメータ
     * @param componentName コンポーネント名
     */
    public static void setComponent(
            final HttpParams params, final ComponentName componentName) {
        params.setParameter(IntentPNames.CONNECTION_COMPONENT_NAME, componentName);
    }

    /**
     * コンポーネント名を設定する.
     * @param params HTTPパラメータ
     * @param componentName コンポーネント名
     */
    public static void setComponent(
            final HttpParams params, final String componentName) {
        setComponent(params, ComponentName.unflattenFromString(componentName));
    }

    /**
     * コンポーネント名を設定する.
     * @param params HTTPパラメータ
     * @param pkg パッケージコンテキスト
     * @param cls レシーバークラス
     */
    public static void setComponent(
            final HttpParams params, final Context pkg, final Class<?> cls) {
        setComponent(params, new ComponentName(pkg, cls));
    }

}


text:
from elite.loader.bpc import prices
from elite.loader.bpc import server


text:
layout: example
categories: example/v1.0.0
version: v1.0.0
title: Rotating and controllable marker
description: Simulate a flight path from vehicle data. Use your left and right arrow keys to change direction.
tags:
  - markers
  - animation
---


text:
/*
 * =====================================================================================
 *
 *       Filename:  TGM_Tangram.cpp
 *
 *    Description:
 *
 *        Created:  08/22/2012 08:38:37 PM
 *       Revision:  none
 *       Compiler:  g++
 *
 *         Author:  Jiantao Wu (),
 *   Inistitution:  Boston College
 *
 * =====================================================================================
 */

#include <cstdio>
#include <cstdlib>

#include "TGM_Array.h"
#include "TGM_Parameters.h"
#include "TGM_FragLenTable.h"
#include "TGM_LibTable.h"
#include "TGM_BamPair.h"
#include "TGM_Detector.h"
#include "TGM_Reference.h"
#include "TGM_Aligner.h"
#include "TGM_Printer.h"
#include "TGM_Genotype.h"

#include "api/BamMultiReader.h"

using namespace std;
using namespace Tangram;
using namespace BamTools;

int main(int argc, char *argv[])
{
    // load the command line arguments
    DetectPars detectPars;
    AlignerPars alignerPars;
    GenotypePars genotypePars;
    Parameters parameters(detectPars, alignerPars, genotypePars);
    parameters.Set((const char**) argv, argc);

    // load the input bam file names
    vector<string> filenames;
    parameters.SetBamFilenames(filenames);

    // open the bam files with bam multi reader
    BamMultiReader bamMultiReader;
    bamMultiReader.Open(filenames);

    // make sure we have the index files at with the input bam files
    if (!bamMultiReader.LocateIndexes())
    {
        // fail to locate the index files
        // we need to create them if necessary
        if (!bamMultiReader.CreateIndexes())
            TGM_ErrQuit("ERROR: Cannot locate or create the index files for the input bam files.\n");
    }

    // read the library information table
    LibTable libTable;
    libTable.Read(detectPars.fpLibInput, detectPars.maxFragDiff);

    // read the fragment length distribution table
    FragLenTable fragLenTable;
    fragLenTable.Read(detectPars.fpHistInput);

    // where should we start to call the SV events
    parameters.ParseRangeStr(bamMultiReader);
    parameters.SetRange(bamMultiReader, libTable.GetFragLenMax());

    BamPairTable bamPairTable(detectPars, libTable, fragLenTable);

    // iterate through the bam files and fill the bam pair table
    BamAlignment alignment;
    while(bamMultiReader.GetNextAlignment(alignment))
    {
        bamPairTable.Update(alignment);
    }

    // clean the fragnment length table
    fragLenTable.Destory();

    // call the SV events with read-pair signal
    Detector detector(detectPars, libTable, bamPairTable);
    detector.Init();
    detector.CallEvents();

    const Reference* pRef = NULL;
    const Aligner* pAligner = NULL;

    Reference reference;
    Aligner aligner(detector, bamPairTable,  alignerPars, reference, libTable);

    // call the SV events with split-read signal
    if (alignerPars.fpRefInput != NULL)
    {
        // always load the whole chromosome reference
        reference.Read(alignerPars.fpRefInput, detectPars.refID, -1, -1);
        reference.CreateFamilyToZA(*(libTable.GetSpecialRefNames()));

        aligner.Map();

        pRef = &reference;
        pAligner = &aligner;
    }

    // Initialize the genotype module
    Genotype genotype(bamMultiReader, genotypePars, libTable, bamPairTable);
    genotype.Init();

    // print out the events (vcf format)
    Printer printer(&detector, detectPars, pAligner, pRef, libTable, bamPairTable, genotypePars, genotype);
    printer.Init();
    printer.Print();

    // clean up and quit
    bamMultiReader.Close();
    return EXIT_SUCCESS;
}


text:
/******************************************************************************
 * 版权所有 刘大磊 2013-07-01												  *
 *	作者:刘大磊								                                              *
 * 电话:13336390671                                                                *
 * email:ldlqdsd@126.com						                               *
 *****************************************************************************/

package com.delmar.sys.dao.mybatis;

import org.springframework.stereotype.Repository;

import com.delmar.sys.dao.UserThirdPartyDao;
import com.delmar.sys.model.UserThirdParty;
import com.delmar.core.dao.mybatis.CoreDaoMyBatis;

/**
 * @author 刘大磊 2015-05-29 15:11:15
 */
@Repository("userThirdPartyDao")
public class UserThirdPartyDaoMybatis extends CoreDaoMyBatis<UserThirdParty> implements UserThirdPartyDao {

	/* (non-Javadoc)
	 * @see com.delmar.core.dao.mybatis.CoreDaoMyBatis#getSqlName()
	 */
	@Override
	protected String getSqlName() {

		return "com.delmar.sys.mybatis.sql.UserThirdPartyMapper";
	}

}


text:
package model

type Media struct {
	Id          int    `xorm:"not null pk autoincr INT(10)"`
	Name        string `xorm:"not null VARCHAR(255)"`
	Belongs     string `xorm:"VARCHAR(255)"`
	ChannelType string `xorm:"not null default '0' VARCHAR(255)"`
	Contacts    string `xorm:"VARCHAR(255)"`
	Phone       string `xorm:"default '' VARCHAR(20)"`
	Status      int    `xorm:"default 0 TINYINT(1)"`
	CreateTime  int    `xorm:"INT(11)"`
	UpdateTime  int    `xorm:"INT(11)"`
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:paddingLeft="20dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textSize="30sp"
        android:layout_gravity="center"
        android:textAlignment="center"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:id="@+id/tv_source_title" />
</LinearLayout>


text:
import {Character} from '../std/character'

export class Condition {
    parent: Character
    constructor(parent: Character) {
        this.parent = parent
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.cosmos.encryption;

import com.azure.cosmos.implementation.encryption.ImplementationBridgeHelpers;

import java.net.URL;

import static com.azure.cosmos.implementation.encryption.ImplementationBridgeHelpers.AzureKeyVaultKeyWrapMetadataHelper;

/**
 * Metadata used by Azure Key Vault to wrap (encrypt) and unwrap (decrypt) keys.
 */
public final class AzureKeyVaultKeyWrapMetadata extends EncryptionKeyWrapMetadata {
    private static final String TYPE_CONSTANT = "akv";

    // TODO: moderakh use URL vs URI?
    /**
     * Creates a new instance of metadata that the Azure Key Vault can use to wrap and unwrap keys.
     *
     * @param masterKeyUri Key Vault URL of the master key to be used for wrapping and unwrapping keys.
     */
    public AzureKeyVaultKeyWrapMetadata(URL masterKeyUri) {
        // masterKeyUri.AbsoluteUri
        super(AzureKeyVaultKeyWrapMetadata.TYPE_CONSTANT, masterKeyUri.toString());
    }

    ///////////////////////////////////////////////////////////////////////////////////////////
    // the following helper/accessor only helps to access this class outside of this package.//
    ///////////////////////////////////////////////////////////////////////////////////////////

    static {
        AzureKeyVaultKeyWrapMetadataHelper.setAzureKeyVaultKeyWrapMetadataAccessor(
            new ImplementationBridgeHelpers.AzureKeyVaultKeyWrapMetadataHelper.AzureKeyVaultKeyWrapMetadataAccessor() {
                @Override
                public String getTypeConstant() {
                    return TYPE_CONSTANT;
                }
            }
        );
    }
}


text:
@interface PodsDummy_Test1 : NSObject
@end
@implementation PodsDummy_Test1
@end


text:
/**
 * @author Alexey A. Ivanov
 */
package javax.swing.text;

import java.awt.Color;
import java.awt.Font;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.Map;
import javax.swing.BasicSwingTestCase;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.StyleContext.SmallAttributeSet;
import junit.framework.TestCase;

public class StyleContextTest extends TestCase implements ChangeListener {
    /**
     * Shared style context object
     */
    protected static StyleContext sc;

    /**
     * The array of attribute key-value pair that is shared in the tests.
     */
    protected static final Object[] attr = { StyleConstants.Bold, Boolean.TRUE,
            StyleConstants.Italic, Boolean.TRUE, StyleConstants.Underline, Boolean.TRUE,
            StyleConstants.StrikeThrough, Boolean.TRUE, StyleConstants.Alignment,
            new Integer(1), StyleConstants.Background, Color.WHITE,
            StyleConstants.FirstLineIndent, new Float(0.75), StyleConstants.FontFamily,
            new String("monospaced"), StyleConstants.FontSize, new Integer(10),
            StyleConstants.Foreground, Color.BLACK };

    /**
     * Tracks that a change listener was been called.
     */
    private boolean bStateChanged;

    /**
     * Adds some attributes from attr array.
     *
     * @param as old attribute set to add to, may be null
     * @param start index of the first attribute in the array
     * @param count the number of attributes to add
     * @return new attribute set with attributes added
     */
    protected static AttributeSet addAttribute(AttributeSet as, int start, int count) {
        if (as == null) {
            as = sc.getEmptySet();
        }
        start <<= 1;
        count <<= 1;
        count += start;
        for (int i = start; i < count; i += 2) {
            as = sc.addAttribute(as, attr[i], attr[i + 1]);
        }
        return as;
    }

    /**
     * Adds some attributes from attr array, starting at index 0.
     *
     * @param as old attribute set to add to, may be null
     * @param count the number of attributes to add
     * @return new attribute set with attributes added
     * @see StyleContextTest#addAttribute(AttributeSet, int, int)
     */
    protected static AttributeSet addAttribute(final AttributeSet as, final int count) {
        return addAttribute(as, 0, count);
    }

    /**
     * Adds count attributes to a newly created attribute set
     * from attr array, starting at index 0.
     *
     * @param count the number of attributes to add
     * @return new attribute set with attributes added
     * @see StyleContextTest#addAttribute(AttributeSet, int, int)
     */
    protected static AttributeSet addAttribute(final int count) {
        return addAttribute(null, 0, count);
    }

    /**
     * Wrapper to access StyleContext.cache field.
     * @return style context's cache
     */
    protected static Map<?, ?> getSCCache() {
        try {
            Field f = sc.getClass().getDeclaredField("cache");
            f.setAccessible(true);
            return (Map<?, ?>) (f.get(sc));
        } catch (IllegalAccessException e) {
            fail(e.getMessage());
        } catch (NoSuchFieldException e) {
            fail(e.getMessage());
        }
        return null;
    }

    /**
     * Wrapper to access StyleContext.fontCache field.
     * @return style context's cache
     */
    protected static Map<?, ?> getSCFontCache() {
        try {
            Field f = sc.getClass().getDeclaredField("fontCache");
            f.setAccessible(true);
            return (Map<?, ?>) (f.get(sc));
        } catch (IllegalAccessException e) {
            fail(e.getMessage());
        } catch (NoSuchFieldException e) {
            fail(e.getMessage());
        }
        return null;
    }

    /*
     * @see TestCase#setUp()
     */
    @Override
    protected void setUp() throws Exception {
        sc = new StyleContext();
    }

    /**
     * Makes sure that after initialization, any style context will
     * contain exactly one style (default).
     */
    public void testStyleContext() {
        int count = 0;
        Enumeration<?> names = sc.getStyleNames();
        Object name = null;
        while (names.hasMoreElements()) {
            name = names.nextElement();
            count++;
        }
        assertEquals(1, count);
        assertEquals("default", (String) name);
    }

    public void testCollectGarbageInCache() {
        if (!BasicSwingTestCase.isHarmony()) {
            // This is internal test only
            return;
        }
        Map<?, ?> cache = getSCCache();
        assertEquals(2, cache.size());
        // Create an attribute set containing 10 items. This will
        // create sets with items from 1 to 10
        addAttribute(10);
        // The sets with number of items from 1 up to 9 will be cached
        // (Plus attribute set to support styles: the named style itself
        //  with "name" attribute and the reference to this style from
        //  the internal list of styles)
        assertEquals(9 + 2, cache.size());
        // Run the garbage collector several times
        for (int i = 0; i < 20; i++) {
            System.gc();
        }
        // Create an attribute set cotaining one and only item. This will
        // lead to a call to collectGarbageInCache method
        addAttribute(1);
        // The cache has been cleared but the newly created set is cached
        assertEquals(1 + 2, cache.size());
    }

    public void testCollectGarbageInCacheFont() {
        if (!BasicSwingTestCase.isHarmony()) {
            // This is internal test only
            return;
        }
        Map<?, ?> fontCache = getSCFontCache();
        assertEquals(0, fontCache.size());
        sc.getFont("Arial", Font.BOLD, 14);
        sc.getFont("Tahoma", Font.PLAIN, 8);
        assertEquals(2, fontCache.size());
        // Run the garbage collector several times
        for (int i = 0; i < 5; i++) {
            System.gc();
        }
        // Create an attribute set cotaining one and only item. This will
        // lead to a call to collectGarbageInCache method
        addAttribute(1);
        // The cache has been cleared but the newly created set is cached
        assertEquals(0, fontCache.size());
    }

    public void testAddStyle() {
        Style aStyle = sc.addStyle("aStyle", null);
        Style anotherStyle = sc.addStyle("anotherStyle", aStyle);
        int count = 0;
        boolean[] was = { false, false, false };
        String styleNames = new String();
        Enumeration<?> names = sc.getStyleNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            styleNames += name + " ";
            if (name == "aStyle") {
                assertSame(aStyle, sc.getStyle(name));
                // Should contain only "name" attribute
                assertEquals(1, aStyle.getAttributeCount());
                assertNull(aStyle.getResolveParent());
                was[0] = true;
            } else if (name == "anotherStyle") {
                assertSame(anotherStyle, sc.getStyle(name));
                // Should contain "name" and "parent" attributes
                assertEquals(2, anotherStyle.getAttributeCount());
                assertNotNull(anotherStyle.getResolveParent());
                assertSame(aStyle, anotherStyle.getResolveParent());
                was[1] = true;
            } else if (name == "default") {
                sc.getStyle(name);
                assertEquals(1, aStyle.getAttributeCount());
                assertNull(aStyle.getResolveParent());
                was[2] = true;
            }
            count++;
        }
        assertEquals(3, count);
        for (int i = 0; i < was.length; i++) {
            assertTrue("The style named '"
                    + (i == 0 ? "aStyle" : (i == 1 ? "anotherStyle" : "default"))
                    + "' was not in the list.", was[i]);
        }
    }

    public void testAddStyleMisc() {
        // Add styles with diff parameters
        Object[] styles = { null, null, "one", null, null, sc.new NamedStyle(), "two",
                sc.new NamedStyle() };
        for (int i = 0; i < styles.length; i += 2) {
            Style style = sc.addStyle((String) styles[i], (Style) styles[i + 1]);
            assertEquals("Iteration: " + i, (String) styles[i], style.getName());
            assertSame("Iteration: " + i, styles[i + 1], style.getResolveParent());
        }
    }

    public void testAddStyleTwice() {
        final String styleName = "styleName";
        final Style style = sc.addStyle(styleName, null);
        final Style another = sc.addStyle(styleName, null);
        assertNotSame(style, another);
        assertSame(another, sc.getStyle(styleName));
    }

    public void testCreateSmallAttributeSet() {
        AttributeSet as = sc.createSmallAttributeSet(sc.getEmptySet());
        assertTrue(as instanceof SmallAttributeSet);
        assertEquals(0, as.getAttributeCount());
        assertEquals(sc.getEmptySet(), as);
    }

    public void testGetStyle() {
        Style style = sc.getStyle("default");
        assertEquals("default", style.getName());
        sc.addStyle("aStyle", style);
        style = sc.getStyle("aStyle");
        assertEquals("aStyle", style.getName());
        assertEquals("default", ((Style) style.getResolveParent()).getName());
    }

    public void testCreateLargeAttributeSet() {
        AttributeSet as = sc.createLargeAttributeSet(new SimpleAttributeSet());
        assertTrue(as instanceof SimpleAttributeSet);
    }

    public void testGetEmptySet() {
        assertSame(sc.getEmptySet(), sc.getEmptySet());
        assertEquals(0, sc.getEmptySet().getAttributeCount());
    }

    // test {add,remove}ChangeListener while adding styles
    public void testChangeListenerAddStyle() {
        bStateChanged = false;
        sc.addStyle("one", null);
        assertFalse(bStateChanged);
        sc.addChangeListener(this);
        bStateChanged = false;
        sc.addStyle("two", null);
        assertTrue(bStateChanged);
        sc.removeChangeListener(this);
        bStateChanged = false;
        sc.addStyle("three", null);
        assertFalse(bStateChanged);
    }

    // test if a listener gets called when adding style with null name
    public void testChangeListenerAddStyleNull() {
        sc.addChangeListener(this);
        bStateChanged = false;
        sc.addStyle(null, StyleContext.getDefaultStyleContext().new NamedStyle());
        assertFalse(bStateChanged);
        int count = 0;
        boolean wasNull = false;
        Enumeration<?> names = sc.getStyleNames();
        while (names.hasMoreElements()) {
            Object name = names.nextElement();
            wasNull = wasNull || name == null;
            count++;
        }
        assertEquals(1, count);
        assertFalse(wasNull);
    }

    // test {add,remove}ChangeListener while removing styles
    public void testChangeListenerRemoveStyle() {
        sc.addStyle("one", null);
        sc.addStyle("two", null);
        sc.addStyle("three", null);
        bStateChanged = false;
        sc.removeStyle("one");
        assertFalse(bStateChanged);
        sc.addChangeListener(this);
        bStateChanged = false;
        sc.removeStyle("two");
        assertTrue(bStateChanged);
        sc.removeChangeListener(this);
        bStateChanged = false;
        sc.removeStyle("three");
        assertFalse(bStateChanged);
    }

    public void testGetChangeListeners() {
        ChangeListener[] listeners = sc.getChangeListeners();
        assertEquals(0, listeners.length);
        sc.addChangeListener(this);
        listeners = sc.getChangeListeners();
        assertEquals(1, listeners.length);
        sc.removeChangeListener(this);
        listeners = sc.getChangeListeners();
        assertEquals(0, listeners.length);
    }

    public void testGetStyleNamesDef() {
        boolean wasDefault = false;
        int count = 0;
        Enumeration<?> names = sc.getStyleNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            wasDefault = name == "default";
            count++;
        }
        assertEquals(1, count);
        assertTrue(wasDefault);
    }

    public void testGetStyleNames() {
        sc.addStyle("style", null);
        boolean wasDefault = false;
        boolean wasStyle = false;
        int count = 0;
        Enumeration<?> names = sc.getStyleNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            wasDefault = wasDefault || name == "default";
            wasStyle = wasStyle || name == "style";
            count++;
        }
        assertEquals(2, count);
        assertTrue(wasDefault);
        assertTrue(wasStyle);
    }

    public void testRemoveStyle() {
        sc.addStyle("style", null);
        sc.removeStyle("style");
        boolean wasDefault = false;
        boolean wasStyle = false;
        int count = 0;
        Enumeration<?> names = sc.getStyleNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            wasDefault = wasDefault || "default".equals(name);
            wasStyle = wasStyle || "style".equals(name);
            count++;
        }
        assertEquals(1, count);
        assertTrue(wasDefault);
        assertFalse(wasStyle);
    }

    public void testToString() {
        Style style = sc.getStyle(StyleContext.DEFAULT_STYLE);
        style.addAttribute(StyleConstants.Bold, Boolean.TRUE);
        style.addAttribute(StyleConstants.Italic, Boolean.FALSE);
        style = sc.addStyle("aStyle", null);
        style.addAttribute(StyleConstants.FontFamily, "Arial");
        style.addAttribute(StyleConstants.FontSize, new Integer(14));
        sc.getFont(style);
        String[] asStr = new String[] { "{family=Arial,name=aStyle,size=14,}",
                "{default=AttributeSet,}", "{family=Arial,name=aStyle,}",
                "{aStyle=AttributeSet,default=AttributeSet,}",
                "{italic=false,bold=true,name=default,}", "{name=default,}", "{name=aStyle,}",
                "{name=default,bold=true,}", };
        String scStr = sc.toString();
        assertNotNull(scStr);
        String[] splitStrs = scStr.replaceAll("\r", "").split("\n");
        assertEquals(asStr.length, splitStrs.length);
        boolean[] met = new boolean[splitStrs.length];
        for (int i = 0; i < splitStrs.length; i++) {
            for (int j = 0; j < asStr.length; j++) {
                if (asStr[j].length() == splitStrs[i].length()
                        && assertAttributes(trimEnds(asStr[j]).split(","), trimEnds(
                                splitStrs[i]).split(","))) {
                    met[j] = true;
                }
            }
        }
        for (int i = 0; i < met.length; i++) {
            assertTrue("asStr[" + i + "] is missing", met[i]);
        }
    }

    public static boolean assertAttributes(final String[] expAttrs, final String[] realAttrs) {
        if (expAttrs.length != realAttrs.length) {
            return false;
        }
        boolean[] met = new boolean[expAttrs.length];
        for (int i = 0; i < realAttrs.length; i++) {
            for (int j = 0; j < expAttrs.length; j++) {
                if (expAttrs[j].equals(realAttrs[i])) {
                    met[j] = true;
                }
            }
        }
        boolean result = true;
        for (int i = 0; i < met.length && result; i++) {
            result = met[i];
        }
        return result;
    }

    public static String trimEnds(final String str) {
        assertEquals('{', str.charAt(0));
        final int len = str.length();
        assertEquals('}', str.charAt(len - 1));
        assertEquals(',', str.charAt(len - 2));
        return str.substring(1, len - 2);
    }

    public void testGetCompressionThreshold() {
        assertEquals(9, sc.getCompressionThreshold());
    }

    public void testGetDefaultStyleContext() {
        StyleContext def;
        assertSame(def = StyleContext.getDefaultStyleContext(), StyleContext
                .getDefaultStyleContext());
        int count = 0;
        Enumeration<?> names = def.getStyleNames();
        Object name = null;
        while (names.hasMoreElements()) {
            count++;
            name = names.nextElement();
        }
        assertEquals(1, count);
        assertEquals(StyleContext.DEFAULT_STYLE, (String) name);
    }

    /**
     * A class to test caching technique.
     * Stores values returned by createSmallAttributeSet in array.
     */
    private static class StyleContextX extends StyleContext {
        private static final long serialVersionUID = 1L;

        public int count;

        public AttributeSet[] attrSet;

        public StyleContextX() {
            count = 0;
            attrSet = new AttributeSet[20];
        }

        @Override
        public SmallAttributeSet createSmallAttributeSet(final AttributeSet a) {
            if (attrSet == null) {
                // This condition is true in StyleContext's constructor
                return super.createSmallAttributeSet(a);
            }
            attrSet[count] = super.createSmallAttributeSet(a);
            return (SmallAttributeSet) attrSet[count++];
        }

        @Override
        public MutableAttributeSet createLargeAttributeSet(final AttributeSet a) {
            attrSet[count] = super.createLargeAttributeSet(a);
            return (MutableAttributeSet) attrSet[count++];
        }
    }

    public void testCaching() {
        StyleContextX sc = new StyleContextX();
        int addStyle = sc.count;
        sc.addStyle("aStyle", null);
        int addAttr = sc.count;
        AttributeSet as = sc.addAttribute(sc.getEmptySet(), AttributeSet.NameAttribute,
                "aStyle");
        assertFalse(addStyle == addAttr);
        assertSame(sc.attrSet[addStyle], as);
    }

    /*
     public void testReclaim() {
     }
     */
    public void stateChanged(final ChangeEvent event) {
        bStateChanged = true;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>Yeah!Fw: Class Members - Functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="style.css" rel="stylesheet" type="text/css" />
<link href="extra.css" rel="stylesheet" type="text/css"/>

Yeah!Fw

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Members

All

Functions

Variables

_

a

b

c

d

e

g

h

i

l

m

n

o

p

r

s

t

u

v

w

 All Classes Namespaces Files Functions Variables Pages

- w -

warning()
: Yeah\Fw\Logger\FileLogger
, Yeah\Fw\Logger\LoggerInterface
, Yeah\Fw\Logger\NullLogger

with()
: Yeah\Fw\Mvc\PhpView
, Yeah\Fw\Mvc\TwigView
, Yeah\Fw\Mvc\ViewInterface

withLayout()
: Yeah\Fw\Mvc\PhpView
, Yeah\Fw\Mvc\TwigView
, Yeah\Fw\Mvc\ViewInterface

withParams()
: Yeah\Fw\Mvc\PhpView
, Yeah\Fw\Mvc\TwigView
, Yeah\Fw\Mvc\ViewInterface

write()
: Yeah\Fw\Filesystem\File
, Yeah\Fw\Http\Response
, Yeah\Fw\Session\DatabaseSessionHandler
, Yeah\Fw\Session\NullSessionHandler
, Yeah\Fw\Session\SessionHandlerAbstract

writeHeaders()
: Yeah\Fw\Http\Response

writeJson()
: Yeah\Fw\Http\Response

writePlain()
: Yeah\Fw\Http\Response

writeXml()
: Yeah\Fw\Http\Response


text:
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.UnitTests;
using Xunit;

namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests
{
    public class PropertiesShouldNotBeWriteOnlyTests : DiagnosticAnalyzerTestBase
    {
        protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
        {
            return new PropertiesShouldNotBeWriteOnlyAnalyzer();
        }

        protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
        {
            return new  PropertiesShouldNotBeWriteOnlyAnalyzer();
        }

        // Valid C# Tests that should not be flagged based on CA1044 (good tests)
        [Fact]
        public void CS_CA1044Good_Read_Write()
        {
            var code = @"
using System;
namespace DesignLibrary
{
    public class CS_GoodClassWithReadWriteProperty
    {
        string CS_someName;
        public string CS_Name
        {
            get { return CS_someName; }
            set { CS_someName = CS_value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Good_Read_Write1()
        { var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests1
{
    public class CS_ClassWithReadableProperty1
    {
        protected string CS_field;
        public virtual string CS_ReadableProperty1
        {
            get { return CS_field; }
            set { CS_field = CS_value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Good_public_Read_private_Write()
        {
            var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests2
{
    public class CS_ClassWithReadableProperty2
    {
        protected string CS_field;
        public string CS_AccessibleProperty2
        {
            get { return CS_field; }
            private set { CS_field = CS_value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Good_protected_Read_private_Write()
        {
            var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests3
{
    public class CS_ClassWithReadableProperty3
    {
        protected string CS_field;
        protected string CS_AccessibleProperty3
        {
        get { return CS_field; }
        private set { CS_field = CS_value; }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Good_internal_Read_private_Write()
        {
            var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests4
{
    public class CS_GoodClassWithReadWriteProperty4
    {
        protected string CS_field;
        internal string CS_AccessibleProperty4
        {
            get { return CS_field; }
            private set { CS_field = CS_value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Good_protected_internal_Read_internal_Write()
        {
            var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests5
{
    public class CS_GoodClassWithReadWriteProperty5
    {
        protected string CS_field;
        protected internal string AccessibleProperty5
        {
            get { return field; }
            internal set { field = value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Good_public_Read_internal_Write()
        {
            var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests6
{
    public class CS_GoodClassWithReadWriteProperty6
    {
        protected string CS_field;
        public string CS_AccessibleProperty6
        {
            get { return CS_field; }
            internal set { CS_field = CS_value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Good_public_Read_protected_Write()
        {
            var code = @"
using System;
namespace DesignLibrary
{
    public class CS_GoodClassWithReadWriteProperty7
    {
        protected string CS_field;
        public string CS_AccessibleProperty7
        {
            get { return CS_field; }
            protected set { CS_field = CS_value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Good_public_override_Write()
        {
            var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests8
{
    protected string CS_field;
    public class CS_DerivedClassWithReadableProperty : CS_ClassWithReadableProperty
    {
        public override string CS_ReadableProperty8
        {
            set { CS_field = CS_value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Interface_Write()
        {
            var code = @"
using System;
namespace GoodPropertiesShouldNotBeWriteOnlyTests9
{
    public class Class1 : IInterface9
    {
        string IInterface.InterfaceProperty
        {
            set { }
        }
    }
}";
            VerifyCSharp(code);
        }

        [Fact]
        public void CS_CA1044Base_Write1()
        {
            var code = @"
using System;
namespace GoodPropertiesShouldNotBeWriteOnlyTests10
{
    public class Derived : Base10
    {
        public override string BaseProperty10
        {
            set { base.BaseProperty = value; }
        }
    }
}";
            VerifyCSharp(code);
        }

        // Valid VB Tests that should not be flagged based on CA1044 (good tests)
        [Fact]
        public void VB_CA1044Good_Read_Write()
        {
            var code = @"
Imports System
Namespace DesignLibrary
    Public Class VB_GoodClassWithReadWriteProperty
		Private VB_someName As String
		Public Property VB_Name() As String
			Get
				Return VB_someName
			End Get
			Set(ByVal value As String)
				VB_someName = VB_value
			End Set
		End Property
	End Class
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Good_Read_Write1()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests1
    Public Class VB_GoodClassWithReadWriteProperty1
		Protected VB_field As String
		Public Overridable Property VB_ReadableProperty1() As String
			Get
				Return VB_field
			End Get
			Set(ByVal value As String)
				VB_field = VB_value
			End Set
		End Property
	End Class
";
            VerifyBasic(code);
        }

         [Fact]
         public void VB_CA1044Good_public_Read_private_Write()
         {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests2
    Public class VB_ClassWithReadableProperty2
		Protected VB_field As String
		Public Property VB_AccessibleProperty2() As String
			Get
				Return VB_field
			End Get
			Private Set(ByVal value As String)
				VB_field = VB_value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Good_protected_Read_private_Write()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests3
    Public class VB_ClassWithReadableProperty3
		Protected VB_field As String
		Protected Property VB_AccessibleProperty3() As String
		Get
			Return VB_field
		End Get
		Private Set(ByVal value As String)
			VB_field = VB_value
		End Set
		End Property
    End Class
End NameSpace
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Good_internal_Read_private_Write()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests4
    Public VB_class ClassWithReadableProperty4
		Protected VB_field As String
		Friend Property VB_AccessibleProperty4() As String
			Get
				Return VB_field
			End Get
			Private Set(ByVal value As String)
				VB_field = VB_value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Good_protected_internal_Read_internal_Write()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests5
    Public class VB_ClassWithReadableProperty5
		Protected VB_field As String
		Protected Friend Property AccessibleProperty5() As String
			Get
				Return field
			End Get
			Friend Set(ByVal value As String)
				field = value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Good_public_Read_internal_Write()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests6
    Public class VB_ClassWithReadableProperty6
		Protected VB_field As String
		Public Property VB_AccessibleProperty6() As String
			Get
				Return VB_field
			End Get
			Friend Set(ByVal value As String)
				VB_field = VB_value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Good_public_Read_protected_Write()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests7
    Public class VB_ClassWithReadableProperty7
		Protected VB_field As String
		Public Property VB_AccessibleProperty7() As String
			Get
				Return VB_field
			End Get
			Protected Set(ByVal value As String)
				VB_field = VB_value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Good_ClassWithReadableProperty()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests8
	Protected VB_field As String
	Public Class VB_DerivedClassWithReadableProperty
		Inherits VB_ClassWithReadableProperty
		Public Overrides WriteOnly Property VB_ReadableProperty8() As String
			Set(ByVal value As String)
				VB_field = VB_value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Interface_Write()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests9
	Public Class Class1
		Implements IInterface9
		Private WriteOnly Property IInterface_InterfaceProperty() As String Implements IInterface.InterfaceProperty
			Set(ByVal value As String)
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code);
        }

        [Fact]
        public void VB_CA1044Base_Write()
        {
            var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests10
	Public Class Derived
		Inherits Base10
		Public Overrides WriteOnly Property BaseProperty10() As String
			Set(ByVal value As String)
				MyBase.BaseProperty = value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code);
        }

        // C# Tests that should be flagged with CA1044 Addgetter
        [Fact]
        public void CS_CA1044Bad_Write_with_NoRead()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests
{
    public class CS_BadClassWithWriteOnlyProperty
    {
        protected string CS_someName;
        public string CS_WriteOnlyProperty
        {
            set { CS_someName = value; }
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(8, 23, CA1044MessageAddGetter, "CS_WriteOnlyProperty"));
        }

        [Fact]
        public void CS_CA1044Bad_Write_with_NoRead1()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests1
{
    public class CS_BadClassWithWriteOnlyProperty1
    {
        protected string CS_someName;
        protected public string CS_WriteOnlyProperty1
        {
            set { CS_someName = value; }
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(8, 33, CA1044MessageAddGetter, "CS_WriteOnlyProperty1"));
        }

        [Fact]
        public void CS_CA1044Bad_Write_with_NoRead2()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests2
{
    public class CS_BadClassWithWriteOnlyProperty2
    {
        protected string CS_someName;
        protected internal string CS_WriteOnlyProperty2
        {
            set { CS_someName = value; }
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(8, 35, CA1044MessageAddGetter, "CS_WriteOnlyProperty2"));
        }

        [Fact]
        public void CS_CA1044bad_Base_Write()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests3
{
    public class CS_Base3
    {
        public virtual string CS_BaseProperty3
        {
            set { }
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(7, 31, CA1044MessageAddGetter, "CS_BaseProperty3"));
        }

        [Fact]
        public void CS_CA1044bad_Interface_Write()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests4
{
    public interface CS_IInterface4
    {
        string CS_InterfaceProperty4
        {
            set;
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(7, 16, CA1044MessageAddGetter, "CS_InterfaceProperty4"));
        }

        // C# Tests that should be flagged with CA1044 MakeMoreAccessible
        [Fact]
        public void CS_CA1044Bad_InaccessibleRead()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests5
{
    public class CS_BadClassWithWriteOnlyProperty5
    {
         public string CS_InaccessibleProperty5
         {
            private get { return field; }
            set { field = value; }
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(7, 24, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty5"));
        }

        [Fact]
        public void CS_CA1044Bad_InaccessibleRead1()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests6
{
    public class CS_BadClassWithWriteOnlyProperty6
    {
        string field;
        protected string CS_InaccessibleProperty6
        {
            private get { return field; }
            set { field = value; }
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(8, 26, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty6"));
        }

        [Fact]
        public void CS_CA1044Bad_InaccessibleRead2()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests7
{
    public class CS_BadClassWithWriteOnlyProperty7
    {
        protected internal string CS_InaccessibleProperty7
        {
            internal get { return field; }
            set { field = value; }
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(7, 35, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty7"));
        }

        [Fact]
        public void CS_CA1044Bad_InaccessibleRead3()
        {
            var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests8
{
    public class CS_BadClassWithWriteOnlyProperty8
    {
        public string CS_InaccessibleProperty8
        {
            internal get { return field; }
            set { field = value; }
        }
    }
}";
            VerifyCSharp(code, GetCA1044CSharpResultAt(7, 23, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty8"));
        }

        // VB Tests that should be flagged with CA1044 Addgetter
        [Fact]
        public void VB_CA1044Bad_Write_with_NoRead()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests
	Public Class VB_BadClassWithWriteOnlyProperty
		Protected VB_someName As String
		Public WriteOnly Property VB_WriteOnlyProperty() As String
			Set(ByVal value As String)
				VB_someName = value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(6, 29, CA1044MessageAddGetter, "VB_WriteOnlyProperty"));
        }

        [Fact]
        public void VB_CA1044Bad_Write_with_NoRead1()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests1
	Public Class VB_BadClassWithWriteOnlyProperty1
		Protected VB_someName As String
		Protected Public WriteOnly Property VB_WriteOnlyProperty1() As String
			Set(ByVal value As String)
				VB_someName = value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(6, 39, CA1044MessageAddGetter, "VB_WriteOnlyProperty1"));
        }

        [Fact]
        public void VB_CA1044Bad_Base_NoRead()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests2
	Public Class VB_BadClassWithWriteOnlyProperty2
		Protected VB_someName As String
		Protected Friend WriteOnly Property VB_WriteOnlyProperty2() As String
			Set(ByVal value As String)
				VB_someName = value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(6, 39, CA1044MessageAddGetter, "VB_WriteOnlyProperty2"));
        }

        [Fact]
        public void VB_CA1044Bad_Base_Write()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests3
	Public Class VB_Base3
		Public Overridable WriteOnly Property VB_BaseProperty3() As String
			Set(ByVal value As String)
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(5, 41, CA1044MessageAddGetter, "VB_BaseProperty3"));
        }

        [Fact]
        public void VB_CA1044Bad_Interface_Write()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests4
    Public Interface VB_IInterface4
		WriteOnly Property VB_InterfaceProperty4() As String
	End Interface
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(5, 22, CA1044MessageAddGetter, "VB_InterfaceProperty4"));
        }

        [Fact]
        public void VB_CA1044Bad_InaccessibleRead()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests5
   	Public Class VB_BadClassWithWriteOnlyProperty5
		 Public Property VB_InaccessibleProperty5() As String
			Private Get
				Return field
			End Get
			Set(ByVal value As String)
				field = value
			End Set
		 End Property
	End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(5, 20, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty5"));
        }

        [Fact]
        public void VB_CA1044Bad_InaccessibleRead1()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests6
	Public Class VB_BadClassWithWriteOnlyProperty6
		Private field As String
		Protected Property VB_InaccessibleProperty6() As String
			Private Get
				Return field
			End Get
			Set(ByVal value As String)
				field = value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(6, 22, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty6"));
        }

        [Fact]
        public void VB_CA1044Bad_InaccessibleRead2()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests7
	Public Class VB_BadClassWithWriteOnlyProperty7
		Protected Friend Property VB_InaccessibleProperty7() As String
			Friend Get
				Return field
			End Get
			Set(ByVal value As String)
				field = value
			End Set
		End Property
	End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(5, 29, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty7"));
        }

        [Fact]
        public void VB_CA1044Bad_InaccessibleRead3()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests8
	Public Class VB_BadClassWithWriteOnlyProperty8
    	Public Property VB_InaccessibleProperty8() As String
	    	Friend Get
		    	Return field
		    End Get
		    Set(ByVal value As String)
			    field = value
		    End Set
	    End Property
    End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(5, 22, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty8"));
        }

        [Fact]
        public void VB_CA1044Bad_ClassWithWriteOnlyProperty()
        {
            var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests8
	Public Class VB_BadClassWithWriteOnlyProperty8
    	Public Property VB_InaccessibleProperty8() As String
	    	Friend Get
		    	Return field
		    End Get
		    Set(ByVal value As String)
			    field = value
		    End Set
	    End Property
    End Class
End NameSpace
";
            VerifyBasic(code, GetCA1044BasicResultAt(5, 22, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty8"));
        }

        private static readonly string CA1044MessageAddGetter = MicrosoftApiDesignGuidelinesAnalyzersResources.PropertiesShouldNotBeWriteOnlyMessageAddGetter;
        private static readonly string CA1044MessageMakeMoreAccessible = MicrosoftApiDesignGuidelinesAnalyzersResources.PropertiesShouldNotBeWriteOnlyMessageMakeMoreAccessible;

        private static DiagnosticResult GetCA1044CSharpResultAt(int line, int column, string CA1044Message, string objectName)
        {
            return GetCSharpResultAt(line, column, PropertiesShouldNotBeWriteOnlyAnalyzer.RuleId, string.Format(CA1044Message, objectName));
        }
        private static DiagnosticResult GetCA1044BasicResultAt(int line, int column, string CA1044Message, string objectName)
        {
            return GetBasicResultAt(line, column, PropertiesShouldNotBeWriteOnlyAnalyzer.RuleId, string.Format(CA1044Message, objectName));
        }
    }
}


text:
package gw.lang.reflect.java.asm;

import gw.internal.ext.org.objectweb.asm.Type;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 */
public class AsmAnnotation {
  private AsmType _type;
  private boolean _bVisibleAtRuntime;
  private Map<String, Object> _fieldValues;

  public AsmAnnotation( String desc, boolean bVisibleAtRuntime ) {
    _type = AsmUtil.makeType( desc );
    _bVisibleAtRuntime = bVisibleAtRuntime;
    _fieldValues = new HashMap<String, Object>();
  }

  public AsmType getType() {
    return _type;
  }

  public Map<String, Object> getFieldValues() {
    return _fieldValues;
  }

  public boolean isVisibleAtRuntime() {
    return _bVisibleAtRuntime;
  }

  void setValue( String field, Object value ) {
    value = makeAppropriateValue( value );
    _fieldValues.put( field, value );
  }

  static Object makeAppropriateValue( Object value ) {
    if( value == null ) {
      return null;
    }
    if( value instanceof ArrayList && ((ArrayList)value).isEmpty() ) {
      // Initial "array" value is an empty list, which is filled in the annotation visitor
      return value;
    }
    Class<?> cls = value.getClass();
    if( cls == Boolean.class ||
        cls == Byte.class ||
        cls == Character.class ||
        cls == Short.class ||
        cls == Integer.class ||
        cls == Long.class ||
        cls == Float.class ||
        cls == Double.class ||
        cls == String.class ||
        cls == AsmAnnotation.class ) {
      return value;
    }
    if( cls == Type.class ) {
      AsmType type = AsmUtil.makeType( (Type)value );
      return type.getFqn();
    }
    if( cls.isArray() ) {
      List<Object> values = new ArrayList<Object>();
      for( int i = 0; i < Array.getLength( value ); i++ ) {
        values.add( makeAppropriateValue( Array.get( value, i ) ) );
      }
      return values;
    }
    throw new IllegalStateException( "Unexpected value " + value );
  }
}


text:
FactoryGirl.define do
  factory :participant do
    association :user
    trait :with_users do
      after(:create) do |participant|
        participant.user = FactoryGirl.create(:user, :with_district)
      end
    end

    trait :with_assessment do
      association :assessment
    end
  end
end


text:
USE PetStoreDB

SELECT TOP 5 Price, Breed, BirthTime
FROM [dbo].[Pets]
WHERE BirthTime > '2012-01-01 00:00:00'
ORDER BY Price DESC