Example usage for java.util HashSet clear

List of usage examples for java.util HashSet clear

Introduction

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

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this set.

Usage

From source file:edu.ku.brc.specify.toycode.mexconabio.AnalysisWithGBIFToGBIF.java

@Override
public void process(final int type, final int options) {
    calcMaxScore();//  w w w.  j a v a  2  s. com

    String gbifSQL = "SELECT DISTINCT id, catalogue_number, genus, species, subspecies, latitude, longitude, country, state_province, collector_name, locality, year, month, day, collector_num ";

    String fromClause1a = "FROM raw WHERE collector_num LIKE ? AND year = ? AND genus = ?";
    String fromClause1b = "FROM raw WHERE collector_num IS NULL AND year = ? AND genus = ?";
    //String fromClause2  = "FROM raw WHERE collector_num IS NULL AND year = ? AND month = ? AND genus = ? AND id <> ?";

    //                        1       2           3        4           5         6          7         8           9               10          11       12    13    14      15
    String postSQL = "FROM raw WHERE collector_num IS NOT NULL GROUP BY collector_num, year, genus";
    String srcSQL = "SELECT id, catalogue_number, genus, species, subspecies, latitude, longitude, country, state_province, collector_name, locality, year, month, day, collector_num "
            + postSQL + " ORDER BY collector_num";

    String grphashSQL = "SELECT name FROM group_hash";

    String gbifgbifInsert = "INSERT INTO gbifgbif (reltype, score, GBIFID, SNIBID) VALUES (?,?,?,?)";

    Statement stmt = null;
    PreparedStatement gStmt1a = null;
    PreparedStatement gStmt1b = null;
    //PreparedStatement gStmt2  = null;
    PreparedStatement gsStmt = null;

    Object[] refRow = new Object[NUM_FIELDS];
    Object[] cmpRow = new Object[NUM_FIELDS];

    long totalRecs = BasicSQLUtils.getCount(dbSrcConn, "SELECT COUNT(*) FROM group_hash");
    long procRecs = 0;
    long startTime = System.currentTimeMillis();
    int secsThreshold = 0;

    String blank = "X?";

    PrintWriter pw = null;
    try {
        pw = new PrintWriter("scoring_gbifgbif.log");

        gStmt1a = dbGBIFConn.prepareStatement(gbifSQL + fromClause1a);
        gStmt1b = dbGBIFConn.prepareStatement(gbifSQL + fromClause1b);

        //gStmt2 = dbGBIFConn.prepareStatement(gbifSQL + fromClause2);
        gsStmt = dbDstConn.prepareStatement(gbifgbifInsert);

        stmt = dbSrcConn.createStatement(ResultSet.FETCH_FORWARD, ResultSet.CONCUR_READ_ONLY);
        stmt.setFetchSize(Integer.MIN_VALUE);

        System.out.println("Starting Query... " + totalRecs);
        pw.println("Starting Query... " + totalRecs);
        System.out.flush();
        pw.flush();

        HashSet<Integer> idHash = new HashSet<Integer>();
        int writeCnt = 0;
        ResultSet rs = stmt.executeQuery(grphashSQL);

        System.out
                .println(String.format("Starting Processing... Total Records %d  Max Score: %d  Threshold: %d",
                        totalRecs, maxScore, thresholdScore));
        pw.println(String.format("Starting Processing... Total Records %d  Max Score: %d  Threshold: %d",
                totalRecs, maxScore, thresholdScore));
        System.out.flush();
        pw.flush();

        Vector<Object[]> group = new Vector<Object[]>();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        while (rs.next()) {
            String[] tokens = StringUtils.split(rs.getString(1), '_');

            String colNum = tokens[0].trim();
            String year = tokens[1].trim();
            String genus = tokens[2].trim();

            if (StringUtils.isEmpty(colNum) || colNum.equals(blank))
                colNum = null;
            if (StringUtils.isEmpty(year) || year.equals(blank))
                year = null;
            if (StringUtils.isEmpty(genus) || genus.equals(blank))
                genus = null;

            PreparedStatement gStmt1;
            if (colNum != null) {
                gStmt1 = gStmt1a;
                gStmt1.setString(1, "%" + colNum + "%");
            } else {
                gStmt1 = gStmt1b;
                gStmt1.setString(1, null);
            }
            gStmt1.setString(2, year);
            gStmt1.setString(3, genus);
            ResultSet gRS = gStmt1.executeQuery();

            ids.clear();
            int maxNonNullTot = -1;
            int maxNonNullInx = -1;
            int inx = 0;
            while (gRS.next()) {

                Object[] row = getRow();
                int cnt = fillRowWithScore(row, gRS);
                if (cnt > maxNonNullTot) {
                    maxNonNullInx = inx;
                    maxNonNullTot = cnt;
                }
                group.add(row);
                ids.add(gRS.getInt(1));
                inx++;
            }
            gRS.close();

            if (inx < 2) {
                for (Object[] r : group) {
                    recycleRow(r);
                }
                group.clear();
                continue;
            }

            System.arraycopy(group.get(maxNonNullInx), 0, refRow, 0, refRow.length);

            Integer srcId = ids.get(maxNonNullInx);

            for (int i = 0; i < group.size(); i++) {
                if (i != maxNonNullInx) {
                    int score = score(refRow, group.get(i));

                    if (score > thresholdScore) {
                        writeCnt++;

                        int gbifID = ids.get(i);
                        gsStmt.setInt(1, 1); // reltype
                        gsStmt.setInt(2, score); // score
                        gsStmt.setInt(3, gbifID);
                        gsStmt.setInt(4, srcId);
                        gsStmt.executeUpdate();

                        idHash.add(gbifID);
                    }
                }
            }

            idHash.clear();

            for (Object[] r : group) {
                recycleRow(r);
            }
            group.clear();

            if (gStmt1 == gStmt1b) {
                continue;
            }

            gStmt1 = gStmt1b;
            gStmt1.setString(1, year);
            gStmt1.setString(2, genus);

            gRS = gStmt1.executeQuery();
            while (gRS.next()) {
                fillRowWithScore(cmpRow, gRS);

                int gbifID = gRS.getInt(1);
                if (gbifID == srcId)
                    continue;

                int score = score(refRow, cmpRow);

                if (score > thresholdScore) {
                    writeCnt++;
                    gsStmt.setInt(1, 1); // reltype
                    gsStmt.setInt(2, score); // score
                    gsStmt.setInt(3, gbifID);
                    gsStmt.setInt(4, srcId);
                    gsStmt.executeUpdate();
                }
            }
            gRS.close();

            procRecs++;
            if (procRecs % 500 == 0) {
                long endTime = System.currentTimeMillis();
                long elapsedTime = endTime - startTime;

                double timePerRecord = (elapsedTime / procRecs);

                double hrsLeft = ((totalRecs - procRecs) * timePerRecord) / HRS;

                int seconds = (int) (elapsedTime / 60000.0);
                if (secsThreshold != seconds) {
                    secsThreshold = seconds;

                    String msg = String.format("Elapsed %8.2f hr.mn   Percent: %6.3f  Hours Left: %8.2f ",
                            ((double) (elapsedTime)) / HRS, 100.0 * ((double) procRecs / (double) totalRecs),
                            hrsLeft);
                    System.out.println(msg);
                    pw.println(msg);
                    pw.flush();
                }
            }
        }
        rs.close();

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

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (gStmt1a != null) {
                gStmt1a.close();
            }
            if (gStmt1b != null) {
                gStmt1b.close();
            }
            /*if (gStmt2 != null)
            {
            gStmt2.close();
            }*/
        } catch (Exception ex) {

        }
    }
    System.out.println("Done.");
    pw.println("Done.");
    pw.flush();
    pw.close();
}

From source file:com.icesoft.faces.renderkit.dom_html_basic.MenuRenderer.java

