Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

In this page you can find the example usage for java.util ArrayList clear.

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:net.siveo.virtualization.vmware.Main.java

public void testFastInventory() throws Exception {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    //String hostName="192.168.101.79";
    //VMware.create(hostName,443,"svc-siveo","S1v30d6m3",false,-1L,1000L);

    //String hostName="10.251.5.14";
    //VMware.create(hostName,443,"SIVEO\\Administrateur","Clmdp@2013$",false,-1L);

    String hostName = "10.1.109.236";
    VMware.create(hostName, 443, "Administrator", "8x63-K/!/", false, -1L);

    // =========================================================================================
    // Inventory//from w ww . j a va  2 s  .  c om
    // =========================================================================================
    InventoryManager inventoryManager = InventoryManager.getInstance();
    Inventory inventory = inventoryManager.getInventoryByVC(hostName);

    TreeNode rootNode = inventory.getRootNode();
    System.out.println("RootNode: " + rootNode);

    VMManager vmManager = VMManager.getInstance();
    VirtualMachine vm = vmManager.getVmByName(hostName, "vcs01vbl");

    HostManager hostManager = HostManager.getInstance();
    Host host = hostManager.getHostByName("10.1.109.242", hostName);

    System.out.println("VirtualMachine Configuration: " + vm.getVmConfiguration());
    System.out.println("VirtualMachine Power State: " + vm.retrievePowerState());
    System.out.println("Host Connection State: " + host.getConnectionState());
    System.out.println("Host Power State: " + host.getPowerState());

    System.out.println("Appuyer sur une touche....");
    System.in.read();

    ArrayList<ManagedObjectReference> listOfManagedObjectReferences = new ArrayList<ManagedObjectReference>();
    listOfManagedObjectReferences.add(vm.getMor());
    inventory.getVirtualMachinePropertiesEx(listOfManagedObjectReferences);

    listOfManagedObjectReferences.clear();
    listOfManagedObjectReferences.add(host.getMor());
    inventory.getHostPropertiesEx(listOfManagedObjectReferences);

    //System.out.println("Host CPU Hz: "+host.getCPU().getHz());
    //System.out.println("Host Num CPU Cores: "+host.getCPU().getNumCpuCores());
    //System.out.println("Host Memory size: "+host.getMemory().getMemorySize());

    System.out.println("Host Connection State: " + host.getConnectionState());
    System.out.println("Host Power State: " + host.getPowerState());

    System.out.println("VirtualMachine Configuration: " + vm.getVmConfiguration());
    System.out.println("VirtualMachine Nb cpu: " + vm.getVmConfiguration().getVirtualCPU().getNbCPU());
    System.out.println("VirtualMachine Mghz: " + vm.getVmConfiguration().getVirtualCPU().getMghz());
    System.out.println("VirtualMachine Memory: " + vm.getVmConfiguration().getVirtualMemory().getMemory());

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void testRecupNetworkProperties() throws Exception {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    //String hostName="192.168.101.79";
    //VMware.create(hostName,443,"svc-siveo","S1v30d6m3",false,-1L,1000L);

    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "SIVEO\\Administrateur", "Clmdp@2013$", false, -1L);

    //String hostName="10.1.109.236";
    //VMware.create(hostName,443,"Administrator","8x63-K/!/",false,-1L);

    // =========================================================================================
    // Inventory/*  w  w w.  jav  a  2s. c o m*/
    // =========================================================================================
    InventoryManager inventoryManager = InventoryManager.getInstance();
    Inventory inventory = inventoryManager.getInventoryByVC(hostName);

    TreeNode rootNode = inventory.getRootNode();
    System.out.println("RootNode: " + rootNode);

    VMManager vmManager = VMManager.getInstance();
    VirtualMachine vm = vmManager.getVmByName(hostName, "templ_rhel5");

    // Get All VMs
    ArrayList<ManagedObjectReference> listOfManagedObjectReferences = new ArrayList<ManagedObjectReference>();
    listOfManagedObjectReferences.add(vm.getMor());
    inventory.getVirtualMachinePropertiesEx(listOfManagedObjectReferences);

    System.out.println("Premier Appel");
    this.displayNet(vm);

    System.out.println("Deuxime Appel");
    listOfManagedObjectReferences.clear();
    listOfManagedObjectReferences.add(vm.getMor());
    inventory.getVirtualMachinePropertiesEx(listOfManagedObjectReferences);
    this.displayNet(vm);

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void testRecupProperties() throws Exception {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    //String hostName="192.168.101.79";
    //VMware.create(hostName,443,"svc-siveo","S1v30d6m3",false,-1L,1000L);

    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "SIVEO\\Administrateur", "Clmdp@2013$", false, -1L);

    //String hostName="10.1.109.236";
    //VMware.create(hostName,443,"Administrator","8x63-K/!/",false,-1L);

    // =========================================================================================
    // Inventory//from   w ww.ja  va 2s.c  o m
    // =========================================================================================
    InventoryManager inventoryManager = InventoryManager.getInstance();
    Inventory inventory = inventoryManager.getInventoryByVC(hostName);

    TreeNode rootNode = inventory.getRootNode();
    System.out.println("RootNode: " + rootNode);

    VMManager vmManager = VMManager.getInstance();

    // Get All VMs
    ArrayList<VirtualMachine> listOfVms = vmManager.getAllVM(hostName);
    ArrayList<ManagedObjectReference> listOfManagedObjectReferences = new ArrayList<ManagedObjectReference>();

    for (VirtualMachine vm : listOfVms) {
        listOfManagedObjectReferences.add(vm.getMor());
    }

    Date dt01 = new Date();
    inventory.getVirtualMachinePropertiesEx(listOfManagedObjectReferences);
    Date dt02 = new Date();

    // Get VM by VM
    listOfManagedObjectReferences.clear();

    Date dt03 = new Date();
    for (VirtualMachine vm : listOfVms) {
        listOfManagedObjectReferences.clear();
        listOfManagedObjectReferences.add(vm.getMor());
        inventory.getVirtualMachinePropertiesEx(listOfManagedObjectReferences);
    }
    Date dt04 = new Date();

    System.out.println("Recup all: " + (dt02.getTime() - dt01.getTime()));
    System.out.println("Recup One by One: " + (dt04.getTime() - dt03.getTime()));

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void testInventory() throws VMwareException {
    // =========================================================================================
    // Connexion au WebService
    // =========================================================================================
    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "SIVEO\\Administrateur", "Clmdp@2013$", false, -1L);
    //VMware.create(hostName,443,"SIVEO\\actidev1","P@ssw0rd",false,-1L);

    // =========================================================================================
    // // w  w w.  jav  a  2  s . c o m
    // =========================================================================================
    InventoryManager inventoryManager = InventoryManager.getInstance();
    Inventory inventory = inventoryManager.getInventoryByVC(hostName);

    VMManager vmManager = VMManager.getInstance();
    ArrayList<VirtualMachine> listOfVirtualMachines = vmManager.getAllVM(hostName);
    ArrayList<ManagedObjectReference> listOfMors = new ArrayList<ManagedObjectReference>();

    System.out.println("Nb VM: " + listOfVirtualMachines.size());

    if (listOfVirtualMachines != null && !listOfVirtualMachines.isEmpty()) {
        for (VirtualMachine vm : listOfVirtualMachines) {
            listOfMors.add(vm.getMor());
        }

        Date dt1 = new Date();
        inventory.getVirtualMachinePropertiesEx(listOfMors);
        Date dt2 = new Date();

        System.out.println("Temps recup VM Properties:  " + (dt2.getTime() - dt1.getTime()));

    }

    // Get All Hosts
    HostManager hostManager = HostManager.getInstance();
    ArrayList<Host> listOfHosts = hostManager.getAllHosts(hostName);
    listOfMors.clear();

    if (listOfHosts != null && !listOfHosts.isEmpty()) {
        for (Host host : listOfHosts) {
            listOfMors.add(host.getMor());
        }

        Date dt1 = new Date();
        inventory.getHostPropertiesEx(listOfMors);
        Date dt2 = new Date();

        System.out.println("Temps recup Host Properties:  " + (dt2.getTime() - dt1.getTime()));

    }

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void testVM() throws VMwareException {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "Administrateur", "Clmdp@2013$", false, -1L);

    // =========================================================================================
    // //from www .  j a va 2s.c o m
    // =========================================================================================
    ArrayList<String> listOfMorIDs = new ArrayList<String>();
    InventoryManager inventoryManager = InventoryManager.getInstance();
    Inventory inventory = inventoryManager.getInventoryByVC(hostName);

    HostManager hostManager = HostManager.getInstance();
    ArrayList<Host> listOfHosts = hostManager.getAllHosts(hostName);

    if (listOfHosts != null && !listOfHosts.isEmpty()) {
        for (Host host : listOfHosts) {
            listOfMorIDs.add(host.getMor().get_value());
        }

        inventory.getHostPropertiesExFromIDs(listOfMorIDs);

    }

    // =========================================================================================
    // 
    // =========================================================================================

    VMManager vmManager = VMManager.getInstance();
    VirtualMachine vm = null;

    //vm=vmManager.getVmByName(hostName, "VMKS-12XSP1-66");
    vm = vmManager.getVmByName(hostName, "CentOSVM");

    listOfMorIDs.clear();
    listOfMorIDs.add(vm.getMor().get_value());

    inventory.getVirtualMachinePropertiesExFromIDs(listOfMorIDs);

    Host host = vm.getHost();
    //listOfMorIDs.clear();
    //listOfMorIDs.add(host.getMor().get_value());
    //inventory.getHostPropertiesExFromIDs(listOfMorIDs);

    System.out.println("Host : " + host.getName());
    System.out.println("Host IP: " + host.getIP());

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void deployVM() throws VMwareException {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "Administrateur", "Clmdp@2013$", false, -1L);

    // =========================================================================================
    // Deploy a VM from a Template and add a new Virtual Network Card
    // =========================================================================================
    VMManager vmManager = VMManager.getInstance();
    // Creation Cross DC
    String hostID = "host-71"; // siveo-esx2.siveo.net
    String dataStoreID = "datastore-535"; // VMFSDEMO
    String vmID = "vm-1027"; //template SmallVM
    String vmFolderID = null; // dossier SCVMM
    String resourcePoolID = "resgroup-1004"; //TestCDO

    Host host = HostManager.getInstance().getHostByID(hostID, hostName);
    Datastore datastore = DataStoreManager.getInstance().getDatastoreByID(dataStoreID, hostName);
    VirtualMachine template = vmManager.getVmByID(hostName, vmID);

    System.out.println("Infos de Clonage:");
    System.out.println("- Host :" + host.getName());
    System.out.println("- Datastore :" + datastore.getName());
    System.out.println("- Template :" + template.getName());

    if (vmFolderID != null) {
        Folder folder = FolderManager.getInstance().getFolderByID(vmFolderID, hostName);
        System.out.println("- Folder :" + folder.getName());
    }//from w  w  w  .ja v  a  2  s  .co m

    if (resourcePoolID != null) {
        ResourcePool resourcePool = ResourcePoolManager.getInstance().getResourcePoolByID(hostName,
                resourcePoolID);
        System.out.println("- ResourcePool :" + resourcePool.getName());
    }

    InventoryManager inventoryManager = InventoryManager.getInstance();
    Inventory inventory = inventoryManager.getInventoryByVC(hostName);

    ArrayList<ManagedObjectReference> listOfMors = new ArrayList<ManagedObjectReference>();
    listOfMors.add(template.getMor());

    inventory.getVirtualMachinePropertiesEx(listOfMors);

    // =========================================================================================
    // Initialize the Sysprep Linux
    // =========================================================================================
    System.out.println("\n*****  Clone Template to VM *****");
    String vmName = "instantvmjpa";
    VMConfiguration vmConfiguration = new VMConfiguration();

    // ---------------------------------------------------------------
    // Set the Society Name
    // ---------------------------------------------------------------
    //vmConfiguration.setUserName("instantvmcdo");   
    //vmConfiguration.setUserName("siveo_test");   
    //vmConfiguration.setSocietyName("Navaho");   
    vmConfiguration.setName(vmName);

    // ---------------------------------------------------------------
    // Initialize the Linux Sysprep 
    // ---------------------------------------------------------------
    SysprepLinux sysprepLinux = new SysprepLinux();
    sysprepLinux.setDomain("siveo.net");
    sysprepLinux.setHostname(vmName);

    // =========================================================================================
    // Initialize the VM Configuration
    // =========================================================================================
    // ---------------------------------------------------------------
    // Set the Sysprep
    // ---------------------------------------------------------------
    //vmConfiguration.setSysprepWindows(winSysPrep);
    vmConfiguration.setSysprepLinux(sysprepLinux);

    // ---------------------------------------------------------------
    // Set the Network configuration
    //
    // If not set the default values are:
    //
    // DHCP
    // ---------------------------------------------------------------

    NetworkAdapter networkAdapter = new NetworkAdapter();
    //networkAdapter.setDnsDomain("siveo.net");
    ////networkAdapter.setDnsServerList(new String[]{"192.168.0.50","212.27.40.240","212.27.40.241"});
    ////networkAdapter.setDnsServerList(new String[]{"192.168.1.13","192.168.1.1"});
    networkAdapter.setDnsServerList(new String[] { "194.133.14.66" });
    networkAdapter.setPrimaryWINS(null);
    networkAdapter.setSecondaryWINS(null);
    networkAdapter.setNetBIOS(null);
    networkAdapter.setIp("10.62.16.73");
    networkAdapter.setSubnetMask("255.255.252.0");
    networkAdapter.setGateway(new String[] { "10.62.16.2" });
    ////networkAdapter.setMacAddress(null);
    vmConfiguration.getListOfNetworkAdapters().add(networkAdapter);

    // !!!
    //vmConfiguration.setDnsServerList(new String[]{"192.168.1.1","192.168.1.50"});
    vmConfiguration.setDnsServerList(new String[] { "194.133.14.66" });
    //vmConfiguration.setDnsSuffixList(new String[]{});
    vmConfiguration.setDnsSuffixList(new String[] {});

    // set the second Network
    //networkAdapter=new NetworkAdapter();
    ////networkAdapter.setDnsDomain("siveo.net");
    //networkAdapter.setDnsServerList(new String[]{"192.168.165.1","194.133.125.66"});
    //networkAdapter.setPrimaryWINS(null);
    //networkAdapter.setSecondaryWINS(null);
    //networkAdapter.setNetBIOS(null);
    //networkAdapter.setIp(null);
    //networkAdapter.setSubnetMask("255.255.255.0");
    //networkAdapter.setGateway(new String[]{"10.0.12.1"});
    //vmConfiguration.setNetworkAdpater(networkAdapter);

    // !!!
    ////vmConfiguration.setDnsServerList(new String[]{"192.168.1.1","192.168.1.50"});
    //vmConfiguration.setDnsServerList(new String[]{"192.168.165.1","194.133.125.66"});
    ////vmConfiguration.setDnsSuffixList(new String[]{});
    //vmConfiguration.setDnsSuffixList(new String[]{});

    //vmConfiguration.getListOfNetworkAdapters().add(networkAdapter);

    // ---------------------------------------------------------------
    // Set the CPU configuration
    // ---------------------------------------------------------------
    VirtualCPU virtualCPU = new VirtualCPU();
    virtualCPU.setLimit(1024);
    virtualCPU.setReservation(1024);
    virtualCPU.setExpandableReservation(false);
    virtualCPU.setNbCPU(2);
    vmConfiguration.setVirtualCPU(virtualCPU);

    // ---------------------------------------------------------------
    // Set the Memory confguration
    // ---------------------------------------------------------------
    VirtualMemory virtualMem = new VirtualMemory();
    virtualMem.setLimit(4096);
    virtualMem.setReservation(2048);
    virtualMem.setMemory(2048);
    virtualMem.setExpandableReservation(false);
    vmConfiguration.setVirtualMemory(virtualMem);

    // ---------------------------------------------------------------
    // Add a new card
    // ---------------------------------------------------------------
    VirtualNetwork virtualNetwork = null;

    //Select a VMware Network
    NetworkManager networkManager = NetworkManager.getInstance();
    Network network = networkManager.getNetworkByID("network-210", hostName);

    virtualNetwork = new VirtualNetwork();
    virtualNetwork.setNetwork(network);
    virtualNetwork.setAction(VirtualDeviceOperation.add);
    vmConfiguration.getListOfVirtualNetworks().add(virtualNetwork);

    // ---------------------------------------------------------------
    // Extend the first Disk and add a new disk 
    // ---------------------------------------------------------------
    net.siveo.virtualization.vmware.virtualdevice.VirtualDisk vDisk = new VirtualDisk();

    // Extend the First Disk
    vDisk = template.getVirtualDeviceManager().getVirtualDisks().get(0);
    vDisk.setAction(VirtualDeviceOperation.edit);
    vDisk.setDiskSize(20 * 1024);
    vmConfiguration.getListOfVirtualDisk().add(vDisk);

    // Add a new DISK
    vDisk = new VirtualDisk();
    vDisk.setAction(VirtualDeviceOperation.add);
    vDisk.setDiskSize(1024 * 3);
    //vDisk.setLabel("Hard disk 2");
    vmConfiguration.getListOfVirtualDisk().add(vDisk);

    // ---------------------------------------------------------------
    // Set the additional fields 
    // ---------------------------------------------------------------
    vmConfiguration.setPowerOn(false);
    vmConfiguration.setCorrelID("1234ABC");

    // ---------------------------------------------------------------
    // ---------------------------------------------------------------
    // Clone Template to VM with reconfiguration and sysprep 
    // ---------------------------------------------------------------
    // ---------------------------------------------------------------
    vmManager.cloneTemplateToVMEx(vmID, hostName, vmConfiguration, hostID, dataStoreID, resourcePoolID,
            vmFolderID);

    System.out.println("Press a key to continue...");

    try {
        System.in.read();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // =========================================================================================
    // Connect the card
    // =========================================================================================

    //Refresh the VM
    VMware.refresh(hostName);
    listOfMors.clear();
    VirtualMachine vm = vmManager.getVmByName(hostName, vmName);
    listOfMors.add(vm.getMor());
    inventory.getVirtualMachinePropertiesEx(listOfMors);

    vm.connectVirtualNetworkOnStart(vm.getVMNetwork().getListOfVirtualNetwork(), "ABCD");

    /*
    ArrayList<VirtualNetwork> listOfVirtualNetworks=vm.getVMNetwork().getListOfVirtualNetwork();
            
    for (VirtualNetwork virtualNetwork2:listOfVirtualNetworks)
    {
       System.out.println("VirtualNetwork: "+virtualNetwork2.getVirtualDevice().getDeviceInfo().getLabel());
               
               
       VirtualDeviceConnectInfo virtualDeviceConnectInfo=virtualNetwork2.getVirtualDevice().getConnectable();
       if (virtualDeviceConnectInfo!=null)
       {
    System.out.println("Connectable");
    System.out.println("AllowGuestControl: "+virtualDeviceConnectInfo.isAllowGuestControl());
    System.out.println("Connected: "+virtualDeviceConnectInfo.isConnected());
    System.out.println("Start Connected "+virtualDeviceConnectInfo.isStartConnected());
       }
    }
    */

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void deployInstantVMOnProd() throws VMwareException {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    String hostName = "10.246.5.10";
    VMware.create(hostName, 443, "instantvm\\siveo-admin", "Sive0@dmin", false, -1L);

    // =========================================================================================
    // Deploy a VM from a Template and add a new Virtual Network Card
    // =========================================================================================
    VMManager vmManager = VMManager.getInstance();
    // Creation Cross DC
    String hostID = "host-28"; // th3-instantvm-esx01.instantvm.navaho.local
    String dataStoreID = "datastore-61"; // ds-EMC_TH3_CX4-InstantVM-Bronze-cli-01
    String vmID = "vm-581"; //template testdga
    String vmFolderID = "group-v466"; // dossier Contrat_1
    String resourcePoolID = "resgroup-429"; //Contrat_1

    Host host = HostManager.getInstance().getHostByID(hostID, hostName);
    Datastore datastore = DataStoreManager.getInstance().getDatastoreByID(dataStoreID, hostName);
    VirtualMachine template = vmManager.getVmByID(hostName, vmID);

    System.out.println("Infos de Clonage:");
    System.out.println("- Host :" + host.getName());
    System.out.println("- Datastore :" + datastore.getName());
    System.out.println("- Template :" + template.getName());

    if (vmFolderID != null) {
        Folder folder = FolderManager.getInstance().getFolderByID(vmFolderID, hostName);
        System.out.println("- Folder :" + folder.getName());
    }//w w  w.j  a  v a2s .c om

    if (resourcePoolID != null) {
        ResourcePool resourcePool = ResourcePoolManager.getInstance().getResourcePoolByID(hostName,
                resourcePoolID);
        System.out.println("- ResourcePool :" + resourcePool.getName());
    }

    InventoryManager inventoryManager = InventoryManager.getInstance();
    Inventory inventory = inventoryManager.getInventoryByVC(hostName);

    ArrayList<ManagedObjectReference> listOfMors = new ArrayList<ManagedObjectReference>();
    listOfMors.add(template.getMor());

    inventory.getVirtualMachinePropertiesEx(listOfMors);

    // =========================================================================================
    // Initialize the Sysprep Linux
    // =========================================================================================
    System.out.println("\n*****  Clone Template to VM *****");
    String vmName = "instantvmjpa";
    VMConfiguration vmConfiguration = new VMConfiguration();

    // ---------------------------------------------------------------
    // Set the Society Name
    // ---------------------------------------------------------------
    //vmConfiguration.setUserName("instantvmcdo");   
    //vmConfiguration.setUserName("siveo_test");   
    //vmConfiguration.setSocietyName("Navaho");   
    vmConfiguration.setName(vmName);

    // ---------------------------------------------------------------
    // Initialize the Linux Sysprep 
    // ---------------------------------------------------------------
    SysprepLinux sysprepLinux = new SysprepLinux();
    sysprepLinux.setDomain("INSTANTVM");
    sysprepLinux.setHostname(vmName);

    // =========================================================================================
    // Initialize the VM Configuration
    // =========================================================================================
    // ---------------------------------------------------------------
    // Set the Sysprep
    // ---------------------------------------------------------------
    //vmConfiguration.setSysprepWindows(winSysPrep);
    vmConfiguration.setSysprepLinux(sysprepLinux);

    // ---------------------------------------------------------------
    // Set the Network configuration
    //
    // If not set the default values are:
    //
    // DHCP
    // ---------------------------------------------------------------

    NetworkAdapter networkAdapter = new NetworkAdapter();
    //networkAdapter.setDnsDomain("siveo.net");
    ////networkAdapter.setDnsServerList(new String[]{"192.168.0.50","212.27.40.240","212.27.40.241"});
    ////networkAdapter.setDnsServerList(new String[]{"192.168.1.13","192.168.1.1"});
    //networkAdapter.setDnsServerList(new String[]{"194.133.14.66"});
    networkAdapter.setDnsServerList(new String[] {});
    networkAdapter.setPrimaryWINS(null);
    networkAdapter.setSecondaryWINS(null);
    networkAdapter.setNetBIOS(null);
    networkAdapter.setIp("81.93.16.200");
    networkAdapter.setSubnetMask("255.255.255.192");
    networkAdapter.setGateway(new String[] { "81.93.16.254" });
    ////networkAdapter.setMacAddress(null);
    vmConfiguration.getListOfNetworkAdapters().add(networkAdapter);

    // !!!
    //vmConfiguration.setDnsServerList(new String[]{"192.168.1.1","192.168.1.50"});
    //vmConfiguration.setDnsServerList(new String[]{"194.133.14.66"});
    vmConfiguration.setDnsServerList(new String[] {});
    //vmConfiguration.setDnsSuffixList(new String[]{});
    vmConfiguration.setDnsSuffixList(new String[] {});

    // set the second Network
    //networkAdapter=new NetworkAdapter();
    ////networkAdapter.setDnsDomain("siveo.net");
    //networkAdapter.setDnsServerList(new String[]{"192.168.165.1","194.133.125.66"});
    //networkAdapter.setPrimaryWINS(null);
    //networkAdapter.setSecondaryWINS(null);
    //networkAdapter.setNetBIOS(null);
    //networkAdapter.setIp(null);
    //networkAdapter.setSubnetMask("255.255.255.0");
    //networkAdapter.setGateway(new String[]{"10.0.12.1"});
    //vmConfiguration.setNetworkAdpater(networkAdapter);

    // !!!
    ////vmConfiguration.setDnsServerList(new String[]{"192.168.1.1","192.168.1.50"});
    //vmConfiguration.setDnsServerList(new String[]{"192.168.165.1","194.133.125.66"});
    ////vmConfiguration.setDnsSuffixList(new String[]{});
    //vmConfiguration.setDnsSuffixList(new String[]{});

    //vmConfiguration.getListOfNetworkAdapters().add(networkAdapter);

    // ---------------------------------------------------------------
    // Set the CPU configuration
    // ---------------------------------------------------------------
    VirtualCPU virtualCPU = new VirtualCPU();
    virtualCPU.setLimit(1024);
    virtualCPU.setReservation(1024);
    virtualCPU.setExpandableReservation(false);
    virtualCPU.setNbCPU(2);
    //vmConfiguration.setVirtualCPU(virtualCPU);

    // ---------------------------------------------------------------
    // Set the Memory confguration
    // ---------------------------------------------------------------
    VirtualMemory virtualMem = new VirtualMemory();
    virtualMem.setLimit(4096);
    virtualMem.setReservation(2048);
    virtualMem.setMemory(2048);
    virtualMem.setExpandableReservation(false);
    //vmConfiguration.setVirtualMemory(virtualMem);

    // ---------------------------------------------------------------
    // Add a new card
    // ---------------------------------------------------------------
    VirtualNetwork virtualNetwork = null;

    //Select a VMware Network
    NetworkManager networkManager = NetworkManager.getInstance();
    Network network = networkManager.getNetworkByID("network-210", hostName);

    virtualNetwork = new VirtualNetwork();
    virtualNetwork.setNetwork(network);
    virtualNetwork.setAction(VirtualDeviceOperation.add);
    //vmConfiguration.getListOfVirtualNetworks().add(virtualNetwork);

    // ---------------------------------------------------------------
    // Add a new card DVSwitch
    // ---------------------------------------------------------------
    DVSwitch dvSwitch = null;
    DVPortGroup dvPortGroup = null;

    DVSwitchManager dvSwitchManager = DVSwitchManager.getInstance();
    dvSwitch = dvSwitchManager.getDVSwitchByUUID("53 50 08 50 ed f4 88 7b-96 ef dd 74 61 59 d8 85", hostName);
    dvPortGroup = dvSwitch.getMapOfDVPortGroupByKey().get("dvportgroup-520");

    VirtualDVSwitch virtualDVSwitch = new VirtualDVSwitch();
    virtualDVSwitch.setDvSwitch(dvSwitch);
    virtualDVSwitch.setDvPortGroup(dvPortGroup);
    virtualDVSwitch.setAction(VirtualDeviceOperation.add);
    vmConfiguration.getListOfVirtualDVSwitchs().add(virtualDVSwitch);

    /*
    ArrayList<VirtualDVSwitch> listOfVirtualDVSwitch =new ArrayList<VirtualDVSwitch>();   
            
            
    DVSwitchManager dvSwitchManager=DVSwitchManager.getInstance();
    DVSwitch dvSwitch=null;
    DVPortGroup dvPortGroup=null;
            
            
            
            
    //virtualDVSwitch=vm.getVMNetwork().getVirtualDVSwitchByUUIDByDvPortGroupKeyByPortKey("a9 9d 2d 50 f1 ad 37 75-61 18 fc 7d 7a 56 52 ac", "dvportgroup-257", "2273");
            
    virtualDVSwitch=vm.getVMNetwork().getVirtualDVSwitchByUuidByDVPortGroupKey("a9 9d 2d 50 f1 ad 37 75-61 18 fc 7d 7a 56 52 ac", "dvportgroup-202");
            
    //virtualDVSwitch=new VirtualDVSwitch();
    //virtualDVSwitch.setSwitchUuid("67 69 2d 50 b8 e5 40 4b-1c f0 c4 ac 38 54 ac 3d");
    //virtualDVSwitch.setPortGroupKey("dvportgroup-6421");
    virtualDVSwitch.setAction(VirtualDeviceOperation.remove);
    //listOfVirtualDVSwitch.add(virtualDVSwitch);
            
    //DVSwitchManager dvSwitchManager=DVSwitchManager.getInstance();
    dvSwitch=dvSwitchManager.getDVSwitchByUUID("a9 9d 2d 50 f1 ad 37 75-61 18 fc 7d 7a 56 52 ac", hostName);
    dvPortGroup=dvSwitch.getMapOfDVPortGroupByKey().get("dvportgroup-257");
            
    virtualDVSwitch=new VirtualDVSwitch();
    virtualDVSwitch.setDvSwitch(dvSwitch);
    virtualDVSwitch.setDvPortGroup(dvPortGroup);
    virtualDVSwitch.setAction(VirtualDeviceOperation.add);
    //listOfVirtualDVSwitch.add(virtualDVSwitch);
            
            
    // Edit a DVSwitch
    virtualDVSwitch=vm.getVMNetwork().getVirtualDVSwitchByUUID("a9 9d 2d 50 f1 ad 37 75-61 18 fc 7d 7a 56 52 ac");
            
    dvSwitch=dvSwitchManager.getDVSwitchByUUID("a9 9d 2d 50 f1 ad 37 75-61 18 fc 7d 7a 56 52 ac", hostName);
    //dvPortGroup=dvSwitch.getMapOfDVPortGroupByKey().get("dvportgroup-202");
    dvPortGroup=dvSwitch.getMapOfDVPortGroupByKey().get("dvportgroup-257");
    System.out.println("dvPortGroup: "+dvPortGroup.getName());
            
    virtualDVSwitch.setDvPortGroup(dvPortGroup);
    virtualDVSwitch.setAction(VirtualDeviceOperation.edit);
    //listOfVirtualDVSwitch.add(virtualDVSwitch);
    */

    // ---------------------------------------------------------------
    // Extend the first Disk and add a new disk 
    // ---------------------------------------------------------------
    net.siveo.virtualization.vmware.virtualdevice.VirtualDisk vDisk = new VirtualDisk();

    // Extend the First Disk
    vDisk = template.getVirtualDeviceManager().getVirtualDisks().get(0);
    vDisk.setAction(VirtualDeviceOperation.edit);
    vDisk.setDiskSize(20 * 1024);
    //vmConfiguration.getListOfVirtualDisk().add(vDisk);

    // Add a new DISK
    vDisk = new VirtualDisk();
    vDisk.setAction(VirtualDeviceOperation.add);
    vDisk.setDiskSize(1024 * 3);
    //vDisk.setLabel("Hard disk 2");
    //vmConfiguration.getListOfVirtualDisk().add(vDisk);

    // ---------------------------------------------------------------
    // Set the additional fields 
    // ---------------------------------------------------------------
    vmConfiguration.setPowerOn(false);
    vmConfiguration.setCorrelID("1234ABC");

    // ---------------------------------------------------------------
    // ---------------------------------------------------------------
    // Clone Template to VM with reconfiguration and sysprep 
    // ---------------------------------------------------------------
    // ---------------------------------------------------------------
    vmManager.cloneTemplateToVMEx(vmID, hostName, vmConfiguration, hostID, dataStoreID, resourcePoolID,
            vmFolderID);

    System.out.println("Press a key to continue...");

    try {
        System.in.read();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // =========================================================================================
    // Connect the card
    // =========================================================================================

    //Refresh the VM
    VMware.refresh(hostName);
    listOfMors.clear();
    VirtualMachine vm = vmManager.getVmByName(hostName, vmName);
    listOfMors.add(vm.getMor());
    inventory.getVirtualMachinePropertiesEx(listOfMors);

    vm.connectVirtualNetworkOnStart(vm.getVMNetwork().getListOfVirtualNetwork(), "ABCD");

    /*
    ArrayList<VirtualNetwork> listOfVirtualNetworks=vm.getVMNetwork().getListOfVirtualNetwork();
            
    for (VirtualNetwork virtualNetwork2:listOfVirtualNetworks)
    {
       System.out.println("VirtualNetwork: "+virtualNetwork2.getVirtualDevice().getDeviceInfo().getLabel());
               
               
       VirtualDeviceConnectInfo virtualDeviceConnectInfo=virtualNetwork2.getVirtualDevice().getConnectable();
       if (virtualDeviceConnectInfo!=null)
       {
    System.out.println("Connectable");
    System.out.println("AllowGuestControl: "+virtualDeviceConnectInfo.isAllowGuestControl());
    System.out.println("Connected: "+virtualDeviceConnectInfo.isConnected());
    System.out.println("Start Connected "+virtualDeviceConnectInfo.isStartConnected());
       }
    }
    */

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void getVirtualMachinesInfo() throws VMwareException {
    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================

    //String hostName="192.168.101.79";
    //VMware.create(hostName,443,"svc-siveo","S1v30d6m3",false,-1L,1000L);

    //String hostName="10.0.12.6";
    //VMware.create(hostName,443,"siveo_admin","s1v3oP0C",false,-1L,1000L);

    //String hostName="10.251.5.14";
    //VMware.create(hostName,443,"Administrateur","Clmdp@09",false,-1L,1000L);

    //String hostName="192.168.101.179";
    //VMware.create(hostName,443,"svc-siveodev","KzT$g#h4",false,-1L);

    //String hostName="10.251.5.75";
    //VMware.create(hostName,443,"Administrateur","Clmdp@09",false,-1L,1000L);

    //      String hostName="10.62.16.34";
    //      VMware.create(hostName,443,"SIVEO\\Administrateur","Clmdp@2013$",false,-1L);

    //String hostName="163.172.7.95";
    //VMware.create(hostName,443,"eva","cahh4gee$2015",false,-1L);

    //      String hostName="10.62.16.33";
    //      VMware.create(hostName,443,"root","cahh4gee$",false,-1L,1000L);

    //      String hostName="163.172.7.95";
    //      VMware.create(hostName,443,"eva","cahh4gee$2015",false,-1L,1000L);

    //      String hostName="192.168.101.122";
    //      VMware.create(hostName,443,"root","cahh4gee$",false,-1L);

    String hostName = "10.10.0.64";
    VMware.create(hostName, 443, "root", "Keonys123", false, -1L);

    // =========================================================================================
    // Get All VirtualMachines and Templates and display their Configuration
    // =========================================================================================
    InventoryManager inventoryManager = InventoryManager.getInstance();
    Inventory inventory = inventoryManager.getInventoryByVC(hostName);
    TreeNode root = inventory.getRootNode();

    System.out.println("RootNode: " + root);

    VMConfiguration vmConfiguration = null;
    String vmName = null;//from w w w .jav  a  2s. co m

    VMManager vmManager = VMManager.getInstance();
    ArrayList<VirtualMachine> vms = vmManager.getAllVM(hostName);

    ArrayList<String> listOfMorIDs = new ArrayList<String>();

    //      System.out.println("List of Power State:");
    //      System.out.println("- "+VirtualMachinePowerState.poweredOff.name());
    //      System.out.println("- "+VirtualMachinePowerState.poweredOn.name());
    //      
    //      System.out.println("List of host Power State:");
    //      System.out.println("- "+HostSystemPowerState.poweredOff+" / "+HostSystemPowerState.poweredOff.name()+" / "+HostSystemPowerState.poweredOff.toString());
    //      System.out.println("- "+VirtualMachinePowerState.poweredOn.name());

    VirtualMachineSummary virtualMachineSummary = null;
    String padding = "#####################################################################################";
    //String paddingSpace="                                             ";
    //String decoration=null;

    if (vms != null && !vms.isEmpty()) {
        for (VirtualMachine vm : vms) {
            listOfMorIDs.add(vm.getMor().get_value());
        }

        inventory.getVirtualMachinePropertiesExFromIDs(listOfMorIDs);

        for (VirtualMachine vm : vms) {
            vmConfiguration = vm.getConfiguration();
            vmName = vm.getName();

            virtualMachineSummary = vm.getSummary();

            System.out.println("\n#################" + padding.substring(0, vmName.length())
                    + "##########################################");
            System.out.println(" " + vmName);
            System.out.println("#################" + padding.substring(0, vmName.length())
                    + "##########################################");

            if (vm.getHost() != null) {
                System.out.println("- Host: " + vm.getHost().getName());
                //vm.getHost()
            }

            System.out.println("- PowerState: " + vm.getPowerState());

            //            if (virtualMachineSummary.getQuickStats()!=null)
            //            {
            //               System.out.println("- QuickStats");
            //               System.out.println(" - CPU Usage: " +virtualMachineSummary.getQuickStats().getOverallCpuUsage());
            //            }

            if (vmConfiguration.getVirtualCPU() != null) {

                System.out.println("\n=====================");
                System.out.println("======== CPU ========");
                System.out.println("=====================");
                System.out.println("- Nb vCPU: " + vmConfiguration.getVirtualCPU().getNbCPU());
                System.out.println("- Mghz: " + vmConfiguration.getVirtualCPU().getMghz());
                System.out.println("- Reservation: " + vmConfiguration.getVirtualCPU().getReservation());
                System.out.println("- Limit: " + vmConfiguration.getVirtualCPU().getLimit());
                if (vmConfiguration.getVirtualCPU().getShareLevel() != null)
                    System.out.println("- Share Level: " + vmConfiguration.getVirtualCPU().getShareLevel());

                System.out.println("- Share Level: " + vmConfiguration.getVirtualCPU().getShares());

            }

            if (vmConfiguration.getVirtualMemory() != null) {
                System.out.println("\n========================");
                System.out.println("======== Memory ========");
                System.out.println("========================");
                System.out.println("- Memory: " + vmConfiguration.getVirtualMemory().getMemory());
                System.out.println("- Memory Size: " + vmConfiguration.getVirtualMemory().getMemorySize());
                System.out.println(
                        "- Memory Reservation: " + vmConfiguration.getVirtualMemory().getReservation());
                System.out.println("- Memory Limit: " + vmConfiguration.getVirtualMemory().getLimit());
                if (vmConfiguration.getVirtualMemory().getShareLevel() != null)
                    System.out.println("- Share Level: " + vmConfiguration.getVirtualMemory().getShareLevel());

                System.out.println("- Share Level: " + vmConfiguration.getVirtualMemory().getShares());

            }

            System.out.println("\n===================================");
            System.out.println("======== Guest Information ========");
            System.out.println("===================================");
            System.out.println("- Host Name: " + vm.getGuest().getHostName());
            System.out.println("- IP Primary Address: " + vm.getGuest().getIpAddress());
            System.out.println("- OS");
            System.out.println("- Family   : " + vm.getGuest().getOSFamily());
            System.out.println("  - Full Name: " + vm.getGuest().getOSFullName());
            System.out.println("  - ID       : " + vm.getGuest().getOSId());
            System.out.println("- VMware Tools");
            //               System.out.println("  - Status        : "+vm.getGuest().getToolsStatus());
            //               System.out.println("  - Running Status: "+vm.getGuest().getToolsRunningStatus().getName());
            //               System.out.println("  - Version       : "+vm.getGuest().getToolsVersion());
            //               System.out.println("  - Version Status: "+vm.getGuest().getToolsVersionStatus().getName());
            if (!vm.getGuest().getDisk().isEmpty()) {
                int nbGuestDisk = 1;
                for (GuestDisk guestDisk : vm.getGuest().getDisk()) {
                    System.out.println("- Disk n" + nbGuestDisk++);
                    System.out.println("  - Capacit    : " + guestDisk.getCapacity());
                    System.out.println("  - Taille libre: " + guestDisk.getFreeSpace());
                    System.out.println("  - Label       : " + guestDisk.getDiskPath());
                }
            }

            System.out.println("\n======================================");
            System.out.println("======== Network Adapter Info ========");
            System.out.println("======================================");

            VMNetwork vmNetwork = vm.getVMNetwork();
            ArrayList<VirtualNetwork> listOfVirtualNetworks = null;
            ArrayList<VirtualDVSwitch> listOfVirtualDVSwitchs = null;

            if (vmNetwork != null) {

                listOfVirtualNetworks = vmNetwork.getListOfVirtualNetwork();
                if (listOfVirtualNetworks != null && !listOfVirtualNetworks.isEmpty()) {
                    for (VirtualNetwork virtualNetwork : listOfVirtualNetworks) {
                        System.out.println("- Label: " + virtualNetwork.getLabel());
                        System.out.println("- Name: " + virtualNetwork.getNetwork().getName());
                        System.out.println("- Vlan ID: " + virtualNetwork.getNetwork().getVlanId());
                        System.out.println("- Mac Address: " + virtualNetwork.getMacAddress());
                        if (virtualNetwork.getListOfIPAddress() != null) {
                            for (String ip : virtualNetwork.getListOfIPAddress()) {
                                System.out.println("- IP: " + ip);
                            }
                        }
                        System.out.println("");
                    }
                }

                listOfVirtualDVSwitchs = vmNetwork.getListOfVirtualDVSwitch();
                if (listOfVirtualDVSwitchs != null && !listOfVirtualDVSwitchs.isEmpty()) {
                    for (VirtualDVSwitch virtualDVSwitch : listOfVirtualDVSwitchs) {
                        System.out.println("- Label: " + virtualDVSwitch.getLabel());
                        System.out.println("- Name: " + virtualDVSwitch.getDvSwitch().getName());
                        System.out.println("- DVPortgroup: " + virtualDVSwitch.getDvPortGroup().getName());
                        System.out.println("- Port: " + virtualDVSwitch.getPortKey());
                        System.out.println("- Mac Address: " + virtualDVSwitch.getMacAddress());
                        //System.out.println("    - Primary Ip Address: "+virtualDVSwitch.getPrimaryIpAddress());

                        if (virtualDVSwitch.getGuestNic() != null
                                && virtualDVSwitch.getGuestNic().getIpConfig() != null
                                && virtualDVSwitch.getGuestNic().getIpConfig()
                                        .getListOfAssignedIpAddress() != null
                                && !virtualDVSwitch.getGuestNic().getIpConfig().getListOfAssignedIpAddress()
                                        .isEmpty()) {
                            System.out.println("    - Assigned Ip Address: ");

                            for (IpConfigInfoIpAddress ipConfigInfoIpAddress : virtualDVSwitch.getGuestNic()
                                    .getIpConfig().getListOfAssignedIpAddress()) {
                                System.out.println("    - Assigned Ip Address: ");
                                System.out.println("      - " + ipConfigInfoIpAddress.getIpAddress());

                            }
                        }

                        System.out.println("");
                    }
                }

            }

            System.out.println("\n==============================");
            System.out.println("======== Virtual Disk ========");
            System.out.println("==============================");
            ArrayList<VirtualDisk> listOfVirtualDisks = vm.getDisk();
            int nbDisk = 1;
            if (listOfVirtualDisks != null && !listOfVirtualDisks.isEmpty()) {
                for (VirtualDisk virtualDisk : listOfVirtualDisks) {
                    System.out.println("- Virtual Disk n" + nbDisk++);
                    System.out.println("  - Label: " + virtualDisk.getLabel());
                    System.out.println("  - Key: " + virtualDisk.getKey());
                    System.out.println("  - Controller Key: " + virtualDisk.getControllerKey());
                    System.out.println("  - UnitNumber: " + virtualDisk.getUnitNumber());
                    System.out.println("  - Size: " + virtualDisk.getDiskSize());
                    System.out.println("  - Backing: " + virtualDisk.getBacking());
                    if (virtualDisk.getBacking() instanceof com.vmware.vim25.VirtualDiskFlatVer2BackingInfo) {
                        com.vmware.vim25.VirtualDiskFlatVer2BackingInfo virtualDiskBacking = (com.vmware.vim25.VirtualDiskFlatVer2BackingInfo) virtualDisk
                                .getBacking();
                        System.out.println("    - Parent: " + virtualDiskBacking.getParent());
                        System.out.println(
                                "    - Datastore Value: " + virtualDiskBacking.getDatastore().get_value());
                        System.out
                                .println("    - Backing Object Id: " + virtualDiskBacking.getBackingObjectId());
                        System.out.println("    - Change Id: " + virtualDiskBacking.getChangeId());
                        System.out.println("    - Content Id: " + virtualDiskBacking.getContentId());
                        System.out
                                .println("    - Delta Disk Format: " + virtualDiskBacking.getDeltaDiskFormat());
                        System.out.println("    - Disk Mode: " + virtualDiskBacking.getDiskMode());
                        System.out.println("    - FileName: " + virtualDiskBacking.getFileName());
                        System.out.println("    - UUID: " + virtualDiskBacking.getUuid());
                        System.out.println("    - Delta Grain Size: " + virtualDiskBacking.getDeltaGrainSize());
                        System.out.println("    - Digest Enabled: " + virtualDiskBacking.getDigestEnabled());
                        System.out.println("    - Eagerly Scrub: " + virtualDiskBacking.getEagerlyScrub());
                        System.out.println("    - Split: " + virtualDiskBacking.getSplit());
                        System.out
                                .println("    - Thin Provisioned: " + virtualDiskBacking.getThinProvisioned());
                        System.out.println("    - Write Through: " + virtualDiskBacking.getWriteThrough());

                    }
                    //com.vmware.vim25.VirtualDiskFlatVer2BackingInfo
                    //System.out.println("  - Backing Class: "+virtualDisk.getBacking().getClass());
                }
            }

            System.out.println("\n===========================");
            System.out.println("======== Datastore ========");
            System.out.println("===========================");
            System.out.println("- Datastore Information");
            if (vm.getDatastores() != null) {
                for (Datastore ds : vm.getDatastores()) {
                    System.out.println(" - Datastore: " + ds.getName());
                }
            }

        }

    }

    /*      
          if (vm.getGuestInfo()!=null && vm.getGuestInfo().getIpStack()!=null && vm.getGuestInfo().getIpStack().length>0)
          {
             GuestStackInfo[] arrayOfGuestStackInfos=null;
                     
             arrayOfGuestStackInfos=vm.getGuestInfo().getIpStack();
                     
             for (GuestStackInfo guestStackInfo:arrayOfGuestStackInfos)
             {
    System.out.println("Internet Protocol stack as configured in the guest operating system");
    System.out.println("");
    System.out.println("");
            
    if (guestStackInfo.getIpRouteConfig()!=null && guestStackInfo.getIpRouteConfig().getIpRoute()!=null && guestStackInfo.getIpRouteConfig().getIpRoute().length>0)
    {
       for (NetIpRouteConfigInfoIpRoute netIpRouteConfigInfoIpRoute:guestStackInfo.getIpRouteConfig().getIpRoute())
       {
          System.out.println("Gateway: "+netIpRouteConfigInfoIpRoute.getGateway().getIpAddress());
       }
    }
            
             }
                     
          }
    */

    /*
            
    if (!vm.getGuest().getListOfNetworkAdapter().isEmpty())
    {
       //GuestInfo guestInfo_=vmConfiguration.getGuestInfo().getGuestInfoo();
       //System.out.println("IPSTACK: "+guestInfo_);
       //System.out.println("IPSTACK: "+guestInfo_.getIpStack());
               
               
               
       int nbGuestnicInfo=1;
       for (GuestNic guestNic:vm.getGuest().getListOfNetworkAdapter())
       {
    System.out.println("    - Network Adapter n"+nbGuestnicInfo++);
    System.out.println("      - Connected: "+guestNic.isConnected());
    System.out.println("      - DeviceConfig Id: "+guestNic.getDeviceConfigId());
    System.out.println("      - Network: "+guestNic.getNetwork());
    System.out.println("      - Network ID: "+guestNic.getNetworkID());
    if (!guestNic.getListOfIPAddress().isEmpty())
    {
       System.out.println("      - IP Address:");
               
       for (String ip:guestNic.getListOfIPAddress())
       {
          System.out.println("        - "+ip);
       }
               
    }
    System.out.println("      - Mac Address: "+guestNic.getMacAddress());
    if (guestNic.getDnsConfig()!=null)
    {
       System.out.println("      - DNS Config:");
       System.out.println("        - Dhcp: "+guestNic.getDnsConfig().isDhcp());
       System.out.println("        - Domain Name: "+guestNic.getDnsConfig().getDomainName());
       System.out.println("        - Host Name: "+guestNic.getDnsConfig().getHostName());
       System.out.println("        - Ip Address:");
       if (!guestNic.getDnsConfig().getIpAddress().isEmpty())
       {
          for (String ipAddress:guestNic.getDnsConfig().getIpAddress())
          {
             System.out.println("          - "+ipAddress);
          }
       }
       System.out.println("        - Search Domain:");
       if (!guestNic.getDnsConfig().getSearchDomain().isEmpty())
       {
          for (String searchDomain:guestNic.getDnsConfig().getSearchDomain())
          {
             System.out.println("          - "+searchDomain);
          }
       }
            
       System.out.println("");
            
    }
            
    if (guestNic.getIpConfig()!=null)
    {
       System.out.println("      - IP Config:");
       System.out.println("        - autoConfigurationEnabled: "+guestNic.getIpConfig().isAutoConfigurationEnabled());
    }
            
            
       }
    }
            
    */

    System.out.println("");
    System.out.println("");

    VirtualMachine vm = vmManager.getVmByName(hostName, "VFOD-TEST-01");
    listOfMorIDs.clear();
    listOfMorIDs.add(vm.getMor().get_value());
    inventory.getVirtualMachinePropertiesExFromIDs(listOfMorIDs);

    //VirtualDevice[] listOfVirtualDevice=vm.getVirtualDeviceManager().getAllVirtualDevices();
    VirtualDevice[] listOfVirtualDevice = vm.getVirtualDeviceManager().getListOfVirtualDevices();
    int nbDevice = 1;
    VirtualEthernetCard virtualEthernetCard = null;
    VirtualController virtualController = null;

    for (VirtualDevice device : listOfVirtualDevice) {
        System.out.println("Device n" + nbDevice++);
        System.out.println("- Device: " + device);
        System.out.println("- Device Class: " + device.getClass());
        if (device.getBacking() != null) {
            System.out.println("- Backing Device Class: " + device.getBacking().getClass());

            if (device.getBacking() instanceof com.vmware.vim25.VirtualDiskFlatVer2BackingInfo) {
                com.vmware.vim25.VirtualDiskFlatVer2BackingInfo backingInfo = (com.vmware.vim25.VirtualDiskFlatVer2BackingInfo) device
                        .getBacking();
                System.out.println(" - FileName: " + backingInfo.getFileName());
            }
        }
        System.out.println("- Device Super Class: " + device.getClass().getSuperclass());
        System.out.println("- Key    : " + device.getKey());
        System.out.println("- ControllerKey: " + device.getControllerKey());
        if (device.getSlotInfo() != null
                && device.getSlotInfo() instanceof com.vmware.vim25.VirtualDevicePciBusSlotInfo) {
            System.out.println("- Slot number: "
                    + ((com.vmware.vim25.VirtualDevicePciBusSlotInfo) device.getSlotInfo()).getPciSlotNumber());
        }
        System.out.println("- Label  : " + device.getDeviceInfo().getLabel());
        System.out.println("- Summary: " + device.getDeviceInfo().getSummary());
        System.out.println("- Unit Number: " + device.getUnitNumber());

        if (device instanceof com.vmware.vim25.VirtualSCSIController) {
            VirtualSCSIController virtualSCSIController = (VirtualSCSIController) device;
            System.out.println("- Scsi Ctlr Unit Number: " + virtualSCSIController.getScsiCtlrUnitNumber());
            System.out.println("- Bus Number: " + virtualSCSIController.getBusNumber());
        }

        if (device instanceof com.vmware.vim25.VirtualLsiLogicSASController) {
            VirtualLsiLogicSASController virtualLsiLogicSASController = (VirtualLsiLogicSASController) device;
            System.out.println(
                    "- Scsi Ctlr Unit Number: " + virtualLsiLogicSASController.getScsiCtlrUnitNumber());
            System.out.println("- Bus Number: " + virtualLsiLogicSASController.getBusNumber());
        }

        if (device.getClass().getSuperclass().equals(com.vmware.vim25.VirtualEthernetCard.class)
                || device.getClass().getSuperclass().equals(com.vmware.vim25.VirtualVmxnet.class)) {
            virtualEthernetCard = (VirtualEthernetCard) device;
            System.out.println("- Device Class: " + device.getClass());
            System.out.println("- Device Super Class: " + device.getClass().getSuperclass());
            System.out.println("- virtualEthernetCard Class: " + virtualEthernetCard.getClass());
            System.out.println("  - AddressType: " + virtualEthernetCard.getAddressType());
            System.out.println("  - MacAddress: " + virtualEthernetCard.getMacAddress());
            System.out.println("  - WakeOnLanEnabled: " + virtualEthernetCard.getWakeOnLanEnabled());
            System.out.println("  - Backing Info: " + virtualEthernetCard.getBacking().getClass());

            if (virtualEthernetCard
                    .getBacking() instanceof com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo) {
                VirtualEthernetCardNetworkBackingInfo virtualEthernetCardNetworkBackingInfo = (VirtualEthernetCardNetworkBackingInfo) virtualEthernetCard
                        .getBacking();
                System.out.println("  - Backing Info: " + virtualEthernetCard.getBacking().getClass());
                System.out
                        .println("    - Device Name: " + virtualEthernetCardNetworkBackingInfo.getDeviceName());
                System.out.println(
                        "    - Use AutoDetect: " + virtualEthernetCardNetworkBackingInfo.getUseAutoDetect());
                System.out.println(
                        "    - inPassthroughMode: " + virtualEthernetCardNetworkBackingInfo.inPassthroughMode);
                System.out.println(
                        "    - Network: " + virtualEthernetCardNetworkBackingInfo.getNetwork().get_value());

            }

            if (virtualEthernetCard.getBacking().getClass()
                    .equals(com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo.class)) {
                VirtualEthernetCardDistributedVirtualPortBackingInfo backing = (VirtualEthernetCardDistributedVirtualPortBackingInfo) virtualEthernetCard
                        .getBacking();
                System.out.println("  - Backing Info: " + virtualEthernetCard.getBacking().getClass());
                System.out.println("    - PortgroupKey: " + backing.getPort().getPortgroupKey());
                System.out.println("    - PortKey: " + backing.getPort().getPortKey());
                System.out.println("    - SwitchUuid: " + backing.getPort().getSwitchUuid());
            }
            //

        }

        if (device.getConnectable() != null) {
            System.out.println("- allowGuestControl: " + device.getConnectable().isAllowGuestControl());
            System.out.println("- connected: " + device.getConnectable().isConnected());
            System.out.println("- startConnected: " + device.getConnectable().isStartConnected());
            if (device.getConnectable().getStatus() != null)
                System.out.println("- status: " + device.getConnectable().getStatus());

        }

        if (device.getClass().getSuperclass().equals(com.vmware.vim25.VirtualController.class)) {
            virtualController = (VirtualController) device;
            if (virtualController.getDevice() != null && virtualController.getDevice().length > 0) {
                String devicesControlled = "- Devices Controlled: ";
                String keys = "";
                for (int deviceKey : virtualController.getDevice()) {
                    keys = deviceKey + "," + keys;
                }

                keys = keys.substring(0, keys.length() - 1);
                System.out.println(devicesControlled + keys);
            }
        }

    } // Fin boucle sur les perihpriques d'une VM

    //System.out.println("Taille disk: "+vm.getHardware().getTotalDiskSpace());

    /*
    WS ws=wsManager.getWS(vmWareHostName);
    ManagedObjectReference mor=null;
    mor=MorManager.getMorRef(ws, ws.getVIMService().getRootFolder(), "VirtualMachine", "ActiBox05");
            
    System.out.println("mor: "+mor.get_value());
            
    ArrayList<VirtualMachine> listOfVM=inventoryMng.getAllVM(vmWareHostName);
    for (VirtualMachine vm_:listOfVM)
    {
       System.out.println("vm: "+vm_.getName()+" / "+vm_.getMor().get_value());
    }
    */

    /*
    vm=vmManager.getVmByName(vmWareHostName, "ActiBox05");
    System.out.println("VirtualMachine: "+vm.getName());
    System.out.println("-CPU Reservation: "+vm.getConfiguration().getVirtualCPU().getReservation());
    System.out.println("-CPU Limit: "+vm.getConfiguration().getVirtualCPU().getLimit());
    System.out.println("-CPU: "+vm.getConfiguration().getVirtualCPU().getMghz());
            
    System.out.println("-Memory Reservation: "+vm.getConfiguration().getVirtualMemory().getReservation());
    System.out.println("-Memory Limit: "+vm.getConfiguration().getVirtualMemory().getLimit());
    System.out.println("-Memory: "+vm.getConfiguration().getVirtualMemory().getMemorySize());
    */

    //Host host=vm.getHost();
    //System.out.println("Host Name: "+host.getName());
    //vm.getHardware().getAlldevices();

    //vmManager.configureVMMemory("ActiBox05", 256L);

    //vm.replaceNetwork("network-14");
    //vm.addNetwork("network-14");
    //vm.removeNetwork("network-14");
    //vmManager.updateNetwork("ActiBox05", "networkID");

    //vm.setNetwork();

    /*
    ArrayList<Network> listOfNetwork=host.getNetworks();
            
    for (Network network:listOfNetwork)
    {
       System.out.println("Network Name: "+network.getName());
       System.out.println("Network ID: "+network.getMor().get_value());
    }
    */

    //HardwareDevice hardware=vm.getHardware();
    //ArrayList<VirtualNetwork> listOfVirtualNetwork=hardware.getNetworks();
    //VirtualNetwork virtualNetwork=listOfVirtualNetwork.get(0);
    //virtualNetwork.getvDevice().getBacking().

    /*
    ArrayList<Network> listOfNet=vm.getAvailableNetwork();
            
    for (Network network:listOfNet)
    {
       System.out.println("Network: "+network.getName());
    }
    */

    /*
    try
    {
       System.in.read();
    }
    catch (IOException e)
            
    {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }
     */

    //AuthorizationManager authorManager=AuthorizationManager.getInstance();
    //authorManager.addPermission("SIVEO\\TestGP", true,"test2", "VMSuperPowerUser","vcenter.siveo.net");

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================

    VMware.delete(hostName);
}

From source file:com.oneapm.base.SparkAggregation.java

public static void main(String[] args) throws IOException {

    String configfile = "alert.cnf";

    final FlowConstant flowConstant = new FlowConstant();

    Properties config = null;/*  w ww  .  j ava 2 s .  co m*/

    try {
        config = getConfig(configfile);

    } catch (IOException e) {
        LOG.error(configfile + " doesnt exist in /etc/analysis/... exit" + e);
        System.exit(-1);
    }

    final int window = Integer.parseInt(config.getProperty("time.window", "60"));

    final List<String> percent = Arrays.asList("tryConnectPer", "cBitpacketAccount", "abortConntionCount",
            "unidirectionalTrafficPer");

    final List<String> jsonList = new ArrayList<>();

    final Map<String, Tuple2<String, Integer>> stats = new HashMap<String, Tuple2<String, Integer>>();

    final Map<ClientKey, BaseData> broadClient = new HashMap<ClientKey, BaseData>();

    final Map<HostKey, BaseData> broadHost = new HashMap<HostKey, BaseData>();

    final Map<ServiceKey, BaseData> broadService = new HashMap<ServiceKey, BaseData>();

    final Map<SubnetKey, BaseData> broadSubnet = new HashMap<SubnetKey, BaseData>();

    final Map<VlanKey, BaseData> broadVlan = new HashMap<VlanKey, BaseData>();

    final String URL = config.getProperty("alert.url");

    final String HEART_BEAT = config.getProperty("alert.heartbeat");

    final String RECOVER = config.getProperty("alert.recover");

    ZookeeperConfigWatcher.startZookeeperWatcherService(getConfig("alert.cnf").getProperty("kafaka.zoo"),
            "/ni/site", new SiteConvertImpl(flowConstant));
    ZookeeperConfigWatcher.startZookeeperWatcherService(getConfig("alert.cnf").getProperty("kafaka.zoo"),
            "/ni/net", new NetConvertImpl(flowConstant));
    ZookeeperConfigWatcher.startZookeeperWatcherService(getConfig("alert.cnf").getProperty("kafaka.zoo"),
            "/ni/vlan_sflow", new LinkConvertImpl(flowConstant));
    ZookeeperConfigWatcher.startZookeeperWatcherService(getConfig("alert.cnf").getProperty("kafaka.zoo"),
            "/ni/subnet", new SubnetConvertImpl(flowConstant));

    zookeeperClient.connectZookeeper(config.getProperty("kafaka.zoo"));

    esGet.setNodeClient();

    startZookeeperService(flowConstant, zookeeperClient);

    zookeeperClient.setRules("/ni/caution");

    JavaPairReceiverInputDStream<String, byte[]> rawStream = setupRawStreamFromKafka(config,
            config.getProperty("group.id", "oneapm-alert"));

    LOG.info("alert config:" + config.toString());

    final Broadcast<IPDataInfo> ipDataBroadcastInfo = getJsc().sparkContext().broadcast(new IPDataInfo());

    final Broadcast<ProtocalTypeInfo> protocalTypeBroadcastInfo = getJsc().sparkContext()
            .broadcast(new ProtocalTypeInfo());

    JavaPairDStream<TimeAgg, BeforeAgg> aggJavaPairDStream = rawStream
            .mapToPair(new PairFunction<Tuple2<String, byte[]>, TimeAgg, BeforeAgg>() {
                private static final long serialVersionUID = -2751318332921803477L;

                @Override
                public Tuple2<TimeAgg, BeforeAgg> call(Tuple2<String, byte[]> stringTuple2) throws Exception {
                    String[] s = TAB.split(new String(stringTuple2._2));
                    String clientIP = s[1];
                    String serverIP = s[2];
                    TimeAgg timeAgg = new TimeAgg();
                    BeforeAgg beforeAgg = new BeforeAgg();
                    timeAgg.setServer_ip(serverIP);
                    if (s.length >= 60) {
                        //setProtocal_type
                        if (!"-".equals(s[11]) && !"".equals(s[11])) {
                            timeAgg.setProtocal_type(s[11]);
                        } else {
                            if ("TCP".equals(s[12])) {
                                ProtocalTypeInfo protocalTypeInfo = protocalTypeBroadcastInfo.value();
                                String protocalType = protocalTypeInfo.config.getProperty(s[4]);

                                if (protocalType != null) {
                                    timeAgg.setProtocal_type(protocalType);
                                } else {
                                    timeAgg.setProtocal_type("TCP_" + s[4]);
                                }
                            } else {
                                timeAgg.setProtocal_type(s[12]);
                            }
                        }

                        timeAgg.setType("tcp");

                        //setVlan_id
                        String vlanLinkAlias = flowConstant.VLAN_LINK.get(s[13]);
                        String portLinkAlias = flowConstant.PROBE_POTR_MAP.get(s[0] + "_" + s[15]);
                        if (flowConstant.PROBE_HOST_ENABLE) {
                            if (portLinkAlias != null) {
                                timeAgg.setVlan_id(portLinkAlias);
                            } else {
                                timeAgg.setVlan_id(s[0] + "-nic" + s[15]);
                            }
                        } else if (flowConstant.VLAN_LINK_ENABLE) {
                            if (vlanLinkAlias != null) {
                                timeAgg.setVlan_id(vlanLinkAlias);
                            } else {
                                timeAgg.setVlan_id(s[13]);
                            }
                        } else {
                            timeAgg.setVlan_id("Vlan" + s[13]);
                        }

                        if (!"-".equals(s[6])) {
                            timeAgg.setTimestamp(format.format((long) Double.parseDouble(s[6]) * 1000));
                        } else {
                            timeAgg.setTimestamp(s[6]);
                        }

                        if (!"-".equals(s[7])) {
                            timeAgg.setTimeEnd(format.format((long) Double.parseDouble(s[7]) * 1000));
                        } else {
                            timeAgg.setTimeEnd(s[7]);
                        }

                        beforeAgg.setPacket_size(Double.parseDouble(s[55]) + Double.parseDouble(s[56]));

                        beforeAgg.setC_packet_size(Double.parseDouble(s[55]));

                        beforeAgg.setS_packet_size(Double.parseDouble(s[56]));

                        beforeAgg.setPacket_count(Double.parseDouble(s[59]) + Double.parseDouble(s[60]));

                        beforeAgg.setLosspacket_count(Double.parseDouble(s[33]) + Double.parseDouble(s[39])
                                + Double.parseDouble(s[35]) + Double.parseDouble(s[41]));

                        double cRto = (Double.valueOf(s[19]) + Double.valueOf(s[21]) + Double.valueOf(s[23]))
                                * 1000;
                        double sRto = (Double.valueOf(s[20]) + Double.valueOf(s[22]) + Double.valueOf(s[24]))
                                * 1000;

                        beforeAgg.setTotal_rto(cRto + sRto);

                        //   ?/TCP????/TCP????/TCP?MTU?MTU/TCP?

                        beforeAgg.setInt_ZWIN_COUNT(Double.parseDouble(s[43]));
                        beforeAgg.setInt_OOR_COUNT(Double.parseDouble(s[46]));
                        beforeAgg.setInt_CONGEST_COUNT(Double.parseDouble(s[47]));
                        beforeAgg.setMTU(Double.parseDouble(s[61]) + Double.parseDouble(s[62]));

                        Boolean hasSynFlag = Boolean.valueOf(s[5]);
                        timeAgg.setHasSyn(hasSynFlag);
                        timeAgg.setBool_FIN(Boolean.valueOf(s[25]));
                        timeAgg.setBool_RST(Boolean.valueOf(s[26]));
                        if (hasSynFlag && "-".equals(s[9])) {
                            beforeAgg.setAbort(1);
                        } else {
                            beforeAgg.setAbort(0);
                        }

                        beforeAgg.setTcpTurns(Integer.parseInt(s[30])); //int_TURN_COUNT
                        beforeAgg.setConnrequest_count(Double.parseDouble(s[48]));
                        beforeAgg.setsAbortConnCount(Integer.valueOf(s[50]));

                        Long cPayLoad = Long.valueOf(s[53]);
                        Long sPayLoad = Long.valueOf(s[54]);
                        long payLoad = cPayLoad + sPayLoad;

                        double sessionJlRtt = 0;

                        if (!"-".equals(s[9])) {
                            sessionJlRtt = Double.valueOf(s[9]) * 1000;
                            beforeAgg.setRtt(sessionJlRtt);
                            beforeAgg.setServerJlRttCount(1);
                            beforeAgg.setClientJlRttCount(1);
                        }

                        if (hasSynFlag && !"-".equals(s[9])) {
                            beforeAgg.setCount(1);
                            if ("true".equals(s[26]) && payLoad == 0) {
                                beforeAgg.setCount(0);
                            }
                        }

                        if (!"-".equals(s[10])) {
                            double clientJlRtt = Double.valueOf(s[10]) * 1000;
                            double serverJlRtt = sessionJlRtt - clientJlRtt;

                            if (clientJlRtt < sessionJlRtt) {
                                beforeAgg.setServer_rtt(clientJlRtt);
                                beforeAgg.setClient_rtt(serverJlRtt);
                            } else {
                                beforeAgg.setServer_rtt(sessionJlRtt / 2);
                                beforeAgg.setClient_rtt(sessionJlRtt / 2);
                            }
                        }

                        if (beforeAgg.tcpTurns > 0) {
                            beforeAgg.setSessionCount(1);
                            if (Double.parseDouble(s[18]) > 0) {
                                beforeAgg.setServer_reponsetime(
                                        Double.parseDouble(s[18]) / beforeAgg.tcpTurns * 1000);
                            }
                            if (Double.parseDouble(s[16]) > 0) {
                                beforeAgg.setResponseTransmissionTime(
                                        Double.parseDouble(s[16]) / beforeAgg.tcpTurns * 1000);
                            }
                            if (Double.parseDouble(s[17]) > 0) {
                                beforeAgg.setRequestTransmissionTime(
                                        Double.parseDouble(s[17]) / beforeAgg.tcpTurns * 1000);
                            }
                            if (beforeAgg.total_rto > 0) {
                                beforeAgg.setTotal_rto(beforeAgg.getTotal_rto() / beforeAgg.tcpTurns);
                            }

                            beforeAgg.setUserResponseTime(
                                    beforeAgg.getRtt() + beforeAgg.getRequestTransmissionTime()
                                            + beforeAgg.getResponseTransmissionTime()
                                            + beforeAgg.getServer_reponsetime() + beforeAgg.total_rto);

                        } else {
                            beforeAgg.setServer_reponsetime(0);
                            beforeAgg.setResponseTransmissionTime(0);
                            beforeAgg.setRequestTransmissionTime(0);
                            beforeAgg.setTotal_rto(0);
                            beforeAgg.setUserResponseTime(0);
                        }

                        beforeAgg.setC_bitpacket_account(Double.parseDouble(s[57]) + Double.parseDouble(s[58]));

                    } else if (s.length <= 28) {
                        if (!"-".equals(s[8]) && !"".equals(s[8])) {
                            timeAgg.setProtocal_type(s[8]);
                        } else {
                            if ("UDP".equals(s[9])) {
                                ProtocalTypeInfo protocalTypeInfo = protocalTypeBroadcastInfo.value();
                                String protocalType = protocalTypeInfo.config.getProperty(s[4]);

                                if (protocalType != null) {
                                    timeAgg.setProtocal_type(protocalType);
                                } else {
                                    timeAgg.setProtocal_type("UDP");
                                }
                            } else {
                                timeAgg.setProtocal_type(s[9]);
                            }
                        }

                        beforeAgg.setCount(0);
                        timeAgg.setType("udp");

                        timeAgg.setHasSyn(false);
                        timeAgg.setBool_FIN(false);
                        timeAgg.setBool_RST(false);

                        //setVlan_id
                        String vlanLinkAlias = flowConstant.VLAN_LINK.get(s[12]);
                        String portLinkAlias = flowConstant.PROBE_POTR_MAP.get(s[0] + "_" + s[10]);
                        if (flowConstant.PROBE_HOST_ENABLE) {
                            if (portLinkAlias != null) {
                                timeAgg.setVlan_id(portLinkAlias);
                            } else {
                                timeAgg.setVlan_id(s[0] + "-nic" + s[10]);
                            }
                        } else if (flowConstant.VLAN_LINK_ENABLE) {
                            if (vlanLinkAlias != null) {
                                timeAgg.setVlan_id(vlanLinkAlias);
                            } else {
                                timeAgg.setVlan_id(s[12]);
                            }
                        } else {
                            timeAgg.setVlan_id("Vlan" + s[12]);
                        }

                        if (!"-".equals(s[5])) {
                            timeAgg.setTimestamp(format.format((long) Double.parseDouble(s[5]) * 1000));
                        } else {
                            timeAgg.setTimestamp(s[5]);
                        }

                        if (!"-".equals(s[6])) {
                            timeAgg.setTimeEnd(format.format((long) Double.parseDouble(s[6]) * 1000));
                        } else {
                            timeAgg.setTimeEnd(s[6]);
                        }

                        beforeAgg.setPacket_size(Double.parseDouble(s[20]) + Double.parseDouble(s[21]));
                        beforeAgg.setPacket_count(Double.parseDouble(s[24]) + Double.parseDouble(s[25]));

                        beforeAgg.setC_packet_size(Double.parseDouble(s[20]));
                        beforeAgg.setS_packet_size(Double.parseDouble(s[21]));

                        beforeAgg.setInt_ZWIN_COUNT(0);
                        beforeAgg.setInt_OOR_COUNT(0);
                        beforeAgg.setInt_CONGEST_COUNT(0);
                        beforeAgg.setMTU(0);

                        beforeAgg.setC_bitpacket_account(Double.parseDouble(s[22]) + Double.parseDouble(s[23]));
                        beforeAgg.setAbort(0);
                        beforeAgg.setClient_rtt(0);
                        beforeAgg.setServer_rtt(0);
                        beforeAgg.setRtt(0);
                        beforeAgg.setServerJlRttCount(0);
                        beforeAgg.setClientJlRttCount(0);
                        beforeAgg.setLosspacket_count(0);
                        beforeAgg.setServer_reponsetime(0);
                        beforeAgg.setTcpTurns(0);
                        beforeAgg.setConnrequest_count(0);
                        beforeAgg.setTotal_rto(0);
                        beforeAgg.setUserResponseTime(0);
                        beforeAgg.setResponseTransmissionTime(0);
                        beforeAgg.setRequestTransmissionTime(0);
                        beforeAgg.setServer_reponsetime(0);
                        beforeAgg.setsAbortConnCount(0);
                        beforeAgg.setSessionCount(0);
                    }

                    String sInOutFlag = IPUtils.isInHomeNet(serverIP, flowConstant.HOMENET);
                    String cInOutFlag = IPUtils.isInHomeNet(clientIP, flowConstant.HOMENET);
                    //setSubnet
                    if ("IN".equals(sInOutFlag)) {
                        String sSubNet = IPUtils.getSubNet(serverIP, flowConstant.NETMASK);
                        timeAgg.setSubnet(sSubNet + "/" + flowConstant.MASKBITS);
                    } else {
                        timeAgg.setSubnet("-");
                    }

                    if ("255.255.255.255".equals(clientIP)) {
                        timeAgg.setClient_site("-");
                    } else {
                        String clientSiteInfo = IPUtils.getSiteInfo(clientIP, flowConstant.SITEINFO_MAP);
                        IPDataInfo ipDataInfo = ipDataBroadcastInfo.getValue();
                        if (clientSiteInfo != null) {
                            String[] clientSiteInfos = clientSiteInfo.split("_", 3);
                            timeAgg.setClient_site(clientSiteInfos[2]);
                        } else {
                            if ("IN".equals(cInOutFlag)) {
                                timeAgg.setClient_site("");
                            } else {
                                if (ipDataInfo != null) {
                                    String[] ipinfo = ipDataInfo.find(clientIP);

                                    //
                                    if (ipinfo.length < 3) {
                                        timeAgg.setClient_site("");
                                    } else {
                                        if ("".equals(ipinfo[0])) {
                                            timeAgg.setClient_site("");
                                        } else {
                                            //,areasite
                                            if ("".equals(ipinfo[1])) {
                                                ipinfo[1] = ipinfo[0];
                                            }
                                            if ("".equals(ipinfo[2])) {
                                                ipinfo[2] = ipinfo[1];
                                            }
                                            timeAgg.setClient_site(ipinfo[2]);
                                        }
                                    }
                                } else {
                                    timeAgg.setClient_site("?");
                                }
                            }
                        }
                    }

                    return new Tuple2<>(timeAgg, beforeAgg);

                }
            }).filter(new Function<Tuple2<TimeAgg, BeforeAgg>, Boolean>() {
                @Override
                public Boolean call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception {
                    return !v1._1.getTimestamp().equals("-") && !v1._1.getTimestamp().equals("");
                }
            });

    //        aggJavaPairDStream.foreachRDD(new Function<JavaPairRDD<TimeAgg, BeforeAgg>, Void>() {
    //            @Override
    //            public Void call(JavaPairRDD<TimeAgg, BeforeAgg> v1) throws Exception {
    //                if (Boolean.parseBoolean(getConfig("alert.cnf").getProperty("save.es")) && v1 != null) {
    //                    JavaRDD<Map<String, ?>> es = v1.map(new Function<Tuple2<TimeAgg, BeforeAgg>, Map<String,
    //                            ?>>() {
    //
    //                        @Override
    //                        public Map<String, ?> call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception {
    //                            ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
    //
    //                            TimeAgg a = v1._1;
    //                            BeforeAgg b = v1._2;
    //                            String todayStr = sdf.format(format.parse(a.getTimestamp()));
    //                            builder.put("server_ip", a.server_ip);
    //                            builder.put("protocal_type", a.protocal_type);
    //                            builder.put("client_site", a.client_site);
    //                            builder.put("vlan_id", a.vlan_id);
    //                            builder.put("subnet", a.subnet);
    //                            builder.put("timestamp", format.parse(a.timestamp));
    //                            if (b.packet_size > 0) {
    //                                builder.put("packet_size", b.packet_size);
    //                            }
    //                            if (b.c_packet_size > 0) {
    //                                builder.put("c_packet_size", b.c_packet_size);
    //                            }
    //
    //                            if (b.packet_count > 0) {
    //                                builder.put("packet_count", b.packet_count);
    //                            }
    //
    //                            if (b.losspacket_count > 0) {
    //                                builder.put("losspacket_count", b.losspacket_count);
    //                            }
    //                            if (b.total_rto > 0) {
    //                                builder.put("total_rto", b.total_rto);
    //                                builder.put("rtoCount", b.rtoCount);
    //                            }
    //
    //
    //                            if (b.tcpTurns > 0) {
    //                                builder.put("tcpTurns", b.tcpTurns);
    //                            }
    //                            if (b.connrequest_count > 0) {
    //                                builder.put("connrequest_count", b.connrequest_count);
    //                            }
    //                            if (b.abort > 0) {
    //                                builder.put("abort", b.abort);
    //                            }
    //                            if (b.client_rtt > 0) {
    //                                builder.put("client_rtt", b.client_rtt);
    //                                builder.put("clientJlRttCount", b.clientJlRttCount);
    //                            }
    //                            if (b.server_rtt > 0) {
    //                                builder.put("server_rtt", b.server_rtt);
    //                                builder.put("serverJlRttCount", b.serverJlRttCount);
    //                            }
    //
    //                            if (b.server_reponsetime > 0) {
    //                                builder.put("server_reponsetime", b.server_reponsetime);
    //                                builder.put("server_reponsetime_count", b.server_reponsetime_count);
    //                            }
    //
    //                            if (b.responseTransmissionTime > 0) {
    //                                builder.put("responseTransmissionTime", b.responseTransmissionTime);
    //                                builder.put("responseTransmissionTimeCount", b.responseTransmissionTimeCount);
    //                            }
    //                            if (b.requestTransmissionTime > 0) {
    //                                builder.put("requestTransmissionTime", b.requestTransmissionTime);
    //                                builder.put("requestTransmissionTimeCount", b.requestTransmissionTimeCount);
    //
    //                            }
    //
    //                            if (b.sAbortConnCount > 0) {
    //                                builder.put("sAbortConnCount", b.sAbortConnCount);
    //                            }
    //
    //                            if (b.userResponseTime > 0) {
    //                                builder.put("userResponseTime", b.userResponseTime);
    //                                builder.put("userResponseTimeCount", b.userResponseTimeCount);
    //                            }
    //                            if (b.c_bitpacket_account > 0) {
    //                                builder.put("c_bitpacket_account", b.c_bitpacket_account);
    //                            }
    //                            builder.put("index_name", todayStr);
    //
    //                            return builder.build();
    //                        }
    //                    }).cache();
    //                    if (es != null) {
    //                        JavaEsSpark.saveToEs(es, "ni-alert-session-{index_name}/alert", ImmutableMap.of
    //                                (ConfigurationOptions.ES_MAPPING_EXCLUDE, "index_name"));
    //                    }
    //                }
    //                return null;
    //            }
    //        });

    JavaPairDStream<TimeAgg, BeforeAgg> reduceByWindow = aggJavaPairDStream
            .reduceByKeyAndWindow(new Function2<BeforeAgg, BeforeAgg, BeforeAgg>() {
                @Override
                public BeforeAgg call(BeforeAgg v1, BeforeAgg v2) throws Exception {
                    BeforeAgg sum = new BeforeAgg();

                    sum.setPacket_size(v1.getPacket_size() + v2.getPacket_size());
                    sum.setC_packet_size(v1.getC_packet_size() + v2.getC_packet_size());
                    sum.setS_packet_size(v1.getS_packet_size() + v2.getS_packet_size());

                    sum.setPacket_count(v1.getPacket_count() + v2.getPacket_count());
                    sum.setC_packet_count(v1.getC_packet_count() + v2.getC_packet_count());
                    sum.setS_packet_count(v1.getS_packet_count() + v2.getS_packet_count());

                    sum.setLosspacket_count(v1.getLosspacket_count() + v2.getLosspacket_count());
                    sum.setTotal_rto(v1.getTotal_rto() + v2.getTotal_rto());
                    sum.setAbort(v1.getAbort() + v2.getAbort());

                    sum.setRequestTransmissionTime(
                            v1.getRequestTransmissionTime() + v2.getRequestTransmissionTime());
                    sum.setResponseTransmissionTime(
                            v1.getResponseTransmissionTime() + v2.getResponseTransmissionTime());
                    sum.setTcpTurns(v1.getTcpTurns() + v2.getTcpTurns());
                    sum.setConnrequest_count(v1.getConnrequest_count() + v2.getConnrequest_count());

                    sum.setRtt(v1.getRtt() + v2.getRtt());
                    sum.setClient_rtt(v1.getClient_rtt() + v2.getClient_rtt());
                    sum.setServer_rtt(v1.getServer_rtt() + v2.getServer_rtt());

                    sum.setServer_reponsetime(v1.getServer_reponsetime() + v2.getServer_reponsetime());
                    sum.setC_bitpacket_account(v1.getC_bitpacket_account() + v2.getC_bitpacket_account());
                    sum.setClientJlRttCount(v1.getClientJlRttCount() + v2.getClientJlRttCount());
                    sum.setServerJlRttCount(v1.getServerJlRttCount() + v2.getServerJlRttCount());
                    sum.setUserResponseTime(v1.getUserResponseTime() + v2.getUserResponseTime());
                    sum.setSessionCount(v1.sessionCount + v2.sessionCount);
                    sum.setsAbortConnCount(v1.sAbortConnCount + v2.sAbortConnCount);

                    sum.setCount(v1.getCount() + v2.getCount());

                    sum.setInt_CONGEST_COUNT(v1.int_CONGEST_COUNT + v2.int_CONGEST_COUNT);
                    sum.setInt_OOR_COUNT(v1.int_OOR_COUNT + v2.int_OOR_COUNT);
                    sum.setInt_ZWIN_COUNT(v1.int_ZWIN_COUNT + v2.int_ZWIN_COUNT);
                    sum.setMTU(v1.MTU + v2.MTU);

                    return sum;
                }
            }, Durations.seconds(300), Durations.seconds(60)).cache();

    reduceByWindow.foreachRDD(new Function<JavaPairRDD<TimeAgg, BeforeAgg>, Void>() {
        private static final long serialVersionUID = -4144342491397135515L;

        @Override
        public Void call(JavaPairRDD<TimeAgg, BeforeAgg> v1) throws Exception {

            if (v1.count() > 0) {

                /**
                 * getStartTime
                 */
                List<Long> timeList = v1.map(new Function<Tuple2<TimeAgg, BeforeAgg>, Long>() {
                    @Override
                    public Long call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception {
                        return format.parse(v1._1.getTimestamp()).getTime();
                    }
                }).distinct().collect();

                Collections.sort(timeList, new MyComparator());

                long a = timeList.get(3);

                final String time = format.format(new Date(a));

                long b = timeList.get(1);

                final String endTime = format.format(new Date(b));

                if (b > 0) {
                    JavaRDD<Map<String, ?>> active = v1
                            .filter(new Function<Tuple2<TimeAgg, BeforeAgg>, Boolean>() {
                                @Override
                                public Boolean call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception {
                                    String sInOutFlag = IPUtils.isInHomeNet(v1._1.getServer_ip(),
                                            flowConstant.HOMENET);

                                    return v1._1.getType().equals("tcp") && "IN".equals(sInOutFlag);

                                }
                            }).mapToPair(
                                    new PairFunction<Tuple2<TimeAgg, BeforeAgg>, Tuple2<String, String>, ConnectStatus>() {
                                        @Override
                                        public Tuple2<Tuple2<String, String>, ConnectStatus> call(
                                                Tuple2<TimeAgg, BeforeAgg> timeAggBeforeAggTuple2)
                                                throws Exception {
                                            ConnectStatus connectStatus = new ConnectStatus();
                                            String serverIp = timeAggBeforeAggTuple2._1.getServer_ip();
                                            String protoType = timeAggBeforeAggTuple2._1.getProtocal_type();
                                            TimeAgg a = timeAggBeforeAggTuple2._1;
                                            BeforeAgg b = timeAggBeforeAggTuple2._2;
                                            //
                                            if (format.parse(a.timestamp).getTime() == format.parse(endTime)
                                                    .getTime() && a.hasSyn) {
                                                connectStatus.setNewCreate(b.getCount());
                                            } else {
                                                connectStatus.setNewCreate(0);
                                            }

                                            //?breakreset?break
                                            if (format.parse(a.timeEnd).getTime() == format.parse(endTime)
                                                    .getTime() && (a.bool_FIN || a.bool_RST)) {
                                                connectStatus.setCloseConn(b.getCount());
                                            } else {
                                                connectStatus.setCloseConn(0);
                                            }

                                            if (format.parse(a.timestamp).getTime() <= format.parse(endTime)
                                                    .getTime()
                                                    && format.parse(a.timeEnd).getTime() > format.parse(endTime)
                                                            .getTime()
                                                    && a.hasSyn) {
                                                connectStatus.setActiveConn(b.getCount());
                                            } else if (format.parse(a.timestamp).getTime() == format
                                                    .parse(endTime).getTime()
                                                    && format.parse(a.timeEnd).getTime() == format
                                                            .parse(endTime).getTime()
                                                    && a.hasSyn) {
                                                connectStatus.setActiveConn(b.getCount());
                                            }

                                            return new Tuple2<>(new Tuple2<>(serverIp, protoType),
                                                    connectStatus);
                                        }
                                    })
                            .reduceByKey(new Function2<ConnectStatus, ConnectStatus, ConnectStatus>() {
                                @Override
                                public ConnectStatus call(ConnectStatus v1, ConnectStatus v2) throws Exception {
                                    ConnectStatus connectStatus = new ConnectStatus();
                                    connectStatus.setNewCreate(v1.newCreate + v2.newCreate);
                                    connectStatus.setActiveConn(v1.activeConn + v2.activeConn);
                                    connectStatus.setCloseConn(v1.closeConn + v2.closeConn);
                                    return connectStatus;
                                }
                            })
                            .map(new Function<Tuple2<Tuple2<String, String>, ConnectStatus>, Map<String, ?>>() {
                                @Override
                                public Map<String, ?> call(Tuple2<Tuple2<String, String>, ConnectStatus> v1)
                                        throws Exception {
                                    ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
                                    String todayStr = sdf.format(format.parse(endTime));
                                    builder.put("server_ip", v1._1._1);
                                    builder.put("protocal_type", v1._1._2);
                                    builder.put("newCreateConn", v1._2.getNewCreate());
                                    builder.put("closeConn", v1._2.getCloseConn());
                                    builder.put("activeConn", v1._2.getActiveConn());
                                    builder.put("index_name", todayStr);
                                    builder.put("timestamp", format.parse(endTime));
                                    return builder.build();
                                }
                            }).cache();

                    if (active != null) {
                        JavaEsSpark.saveToEs(active, "ni-active-conn-{index_name}/active",
                                ImmutableMap.of(ConfigurationOptions.ES_MAPPING_EXCLUDE, "index_name"));
                    }
                }

                JavaPairRDD<TimeAgg, BeforeAgg> before = v1
                        .filter(new Function<Tuple2<TimeAgg, BeforeAgg>, Boolean>() {
                            @Override
                            public Boolean call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception {
                                return v1._1.getTimestamp().equals(time);
                            }
                        });

                if (Boolean.parseBoolean(getConfig("alert.cnf").getProperty("save.es")) && before != null) {
                    JavaRDD<Map<String, ?>> es = before
                            .map(new Function<Tuple2<TimeAgg, BeforeAgg>, Map<String, ?>>() {

                                @Override
                                public Map<String, ?> call(Tuple2<TimeAgg, BeforeAgg> v1) throws Exception {
                                    ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();

                                    TimeAgg a = v1._1;
                                    BeforeAgg b = v1._2;
                                    String todayStr = sdf.format(format.parse(a.getTimestamp()));
                                    builder.put("server_ip", a.server_ip);
                                    builder.put("protocal_type", a.protocal_type);
                                    builder.put("client_site", a.client_site);
                                    builder.put("vlan_id", a.vlan_id);
                                    builder.put("subnet", a.subnet);
                                    builder.put("timestamp", format.parse(a.timestamp));
                                    if (b.packet_size > 0) {
                                        builder.put("packet_size", b.packet_size);
                                    }
                                    if (b.c_packet_size > 0) {
                                        builder.put("c_packet_size", b.c_packet_size);
                                    }

                                    builder.put("count", b.count);

                                    if (b.packet_count > 0) {
                                        builder.put("packet_count", b.packet_count);
                                    }

                                    if (b.losspacket_count > 0) {
                                        builder.put("losspacket_count", b.losspacket_count);
                                    }
                                    if (b.total_rto > 0) {
                                        builder.put("total_rto", b.total_rto);
                                    }

                                    if (b.tcpTurns > 0) {
                                        builder.put("tcpTurns", b.tcpTurns);
                                        builder.put("sessionCount", b.sessionCount);
                                    }
                                    if (b.connrequest_count > 0) {
                                        builder.put("connrequest_count", b.connrequest_count);
                                    }
                                    if (b.abort > 0) {
                                        builder.put("abort", b.abort);
                                    }
                                    if (b.client_rtt > 0) {
                                        builder.put("client_rtt", b.client_rtt);
                                        builder.put("clientJlRttCount", b.clientJlRttCount);
                                    }
                                    if (b.server_rtt > 0) {
                                        builder.put("server_rtt", b.server_rtt);
                                        builder.put("serverJlRttCount", b.serverJlRttCount);
                                    }

                                    if (b.server_reponsetime > 0) {
                                        builder.put("server_reponsetime", b.server_reponsetime);
                                    }

                                    if (b.responseTransmissionTime > 0) {
                                        builder.put("responseTransmissionTime", b.responseTransmissionTime);
                                    }
                                    if (b.requestTransmissionTime > 0) {
                                        builder.put("requestTransmissionTime", b.requestTransmissionTime);

                                    }

                                    if (b.sAbortConnCount > 0) {
                                        builder.put("sAbortConnCount", b.sAbortConnCount);
                                    }

                                    if (b.userResponseTime > 0) {
                                        builder.put("userResponseTime", b.userResponseTime);
                                    }
                                    if (b.c_bitpacket_account > 0) {
                                        builder.put("c_bitpacket_account", b.c_bitpacket_account);
                                    }
                                    builder.put("index_name", todayStr);

                                    return builder.build();
                                }
                            }).cache();

                    if (es != null) {
                        JavaEsSpark.saveToEs(es, "ni-alert-session-{index_name}/alert",
                                ImmutableMap.of(ConfigurationOptions.ES_MAPPING_EXCLUDE, "index_name"));
                    }
                }

                UrlPostMethod.urlPostMethod(HEART_BEAT, "frequency=" + window);

                rules = zookeeperClient.getRules();

                if (rules != null) {

                    ArrayList<String> flagRules = new ArrayList<String>(); //?ruleType

                    for (final RuleRecover ruleRecover : rules) {

                        final Rule rule = ruleRecover.getRule();

                        if (rule.isEnable() && !flagRules.contains(rule.getType())) { //ruleType?

                            flagRules.add(rule.getType()); //ruleType?

                            JavaPairRDD<String, AggResult> alert = before.mapToPair(
                                    new PairFunction<Tuple2<TimeAgg, BeforeAgg>, String, BeforeAgg>() {
                                        @Override
                                        public Tuple2<String, BeforeAgg> call(
                                                Tuple2<TimeAgg, BeforeAgg> timeAggBeforeAggTuple2)
                                                throws Exception {
                                            Field field1 = timeAggBeforeAggTuple2._1.getClass()
                                                    .getDeclaredField(rule.getType());
                                            field1.setAccessible(true);
                                            String result1 = (String) field1.get(timeAggBeforeAggTuple2._1);
                                            if (rule.getType().equals("server_ip")) {
                                                String sInOutFlag = IPUtils.isInHomeNet(
                                                        timeAggBeforeAggTuple2._1.getServer_ip(),
                                                        flowConstant.HOMENET);
                                                if ("IN".equals(sInOutFlag)) {
                                                    return new Tuple2<>(result1, timeAggBeforeAggTuple2._2);
                                                } else {
                                                    return new Tuple2<>(result1, null);
                                                }
                                            } else {
                                                return new Tuple2<>(result1, timeAggBeforeAggTuple2._2);
                                            }
                                        }
                                    }).filter(new Function<Tuple2<String, BeforeAgg>, Boolean>() {
                                        @Override
                                        public Boolean call(Tuple2<String, BeforeAgg> v1) throws Exception {
                                            return v1._2 != null && !v1._1.equals("") && !v1._1.equals("-");
                                        }
                                    }).reduceByKey(new Function2<BeforeAgg, BeforeAgg, BeforeAgg>() {
                                        @Override
                                        public BeforeAgg call(BeforeAgg v1, BeforeAgg v2) throws Exception {
                                            BeforeAgg sum = new BeforeAgg();
                                            sum.setPacket_size(v1.getPacket_size() + v2.getPacket_size());
                                            sum.setC_packet_size(v1.getC_packet_size() + v2.getC_packet_size());
                                            sum.setS_packet_size(v1.getS_packet_size() + v2.getS_packet_size());

                                            sum.setPacket_count(v1.getPacket_count() + v2.getPacket_count());
                                            sum.setC_packet_count(
                                                    v1.getC_packet_count() + v2.getC_packet_count());
                                            sum.setS_packet_count(
                                                    v1.getS_packet_count() + v2.getS_packet_count());

                                            sum.setLosspacket_count(
                                                    v1.getLosspacket_count() + v2.getLosspacket_count());
                                            sum.setTotal_rto(v1.getTotal_rto() + v2.getTotal_rto());
                                            sum.setAbort(v1.getAbort() + v2.getAbort());

                                            sum.setRequestTransmissionTime(v1.getRequestTransmissionTime()
                                                    + v2.getRequestTransmissionTime());
                                            sum.setResponseTransmissionTime(v1.getResponseTransmissionTime()
                                                    + v2.getResponseTransmissionTime());

                                            sum.setTcpTurns(v1.getTcpTurns() + v2.getTcpTurns());
                                            sum.setConnrequest_count(
                                                    v1.getConnrequest_count() + v2.getConnrequest_count());

                                            sum.setRtt(v1.getRtt() + v2.getRtt());
                                            sum.setClient_rtt(v1.getClient_rtt() + v2.getClient_rtt());
                                            sum.setServer_rtt(v1.getServer_rtt() + v2.getServer_rtt());

                                            sum.setServer_reponsetime(
                                                    v1.getServer_reponsetime() + v2.getServer_reponsetime());
                                            sum.setC_bitpacket_account(
                                                    v1.getC_bitpacket_account() + v2.getC_bitpacket_account());
                                            sum.setClientJlRttCount(
                                                    v1.getClientJlRttCount() + v2.getClientJlRttCount());
                                            sum.setServerJlRttCount(
                                                    v1.getServerJlRttCount() + v2.getServerJlRttCount());
                                            sum.setUserResponseTime(
                                                    v1.getUserResponseTime() + v2.getUserResponseTime());
                                            sum.setSessionCount(v1.sessionCount + v2.sessionCount);
                                            sum.setsAbortConnCount(v1.sAbortConnCount + v2.sAbortConnCount);
                                            return sum;
                                        }
                                    }).mapToPair(
                                            new PairFunction<Tuple2<String, BeforeAgg>, String, AggResult>() {
                                                @Override
                                                public Tuple2<String, AggResult> call(
                                                        Tuple2<String, BeforeAgg> stringBeforeAggTuple2)
                                                        throws Exception {
                                                    BeforeAgg before = stringBeforeAggTuple2._2;
                                                    AggResult result = new AggResult();
                                                    result.setTimestamp(time);

                                                    result.setThroughput(before.packet_size * 8 / window);
                                                    result.setS_throughput(before.s_packet_size * 8 / window);
                                                    result.setC_throughput(
                                                            before.c_bitpacket_account * 8 / window);

                                                    result.setPacketThroughput(before.packet_count / window);
                                                    result.setLossRate(before.losspacket_count
                                                            / before.packet_count * 100);
                                                    if (before.sessionCount > 0) {
                                                        result.setRetransferTime(
                                                                before.total_rto / before.sessionCount);
                                                    } else {
                                                        result.setRetransferTime(0);
                                                    }

                                                    if (before.clientJlRttCount > 0) {

                                                        result.setClientRoundTripTime(
                                                                before.client_rtt / before.clientJlRttCount);
                                                        result.setRtt(before.rtt / before.clientJlRttCount);
                                                    } else {
                                                        result.setClientRoundTripTime(0);
                                                        result.setRtt(0);
                                                    }

                                                    if (before.serverJlRttCount > 0) {
                                                        result.setServerRoundTripTime(
                                                                before.server_rtt / before.serverJlRttCount);
                                                    } else {
                                                        result.setServerRoundTripTime(0);
                                                    }

                                                    if (before.sessionCount > 0) {
                                                        result.setUserRespTime(before.getUserResponseTime()
                                                                / before.sessionCount);
                                                        result.setTransmissionTime(
                                                                (before.requestTransmissionTime
                                                                        + before.responseTransmissionTime)
                                                                        / before.sessionCount);

                                                    } else {
                                                        result.setUserRespTime(0);
                                                        result.setTransmissionTime(0);
                                                    }

                                                    if (before.sessionCount > 0) {
                                                        result.setServerRespTime(before.server_reponsetime
                                                                / before.sessionCount);
                                                    } else {
                                                        result.setServerRespTime(0);
                                                    }

                                                    result.setConnectFailedRate(before.abort / window);

                                                    //@Deprecates
                                                    result.setTryConnectPer(0);

                                                    result.setCongest_pre(before.getInt_CONGEST_COUNT()
                                                            / before.getCount() * 100);
                                                    result.setOutoforder_pre(before.getInt_OOR_COUNT()
                                                            / before.getCount() * 100);
                                                    result.setZerowindow_pre(before.getInt_ZWIN_COUNT()
                                                            / before.getCount() * 100);
                                                    result.setMTU_pre(
                                                            before.getMTU() / before.getCount() * 100);

                                                    if (before.packet_count > 0) {
                                                        result.setcBitpacketAccount(before.c_bitpacket_account
                                                                / before.packet_count * 100);
                                                    } else {
                                                        result.setcBitpacketAccount(0);
                                                    }

                                                    if (before.connrequest_count - before.abort > 0) {
                                                        result.setAbortConntionCount(before.sAbortConnCount
                                                                / (before.connrequest_count - before.abort)
                                                                * 100);
                                                    } else {
                                                        result.setAbortConntionCount(0);
                                                    }

                                                    return new Tuple2<>(stringBeforeAggTuple2._1, result);
                                                }
                                            })
                                    .cache();

                            if (alert.count() > 0) {

                                List<String> alertList = new ArrayList<>();

                                for (final RuleRecover newRule : rules) {
                                    final Rule sameRule = newRule.getRule();
                                    if (Boolean.parseBoolean(getConfig("alert.cnf").getProperty("save.es"))) {
                                        System.out.println(
                                                "rule:" + sameRule.toString() + "--------------");
                                    }

                                    final int recover = newRule.getRecover();

                                    if (sameRule.isEnable()
                                            && sameRule.getType().equals(flagRules.get(flagRules.size() - 1))) {
                                        if (!sameRule.getThresholdErrType().equals("absolute")) {
                                            if (esGet.getClient() == null) {
                                                esGet.setNodeClient();
                                            }

                                            final Calendar now = Calendar.getInstance();

                                            now.setTime(format.parse(time));

                                            int minute = now.get(Calendar.MINUTE);

                                            Key key = null;

                                            switch (sameRule.getType()) {
                                            case "server_ip":
                                                if (minute % 5 != 0) {
                                                    now.set(Calendar.MINUTE, minute / 5 * 5);
                                                    if (broadHost.isEmpty()) {
                                                        Map<HostKey, BaseData> service = esGet
                                                                .setHost(now.getTime(), "ni-base-hostname");
                                                        broadHost.putAll(service);
                                                    }
                                                } else {
                                                    Map<HostKey, BaseData> service = esGet
                                                            .setHost(now.getTime(), "ni-base-hostname");
                                                    broadHost.clear();
                                                    broadHost.putAll(service);
                                                }
                                                key = new HostKey();
                                                //                                                        baseData = broadHost.get(key);
                                                break;
                                            case "protocal_type":
                                                if (minute % 5 != 0) {
                                                    now.set(Calendar.MINUTE, minute / 5 * 5);
                                                    if (broadService.isEmpty()) {
                                                        Map<ServiceKey, BaseData> service = esGet
                                                                .setService(now.getTime(), "ni-base-service");
                                                        broadService.putAll(service);
                                                    }
                                                } else {
                                                    Map<ServiceKey, BaseData> service = esGet
                                                            .setService(now.getTime(), "ni-base-service");
                                                    broadService.clear();
                                                    broadService.putAll(service);
                                                }
                                                key = new ServiceKey();
                                                //                                                        key.setKeyWord(stringAggResultTuple2._1);
                                                //                                                        key.setStart_timestamp(now.getTime());
                                                //                                                        baseData = broadService.get(key);
                                                break;
                                            case "client_site":
                                                if (minute % 5 != 0) {
                                                    now.set(Calendar.MINUTE, minute / 5 * 5);
                                                    if (broadClient.isEmpty()) {
                                                        Map<ClientKey, BaseData> service = esGet
                                                                .setClient(now.getTime(), "ni-base-clientsite");
                                                        broadClient.putAll(service);
                                                    }
                                                } else {
                                                    Map<ClientKey, BaseData> service = esGet
                                                            .setClient(now.getTime(), "ni-base-clientsite");
                                                    broadClient.clear();
                                                    broadClient.putAll(service);
                                                }
                                                key = new ClientKey();
                                                //                                                        key.setKeyWord(stringAggResultTuple2._1);
                                                //                                                        key.setStart_timestamp(now.getTime());
                                                //                                                        baseData = broadClient.get(key);
                                                break;
                                            case "vlan_id":
                                                if (minute % 5 != 0) {
                                                    now.set(Calendar.MINUTE, minute / 5 * 5);
                                                    if (broadVlan.isEmpty()) {
                                                        Map<VlanKey, BaseData> service = esGet
                                                                .setVlan(now.getTime(), "ni-base-link");
                                                        broadVlan.putAll(service);
                                                    }
                                                } else {
                                                    Map<VlanKey, BaseData> service = esGet
                                                            .setVlan(now.getTime(), "ni-base-link");
                                                    broadVlan.clear();
                                                    broadVlan.putAll(service);
                                                }
                                                key = new VlanKey();
                                                //                                                        key.setKeyWord(stringAggResultTuple2._1);
                                                //                                                        key.setStart_timestamp(now.getTime());
                                                //                                                        baseData = broadVlan.get(key);
                                                break;
                                            case "subnet":
                                                if (minute % 5 != 0) {
                                                    now.set(Calendar.MINUTE, minute / 5 * 5);
                                                    if (broadSubnet.isEmpty()) {
                                                        Map<SubnetKey, BaseData> service = esGet
                                                                .setSubnet(now.getTime(), "ni-base-subnet");
                                                        broadSubnet.putAll(service);
                                                    }
                                                } else {
                                                    Map<SubnetKey, BaseData> service = esGet
                                                            .setSubnet(now.getTime(), "ni-base-subnet");
                                                    broadSubnet.clear();
                                                    broadSubnet.putAll(service);
                                                }
                                                key = new SubnetKey();
                                                //                                                        key.setKeyWord(stringAggResultTuple2._1);
                                                //                                                        key.setStart_timestamp(now.getTime());
                                                //                                                        baseData = broadSubnet.get(key);
                                                break;
                                            }

                                            final Key finalKey = key;
                                            alertList = alert
                                                    .filter(new Function<Tuple2<String, AggResult>, Boolean>() {
                                                        @Override
                                                        public Boolean call(Tuple2<String, AggResult> v1)
                                                                throws Exception {
                                                            Field field2 = v1._2.getClass()
                                                                    .getDeclaredField(sameRule.getValue());
                                                            field2.setAccessible(true);
                                                            double result2 = (double) field2.get(v1._2);
                                                            if (result2 == 0) {
                                                                return false;
                                                            }
                                                            String contain = sameRule.getContain();
                                                            if (contain.equals("") && !v1._1.equals("")) {
                                                                return true;
                                                            }
                                                            if (v1._1 == null || v1._1.equals("")) {
                                                                return false;
                                                            }
                                                            return v1._1.contains(sameRule.getContain());
                                                        }
                                                    }).mapToPair(
                                                            new PairFunction<Tuple2<String, AggResult>, String, String>() {
                                                                @Override
                                                                public Tuple2<String, String> call(
                                                                        Tuple2<String, AggResult> stringAggResultTuple2)
                                                                        throws Exception {

                                                                    Field field2 = stringAggResultTuple2._2
                                                                            .getClass().getDeclaredField(
                                                                                    sameRule.getValue());
                                                                    field2.setAccessible(true);
                                                                    double alertCursor = (double) field2
                                                                            .get(stringAggResultTuple2._2);

                                                                    JSONObject json = new JSONObject();
                                                                    BaseData baseData = new BaseData();

                                                                    finalKey.setKeyWord(
                                                                            stringAggResultTuple2._1);
                                                                    finalKey.setStart_timestamp(now.getTime());
                                                                    baseData = broadService.get(finalKey);

                                                                    if (baseData != null) {
                                                                        Field field = baseData.getClass()
                                                                                .getDeclaredField(
                                                                                        sameRule.getValue());
                                                                        field.setAccessible(true);
                                                                        double result = (double) field
                                                                                .get(baseData);

                                                                        AlertLevel alertLevel = new AlertLevel();

                                                                        if (sameRule.getThresholdErrOp()
                                                                                .equals("ge")) {
                                                                            if (alertCursor - result >= sameRule
                                                                                    .getMax_cardinality()) {
                                                                                alertLevel.setWarningLevel(
                                                                                        "levelBad");

                                                                            } else if (alertCursor
                                                                                    - result >= sameRule
                                                                                            .getMin_cardinality()) {
                                                                                alertLevel.setWarningLevel(
                                                                                        "levelWarn");

                                                                            } else {
                                                                                alertLevel.setWarningLevel(
                                                                                        "levelNormal");
                                                                            }
                                                                        }

                                                                        if (sameRule.getThresholdErrOp()
                                                                                .equals("le")) {
                                                                            if (result - alertCursor <= sameRule
                                                                                    .getMax_cardinality()) {
                                                                                alertLevel.setWarningLevel(
                                                                                        "levelBad");
                                                                            } else if (result
                                                                                    - alertCursor <= sameRule
                                                                                            .getMin_cardinality()) {
                                                                                alertLevel.setWarningLevel(
                                                                                        "levelWarn");
                                                                            } else {
                                                                                alertLevel.setWarningLevel(
                                                                                        "levelNormal");
                                                                            }
                                                                        }

                                                                        alertLevel.setResourceName(
                                                                                stringAggResultTuple2._1);
                                                                        if (sameRule.getType()
                                                                                .equals("server_ip")) {
                                                                            alertLevel.setIpAddress(
                                                                                    stringAggResultTuple2._1);
                                                                        } else {
                                                                            alertLevel.setIpAddress("");
                                                                        }
                                                                        alertLevel.setOccureTime(
                                                                                esFormat.format(format.parse(
                                                                                        stringAggResultTuple2._2
                                                                                                .getTimestamp())));
                                                                        alertLevel.setResourceType(
                                                                                sameRule.getType());
                                                                        alertLevel.setMetricId(
                                                                                sameRule.getValue());
                                                                        alertLevel.setResourceInstanceId(
                                                                                stringAggResultTuple2._1);

                                                                        // top2  d?>10%?
                                                                        Map<String, Double> top2 = new HashMap<String, Double>();
                                                                        top2.put("MTU?",
                                                                                stringAggResultTuple2._2
                                                                                        .getMTU_pre());
                                                                        top2.put("?",
                                                                                stringAggResultTuple2._2
                                                                                        .getCongest_pre());
                                                                        top2.put("??",
                                                                                stringAggResultTuple2._2
                                                                                        .getOutoforder_pre());
                                                                        top2.put("??",
                                                                                stringAggResultTuple2._2
                                                                                        .getZerowindow_pre());
                                                                        List<Map.Entry<String, Double>> list = SortHashMap
                                                                                .sortHashMap(top2);

                                                                        if ("lossRate"
                                                                                .equals(sameRule.getValue())) {
                                                                            if (list.get(0).getValue() > 10
                                                                                    && list.get(1)
                                                                                            .getValue() > 10) {
                                                                                alertLevel.setWarningContent(
                                                                                        alertLevel.getMetricId()
                                                                                                + ""
                                                                                                + df.format(
                                                                                                        alertCursor)
                                                                                                + "%25,"
                                                                                                + list.get(0)
                                                                                                        .getKey()
                                                                                                + ""
                                                                                                + list.get(0)
                                                                                                        .getValue()
                                                                                                + "%25,"
                                                                                                + list.get(1)
                                                                                                        .getKey()
                                                                                                + ""
                                                                                                + list.get(1)
                                                                                                        .getValue()
                                                                                                + "%25."
                                                                                                + result
                                                                                                + "."
                                                                                                + sameRule
                                                                                                        .getMin_cardinality()
                                                                                                + ","
                                                                                                + sameRule
                                                                                                        .getMax_cardinality());
                                                                            } else {
                                                                                alertLevel.setWarningContent(
                                                                                        alertLevel.getMetricId()
                                                                                                + ""
                                                                                                + df.format(
                                                                                                        alertCursor)
                                                                                                + "%25,"
                                                                                                + result
                                                                                                + "."
                                                                                                + sameRule
                                                                                                        .getMin_cardinality()
                                                                                                + ","
                                                                                                + sameRule
                                                                                                        .getMax_cardinality());
                                                                            }
                                                                        } else {
                                                                            if ("userRespTime".equals(
                                                                                    sameRule.getValue())) {
                                                                                if (list.get(0).getValue() > 10
                                                                                        && list.get(1)
                                                                                                .getValue() > 10) {
                                                                                    alertLevel
                                                                                            .setWarningContent(
                                                                                                    alertLevel
                                                                                                            .getMetricId()
                                                                                                            + ""
                                                                                                            + millToSec(
                                                                                                                    (long) alertCursor)
                                                                                                            + ","
                                                                                                            + millToSec(
                                                                                                                    (long) stringAggResultTuple2._2
                                                                                                                            .getRtt())
                                                                                                            + "ms,?"
                                                                                                            + millToSec(
                                                                                                                    (long) stringAggResultTuple2._2
                                                                                                                            .getServerRespTime())
                                                                                                            + "ms,"
                                                                                                            + millToSec(
                                                                                                                    (long) stringAggResultTuple2._2
                                                                                                                            .getTransmissionTime())
                                                                                                            + "ms,?"
                                                                                                            + millToSec(
                                                                                                                    (long) stringAggResultTuple2._2
                                                                                                                            .getRetransferTime())
                                                                                                            + "."
                                                                                                            + list.get(
                                                                                                                    0)
                                                                                                                    .getKey()
                                                                                                            + ""
                                                                                                            + list.get(
                                                                                                                    0)
                                                                                                                    .getValue()
                                                                                                            + "%25,"
                                                                                                            + list.get(
                                                                                                                    1)
                                                                                                                    .getKey()
                                                                                                            + ""
                                                                                                            + list.get(
                                                                                                                    1)
                                                                                                                    .getValue()
                                                                                                            + "%25."
                                                                                                            + result
                                                                                                            + "."
                                                                                                            + sameRule
                                                                                                                    .getMin_cardinality()
                                                                                                            + ","
                                                                                                            + sameRule
                                                                                                                    .getMax_cardinality());
                                                                                } else {
                                                                                    alertLevel
                                                                                            .setWarningContent(
                                                                                                    alertLevel
                                                                                                            .getMetricId()
                                                                                                            + ""
                                                                                                            + millToSec(
                                                                                                                    (long) alertCursor)
                                                                                                            + ","
                                                                                                            + millToSec(
                                                                                                                    (long) stringAggResultTuple2._2
                                                                                                                            .getRtt())
                                                                                                            + "ms,?"
                                                                                                            + millToSec(
                                                                                                                    (long) stringAggResultTuple2._2
                                                                                                                            .getServerRespTime())
                                                                                                            + "ms,"
                                                                                                            + millToSec(
                                                                                                                    (long) stringAggResultTuple2._2
                                                                                                                            .getTransmissionTime())
                                                                                                            + "ms,?"
                                                                                                            + millToSec(
                                                                                                                    (long) stringAggResultTuple2._2
                                                                                                                            .getRetransferTime())
                                                                                                            + "."
                                                                                                            + result
                                                                                                            + "."
                                                                                                            + sameRule
                                                                                                                    .getMin_cardinality()
                                                                                                            + ","
                                                                                                            + sameRule
                                                                                                                    .getMax_cardinality());
                                                                                }
                                                                            } else if ("rtt".equals(
                                                                                    sameRule.getValue())) {
                                                                                alertLevel.setWarningContent(
                                                                                        "RTT" + millToSec(
                                                                                                (long) alertCursor)
                                                                                                + ",RTT"
                                                                                                + millToSec(
                                                                                                        (long) stringAggResultTuple2._2
                                                                                                                .getClientRoundTripTime())
                                                                                                + "ms,?RTT"
                                                                                                + millToSec(
                                                                                                        (long) stringAggResultTuple2._2
                                                                                                                .getServerRoundTripTime())
                                                                                                + "ms."
                                                                                                + result
                                                                                                + "."
                                                                                                + sameRule
                                                                                                        .getMin_cardinality()
                                                                                                + ","
                                                                                                + sameRule
                                                                                                        .getMax_cardinality());
                                                                            } else if ("throughput".equals(
                                                                                    sameRule.getType())) {
                                                                                alertLevel.setWarningContent(
                                                                                        alertLevel.getMetricId()
                                                                                                + ""
                                                                                                + convertUnit(
                                                                                                        (long) alertCursor)
                                                                                                + ",????"
                                                                                                + convertUnit(
                                                                                                        (long) stringAggResultTuple2._2
                                                                                                                .getS_throughput())
                                                                                                + ",????"
                                                                                                + convertUnit(
                                                                                                        (long) stringAggResultTuple2._2
                                                                                                                .getC_throughput())
                                                                                                + "."
                                                                                                + convertUnit(
                                                                                                        (long) result)
                                                                                                + "."
                                                                                                + sameRule
                                                                                                        .getMin_cardinality()
                                                                                                + ","
                                                                                                + sameRule
                                                                                                        .getMax_cardinality());
                                                                            } else if ("packetThroughput"
                                                                                    .equals(sameRule
                                                                                            .getValue())) {
                                                                                alertLevel.setWarningContent(
                                                                                        alertLevel.getMetricId()
                                                                                                + ""
                                                                                                + df.format(
                                                                                                        alertCursor)
                                                                                                + ",????"
                                                                                                + stringAggResultTuple2._2
                                                                                                        .getS_packetThroughput()
                                                                                                + ",????"
                                                                                                + stringAggResultTuple2._2
                                                                                                        .getC_packetThroughput()
                                                                                                + "."
                                                                                                + result
                                                                                                + "."
                                                                                                + sameRule
                                                                                                        .getMin_cardinality()
                                                                                                + ","
                                                                                                + sameRule
                                                                                                        .getMax_cardinality());
                                                                            } else if (percent.contains(
                                                                                    sameRule.getValue())) {
                                                                                alertLevel.setWarningContent(
                                                                                        alertLevel.getMetricId()
                                                                                                + ""
                                                                                                + df.format(
                                                                                                        alertCursor)
                                                                                                + "%25,"
                                                                                                + sameRule
                                                                                                        .getMin_cardinality()
                                                                                                + "."
                                                                                                + result
                                                                                                + "."
                                                                                                + sameRule
                                                                                                        .getMax_cardinality());
                                                                            } else {
                                                                                alertLevel.setWarningContent(
                                                                                        alertLevel.getMetricId()
                                                                                                + ""
                                                                                                + df.format(
                                                                                                        alertCursor)
                                                                                                + "."
                                                                                                + result
                                                                                                + "."
                                                                                                + sameRule
                                                                                                        .getMin_cardinality()
                                                                                                + ","
                                                                                                + sameRule
                                                                                                        .getMax_cardinality());
                                                                            }
                                                                        }

                                                                        alertLevel.setRuleId(
                                                                                sameRule.getRuleName());
                                                                        alertLevel.setUniqueMark(sameRule
                                                                                .getRuleName() + "-"
                                                                                + stringAggResultTuple2._1 + "-"
                                                                                + sameRule.getValue());

                                                                        if (stats.containsKey(
                                                                                alertLevel.getUniqueMark())) {
                                                                            String preLevel = stats
                                                                                    .get(alertLevel
                                                                                            .getUniqueMark())._1;
                                                                            int num = stats.get(alertLevel
                                                                                    .getUniqueMark())._2;
                                                                            boolean preWarning = preLevel
                                                                                    .equals("levelWarn")
                                                                                    || preLevel
                                                                                            .equals("levelBad");
                                                                            boolean newWarning = alertLevel
                                                                                    .getWarningLevel()
                                                                                    .equals("levelWarn")
                                                                                    || alertLevel
                                                                                            .getWarningLevel()
                                                                                            .equals("levelBad");
                                                                            if (preWarning && !newWarning) {
                                                                                num = 1 - num;
                                                                                stats.put(alertLevel
                                                                                        .getUniqueMark(),
                                                                                        new Tuple2<String, Integer>(
                                                                                                alertLevel
                                                                                                        .getWarningLevel(),
                                                                                                num));
                                                                            } else if (!preWarning
                                                                                    && newWarning) {
                                                                                stats.put(alertLevel
                                                                                        .getUniqueMark(),
                                                                                        new Tuple2<String, Integer>(
                                                                                                alertLevel
                                                                                                        .getWarningLevel(),
                                                                                                0 - recover));
                                                                            } else if (!preWarning
                                                                                    && !preWarning) {
                                                                                num = 1 - num;
                                                                                stats.put(alertLevel
                                                                                        .getUniqueMark(),
                                                                                        new Tuple2<String, Integer>(
                                                                                                alertLevel
                                                                                                        .getWarningLevel(),
                                                                                                num));
                                                                            } else {
                                                                                num = 0 - num;
                                                                                stats.put(alertLevel
                                                                                        .getUniqueMark(),
                                                                                        new Tuple2<String, Integer>(
                                                                                                alertLevel
                                                                                                        .getWarningLevel(),
                                                                                                num));
                                                                            }
                                                                        } else {
                                                                            if (alertLevel.getWarningLevel()
                                                                                    .equals("levelWarn")
                                                                                    || alertLevel
                                                                                            .getWarningLevel()
                                                                                            .equals("levelBad")) {
                                                                                stats.put(alertLevel
                                                                                        .getUniqueMark(),
                                                                                        new Tuple2<String, Integer>(
                                                                                                alertLevel
                                                                                                        .getWarningLevel(),
                                                                                                0 - recover));
                                                                                json = (JSONObject) JSON
                                                                                        .toJSON(alertLevel);
                                                                                return new Tuple2<>(
                                                                                        stringAggResultTuple2._1,
                                                                                        json.toString());
                                                                            }
                                                                        }
                                                                    }

                                                                    return new Tuple2<>(
                                                                            stringAggResultTuple2._1, "");
                                                                }
                                                            })
                                                    .filter(new Function<Tuple2<String, String>, Boolean>() {
                                                        @Override
                                                        public Boolean call(Tuple2<String, String> v1)
                                                                throws Exception {
                                                            return !v1._2.equals("") && v1._2 != null;
                                                        }
                                                    }).map(new Function<Tuple2<String, String>, String>() {
                                                        @Override
                                                        public String call(Tuple2<String, String> v1)
                                                                throws Exception {
                                                            return v1._2;
                                                        }
                                                    }).collect();

                                        } else {
                                            alertList = alert
                                                    .filter(new Function<Tuple2<String, AggResult>, Boolean>() {
                                                        @Override
                                                        public Boolean call(Tuple2<String, AggResult> v1)
                                                                throws Exception {
                                                            Field field2 = v1._2.getClass()
                                                                    .getDeclaredField(sameRule.getValue());
                                                            field2.setAccessible(true);
                                                            double result2 = (double) field2.get(v1._2);
                                                            if (result2 == 0.0) {
                                                                return false;
                                                            }
                                                            String contain = sameRule.getContain();
                                                            if (contain.equals("") && !v1._1.equals("")) {
                                                                return true;
                                                            }
                                                            if (v1._1 == null || v1._1.equals("")) {
                                                                return false;
                                                            }
                                                            return v1._1.contains(sameRule.getContain());
                                                        }
                                                    }).mapToPair(
                                                            new PairFunction<Tuple2<String, AggResult>, String, String>() {

                                                                @Override
                                                                public Tuple2<String, String> call(
                                                                        Tuple2<String, AggResult> stringAggResultTuple2)
                                                                        throws Exception {
                                                                    Field field2 = stringAggResultTuple2._2
                                                                            .getClass().getDeclaredField(
                                                                                    sameRule.getValue());
                                                                    field2.setAccessible(true);
                                                                    double alertCursor = (double) field2
                                                                            .get(stringAggResultTuple2._2);
                                                                    JSONObject json = new JSONObject();
                                                                    AlertLevel alertLevel = new AlertLevel();
                                                                    if (alertCursor >= sameRule
                                                                            .getMax_cardinality()) {
                                                                        alertLevel.setWarningLevel("levelBad");

                                                                    } else if (alertCursor >= sameRule
                                                                            .getMin_cardinality()) {
                                                                        alertLevel.setWarningLevel("levelWarn");
                                                                    } else {
                                                                        alertLevel
                                                                                .setWarningLevel("levelNormal");
                                                                    }

                                                                    alertLevel.setResourceName(
                                                                            stringAggResultTuple2._1);
                                                                    if (sameRule.getType()
                                                                            .equals("server_ip")) {
                                                                        alertLevel.setIpAddress(
                                                                                stringAggResultTuple2._1);
                                                                    } else {
                                                                        alertLevel.setIpAddress("");
                                                                    }

                                                                    alertLevel.setResourceType(
                                                                            sameRule.getType());
                                                                    alertLevel.setOccureTime(
                                                                            esFormat.format(format.parse(
                                                                                    stringAggResultTuple2._2
                                                                                            .getTimestamp())));
                                                                    alertLevel.setMetricId(sameRule.getValue());
                                                                    alertLevel.setResourceInstanceId(
                                                                            stringAggResultTuple2._1);

                                                                    // top2  d?>10%?
                                                                    Map<String, Double> top2 = new HashMap<String, Double>();
                                                                    top2.put("MTU?",
                                                                            stringAggResultTuple2._2
                                                                                    .getMTU_pre());
                                                                    top2.put("?",
                                                                            stringAggResultTuple2._2
                                                                                    .getCongest_pre());
                                                                    top2.put("??",
                                                                            stringAggResultTuple2._2
                                                                                    .getOutoforder_pre());
                                                                    top2.put("??",
                                                                            stringAggResultTuple2._2
                                                                                    .getZerowindow_pre());
                                                                    List<Map.Entry<String, Double>> list = SortHashMap
                                                                            .sortHashMap(top2);

                                                                    if ("lossRate"
                                                                            .equals(sameRule.getValue())) {
                                                                        if (list.get(0).getValue() > 10 && list
                                                                                .get(1).getValue() > 10) {
                                                                            alertLevel.setWarningContent(
                                                                                    alertLevel.getMetricId()
                                                                                            + ""
                                                                                            + df.format(
                                                                                                    alertCursor)
                                                                                            + "%25,"
                                                                                            + list.get(0)
                                                                                                    .getKey()
                                                                                            + ""
                                                                                            + list.get(0)
                                                                                                    .getValue()
                                                                                            + "%25,"
                                                                                            + list.get(1)
                                                                                                    .getKey()
                                                                                            + ""
                                                                                            + list.get(1)
                                                                                                    .getValue()
                                                                                            + "%25."
                                                                                            + ""
                                                                                            + sameRule
                                                                                                    .getMin_cardinality()
                                                                                            + ","
                                                                                            + sameRule
                                                                                                    .getMax_cardinality());
                                                                        } else {
                                                                            alertLevel.setWarningContent(
                                                                                    alertLevel.getMetricId()
                                                                                            + ""
                                                                                            + df.format(
                                                                                                    alertCursor)
                                                                                            + "%25,"
                                                                                            + ","
                                                                                            + sameRule
                                                                                                    .getMin_cardinality()
                                                                                            + ","
                                                                                            + sameRule
                                                                                                    .getMax_cardinality());
                                                                        }
                                                                    } else if ("userRespTime"
                                                                            .equals(sameRule.getValue())) {
                                                                        if (list.get(0).getValue() > 10 && list
                                                                                .get(1).getValue() > 10) {
                                                                            alertLevel.setWarningContent(
                                                                                    alertLevel.getMetricId()
                                                                                            + ""
                                                                                            + millToSec(
                                                                                                    (long) alertCursor)
                                                                                            + ","
                                                                                            + millToSec(
                                                                                                    (long) stringAggResultTuple2._2
                                                                                                            .getRtt())
                                                                                            + ",?"
                                                                                            + millToSec(
                                                                                                    (long) stringAggResultTuple2._2
                                                                                                            .getServerRespTime())
                                                                                            + ","
                                                                                            + millToSec(
                                                                                                    (long) stringAggResultTuple2._2
                                                                                                            .getTransmissionTime())
                                                                                            + "?"
                                                                                            + millToSec(
                                                                                                    (long) stringAggResultTuple2._2
                                                                                                            .getRetransferTime())
                                                                                            + "."
                                                                                            + list.get(0)
                                                                                                    .getKey()
                                                                                            + ""
                                                                                            + list.get(0)
                                                                                                    .getValue()
                                                                                            + "%25,"
                                                                                            + list.get(1)
                                                                                                    .getKey()
                                                                                            + ""
                                                                                            + list.get(1)
                                                                                                    .getValue()
                                                                                            + "%25."
                                                                                            + ""
                                                                                            + sameRule
                                                                                                    .getMin_cardinality()
                                                                                            + ","
                                                                                            + sameRule
                                                                                                    .getMax_cardinality());
                                                                        } else {
                                                                            alertLevel.setWarningContent(
                                                                                    alertLevel.getMetricId()
                                                                                            + ""
                                                                                            + millToSec(
                                                                                                    (long) alertCursor)
                                                                                            + ","
                                                                                            + millToSec(
                                                                                                    (long) stringAggResultTuple2._2
                                                                                                            .getRtt())
                                                                                            + ",?"
                                                                                            + millToSec(
                                                                                                    (long) stringAggResultTuple2._2
                                                                                                            .getServerRespTime())
                                                                                            + ","
                                                                                            + millToSec(
                                                                                                    (long) stringAggResultTuple2._2
                                                                                                            .getTransmissionTime())
                                                                                            + "?"
                                                                                            + millToSec(
                                                                                                    (long) stringAggResultTuple2._2
                                                                                                            .getRetransferTime())
                                                                                            + "."
                                                                                            + sameRule
                                                                                                    .getMin_cardinality()
                                                                                            + ","
                                                                                            + sameRule
                                                                                                    .getMax_cardinality());
                                                                        }
                                                                    } else if ("rtt"
                                                                            .equals(sameRule.getValue())) {
                                                                        alertLevel.setWarningContent("RTT"
                                                                                + millToSec((long) alertCursor)
                                                                                + ",RTT"
                                                                                + millToSec(
                                                                                        (long) stringAggResultTuple2._2
                                                                                                .getClientRoundTripTime())
                                                                                + ",?RTT"
                                                                                + millToSec(
                                                                                        (long) stringAggResultTuple2._2
                                                                                                .getServerRoundTripTime())
                                                                                + "."
                                                                                + sameRule.getMin_cardinality()
                                                                                + "," + sameRule
                                                                                        .getMax_cardinality());
                                                                    } else if ("throughput"
                                                                            .equals(sameRule.getType())) {
                                                                        alertLevel.setWarningContent(alertLevel
                                                                                .getMetricId()
                                                                                + ""
                                                                                + convertUnit(
                                                                                        (long) alertCursor)
                                                                                + ",????"
                                                                                + convertUnit(
                                                                                        (long) stringAggResultTuple2._2
                                                                                                .getS_throughput())
                                                                                + ",????"
                                                                                + convertUnit(
                                                                                        (long) stringAggResultTuple2._2
                                                                                                .getC_throughput())
                                                                                + "."
                                                                                + sameRule.getMin_cardinality()
                                                                                + "," + sameRule
                                                                                        .getMax_cardinality());
                                                                    } else if ("packetThroughput"
                                                                            .equals(sameRule.getValue())) {
                                                                        alertLevel.setWarningContent(alertLevel
                                                                                .getMetricId() + ""
                                                                                + df.format(alertCursor)
                                                                                + ",????"
                                                                                + stringAggResultTuple2._2
                                                                                        .getS_packetThroughput()
                                                                                + ",????"
                                                                                + stringAggResultTuple2._2
                                                                                        .getC_packetThroughput()
                                                                                + "."
                                                                                + sameRule.getMin_cardinality()
                                                                                + "," + sameRule
                                                                                        .getMax_cardinality());
                                                                    } else if (percent
                                                                            .contains(sameRule.getValue())) {
                                                                        alertLevel.setWarningContent(alertLevel
                                                                                .getMetricId() + ""
                                                                                + df.format(alertCursor)
                                                                                + "%25,"
                                                                                + sameRule.getMin_cardinality()
                                                                                + "," + sameRule
                                                                                        .getMax_cardinality());
                                                                    } else {
                                                                        alertLevel.setWarningContent(alertLevel
                                                                                .getMetricId() + ""
                                                                                + df.format(alertCursor)
                                                                                + ","
                                                                                + sameRule.getMin_cardinality()
                                                                                + "," + sameRule
                                                                                        .getMax_cardinality());
                                                                    }
                                                                    alertLevel
                                                                            .setRuleId(sameRule.getRuleName());
                                                                    alertLevel.setUniqueMark(
                                                                            sameRule.getRuleName() + "-"
                                                                                    + stringAggResultTuple2._1
                                                                                    + "-"
                                                                                    + sameRule.getValue());

                                                                    if (stats.containsKey(
                                                                            alertLevel.getUniqueMark())) {
                                                                        String preLevel = stats.get(
                                                                                alertLevel.getUniqueMark())._1;
                                                                        int num = stats.get(
                                                                                alertLevel.getUniqueMark())._2;
                                                                        boolean preWarning = preLevel
                                                                                .equals("levelWarn")
                                                                                || preLevel.equals("levelBad");
                                                                        boolean newWarning = alertLevel
                                                                                .getWarningLevel()
                                                                                .equals("levelWarn")
                                                                                || alertLevel.getWarningLevel()
                                                                                        .equals("levelBad");
                                                                        if (preWarning && !newWarning) {
                                                                            num = 1 - num;
                                                                            stats.put(
                                                                                    alertLevel.getUniqueMark(),
                                                                                    new Tuple2<String, Integer>(
                                                                                            alertLevel
                                                                                                    .getWarningLevel(),
                                                                                            num));
                                                                        } else if (!preWarning && newWarning) {
                                                                            stats.put(
                                                                                    alertLevel.getUniqueMark(),
                                                                                    new Tuple2<String, Integer>(
                                                                                            alertLevel
                                                                                                    .getWarningLevel(),
                                                                                            0 - recover));
                                                                        } else if (!preWarning && !preWarning) {
                                                                            num = 1 - num;
                                                                            stats.put(
                                                                                    alertLevel.getUniqueMark(),
                                                                                    new Tuple2<String, Integer>(
                                                                                            alertLevel
                                                                                                    .getWarningLevel(),
                                                                                            num));
                                                                        } else {
                                                                            num = 0 - num;
                                                                            stats.put(
                                                                                    alertLevel.getUniqueMark(),
                                                                                    new Tuple2<String, Integer>(
                                                                                            alertLevel
                                                                                                    .getWarningLevel(),
                                                                                            num));
                                                                        }
                                                                    } else {
                                                                        if (alertLevel.getWarningLevel()
                                                                                .equals("levelWarn")
                                                                                || alertLevel.getWarningLevel()
                                                                                        .equals("levelBad")) {
                                                                            stats.put(
                                                                                    alertLevel.getUniqueMark(),
                                                                                    new Tuple2<String, Integer>(
                                                                                            alertLevel
                                                                                                    .getWarningLevel(),
                                                                                            0 - recover));
                                                                            json = (JSONObject) JSON
                                                                                    .toJSON(alertLevel);
                                                                            return new Tuple2<>(
                                                                                    stringAggResultTuple2._1,
                                                                                    json.toString());
                                                                        }
                                                                    }

                                                                    return new Tuple2<>(
                                                                            stringAggResultTuple2._1, "");
                                                                }
                                                            })
                                                    .filter(new Function<Tuple2<String, String>, Boolean>() {

                                                        private static final long serialVersionUID = 662946729452638751L;

                                                        @Override
                                                        public Boolean call(Tuple2<String, String> v1)
                                                                throws Exception {
                                                            return !v1._2.equals("") && v1._2 != null;
                                                        }
                                                    }).map(new Function<Tuple2<String, String>, String>() {
                                                        @Override
                                                        public String call(Tuple2<String, String> v1)
                                                                throws Exception {
                                                            return v1._2;
                                                        }
                                                    }).collect();
                                        }
                                    }

                                    jsonList.addAll(alertList);

                                    alertList.clear();
                                }
                            }
                        }
                    }

                    flagRules.clear();
                }

                Iterator<Map.Entry<String, Tuple2<String, Integer>>> iterator = stats.entrySet().iterator();

                while (iterator.hasNext()) {
                    Map.Entry<String, Tuple2<String, Integer>> entry = iterator.next();
                    int num = entry.getValue()._2;
                    if (num == 0) {
                        UrlPostMethod.urlPostMethod(RECOVER, entry.getValue()._1);
                        iterator.remove();
                    } else if (num < 0) {
                        num = 0 - num;
                        entry.setValue(new Tuple2<String, Integer>(entry.getValue()._1, num));
                    } else {
                        num = 1 - num;
                        if (num == 0) {
                            UrlPostMethod.urlPostMethod(RECOVER, entry.getValue()._1);
                            iterator.remove();
                        } else {
                            entry.setValue(new Tuple2<String, Integer>(entry.getValue()._1, num));
                        }
                    }
                }

                if (stats.size() > 200000) {
                    stats.clear();
                }

                if (jsonList.size() > 0) {
                    if (Boolean.parseBoolean(getConfig("alert.cnf").getProperty("save.es"))) {
                        System.out.println(
                                "-------------------" + jsonList.toString() + "-----------------------");
                    }

                    for (int i = 0; i <= jsonList.size() / 2000; i++) {
                        UrlPostMethod.urlPostMethod(URL, "warnings=" + Arrays.asList(Arrays.copyOfRange(
                                jsonList.toArray(), i * 2000,
                                (i + 1) * 2000 - 1 > jsonList.size() ? jsonList.size() : (i + 1) * 2000 - 1))
                                .toString());
                    }

                    jsonList.clear();
                }
            }

            return null;
        }
    });

    rawStream.context().start();
    rawStream.context().awaitTermination();

}