Example usage for org.apache.commons.net.util SubnetUtils getInfo

List of usage examples for org.apache.commons.net.util SubnetUtils getInfo

Introduction

In this page you can find the example usage for org.apache.commons.net.util SubnetUtils getInfo.

Prototype

public final SubnetInfo getInfo() 

Source Link

Document

Return a SubnetInfo instance that contains subnet-specific statistics

Usage

From source file:org.xlcloud.network.validatation.CIDRValidator.java

private static SubnetUtils toSubnetUtils(String cidr) {
    validateThat(cidr).as("cidr").isNotBlank();
    SubnetUtils utils = null;

    try {//w w w .ja va2s.c o m
        utils = new SubnetUtils(cidr);
    } catch (IllegalArgumentException ex) {
        throw new ValidationException("Invalid CIDR format", ValidationFailureType.CIDR_FORMAT);
    }

    int cidrAddress = ipAddressToInt(utils.getInfo().getAddress());
    int lowestAddress = ipAddressToInt(utils.getInfo().getLowAddress());
    if (cidrAddress > lowestAddress) {
        throw new ValidationException("Ip address for CIDR has numbers for 0 mask",
                ValidationFailureType.CIDR_FORMAT);
    }

    return utils;
}

From source file:org.xlcloud.network.validatation.CIDRValidator.java

/**
 * Validates if CIDR is has valid format and validates if 0 in mask are
 * equal 0 in IpAddress/*from w  w  w .  ja va 2  s . com*/
 * 
 * @throws ValidationException
 *             , when at least one of CIDR has invalid format
 * @throws DuplicatedEntityException
 *             , when CIDR addresses are overlaped
 */
public static void validateSeparableCIDR(String incoming, String external) {

    SubnetUtils utils1 = toSubnetUtils(incoming);
    SubnetUtils utils2 = toSubnetUtils(external);

    String ipAddress1 = utils1.getInfo().getAddress();
    String ipAddress2 = utils2.getInfo().getAddress();

    String mask1 = utils1.getInfo().getNetmask();
    String mask2 = utils2.getInfo().getNetmask();

    int intMask1 = ipAddressToInt(mask1);
    int intMask2 = ipAddressToInt(mask2);
    int mask = (Integer.valueOf(incoming.split("/")[1]) < Integer.valueOf(external.split("/")[1])) ? (intMask1)
            : (intMask2);

    if ((ipAddressToInt(ipAddress1) & mask) == (ipAddressToInt(ipAddress2) & mask)) {
        throw new DuplicatedEntityException("CIDR address has overlap ranges", EntityType.CIDR_ADDRESS,
                incoming);
    }
}

From source file:OSFFM_ORC.FederationActionManager.java

/**
 * This function is prepared for future usage it has the scope to add a
 * network segment inside Openstack in order to absolve at a FEDSDN calls.
 *
 * @param fu/*from   ww  w  .j a v a2  s  .  c om*/
 * @param OSF_network_segment_id
 * @param OSF_cloud
 * @param netParameter
 * @param federationTenant
 * @return
 * @throws Exception
 */