void renderSelect(FacesContext facesContext, UIComponent uiComponent) throws IOException {
    HashSet excludes = new HashSet();
    // setup/*w w  w.j  a v a 2s  . c o  m*/
    DOMContext domContext = DOMContext.attachDOMContext(facesContext, uiComponent);
    if (!domContext.isInitialized()) {
        Element root = domContext.createElement("select");
        domContext.setRootNode(root);
        setRootElementId(facesContext, root, uiComponent);
        root.setAttribute("name", uiComponent.getClientId(facesContext));
        // render styleClass attribute if present.
        String styleClass = null;
        if (null != (styleClass = (String) uiComponent.getAttributes().get("styleClass"))) {
            root.setAttribute("class", styleClass);
        }
        if (!getMultipleText(uiComponent).equals("")) {
            root.setAttribute("multiple", "multiple");
        }
    }
    Element root = (Element) domContext.getRootNode();

    // Determine how many option(s) we need to render, and update
    // the component's "size" attribute accordingly; The "size"
    // attribute will be rendered as one of the "pass thru" attributes
    int itemCount = countSelectOptionsRecursive(facesContext, uiComponent);
    // If "size" is *not* set explicitly, we have to default it correctly
    Object size = uiComponent.getAttributes().get("size");
    if ((null == size) || ((size instanceof Integer)
            && (((Integer) size).intValue() == Integer.MIN_VALUE || ((Integer) size).intValue() == 0))) {
        renderSizeAttribute(root, itemCount);
        excludes.add("size");
    } else {
        renderSizeAttribute(root, Integer.valueOf(size.toString()).intValue());
    }

    Object currentValue = null;
    if (null == (currentValue = ((UIInput) uiComponent).getSubmittedValue())) {
        currentValue = "";
    }

    addJavaScript(facesContext, uiComponent, root, currentValue.toString(), excludes);

    if (uiComponent instanceof HtmlSelectOneMenu) {
        PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent,
                selectOneMenuPassThruAttributes);
    } else if (uiComponent instanceof HtmlSelectManyMenu) {
        PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent,
                selectManyMenuPassThruAttributes);
    } else if (uiComponent instanceof HtmlSelectOneListbox) {
        PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent,
                selectOneListboxPassThruAttributes);
    } else if (uiComponent instanceof HtmlSelectManyListbox) {
        PassThruAttributeRenderer.renderHtmlAttributes(facesContext, uiComponent,
                selectManyListboxPassThruAttributes);
    }
    String[] attributes = new String[] { HTML.DISABLED_ATTR, HTML.READONLY_ATTR };
    Object attribute;
    for (int i = 0; i < attributes.length; i++) {
        attribute = uiComponent.getAttributes().get(attributes[i]);
        if (attribute instanceof Boolean && ((Boolean) attribute).booleanValue()) {
            root.setAttribute(attributes[i], attributes[i]);
        }
    }
    excludes.clear();

    domContext.stepInto(uiComponent);
    renderOptions(facesContext, uiComponent);
    domContext.stepOver();
}

From source file:gov.nih.nci.evs.browser.utils.DataUtils.java

public static Vector getConceptSources(String scheme, String version, String code) {
    Entity c = getConceptByCode(scheme, version, null, code);
    if (c == null)
        return null;
    Presentation[] presentations = c.getPresentation();
    HashSet hset = new HashSet();
    Vector v = new Vector();

    for (int i = 0; i < presentations.length; i++) {
        Presentation presentation = presentations[i];
        // java.lang.String name = presentation.getPropertyName();
        // java.lang.String prop_value =
        // presentation.getValue().getContent();
        Source[] sources = presentation.getSource();
        for (int j = 0; j < sources.length; j++) {
            Source source = (Source) sources[j];
            java.lang.String sab = source.getContent();
            if (!hset.contains(sab)) {
                hset.add(sab);/*  w ww .j av a 2s.c  o  m*/
                v.add(sab);
            }
        }
    }
    hset.clear();
    return v;
}

From source file:org.gbif.ipt.task.Eml2Rtf.java

/**
 * Add authors section.//from   w  w  w  . j a  va  2  s. c  om
 * 
 * @param doc Document
 * @param eml EML
 * @throws DocumentException if problem occurs during add
 */
private void addAuthors(Document doc, Eml eml) throws DocumentException {
    // Creating set of authors with different names. (first names + last names).
    HashSet<Agent> tempAgents = new LinkedHashSet<Agent>();
    if (exists(eml.getResourceCreator()) && exists(eml.getResourceCreator().getLastName())) {
        tempAgents.add(eml.getResourceCreator());
    }
    if (exists(eml.getMetadataProvider()) && exists(eml.getMetadataProvider().getLastName())) {
        tempAgents.add(eml.getMetadataProvider());
    }
    tempAgents.addAll(eml.getAssociatedParties());

    // comparing and removing those repeated agents with same name and same address.
    Collection<Integer> toRemove = new ArrayList<Integer>();
    int counter = 0;
    for (Iterator<Agent> i = tempAgents.iterator(); i.hasNext(); counter++) {
        if (toRemove.contains(counter)) {
            i.next();
            i.remove();
        } else {
            Agent agentA = i.next();
            // when second iterator should be start
            boolean flag = false;
            int countTemp = 0;
            for (Iterator<Agent> j = tempAgents.iterator(); j.hasNext(); countTemp++) {
                Agent agentB = j.next();
                if (flag) {
                    if (equal(agentA.getLastName(), agentB.getLastName())
                            && equal(agentA.getFirstName(), agentB.getFirstName())
                            && equal(agentA.getAddress(), agentB.getAddress())) {
                        toRemove.add(countTemp);
                    }
                } else if (agentA.equals(agentB)) {
                    flag = true;
                }
            }
        }
    }

    Agent[] agentsArray = new Agent[tempAgents.size()];
    tempAgents.toArray(agentsArray);
    // Adding authors
    Paragraph p = new Paragraph();
    p.setFont(font);
    p.setAlignment(Element.ALIGN_CENTER);
    java.util.List<Agent> affiliations = new ArrayList<Agent>();
    int superScriptCounter = 1;
    for (int c = 0; c < agentsArray.length; c++) {
        if (exists(agentsArray[c].getLastName())) {
            if (c != 0) {
                p.add(", ");
            }
            // First Name and Last Name
            if (exists(agentsArray[c].getFirstName())) {
                p.add(agentsArray[c].getFirstName() + " ");
            }
            p.add(agentsArray[c].getLastName());
            // Looking for addresses and organisations of other authors
            // (superscripts should not be repeated).
            boolean isRepeated = false;
            // look into the affiliations array to find any previous repeated agent info.
            for (int index = 0; index < affiliations.size(); index++) {
                if (equal(agentsArray[c].getAddress(), affiliations.get(index).getAddress())
                        && equal(agentsArray[c].getOrganisation(), affiliations.get(index).getOrganisation())) {
                    p.add(createSuperScript(String.valueOf(index + 1)));
                    isRepeated = true;
                    break;
                }
            }
            // if the agent is not repeated.
            if (!isRepeated) {
                p.add(createSuperScript(String.valueOf(superScriptCounter)));
                affiliations.add(agentsArray[c]);
                superScriptCounter++;
            }
        }
    }
    doc.add(p);
    p.clear();
    doc.add(Chunk.NEWLINE);
    tempAgents.clear();
    // <AFFILIATIONS>
    p = new Paragraph();
    p.setFont(font);
    p.setAlignment(Element.ALIGN_JUSTIFIED);
    for (int c = 0; c < affiliations.size(); c++) {
        if (c != 0) {
            p.add("; ");
        }
        p.add((c + 1) + " ");
        if (exists(affiliations.get(c).getOrganisation())) {
            p.add(affiliations.get(c).getOrganisation() + ", ");
        }
        if (exists(affiliations.get(c).getAddress().getAddress())) {
            p.add(affiliations.get(c).getAddress().getAddress() + ", ");
        }
        if (exists(affiliations.get(c).getAddress().getPostalCode())) {
            p.add(affiliations.get(c).getAddress().getPostalCode() + ", ");
        }
        if (exists(affiliations.get(c).getAddress().getCity())) {
            p.add(affiliations.get(c).getAddress().getCity());
        }
        if (exists(affiliations.get(c).getAddress().getCountry())) {
            VocabularyConcept concept = vocabManager.get(Constants.VOCAB_URI_COUNTRY)
                    .findConcept(affiliations.get(c).getAddress().getCountry());
            // write country in default language as matched from vocabulary or original value
            if (exists(concept)) {
                p.add(", " + WordUtils.capitalizeFully(concept.getPreferredTerm(DEFAULT_LANGUAGE).getTitle()));
            } else {
                p.add(", " + WordUtils.capitalizeFully(affiliations.get(c).getAddress().getCountry()));
            }
        }
    }
    doc.add(p);
    p.clear();
    doc.add(Chunk.NEWLINE);
    // <Corresponding Authors>
    p = new Paragraph();
    p.setAlignment(Element.ALIGN_JUSTIFIED);
    p.add(new Phrase(getText("rtf.authors") + ": ", fontTitle));
    p.setFont(font);
    boolean isFirst = true;
    if (exists(eml.getResourceCreator())) {
        if (exists(eml.getResourceCreator().getFirstName())) {
            p.add(eml.getResourceCreator().getFirstName() + " ");
        }
        p.add(eml.getResourceCreator().getLastName());
        if (exists(eml.getResourceCreator().getEmail())) {
            p.add(" (" + eml.getResourceCreator().getEmail() + ")");
        }
        isFirst = false;
    }
    if (exists(eml.getMetadataProvider())) {
        boolean sameAsCreator = false;
        if (!isFirst) {
            sameAsCreator = equal(eml.getMetadataProvider().getAddress(), eml.getResourceCreator().getAddress())
                    && equal(eml.getMetadataProvider().getEmail(), eml.getResourceCreator().getEmail());
        }
        if (!sameAsCreator) {
            p.add(", ");
            if (exists(eml.getMetadataProvider().getFirstName())) {
                p.add(eml.getMetadataProvider().getFirstName() + " ");
            }
            p.add(eml.getMetadataProvider().getLastName());
            if (exists(eml.getMetadataProvider().getEmail())) {
                p.add(" (" + eml.getMetadataProvider().getEmail() + ")");
            }
        }
    }
    p.add(Chunk.NEWLINE);
    doc.add(p);
    p.clear();
}

From source file:com.dell.asm.asmcore.asmmanager.util.ServiceTemplateValidator.java

/**
 * Validate server network configuration
 * @param component//from   w  w w. j  a  v a 2  s. c o m
 */
public void validateNetworks(ServiceTemplateComponent component, final Map<String, String> repoToTaskMap) {
    // for use with partition mask
    int M_PXE = 0x0000001;
    int M_HMGMT = 0x0000010;
    int M_HMGRN = 0x0000100;
    int M_HCLST = 0x0001000;
    int M_ISCSI = 0x0010000;
    int M_FILE = 0x0100000;
    int M_OTHER = 0x1000000;

    ServiceTemplateSetting networking = component
            .getTemplateSetting(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_NETWORK_CONFIG_ID);
    if (networking == null) {
        // some server components may not include networking configuration
        return;
    }

    // Skip network validation of hardware only configuration
    if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_COMPID_HW.equals(component.getComponentID())) {
        return;
    }

    com.dell.asm.asmcore.asmmanager.client.networkconfiguration.NetworkConfiguration networkConfig = getServiceTemplateUtil()
            .deserializeNetwork(networking.getValue());

    if (networkConfig == null) {
        LOGGER.warn("No networking configuration on server component: " + component.getAsmGUID());
        return;
    }
    boolean isSanBoot = component.hasSanBoot();
    boolean isNoneBoot = component.hasNoneBoot();
    boolean hasESX = component.hasESX(repoToTaskMap);
    boolean hasHyperV = component.hasHyperV();
    boolean hasBareMetalOS = component.hasBareMetal(repoToTaskMap);
    boolean isISCSIBoot = component.hasSanISCSIBoot();

    List<String> vMotionNetworks = new ArrayList<String>();
    List<String> pxeNetworks = new ArrayList<String>();
    List<String> hypManangementNetworks = new ArrayList<String>();
    List<String> vsanNetworks = new ArrayList<String>();
    List<String> fipsNetworks = new ArrayList<String>();

    boolean hasPXE = false;
    boolean hasStaticPXE = false;
    boolean hasPXEOnPartNot1 = false;
    boolean hasHypervisorMgmt = false;
    boolean hasHMOnPart1 = false;
    boolean hasHypervisorMigration = false;
    boolean hasHypervisorCluster = false;
    boolean hasISCSI = false;

    boolean hasHypervisorMgmtStatic = false;
    boolean hasHypervisorMigrationStatic = false;
    boolean hasHypervisorClusterStatic = false;
    boolean hasISCSIStatic = false;
    boolean hasInvalidPartitionNetwork = false;

    boolean hasOtherStatic = false;

    boolean componentInvalidForEsx = false;
    String errorCase = null;

    List<Interface> interfaces = networkConfig.getUsedInterfaces();

    HashSet<String> partitionNetworkTypes = new HashSet<String>();
    List<List<String>> workloadNetworksCheck = new ArrayList<List<String>>();
    List<String> bareMetalOsNetworkCheck = new ArrayList<String>();

    boolean iscsiOnPort1 = false;
    boolean foundSingleISCSIOnPort1 = false;

    boolean isBootDeviceFc = false;
    boolean fcNetworkPresent = false;

    final ServiceTemplateValid componentValid = component.getComponentValid();

    for (ServiceTemplateCategory category : safeList(component.getResources())) {
        for (ServiceTemplateSetting setting : safeList(category.getParameters())) {
            if ((setting.getId()
                    .equalsIgnoreCase(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_ID)
                    && setting.getValue()
                            .equals(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_TARGET_BOOTDEVICE_FC))) {
                isBootDeviceFc = true;
            }
            if (((setting.getId()
                    .equalsIgnoreCase(ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_NETWORK_CONFIG_ID)
                    && setting.getValue().toLowerCase().contains("\"usedforfc\":true")))
                    || ((setting.getId().equalsIgnoreCase(
                            ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_NETWORK_CONFIG_ID)
                            && setting.getValue().toLowerCase().contains("\"fabrictype\":\"fc\"")))) {
                fcNetworkPresent = true;
            }
        }
    }

    if (isBootDeviceFc && !fcNetworkPresent) {
        LOGGER.error("fcNetworksError");
        componentValid.addMessage(AsmManagerMessages.fcNwtworksValidation());
        componentValid.setValid(Boolean.FALSE);
    }

    for (Interface interfaceObject : interfaces) {

        if (interfaceObject.isPartitioned() && hasHyperV) {
            // stop vaidation here and return
            componentValid.addMessage(AsmManagerMessages.serverWithHyperVPartitioned());
            componentValid.setValid(Boolean.FALSE);
            return;
        }

        List<Partition> partitions = interfaceObject.getPartitions();

        for (Partition partition : partitions) {

            partitionNetworkTypes.clear();
            bareMetalOsNetworkCheck.clear();

            List<String> networkIds = partition.getNetworks();
            Integer curMask = 0;

            if (networkIds != null) {
                for (String networkId : networkIds) {

                    Network networkObject = getNetworkService().getNetwork(networkId);

                    // In general networkObject should never be null, but ran into cases with
                    // invalid default templates where it was.
                    String networkType = networkObject == null ? "" : networkObject.getType().value();

                    boolean isStatic = networkObject != null && networkObject.isStatic();
                    if (networkType.equals(NetworkType.STORAGE_ISCSI_SAN.value())) {
                        hasISCSI = true;
                        curMask |= M_ISCSI;
                        hasISCSIStatic = isStatic;

                        if (isSanBoot && !isStatic) {
                            // iSCSI must be static fo SAN boot iSCSI
                            componentValid.addMessage(AsmManagerMessages.iscsiMustHaveStatic());
                        }
                    } else if (networkType.equals(NetworkType.PXE.value())) {
                        hasPXE = true;
                        curMask |= M_PXE;
                        if (networkObject.isStatic()) {
                            hasStaticPXE = true;
                        }
                        if (!partition.getName().equals("1"))
                            hasPXEOnPartNot1 = true;

                    } else if (networkType.equals(NetworkType.HYPERVISOR_MANAGEMENT.value())) {
                        hasHypervisorMgmt = true;
                        curMask |= M_HMGMT;
                        if (partition.getName().equals("1"))
                            hasHMOnPart1 = true;

                        hasHypervisorMgmtStatic = isStatic;

                    } else if (networkType.equals(NetworkType.HYPERVISOR_CLUSTER_PRIVATE.value())) {
                        hasHypervisorCluster = true;
                        hasHypervisorClusterStatic = isStatic;
                        curMask |= M_HCLST;
                    } else if (networkType.equals(NetworkType.HYPERVISOR_MIGRATION.value())) {
                        hasHypervisorMigration = true;
                        hasHypervisorMigrationStatic = isStatic;
                        curMask |= M_HMGRN;
                    } else if (networkType.equals(NetworkType.FILESHARE.value())) {
                        curMask |= M_FILE;
                    } else {
                        curMask |= M_OTHER;

                        if (isStatic) {
                            hasOtherStatic = true;
                        }
                    }

                    if (hasESX) {
                        if (networkType.equals(NetworkType.HYPERVISOR_MIGRATION.value())) {
                            vMotionNetworks.add(networkId);
                        }

                        if (networkType.equals(NetworkType.PXE.value())) {
                            pxeNetworks.add(networkId);
                        }

                        if (networkType.equals(NetworkType.VSAN.value())) {
                            vsanNetworks.add(networkId);
                        }

                        if (networkType.equals(NetworkType.FIP_SNOOPING.value())) {
                            fipsNetworks.add(networkId);
                        }

                        if (networkType.equals(NetworkType.HYPERVISOR_MANAGEMENT.value())) {
                            hypManangementNetworks.add(networkId);
                        }

                        if (networkType.equals(NetworkType.PRIVATE_LAN.value())
                                || networkType.equals(NetworkType.PUBLIC_LAN.value())) {
                            List<String> netTemp = new ArrayList<String>();
                            for (String netId : networkIds) {
                                if (NetworkType.PRIVATE_LAN
                                        .equals(getNetworkService().getNetwork(netId).getType())
                                        || NetworkType.PUBLIC_LAN
                                                .equals(getNetworkService().getNetwork(netId).getType())) {
                                    netTemp.add(netId);
                                }
                            }
                            workloadNetworksCheck.add(netTemp);
                        }
                        partitionNetworkTypes.add(networkType);
                    }

                    if (hasBareMetalOS) {
                        if (!hasInvalidPartitionNetwork) {
                            // partition index, number, etc. is always 0; use the name to identify the partition index
                            if (component.hasLinuxOS() && !partition.getName().equals("1")) {
                                hasInvalidPartitionNetwork = true;
                                componentValid.addMessage(
                                        AsmManagerMessages.invalidPartitionForNetwork(component.getName()));
                            }
                        }
                        bareMetalOsNetworkCheck.add(networkType);
                    }
                }
            }

            if (hasBareMetalOS && bareMetalOsNetworkCheck.size() != 0) {
                boolean validNets = true;
                for (String netType : bareMetalOsNetworkCheck) {
                    if (!netType.equals(NetworkType.PXE.value())
                            && !netType.equals(NetworkType.PRIVATE_LAN.value())
                            && !netType.equals(NetworkType.PUBLIC_LAN.value())
                            && !netType.equals(NetworkType.STORAGE_FCOE_SAN.value())
                            && !netType.equals(NetworkType.FIP_SNOOPING.value())
                            && !netType.equals(NetworkType.FILESHARE.value())
                            && !netType.equals(NetworkType.STORAGE_ISCSI_SAN.value())) {
                        validNets = false;
                        LOGGER.error("incorrectNetworksOnBareMetalOs");
                        componentValid
                                .addMessage(AsmManagerMessages.incorrectNetworkConfForBareMetalAndLinux2());
                        break;
                    }
                }
                if (!validNets)
                    break;
            }

            if (hasESX) {
                if (partitionNetworkTypes.contains(NetworkType.FIP_SNOOPING.value())
                        && !(partitionNetworkTypes.contains(NetworkType.FIP_SNOOPING.value())
                                && partitionNetworkTypes.contains(NetworkType.STORAGE_FCOE_SAN.value()))) {
                    componentInvalidForEsx = true;
                    errorCase = ERROR_DUPLICATE_NETWORK_TYPE;
                    LOGGER.error(
                            "networkTypeDuplicateOnSamePartition - FIP Snooping FCOE Networks Partitions Error");
                }
            }

            // checks per port
            // Bare metal OS
            if (hasBareMetalOS) {
                if (interfaceObject.getName().equals("Port 1")) {

                    //  In the case of boot from iSCSI, iSCSI network must be selected for one of the NIC port1. And no other network can be seleced on the same port.
                    if (isISCSIBoot && hasISCSI) {
                        iscsiOnPort1 = true;
                    }

                    if (isISCSIBoot && hasISCSI && curMask == M_ISCSI) {
                        foundSingleISCSIOnPort1 = true;
                    }
                }
            }

            // ignore all but first partitions
            if (!interfaceObject.isPartitioned())
                break;
            // Different nic types have different number of partitions but data may include more that should be ignored
            if (partition.getName().equals(Integer.toString(interfaceObject.getMaxPartitions()))) {
                break;
            }

        }
    }

    if (hasBareMetalOS) {
        //  In the case of boot from iSCSI, iSCSI network must be selected for one of the NIC port1. And no other network can be seleced on the same port.
        if (isISCSIBoot && !iscsiOnPort1) {
            componentValid.addMessage(AsmManagerMessages.iscsiMustBeOnPort1());
        }
        if (isISCSIBoot && hasISCSI && !foundSingleISCSIOnPort1) {
            componentValid.addMessage(AsmManagerMessages.iscsiMustBeTheOnlyNetwork());
        }
    }

    // For any cases that requires ASM to deploy OS, need to make sure PXE network is selected.
    // this is required for full server component
    if (ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_COMPID_ALL.equals(component.getComponentID())) {
        if (!isSanBoot && !isNoneBoot && !hasPXE) {
            componentValid.addMessage(AsmManagerMessages.serverMustHavePXE());
        } else {
            // Installing Hyper-V or Windows using a static OS Installation network is not currently supported
            if (hasStaticPXE) {
                ServiceTemplateSetting osVersion = component.getParameter(
                        ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_OS_RESOURCE,
                        ServiceTemplateSettingIDs.SERVICE_TEMPLATE_SERVER_OS_VERSION_ID);
            }

            if (hasBareMetalOS) {
                if (hasPXE && hasPXEOnPartNot1)
                    componentValid.addMessage(AsmManagerMessages.wrongPartition(NetworkType.PXE.value(), 1));
            }

            // In the case for Hyper-v, make sure required networks are selected.
            // Hypervisor Mgmt, Hypervisor Migration, Hypervisor Cluster private, PXE, iSCSI
            // no partitions
            if (hasHyperV) {
                if (!hasPXE)
                    componentValid.addMessage(
                            AsmManagerMessages.serverMissedNetwork("Hyper-V", NetworkType.PXE.value()));
                else if (hasPXE && hasPXEOnPartNot1)
                    componentValid.addMessage(AsmManagerMessages.wrongPartition(NetworkType.PXE.value(), 1));
                else if (!hasHypervisorMgmt)
                    componentValid.addMessage(AsmManagerMessages.serverMissedNetwork("Hyper-V",
                            NetworkType.HYPERVISOR_MANAGEMENT.value()));
                else if (hasHypervisorMgmt && !hasHMOnPart1)
                    componentValid.addMessage(
                            AsmManagerMessages.wrongPartition(NetworkType.HYPERVISOR_MANAGEMENT.value(), 1));
                else if (!hasHypervisorMigration)
                    componentValid.addMessage(AsmManagerMessages.serverMissedNetwork("Hyper-V",
                            NetworkType.HYPERVISOR_MIGRATION.value()));
                else if (!hasHypervisorCluster)
                    componentValid.addMessage(AsmManagerMessages.serverMissedNetwork("Hyper-V",
                            NetworkType.HYPERVISOR_CLUSTER_PRIVATE.value()));

                if (hasISCSI && !hasISCSIStatic) {
                    componentValid.addMessage(
                            AsmManagerMessages.hypervRequiresStatic(NetworkType.STORAGE_ISCSI_SAN.value()));
                } else if (!hasHypervisorMgmtStatic) {
                    componentValid.addMessage(
                            AsmManagerMessages.hypervRequiresStatic(NetworkType.HYPERVISOR_MANAGEMENT.value()));
                } else if (!hasHypervisorMigrationStatic) {
                    componentValid.addMessage(
                            AsmManagerMessages.hypervRequiresStatic(NetworkType.HYPERVISOR_MIGRATION.value()));
                } else if (!hasHypervisorClusterStatic) {
                    componentValid.addMessage(AsmManagerMessages
                            .hypervRequiresStatic(NetworkType.HYPERVISOR_CLUSTER_PRIVATE.value()));
                }
            }

            // In the case for ESXi, make sure required networks are selected.
            // Hypervisor Mgmt, Hypervisor Migration, Hypervisor Cluster private, PXE must be partition 1
            if (hasESX) {

                HashSet<String> duplicateNetworkCheck;

                if (!hasPXE)
                    componentValid
                            .addMessage(AsmManagerMessages.serverMissedNetwork("ESX", NetworkType.PXE.value()));
                else if (hasPXE && hasPXEOnPartNot1)
                    componentValid.addMessage(AsmManagerMessages.wrongPartition(NetworkType.PXE.value(), 1));
                else if (!hasHypervisorMgmt)
                    componentValid.addMessage(AsmManagerMessages.serverMissedNetwork("ESX",
                            NetworkType.HYPERVISOR_MANAGEMENT.value()));

                if (workloadNetworksCheck.size() > 1) {
                    for (List<String> partitionNetworks : workloadNetworksCheck) {
                        if (!(partitionNetworks.containsAll(workloadNetworksCheck.get(1))
                                && workloadNetworksCheck.get(1).containsAll(partitionNetworks))) {
                            componentInvalidForEsx = true;
                            errorCase = ERROR_WORKLOAD_NETS_NOT_SAME;
                            LOGGER.error(ERROR_WORKLOAD_NETS_NOT_SAME);
                        }
                    }
                }

                duplicateNetworkCheck = new HashSet<>(pxeNetworks);
                if (duplicateNetworkCheck.size() > 1) {
                    componentInvalidForEsx = true;
                    errorCase = ERROR_DUPLICATE_NETWORKS;
                    LOGGER.error("duplicateNetworkCheck - PXE");
                }

                duplicateNetworkCheck = new HashSet<>(vMotionNetworks);
                if (duplicateNetworkCheck.size() > 1) {
                    componentInvalidForEsx = true;
                    errorCase = ERROR_DUPLICATE_NETWORKS;
                    LOGGER.error("duplicateNetworkCheck - vMotionNetworks");
                }

                duplicateNetworkCheck = new HashSet<>(hypManangementNetworks);
                if (duplicateNetworkCheck.size() > 1) {
                    componentInvalidForEsx = true;
                    errorCase = ERROR_DUPLICATE_NETWORKS;
                    LOGGER.error("duplicateNetworkCheck - hypManangementNetworks");
                }

                duplicateNetworkCheck = new HashSet<>(fipsNetworks);
                if (duplicateNetworkCheck.size() > 1) {
                    componentInvalidForEsx = true;
                    errorCase = ERROR_DUPLICATE_NETWORKS;
                    LOGGER.error("duplicateNetworkCheck - fipsNetworks");
                }

                if (componentInvalidForEsx) {
                    if (ERROR_DUPLICATE_NETWORKS.equals(errorCase))
                        componentValid.addMessage(AsmManagerMessages.networksDuplicate());

                    if (ERROR_DUPLICATE_NETWORK_TYPE.equals(errorCase))
                        componentValid.addMessage(AsmManagerMessages.networkTypeDuplicate());

                    if (ERROR_WORKLOAD_NETS_NOT_SAME.equals(errorCase))
                        componentValid.addMessage(AsmManagerMessages.workloadNetworksNotSame());
                }
            }
        }
    }

    if (CollectionUtils.isNotEmpty(componentValid.getMessages())) {
        componentValid.setValid(Boolean.FALSE);
    }
}