public JSONObject networkSegmentAdd(FederationUser fu, String OSF_network_segment_id, String OSF_cloud,
        HashMap netParameter, String federationTenant) throws Exception {
    DBMongo db = new DBMongo();
    JSONObject reply = new JSONObject();
    db.init();
    db.setDbName(federationTenant);
    db.connectLocale(db.getMdbIp());
    HashMap fum = this.getAllFederatedCloudCreds(fu);
    JSONObject network_info = new JSONObject(), network_infoGLOBAL = new JSONObject();
    JSONArray ja = new JSONArray();

    Set s = fum.keySet();
    OpenstackInfoContainer credential = null;
    NeutronTest neutron = null;
    Iterator i = s.iterator();
    FederatedUser fed_U = null;
    while (i.hasNext()) {
        try {
            //Momentaneamente viene implementata una gestione singola del cloud federato.
            //nel caso in cui si decider di gestire globalmente l'insieme dei cloud federati fare come indicato sotto, rimuovendo 
            ////l'if che controlla il cloud
            //////>>>BEACON: inserire gestione con array di thread ogni thread dovr:
            JSONObject fdu = (JSONObject) fum.get(i.next());
            if (!((String) fdu.get("federatedCloud")).equals(OSF_cloud)) {
                continue;
            }
            fed_U = new FederatedUser(fdu.toString());
            String federated_cmp_endp = (String) db
                    .getDatacenterFromId(fu.getUser(), (String) fdu.get("federatedCloud")).get("idmEndpoint");//TO BE VERIFIED
            credential = new OpenstackInfoContainer((String) fdu.get("federatedCloud"), federated_cmp_endp,
                    fu.getUser(), (String) fdu.get("federatedUser"), (String) fdu.get("federatedPassword"),
                    fed_U.getRegion());
            neutron = new NeutronTest(credential.getEndpoint(), credential.getTenant(), credential.getUser(),
                    credential.getPassword(), credential.getRegion());
        } catch (Exception e) {
            reply.put("returncode", 1);
            reply.put("errormesg", "USER_AUTHENTICATION_EXCEPTION: OPERATION ABORTED");
            reply.put("network_info", "null");
            LOGGER.error("USER_AUTHENTICATION_EXCEPTION: OPERATION ABORTED >>>[Token:" + fu.getToken()
                    + "]; No federated credential has found for selected parameters.");
            throw new Exception(reply.toString());
        }

        String cidr = "";
        boolean found = false, cidrPresent = false;
        String internalNetId = db.getInternalNetworkID(fu.getUser(), OSF_network_segment_id, fed_U.getCloud());
        if (internalNetId != null) {
            Networks N = neutron.listNetworks();
            Iterator<Network> iN = N.iterator();
            found = false;
            while (i.hasNext() && !found) {
                Network n = iN.next();
                if (internalNetId.equals(n.getId())) {
                    found = true;//nothing to do
                }
            }
            if (!found) {
                //this is the case when some info aren't aligned, the internal ID for netsegment are present but 
                //// no network is retrieved for tenant inside the cloud match it.
                //Inserire qui la chiamata relativa al Network Segment verso l'API "/fednet/{fednetId}/{site_id}/netsegment/{netsegment_id}"
                ////da cui ritrovare tutte le varie 
                //in alternativa creare le informazioni qui:
                HashMap th = new HashMap();
                th.put("netsegments", OSF_network_segment_id);
                org.json.JSONObject j = db.getcidrInfoes(fu.getUser(), th);
                if (j != null) {
                    //this is the case when a cidr is already defined for this fednet and FederationUser. That would mean that we have to create the 
                    ////other netsegments of the fednet with ther same parameters.                         
                    th = new HashMap();
                    th.put("netsegments", OSF_network_segment_id);
                    th.put("cloudId", fed_U.getCloud());
                    org.json.JSONObject j2 = db.getcidrInfoes(fu.getUser(), th);
                    if (j2 == null) {
                        //on mongo the netsegments searched is not found for this cloud then we will take the federation cidr
                        cidr = (String) j.get("cidr");
                    } else {
                        //disallineamento  presente un cidr ma non c' un internalId che corrisponda al netsegments
                        //sarebbe giusto creare un eccezione
                        throw new Exception(
                                "A problematic situation is founded! MongoDB information aren't alingned Contact the administrator!");
                    }
                } else {
                    //this is the case when on mongo the cidr for netsegments indicated is not found. This case represent first istantiation of the
                    ////netsegment for this fednet and FederationUser.   
                    cidrPresent = true;
                }
            } else {
                //match
                //nothing to do
            }

        } else {
            internalNetId = java.util.UUID.randomUUID().toString();
        }
        //prepare and retrieve information for creation of network
        Boolean dhcp = (Boolean) netParameter.get("dhcpEnable");
        if (dhcp == null) {
            dhcp = false;
        }
        Boolean shared = (Boolean) netParameter.get("shared");
        if (shared == null) {
            shared = false;
        }
        Boolean external = (Boolean) netParameter.get("external");
        if (external == null) {
            external = false;
        }
        Boolean adminStateUp = (Boolean) netParameter.get("adminStateUp");
        if (adminStateUp == null) {
            adminStateUp = false;
        }
        String subnetId = java.util.UUID.randomUUID().toString();
        if (!cidrPresent) {
            cidr = this.cidrgen();
        }
        HashMap allpo = this.calculateAllocationPool(cidr);
        SubnetUtils su = new SubnetUtils(cidr);
        SubnetInfo si = su.getInfo();
        String gwadd = si.getLowAddress();
        String fednets = "";//fednet;
        try {
            FunctionResponseContainer frc = neutron.createCompleteNetw(fed_U.getRegion(), internalNetId, cidr,
                    (String) allpo.get("allocationPoolStart"), (String) allpo.get("allocationPoolEnd"),
                    subnetId, gwadd, dhcp, fu.getUser(), shared, external, adminStateUp, fednets);

            //da frc. si possono ottenere le informazioni qui presenti 
            /*
             Network{id=258453f7-b655-4fbd-bee6-d1ac2d9fe7bc, 
             status=ACTIVE, 
             subnets=[], 
             name=ert, 
             adminStateUp=true, 
             shared=true, 
             tenantId=demo, 
             networkType=null,
             physicalNetworkName=null,
             segmentationId=null, 
             external=true, 
             portSecurity=null, 
             profileId=null,
             multicastIp=null, 
             segmentAdd=null, 
             segmentDel=null, 
             memberSegments=null, 
             segments=null, 
             networkFlavor=null}
             */
        } catch (Exception e) {
            LOGGER.error("Exception occurred in network creation operation!");
        }
        db.storeInternalNetworkID(fu.getUser(), OSF_network_segment_id, fed_U.getCloud(), internalNetId);
        db.insertcidrInfoes(fu.getUser(), cidr, fednets, OSF_network_segment_id, fed_U.getCloud());
        network_info = new JSONObject();
        network_info.put("cloudId", fed_U.getCloud());
        network_info.put("internalId", internalNetId);
        network_info.put("FedSDN_netSegId", OSF_network_segment_id);
        network_info.put("network_address", cidr.subSequence(0, cidr.indexOf("/")));
        network_info.put("network_mask", si.getNetmask());
        network_info.put("size", si.getAddressCount());
        ja.put(network_info);

    }
    network_infoGLOBAL.put("ResponseArray", ja);
    ///DECIDERE COME GESTIRE LE INFORMAZIONI: COSA RESTITUIRE AL FEDSDN 
    ////momentaneamente viene restituito un JSONarray con un solo elemento, quello della cloud indicata da OSF_cloud
    reply.put("returncode", 0);
    reply.put("errormesg", "None");
    reply.put("network_info", network_infoGLOBAL);

    return reply;

}