From source file:com.krawler.formbuilder.servlet.ReportBuilderDaoImpl.java

public String saveReportGridConfig(String jsonstr, String reportid, boolean createTable, String tbar,
        String bbar) throws ServiceException {
    String result = "{\"success\":true}";
    String tableName = "";
    //        String jsonstr = request.getParameter("jsondata");
    try {/*from  w w w .j  av  a  2 s  . c om*/
        JSONObject jobj = new JSONObject();
        //            String reportid = request.getParameter("reportid");
        //            boolean createTable = Boolean.parseBoolean(request.getParameter("createtable"));
        mb_reportlist report = (mb_reportlist) get(mb_reportlist.class, reportid);
        if (createTable) {
            tableName = "rb_" + toLZ(report.getReportkey(), 3) + "_"
                    + report.getReportname().replace(" ", "").toLowerCase();
        } else {
            tableName = report.getTablename();
        }
        HashSet<String> hashSet = new HashSet<String>();
        HashSet<String> finalHashSet = new HashSet<String>();

        String hql = "delete from com.krawler.esp.hibernate.impl.mb_gridconfig as mb_gridconfig where mb_gridconfig.reportid = ? ";
        int numDelRec = executeUpdate(hql, new Object[] { report });
        JSONArray jsonArray = new JSONArray(jsonstr);
        int confCnt = 0;
        for (int k = 0; k < jsonArray.length(); k++) {
            jobj = jsonArray.getJSONObject(k);
            if (!jobj.getString("name").equals("id")) {
                com.krawler.esp.hibernate.impl.mb_gridconfig gridConf = new com.krawler.esp.hibernate.impl.mb_gridconfig();
                //                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-d HH:mm:ss");
                //                java.sql.Timestamp timestamp1 = Timestamp.valueOf(sdf.format(new java.util.Date()));
                if (jobj.getString("name").indexOf(".") > -1) {
                    String[] tablecolumn = jobj.getString("name").split("\\.");
                    gridConf.setName(
                            tablecolumn[0] + PropsValues.REPORT_HARDCODE_STR + tablecolumn[1].toLowerCase());
                } else {
                    if (jobj.getString("name").indexOf(PropsValues.REPORT_HARDCODE_STR) == -1) {
                        //                            String Columnname = moduleBuilderMethods.getColumnName(moduleBuilderMethods.getcolumnNameStr(jobj.getString("name").toLowerCase()));
                        String Columnname = jobj.getString("name").toLowerCase();
                        gridConf.setName(tableName + PropsValues.REPORT_HARDCODE_STR + Columnname);
                    }
                }

                if (StringUtil.isNullOrEmpty(jobj.getString("displayfield")))
                    gridConf.setDisplayfield(jobj.getString("name"));
                else
                    gridConf.setDisplayfield(jobj.getString("displayfield"));

                if (!StringUtil.isNullOrEmpty(jobj.getString("reftable"))) {
                    gridConf.setReftable(jobj.getString("reftable"));
                } else if (StringUtil.isNullOrEmpty(jobj.getString("reftable"))
                        && !jobj.getString("combogridconfig").equals("-1")) {
                    gridConf.setReftable("");
                } else {
                    if (createTable)
                        gridConf.setReftable(tableName);
                }
                gridConf.setXtype(jobj.getString("xtype"));
                renderer render = null;
                if (jobj.getString("renderer").length() > 0) {
                    render = (renderer) get(renderer.class, jobj.getString("renderer"));
                } else {
                    render = (renderer) get(renderer.class, "0");
                } //
                gridConf.setRenderer(render);
                // gridConf.setFilter(jobj.getString("filter"));
                gridConf.setSummaryType(jobj.getString("summaryType"));
                gridConf.setDefaultValue(jobj.getString("defaultValue"));
                gridConf.setHidden(Boolean.parseBoolean(jobj.getString("hidden")));
                gridConf.setCountflag(Boolean.parseBoolean(jobj.getString("countflag")));
                String combogridconfig = "-1";
                String refTable = jobj.getString("reftable");
                String xtype = jobj.getString("xtype");
                if (xtype.equals("Combobox") && !StringUtil.isNullOrEmpty(refTable)
                        && !refTable.equals(tableName)) {
                    String SELECT_QUERY = "Select mb_reportlist.reportid from com.krawler.esp.hibernate.impl.mb_reportlist as mb_reportlist "
                            + " where mb_reportlist.tablename = ?";
                    List list = find(SELECT_QUERY, new Object[] { refTable });

                    Iterator ite = list.iterator();
                    String reportid1 = null;
                    if (ite.hasNext()) {
                        reportid1 = (String) ite.next();
                    }
                    if (reportid1 != null) {
                        String name = null;
                        if (jobj.getString("name").indexOf(".") > -1) {
                            String[] tablecolumn = jobj.getString("name").split("\\.");
                            name = tablecolumn[0] + PropsValues.REPORT_HARDCODE_STR
                                    + tablecolumn[1].toLowerCase();
                        } else {
                            if (jobj.getString("name").indexOf(PropsValues.REPORT_HARDCODE_STR) == -1)
                                name = tableName + PropsValues.REPORT_HARDCODE_STR
                                        + jobj.getString("name").toLowerCase();
                        }
                        mb_reportlist report1 = (mb_reportlist) get(mb_reportlist.class, reportid1);
                        SELECT_QUERY = "select mb_gridconfig.combogridconfig from com.krawler.esp.hibernate.impl.mb_gridconfig as mb_gridconfig "
                                + "where mb_gridconfig.reportid = ? and mb_gridconfig.name = ?";
                        list = find(SELECT_QUERY, new Object[] { report1, name });
                        ite = list.iterator();
                        if (ite.hasNext()) {
                            combogridconfig = (String) ite.next();
                        }
                    }
                } else if (!jobj.getString("combogridconfig").equals("-1")) {
                    combogridconfig = jobj.getString("combogridconfig");
                }

                gridConf.setCombogridconfig(combogridconfig);
                gridConf.setColumnindex(k);
                gridConf.setReportid(report);
                save(gridConf);
                String strid = gridConf.getId();
                confCnt++;
                if (!StringUtil.isNullOrEmpty(jobj.getString("reftable"))
                        && !jobj.getString("reftable").equals(tableName)) {
                    String fkKeyName = jobj.getString("reftable") + "."
                            + (getPrimaryColName(jobj.getString("reftable")));
                    if (fkKeyName.equals(jobj.getString("name"))) {
                        hashSet.add(fkKeyName);
                        finalHashSet.remove(fkKeyName);
                    } else if (!hashSet.contains(fkKeyName)) {
                        finalHashSet.add(fkKeyName);
                    }
                }
            }
        }

        if (finalHashSet.size() > 0) {
            Iterator itr = finalHashSet.iterator();
            while (itr.hasNext()) {
                //Insert id fields of reference tables
                com.krawler.esp.hibernate.impl.mb_gridconfig gridConf = new com.krawler.esp.hibernate.impl.mb_gridconfig();
                String tablecolumn = itr.next().toString();
                tablecolumn = tablecolumn.replace(".", PropsValues.REPORT_HARDCODE_STR);
                gridConf.setName(tablecolumn);
                gridConf.setDisplayfield(tablecolumn);
                gridConf.setReftable(tablecolumn.split(PropsValues.REPORT_HARDCODE_STR)[0]);
                gridConf.setXtype("None");
                gridConf.setHidden(true);
                renderer render = (renderer) get(renderer.class, "0");
                gridConf.setRenderer(render);
                gridConf.setColumnindex(confCnt++);
                gridConf.setReportid(report);
                gridConf.setCombogridconfig("-1");
                //gridConf.setFilter("");
                gridConf.setCountflag(false);
                save(gridConf);
            }
            //            String actionType = "Add Report Grid Config";
            //            String details = "Grid Config added for Report "+report.getReportname();
            //            long actionId = AuditTrialHandler.getActionId(session, actionType);
            //            AuditTrialHandler.insertAuditLog(session, actionId, details, request);
        }

        if (createTable) {
            int cnt = 0;
            //Insert id field of new table
            com.krawler.esp.hibernate.impl.mb_gridconfig gridConf = new com.krawler.esp.hibernate.impl.mb_gridconfig();
            gridConf.setName(tableName + PropsValues.REPORT_HARDCODE_STR + "id");
            gridConf.setDisplayfield("id");
            gridConf.setReftable(tableName);
            gridConf.setXtype("None");
            gridConf.setHidden(true);
            renderer render = (renderer) get(renderer.class, "0");
            gridConf.setRenderer(render);
            gridConf.setColumnindex(confCnt++);
            gridConf.setReportid(report);
            gridConf.setCombogridconfig("-1");
            //            gridConf.setFilter("");
            gridConf.setCountflag(false);
            save(gridConf);

            // save report table name
            report.setTablename(tableName);
            save(report);

            ArrayList<Hashtable<String, Object>> aList = new ArrayList<Hashtable<String, Object>>();

            Object[] objArrField = new Object[] { "name", "type", "primaryid", "default" };
            Object[] objArr = new Object[] { "id", "String", "true", "" };
            moduleBuilderGenerateTable.makeEntryToArrayList(cnt, aList, objArr, objArrField);

            objArrField = new Object[] { "name", "type", "default" };
            objArr = new Object[] { "createdby", "String", "" };
            moduleBuilderGenerateTable.makeEntryToArrayList(cnt, aList, objArr, objArrField);

            objArr = new Object[] { "createddate", "Date", "" };
            moduleBuilderGenerateTable.makeEntryToArrayList(cnt, aList, objArr, objArrField);

            objArr = new Object[] { "modifieddate", "Date", "" };
            moduleBuilderGenerateTable.makeEntryToArrayList(cnt, aList, objArr, objArrField);

            objArr = new Object[] { "deleteflag", "double", "" };
            moduleBuilderGenerateTable.makeEntryToArrayList(cnt, aList, objArr, objArrField);

            HashSet<String> hs = new HashSet<String>();
            for (int k = 0; k < jsonArray.length(); k++) {
                JSONObject obj = jsonArray.getJSONObject(k);

                if (!StringUtil.isNullOrEmpty(obj.getString("reftable"))
                        && !obj.getString("reftable").equals(tableName)) {
                    if (!Boolean.parseBoolean(obj.getString("countflag"))) {
                        if (hs.add(obj.getString("reftable"))) {
                            Object[] objArrField1 = new Object[] { "name", "reftable", "type", "foreignid",
                                    "default" };
                            String fkKeyName = obj.getString("reftable")
                                    .concat(getPrimaryColName(obj.getString("reftable")));
                            objArr = new Object[] { fkKeyName, obj.getString("reftable"), "String", true,
                                    obj.getString("defaultValue") };
                            moduleBuilderGenerateTable.makeEntryToArrayList(cnt, aList, objArr, objArrField1);
                        }
                    }
                } else {
                    if (!obj.getString("name").equals("id")) {
                        String type = "";
                        if (obj.getString("xtype").equals("Checkbox")
                                || obj.getString("xtype").equals("Radio")) {
                            type = "boolean";
                        } else if (obj.getString("xtype").equals("Date")) {
                            type = "Date";
                        } else if (obj.getString("xtype").equals("Number(Integer)")) {
                            type = "int";
                        } else if (obj.getString("xtype").equals("Number(Float)")) {
                            type = "double";
                        } else if (obj.getString("xtype").equals("Combobox")) {
                            type = "String";
                        } else {
                            type = "String";
                        }

                        objArr = new Object[] { obj.getString("name").toLowerCase(), type,
                                obj.getString("defaultValue") };
                        moduleBuilderGenerateTable.makeEntryToArrayList(cnt, aList, objArr, objArrField);
                    }
                }
            }
            hs.clear();
            ServiceBuilder sb = new ServiceBuilder();
            //                sb.createServiceXMLFile(aList, tableName);
            sb.createJavaFile(tableName, true);
            //                String actionType = "Add Report Grid Config Table";
            //                String details = "Grid Cofig Table added for Report "+report.getReportname();
            //                long actionId = AuditTrialHandler.getActionId(session, actionType);
            //                AuditTrialHandler.insertAuditLog(session, actionId, details, request);
        } else {
            String className = "rb_" + toLZ(report.getReportkey(), 3) + "_"
                    + report.getReportname().replace(" ", "").toLowerCase();
            // save report table name
            //report.setTablename(className);
            //session.save(report);
            //Create only implementation java class for report for which no new table is created.
            ServiceBuilder sb = new ServiceBuilder();
            sb.createImplJavaFile(className, true);
        }

        //            if(numDelRec==0) { // if first time store then add permission entry for add/edit/delete action
        //                mb_permgrmaster permgrmaster = new mb_permgrmaster();
        //                accessRight.addPermGrp(session,permgrmaster,report);
        //                com.krawler.esp.hibernate.impl.mb_permmaster permmaster = null;
        //                for(int i=2;i<9;i++) {
        //                    permmaster = new com.krawler.esp.hibernate.impl.mb_permmaster();
        //                    mb_permactions permaction = (mb_permactions) session.load(mb_permactions.class,i);
        //                    permmaster.setPermaction(permaction);
        //                    permmaster.setPermname(permaction.getName());
        //                    permmaster.setDescription(permaction.getName());
        //                    permmaster.setPermgrid(permgrmaster);
        //                    permmaster.setPermid(accessRight.getMaxPermid(session, permgrmaster.getPermgrid()));
        //                    session.save(permmaster);
        //                }
        //            }

        storeToolbarConf(reportid, tbar, bbar);

        hql = "SELECT mb_gridconfig.columnindex,mb_gridconfig.hidden,mb_gridconfig.reftable,mb_gridconfig.renderer,mb_gridconfig.xtype,mb_gridconfig.displayfield,mb_gridconfig.name "
                + "FROM com.krawler.esp.hibernate.impl.mb_gridconfig AS mb_gridconfig "
                + "WHERE mb_gridconfig.reportid = ?";
        List list = find(hql, new Object[] { report });
        Iterator ite = list.iterator();
        JSONObject r = new JSONObject();
        while (ite.hasNext()) {
            Object[] row = (Object[]) ite.next();
            JSONObject temp = new JSONObject();
            temp.put("index", row[0]);
            temp.put("hidden", row[1]);
            temp.put("reftable", row[2]);
            temp.put("renderer", row[3]);
            temp.put("xtype", row[4]);
            temp.put("displayfield", row[5]);
            temp.put("name", row[6]);
            r.append("data", temp);
        }
        r.put("success", true);
        r.put("reportId", reportid);
        r.put("tablename", tableName);
        result = r.toString();
    } catch (JSONException e) {
        logger.warn(e.getMessage(), e);
        result = "{\"success\":false}";
        throw ServiceException.FAILURE("reportbuilder.saveReportGridConfig", e);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        result = "{\"success\":false}";
        throw ServiceException.FAILURE("reportbuilder.saveReportGridConfig", e);
    }
    return result;
}