From source file:OSFFM_ORC.FederationActionManager.java

/**
 *
 * @param cidr/*from   w w w . ja v a  2  s. c o m*/
 * @return
 * @throws Exception
 * @author gtricomi
 */
private HashMap calculateAllocationPool(String cidr) throws Exception {
    HashMap hm = new HashMap();
    String allocationPoolStart = this.nextIpAddress(cidr);
    //we need the third IP of the allocation pool
    for (int i = 0; i < 2; i++) {
        allocationPoolStart = this.nextIpAddress(allocationPoolStart);
    }

    hm.put("allocationPoolStart", allocationPoolStart);
    SubnetUtils su = new SubnetUtils(cidr);
    SubnetInfo si = su.getInfo();
    hm.put("allocationPoolEnd", si.getHighAddress());
    return hm;
}

From source file:projetohorus.DadosColetadosPDF.java

void GerarPDF() throws IOException, DocumentException, EmailException {
    Document doc = null;/*from w ww  .jav a  2  s.c  o  m*/
    OutputStream os = null;

    try {
        doc = new Document(PageSize.A4, 72, 72, 72, 72);
        os = new FileOutputStream("tesfinal11.pdf");
        PdfWriter.getInstance(doc, os);
        doc.open();
        Image img = Image.getInstance("LogoProject.png");
        img.setAlignment(Element.ALIGN_CENTER);

        doc.add(img);

        InetAddress localHost = Inet4Address.getLocalHost();
        NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
        short x = networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
        String n = localHost.getHostAddress() + "/" + x;
        SubnetUtils utils = new SubnetUtils(n);
        ;

        PdfPTable table = new PdfPTable(new float[] { 0.50f, 0.70f, 0.90f });

        table = new PdfPTable(3);

        Paragraph p = new Paragraph("");
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(30);
        doc.add(p);
        p = new Paragraph("Informaes da Network");
        p.setAlignment(Element.ALIGN_CENTER);
        p.setSpacingAfter(30);

        doc.add(p);
        Paragraph paragraph = new Paragraph("" + utils.getInfo());
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.setSpacingAfter(30);
        doc.add(paragraph);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        PdfPCell header = new PdfPCell(new Paragraph("Diagnostico do Scanner da Rede"));
        header.setColspan(3);
        table.addCell(header);
        table.addCell("IP");
        table.addCell("HostName");
        table.addCell("Portas Abertas");
        for (int i = 0; i < IP.size(); i++) {

            table.addCell(IP.get(i));
            table.addCell(NameHost.get(i));
            table.addCell("" + PortasA.get(i));
        }
        doc.add(table);

    } finally {
        if (doc != null) {

            doc.close();
        }
        if (os != null) {

            os.close();
        }

    }
    EnvioEmail sc = new EnvioEmail();
    sc.EnvioEmail();

}