From source file:hudson.plugins.project_inheritance.projects.InheritanceProject.java

public Map<InheritanceProject, Relationship> getRelationships() {
    Object obj = onInheritChangeBuffer.get(this, "getRelationships");
    if (obj != null && obj instanceof Map) {
        return (Map) obj;
    }//from   w  w w. j  ava2  s .  c  o m

    //Creating the returned map and pre-filling it with empty lists
    Map<InheritanceProject, Relationship> map = new HashMap<InheritanceProject, Relationship>();

    //Preparing the set of projects that were already explored
    HashSet<String> seenProjects = new HashSet<String>();

    //Fetching the map of all projects and their connections
    Map<String, ProjectGraphNode> connGraph = getConnectionGraph();

    //Fetching the node for the current (this) project
    ProjectGraphNode node = connGraph.get(this.getName());
    if (node == null) {
        return map;
    }

    //Mates can be filled quite easily
    for (String mate : node.mates) {
        InheritanceProject p = InheritanceProject.getProjectByName(mate);
        ProjectGraphNode mateNode = connGraph.get(mate);
        boolean isLeaf = (mateNode == null) ? true : mateNode.children.isEmpty();
        if (p == null) {
            continue;
        }
        //Checking if we've seen this mate already
        if (!seenProjects.contains(p.getName())) {
            map.put(p, new Relationship(Relationship.Type.MATE, 0, isLeaf));
            seenProjects.add(p.getName());
        }
    }

    //Exploring parents
    int distance = 1;
    seenProjects.clear();
    LinkedList<InheritanceProject> cOpen = new LinkedList<InheritanceProject>();
    LinkedList<InheritanceProject> nOpen = new LinkedList<InheritanceProject>();
    cOpen.add(this);
    while (!cOpen.isEmpty()) {
        InheritanceProject ip = cOpen.pop();
        if (ip == null || seenProjects.contains(ip.getName())) {
            continue;
        }
        seenProjects.add(ip.getName());

        node = connGraph.get(ip.getName());
        if (ip == null || node == null) {
            continue;
        }
        //Adding all parents
        for (String parent : node.parents) {
            InheritanceProject par = InheritanceProject.getProjectByName(parent);
            if (par == null || seenProjects.contains(parent)) {
                continue;
            }
            map.put(par, new Relationship(Relationship.Type.PARENT, distance, false));
            nOpen.push(par);
        }
        if (cOpen.isEmpty() && !nOpen.isEmpty()) {
            cOpen = nOpen;
            nOpen = new LinkedList<InheritanceProject>();
            distance++;
        }
    }

    //Exploring children
    distance = 1;
    seenProjects.clear();
    cOpen.clear();
    nOpen.clear();
    cOpen.add(this);
    while (!cOpen.isEmpty()) {
        InheritanceProject ip = cOpen.pop();
        if (ip == null || seenProjects.contains(ip.getName())) {
            continue;
        }
        seenProjects.add(ip.getName());

        node = connGraph.get(ip.getName());
        if (ip == null || node == null) {
            continue;
        }
        //Adding all parents
        for (String child : node.children) {
            InheritanceProject cProj = InheritanceProject.getProjectByName(child);
            if (cProj == null || seenProjects.contains(child)) {
                continue;
            }
            ProjectGraphNode childNode = connGraph.get(child);
            boolean isLeaf = (childNode == null) ? true : childNode.children.isEmpty();
            map.put(cProj, new Relationship(Relationship.Type.CHILD, distance, isLeaf));
            nOpen.push(cProj);
        }
        if (cOpen.isEmpty() && !nOpen.isEmpty()) {
            cOpen = nOpen;
            nOpen = new LinkedList<InheritanceProject>();
            distance++;
        }
    }

    onInheritChangeBuffer.set(this, "getRelationships", map);
    return map;
}