From source file:projetohorus.TamanhoHost.java

void TamanhoHost() throws UnknownHostException, SocketException {
    InetAddress localHost = Inet4Address.getLocalHost();
    NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
    short x = networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
    String n = localHost.getHostAddress() + "/" + x;
    System.out.println(n);//  w  w w .j  av  a2s  .  com
    SubnetUtils utils = new SubnetUtils(n);

    System.out.println(utils.getInfo());
    String first = utils.getInfo().getLowAddress();
    String last = utils.getInfo().getHighAddress();
    String[] iplast = last.split(Pattern.quote("."));
    String[] ipfirst = first.split(Pattern.quote("."));

    numfirst = Integer.parseInt(ipfirst[3]);
    numlast = Integer.parseInt(iplast[3]);

}

From source file:vn.vnpttech.ssdc.nms.webapp.util.SubnetUtil.java

/**
 * check ip range of two cidr is overlap
 *
 * @param cidr1//from   ww w .j ava2  s  .co  m
 * @param cidr2
 * @return true if overlap, false if not
 */
public static boolean checkCidrOverlap(String cidr1, String cidr2) {
    SubnetUtils su = new SubnetUtils(cidr1);
    SubnetUtils su2 = new SubnetUtils(cidr2);

    int start1 = su.getInfo().asInteger(su.getInfo().getLowAddress());
    int end1 = su.getInfo().asInteger(su.getInfo().getHighAddress());

    int start2 = su2.getInfo().asInteger(su2.getInfo().getLowAddress());
    int end2 = su2.getInfo().asInteger(su2.getInfo().getHighAddress());

    boolean ret = false;

    if (!((end2 <= start1) && (end1 <= start2))) {
        ret = true;
    } else {
        ret = false;
    }
    return ret;

}

From source file:vn.vnpttech.ssdc.nms.webapp.util.SubnetUtil.java

/**
 * Check ip range of cidr2 in ip range cidr1
 *
 * @param cidr1//  w  ww  . jav  a2 s.c o  m
 * @param cidr2
 * @return true if cidr2 in cidr1, false if not
 */
public static boolean checkCidrInCdir(String cidr1, String cidr2) {
    SubnetUtils su = new SubnetUtils(cidr1);
    SubnetUtils su2 = new SubnetUtils(cidr2);

    System.out.println(su.getInfo().getCidrSignature());

    System.out.println(su.getInfo().getLowAddress());
    System.out.println(su.getInfo().getHighAddress());

    int end1 = su.getInfo().asInteger(su.getInfo().getHighAddress());
    int start1 = su.getInfo().asInteger(su.getInfo().getLowAddress());

    int end2 = su2.getInfo().asInteger(su2.getInfo().getHighAddress());
    int start2 = su2.getInfo().asInteger(su2.getInfo().getLowAddress());

    boolean ret = false;

    if ((start1 <= start2) && (end2 <= end1)) {
        ret = true;
    } else {
        ret = false;
    }
    return ret;

}