From source file:org.apache.stratos.aws.extension.AWSLoadBalancer.java

public boolean configure(Topology topology) throws LoadBalancerExtensionException {

    log.info("AWS load balancer extension is being reconfigured.");

    HashSet<String> activeClusters = new HashSet<String>();

    for (Service service : topology.getServices()) {
        for (Cluster cluster : service.getClusters()) {
            // Check if a load balancer is created for this cluster
            if (clusterIdToLoadBalancerMap.containsKey(cluster.getClusterId())) {
                // A load balancer is already present for this cluster
                // Get the load balancer and update it.

                if (log.isDebugEnabled()) {
                    log.debug(String.format("Load balancer for cluster %s is already present.",
                            cluster.getClusterId()));
                }/*w ww.  ja  va  2s.  c o  m*/

                if (updateExistingLoadBalancer(cluster)) {
                    activeClusters.add(cluster.getClusterId());
                }

            } else {
                // Create a new load balancer for this cluster
                Collection<Member> clusterMembers = cluster.getMembers();

                if (clusterMembers.size() > 0) {
                    Member aMember = clusterMembers.iterator().next();

                    // a unique load balancer name with user-defined prefix and a sequence number.
                    String loadBalancerName = awsHelper.generateLoadBalancerName(cluster.getServiceName());

                    String region = awsHelper.getAWSRegion(aMember.getInstanceId());

                    // list of AWS listeners obtained using port mappings of one of the members of the cluster.
                    List<Listener> listenersForThisCluster = awsHelper.getRequiredListeners(aMember);

                    // Get the initial zone identifier list (a, b, c) to consider in creating
                    // the LB as defined in aws.properties file
                    Set<String> initialZones = awsHelper.getInitialZones();

                    Set<String> initialAvailabilityZones = new HashSet<>();
                    if (initialZones.isEmpty()) {
                        // initial availability zones not defined
                        // use the default (<region>a)
                        initialAvailabilityZones.add(awsHelper.getAvailabilityZoneFromRegion(region));
                    } else {
                        // prepend the region and construct the availability zone list with
                        // full names (<region> + <zone>)
                        for (String zone : initialZones) {
                            initialAvailabilityZones.add(region + zone);
                        }
                    }
                    String loadBalancerDNSName = createAWSLoadBalancer(loadBalancerName, region,
                            listenersForThisCluster, initialAvailabilityZones);

                    log.info(String.format("Load balancer %s  created for cluster %s ", loadBalancerDNSName,
                            cluster.getClusterId()));

                    if (addClusterMembersInfo(clusterMembers, loadBalancerName, region)) {
                        activeClusters.add(cluster.getClusterId());
                    }

                    // persist LB info
                    try {
                        persistenceManager
                                .persist(new LBInfoDTO(loadBalancerName, cluster.getClusterId(), region));

                    } catch (PersistenceException e) {
                        log.error(String.format(
                                "Unable to persist LB Information for %s , cluster id %s " + loadBalancerName,
                                cluster.getClusterId()));
                    }

                    LoadBalancerInfo loadBalancerInfo = new LoadBalancerInfo(loadBalancerName, region);
                    clusterIdToLoadBalancerMap.put(cluster.getClusterId(), loadBalancerInfo);

                }

                pause(3000);
            }
        }
    }

    // if 'terminate.lb.on.cluster.removal' = true in aws-extension.sh
    if (AWSExtensionContext.getInstance().terminateLBOnClusterRemoval()) {

        // Find out clusters which were present earlier but are not now.
        List<String> clustersToRemoveFromMap = new ArrayList<String>();
        // TODO: improve using an iterator and removing the unwanted cluster id in this loop
        for (String clusterId : clusterIdToLoadBalancerMap.keySet()) {
            if (!activeClusters.contains(clusterId)) {
                clustersToRemoveFromMap.add(clusterId);

                if (log.isDebugEnabled()) {
                    log.debug("Load balancer for cluster " + clusterId + " needs to be removed.");
                }

            }
        }

        // Delete load balancers associated with these clusters.
        for (String clusterId : clustersToRemoveFromMap) {
            // Remove load balancer for this cluster.
            final String loadBalancerName = clusterIdToLoadBalancerMap.get(clusterId).getName();
            final String region = clusterIdToLoadBalancerMap.get(clusterId).getRegion();
            awsHelper.deleteLoadBalancer(loadBalancerName, region);
            //remove and persist
            try {
                persistenceManager.remove(new LBInfoDTO(loadBalancerName, clusterId, region));

            } catch (PersistenceException e) {
                log.error("Unable to persist LB Information for " + loadBalancerName + ", cluster id "
                        + clusterId);
            }
            clusterIdToLoadBalancerMap.remove(clusterId);
        }
    }

    activeClusters.clear();
    log.info("AWS load balancer extension was reconfigured as per the topology.");
    return true;
}

From source file:gov.nih.nci.evs.browser.utils.SearchUtils.java

ResolvedConceptReferencesIterator getResolvedConceptReferencesIteratorUnion(String scheme, String version,
        Vector<ResolvedConceptReferencesIterator> v) {
    if (v == null)
        return null;
    int maxReturn = 100;
    Vector w = new Vector();
    HashSet hset = new HashSet();
    ResolvedConceptReferencesIterator matchIterator = null;

    for (int i = 0; i < v.size(); i++) {
        ResolvedConceptReferencesIterator iterator = (ResolvedConceptReferencesIterator) v.elementAt(i);
        try {/*from   www. ja  v a 2s .  co m*/
            while (iterator != null && iterator.hasNext()) {
                ResolvedConceptReferenceList rcrl = iterator.next(maxReturn);
                if (rcrl != null) {
                    ResolvedConceptReference[] refs = rcrl.getResolvedConceptReference();

                    if (refs != null) {
                        for (ResolvedConceptReference ref : refs) {
                            if (ref != null) {
                                if (!hset.contains(ref.getConceptCode())) {
                                    w.add(ref.getConceptCode());
                                    hset.add(ref.getConceptCode());
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    if (w.size() > 0) {
        String[] codes = new String[w.size()];
        for (int i = 0; i < w.size(); i++) {
            String code = (String) w.elementAt(i);
            codes[i] = code;
        }

        try {
            LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
            if (lbSvc == null) {
                _logger.warn("lbSvc == null???");
                return null;
            }

            CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
            if (version != null)
                versionOrTag.setVersion(version);

            ConceptReferenceList crefs = createConceptReferenceList(codes, scheme);
            CodedNodeSet cns = lbSvc.getCodingSchemeConcepts(scheme, null);
            cns = cns.restrictToCodes(crefs);
            CodedNodeSet.PropertyType[] types = new PropertyType[] { PropertyType.PRESENTATION };
            cns = cns.restrictToProperties(null, types, null, null, null);

            try {
                matchIterator = cns.resolve(null, null, null);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        hset.clear();
    }
    return matchIterator;

}