Example usage for java.util HashSet size

List of usage examples for java.util HashSet size

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:org.kuali.ole.vnd.document.validation.impl.VendorRule.java

/**
 * Validates vendor address fields.//from w  w w .j a v a  2 s .co  m
 *
 * @param document MaintenanceDocument
 * @return boolean false or true
 */
boolean processAddressValidation(MaintenanceDocument document) {
    boolean valid = true;
    boolean validAddressType = false;

    List<VendorAddress> addresses = newVendor.getVendorAddresses();
    String vendorTypeCode = newVendor.getVendorHeader().getVendorTypeCode();
    String vendorAddressTypeRequiredCode = newVendor.getVendorHeader().getVendorType()
            .getVendorAddressTypeRequiredCode();
    if (addresses.size() == 0) {
        putFieldError(VendorPropertyConstants.VENDOR_ADDRESS, VendorKeyConstants.OLE_VENDOR_ADDRESS);
        //GlobalVariables.getMessageMap().putError(VendorPropertyConstants.VENDOR_ADDRESS, VendorKeyConstants.OLE_VENDOR_ADDRESS, "");
        valid = false;
        validAddressType = false;
    }
    if (valid) {

        for (int i = 0; i < addresses.size(); i++) {
            VendorAddress address = addresses.get(i);
            String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i
                    + "]";
            GlobalVariables.getMessageMap().clearErrorPath();
            GlobalVariables.getMessageMap().addToErrorPath(errorPath);

            this.getDictionaryValidationService().validateBusinessObject(address);
            if (GlobalVariables.getMessageMap().hasErrors()) {
                valid = false;
            }

            if (address.getVendorAddressTypeCode().equals(vendorAddressTypeRequiredCode)) {
                validAddressType = true;
            }

            valid &= checkFaxNumber(address);

            valid &= checkAddressCountryEmptyStateZip(address);

            GlobalVariables.getMessageMap().clearErrorPath();
        }

        List<VendorPhoneNumber> phoneNumbers = newVendor.getVendorPhoneNumbers();
        for (int j = 0; j < phoneNumbers.size(); j++) {
            VendorPhoneNumber phoneNumber = phoneNumbers.get(j);
            String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_PHONE_NUMBERS + "["
                    + j + "]";
            GlobalVariables.getMessageMap().clearErrorPath();
            GlobalVariables.getMessageMap().addToErrorPath(errorPath);
            this.getDictionaryValidationService().validateBusinessObject(phoneNumber);
            valid &= checkPhoneNumber(phoneNumber);
        }

        // validate Address Type
        String vendorAddressTabPrefix = OLEConstants.ADD_PREFIX + "." + VendorPropertyConstants.VENDOR_ADDRESS
                + ".";
        if (!StringUtils.isBlank(vendorTypeCode) && !StringUtils.isBlank(vendorAddressTypeRequiredCode)
                && !validAddressType) {
            String[] parameters = new String[] { vendorTypeCode, vendorAddressTypeRequiredCode };
            putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_TYPE_CODE,
                    VendorKeyConstants.ERROR_ADDRESS_TYPE, parameters);
            String addressLine1Label = SpringContext.getBean(DataDictionaryService.class)
                    .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_LINE_1);
            String addressCityLabel = SpringContext.getBean(DataDictionaryService.class)
                    .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_CITY);
            String addressCountryLabel = SpringContext.getBean(DataDictionaryService.class)
                    .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_COUNTRY);
            putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_LINE_1,
                    OLEKeyConstants.ERROR_REQUIRED, addressLine1Label);
            putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_CITY,
                    OLEKeyConstants.ERROR_REQUIRED, addressCityLabel);
            putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_COUNTRY,
                    OLEKeyConstants.ERROR_REQUIRED, addressCountryLabel);
            valid = false;
        }

        valid &= validateDefaultAddressCampus(newVendor);

        // Check to see if all divisions have one desired address for this vendor type
        Map fieldValues = new HashMap();
        fieldValues.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID,
                newVendor.getVendorHeaderGeneratedIdentifier());
        // Find all the addresses for this vendor and its divisions:
        List<VendorAddress> vendorDivisionAddresses = new ArrayList(
                SpringContext.getBean(BusinessObjectService.class).findMatchingOrderBy(VendorAddress.class,
                        fieldValues, VendorPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, true));

        // This set stores the vendorDetailedAssignedIds for the vendor divisions which is
        // bascically the division numbers 0, 1, 2, ...
        HashSet<Integer> vendorDetailedIds = new HashSet();
        // This set stores the vendor division numbers of the ones which have one address of the desired type
        HashSet<Integer> vendorDivisionsIdsWithDesiredAddressType = new HashSet();

        for (VendorAddress vendorDivisionAddress : vendorDivisionAddresses) {
            // We need to exclude the first one Since we already checked for this in valid AddressType above.
            if (vendorDivisionAddress.getVendorDetailAssignedIdentifier() != 0) {
                vendorDetailedIds.add(vendorDivisionAddress.getVendorDetailAssignedIdentifier());
                if (vendorDivisionAddress.getVendorAddressTypeCode()
                        .equalsIgnoreCase(vendorAddressTypeRequiredCode)) {
                    vendorDivisionsIdsWithDesiredAddressType
                            .add(vendorDivisionAddress.getVendorDetailAssignedIdentifier());
                }
            }
        }

        // If the number of divisions with the desired address type is less than the number of divisions for his vendor
        if (vendorDivisionsIdsWithDesiredAddressType.size() < vendorDetailedIds.size()) {
            Iterator itr = vendorDetailedIds.iterator();
            Integer value;
            String vendorId;

            while (itr.hasNext()) {
                value = (Integer) itr.next();
                if (!vendorDivisionsIdsWithDesiredAddressType.contains(value)) {
                    vendorId = newVendor.getVendorHeaderGeneratedIdentifier().toString() + '-'
                            + value.toString();
                    String[] parameters = new String[] { vendorId, vendorTypeCode,
                            vendorAddressTypeRequiredCode };

                    //divisions without the desired address type should only be an warning
                    GlobalVariables.getMessageMap().putWarningWithoutFullErrorPath(
                            MAINTAINABLE_ERROR_PREFIX + vendorAddressTabPrefix
                                    + VendorPropertyConstants.VENDOR_ADDRESS_TYPE_CODE,
                            VendorKeyConstants.ERROR_ADDRESS_TYPE_DIVISIONS, parameters);
                }
            }
        }

    }
    return valid;
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * List certificates in a vault./* w  ww  .  j  a  va 2  s. c  o  m*/
 */
@Test
public void listCertificates() throws Exception {
    String certificateName = "listCertificate";
    String certificateContent = "MIIJOwIBAzCCCPcGCSqGSIb3DQEHAaCCCOgEggjkMIII4DCCBgkGCSqGSIb3DQEHAaCCBfoEggX2MIIF8jCCBe4GCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAj15YH9pOE58AICB9AEggTYLrI+SAru2dBZRQRlJY7XQ3LeLkah2FcRR3dATDshZ2h0IA2oBrkQIdsLyAAWZ32qYR1qkWxLHn9AqXgu27AEbOk35+pITZaiy63YYBkkpR+pDdngZt19Z0PWrGwHEq5z6BHS2GLyyN8SSOCbdzCz7blj3+7IZYoMj4WOPgOm/tQ6U44SFWek46QwN2zeA4i97v7ftNNns27ms52jqfhOvTA9c/wyfZKAY4aKJfYYUmycKjnnRl012ldS2lOkASFt+lu4QCa72IY6ePtRudPCvmzRv2pkLYS6z3cI7omT8nHP3DymNOqLbFqr5O2M1ZYaLC63Q3xt3eVvbcPh3N08D1hHkhz/KDTvkRAQpvrW8ISKmgDdmzN55Pe55xHfSWGB7gPw8sZea57IxFzWHTK2yvTslooWoosmGxanYY2IG/no3EbPOWDKjPZ4ilYJe5JJ2immlxPz+2e2EOCKpDI+7fzQcRz3PTd3BK+budZ8aXX8aW/lOgKS8WmxZoKnOJBNWeTNWQFugmktXfdPHAdxMhjUXqeGQd8wTvZ4EzQNNafovwkI7IV/ZYoa++RGofVR3ZbRSiBNF6TDj/qXFt0wN/CQnsGAmQAGNiN+D4mY7i25dtTu/Jc7OxLdhAUFpHyJpyrYWLfvOiS5WYBeEDHkiPUa/8eZSPA3MXWZR1RiuDvuNqMjct1SSwdXADTtF68l/US1ksU657+XSC+6ly1A/upz+X71+C4Ho6W0751j5ZMT6xKjGh5pee7MVuduxIzXjWIy3YS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Txt4AQU4O/NX4MjxSodbE7ApNAMIvrtREwCAgfQ";
    String certificatePassword = "123";

    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties();
    secretProperties.withContentType(MIME_PKCS12);
    CertificatePolicy certificatePolicy = new CertificatePolicy();
    certificatePolicy.withSecretProperties(secretProperties);

    HashSet<String> certificates = new HashSet<String>();
    for (int i = 0; i < MAX_CERTS; ++i) {
        int failureCount = 0;
        for (;;) {
            try {
                CertificateBundle certificateBundle = keyVaultClient
                        .importCertificate(new ImportCertificateRequest.Builder(getVaultUri(),
                                certificateName + i, certificateContent).withPassword(certificatePassword)
                                        .withPolicy(certificatePolicy).build());
                CertificateIdentifier id = certificateBundle.certificateIdentifier();
                certificates.add(id.baseIdentifier());
                break;
            } catch (KeyVaultErrorException e) {
                ++failureCount;
                if (e.body().error().code().equals("Throttled")) {
                    System.out.println("Waiting to avoid throttling");
                    Thread.sleep(failureCount * 1500);
                    continue;
                }
                throw e;
            }
        }
    }

    PagedList<CertificateItem> listResult = keyVaultClient.listCertificates(getVaultUri(), PAGELIST_MAX_CERTS);
    Assert.assertTrue(PAGELIST_MAX_CERTS >= listResult.currentPage().items().size());

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

    for (CertificateItem item : listResult) {
        if (item != null) {
            CertificateIdentifier id = new CertificateIdentifier(item.id());
            toDelete.add(id.name());
            certificates.remove(item.id());
        }
    }

    Assert.assertEquals(0, certificates.size());

    for (String toDeleteCertificateName : toDelete) {
        keyVaultClient.deleteCertificate(getVaultUri(), toDeleteCertificateName);
    }
}

From source file:org.kuali.kfs.vnd.document.validation.impl.VendorRule.java

/**
 * Validates vendor address fields.//from w  w  w. j a  va  2 s  .co  m
 *
 * @param document MaintenanceDocument
 * @return boolean false or true
 */
boolean processAddressValidation(MaintenanceDocument document) {
    boolean valid = true;
    boolean validAddressType = false;

    List<VendorAddress> addresses = newVendor.getVendorAddresses();
    String vendorTypeCode = newVendor.getVendorHeader().getVendorTypeCode();
    String vendorAddressTypeRequiredCode = newVendor.getVendorHeader().getVendorType()
            .getVendorAddressTypeRequiredCode();

    for (int i = 0; i < addresses.size(); i++) {
        VendorAddress address = addresses.get(i);
        String errorPath = MAINTAINABLE_ERROR_PREFIX + VendorPropertyConstants.VENDOR_ADDRESS + "[" + i + "]";
        GlobalVariables.getMessageMap().clearErrorPath();
        GlobalVariables.getMessageMap().addToErrorPath(errorPath);

        this.getDictionaryValidationService().validateBusinessObject(address);
        if (GlobalVariables.getMessageMap().hasErrors()) {
            valid = false;
        }

        if (address.getVendorAddressTypeCode().equals(vendorAddressTypeRequiredCode)) {
            validAddressType = true;
        }

        valid &= checkAddressCountryEmptyStateZip(address);

        GlobalVariables.getMessageMap().clearErrorPath();
    }

    // validate Address Type
    String vendorAddressTabPrefix = KFSConstants.ADD_PREFIX + "." + VendorPropertyConstants.VENDOR_ADDRESS
            + ".";
    if (!StringUtils.isBlank(vendorTypeCode) && !StringUtils.isBlank(vendorAddressTypeRequiredCode)
            && !validAddressType) {
        String[] parameters = new String[] { vendorTypeCode, vendorAddressTypeRequiredCode };
        putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_TYPE_CODE,
                VendorKeyConstants.ERROR_ADDRESS_TYPE, parameters);
        String addressLine1Label = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_LINE_1);
        String addressCityLabel = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_CITY);
        String addressCountryLabel = SpringContext.getBean(DataDictionaryService.class)
                .getAttributeLabel(VendorAddress.class, VendorPropertyConstants.VENDOR_ADDRESS_COUNTRY);
        putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_LINE_1,
                KFSKeyConstants.ERROR_REQUIRED, addressLine1Label);
        putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_CITY,
                KFSKeyConstants.ERROR_REQUIRED, addressCityLabel);
        putFieldError(vendorAddressTabPrefix + VendorPropertyConstants.VENDOR_ADDRESS_COUNTRY,
                KFSKeyConstants.ERROR_REQUIRED, addressCountryLabel);
        valid = false;
    }

    valid &= validateDefaultAddressCampus(newVendor);

    // Check to see if all divisions have one desired address for this vendor type
    Map fieldValues = new HashMap();
    fieldValues.put(VendorPropertyConstants.VENDOR_HEADER_GENERATED_ID,
            newVendor.getVendorHeaderGeneratedIdentifier());
    // Find all the addresses for this vendor and its divisions:
    List<VendorAddress> vendorDivisionAddresses = new ArrayList(
            SpringContext.getBean(BusinessObjectService.class).findMatchingOrderBy(VendorAddress.class,
                    fieldValues, VendorPropertyConstants.VENDOR_DETAIL_ASSIGNED_ID, true));

    // This set stores the vendorDetailedAssignedIds for the vendor divisions which is
    // bascically the division numbers 0, 1, 2, ...
    HashSet<Integer> vendorDetailedIds = new HashSet();
    // This set stores the vendor division numbers of the ones which have one address of the desired type
    HashSet<Integer> vendorDivisionsIdsWithDesiredAddressType = new HashSet();

    for (VendorAddress vendorDivisionAddress : vendorDivisionAddresses) {
        // We need to exclude the first one Since we already checked for this in valid AddressType above.
        if (vendorDivisionAddress.getVendorDetailAssignedIdentifier() != 0) {
            vendorDetailedIds.add(vendorDivisionAddress.getVendorDetailAssignedIdentifier());
            if (vendorDivisionAddress.getVendorAddressTypeCode()
                    .equalsIgnoreCase(vendorAddressTypeRequiredCode)) {
                vendorDivisionsIdsWithDesiredAddressType
                        .add(vendorDivisionAddress.getVendorDetailAssignedIdentifier());
            }
        }
    }

    // If the number of divisions with the desired address type is less than the number of divisions for his vendor
    if (vendorDivisionsIdsWithDesiredAddressType.size() < vendorDetailedIds.size()) {
        Iterator itr = vendorDetailedIds.iterator();
        Integer value;
        String vendorId;

        while (itr.hasNext()) {
            value = (Integer) itr.next();
            if (!vendorDivisionsIdsWithDesiredAddressType.contains(value)) {
                vendorId = newVendor.getVendorHeaderGeneratedIdentifier().toString() + '-' + value.toString();
                String[] parameters = new String[] { vendorId, vendorTypeCode, vendorAddressTypeRequiredCode };

                //divisions without the desired address type should only be an warning
                GlobalVariables.getMessageMap().putWarningWithoutFullErrorPath(
                        MAINTAINABLE_ERROR_PREFIX + vendorAddressTabPrefix
                                + VendorPropertyConstants.VENDOR_ADDRESS_TYPE_CODE,
                        VendorKeyConstants.ERROR_ADDRESS_TYPE_DIVISIONS, parameters);
            }
        }
    }

    return valid;
}

From source file:ded.ui.DiagramController.java

/** Set the set of selected controllers according to the filter. */
protected void selectAccordingToFilter(ControllerFilter filter) {
    // During the loop, merely collect the sets of controllers
    // to select and deselect, then set the selection state afterward;
    // otherwise, we risk trying to modify the set of controllers
    // while it is being iterated over, since changing the selection
    // state of a controller can add or remove resize handles.
    HashSet<Controller> toSelect = new HashSet<Controller>();
    HashSet<Controller> toDeselect = new HashSet<Controller>();

    for (Controller c : this.controllers) {
        if (filter.satisfies(c)) {
            toSelect.add(c);//  ww w  . ja v  a2s .c  o m
        } else if (c.isSelected()) {
            toDeselect.add(c);
        } else {
            // 'c' is not selected and should not be; just leave
            // it alone.
        }
    }

    // Deselect everything that should not be selected but
    // previously was.
    setMultipleSelected(toDeselect, SelectionState.SS_UNSELECTED);

    if (toSelect.size() == 1) {
        // Exclusively select the one lasso'd controller.  (Using
        // the "multi" call is merely syntactically convenient.)
        //
        // This will show resize controls.
        setMultipleSelected(toSelect, SelectionState.SS_EXCLUSIVE);
    } else {
        // Set state of all selected controls.
        setMultipleSelected(toSelect, SelectionState.SS_SELECTED);
    }
}

From source file:org.apache.ctakes.ytex.kernel.IntrinsicInfoContentEvaluatorImpl.java

/**
 * recursively compute the number of leaves. fill in the icInfoMap as we go
 * along/*from  w ww.  j  a  va 2 s . c o  m*/
 * 
 * @param concept
 *            concept for which we should get the leaves
 * @param leafCache
 *            cache of concept's leaves
 * @param icInfoMap
 *            to be updated with leaf counts
 * @param cg
 * @param w
 * @param visitedNodes
 *            list of nodes that have already been visited - we don't need
 *            to revisit them when getting the leaves
 * @return
 * @throws IOException
 */
private HashSet<Integer> getLeaves(ConcRel concept, SoftReference<HashSet<Integer>>[] leafCache,
        Map<String, IntrinsicICInfo> icInfoMap, ConceptGraph cg, BufferedWriter w,
        HashSet<Integer> visitedNodes) throws IOException {
    // look in cache
    SoftReference<HashSet<Integer>> refLeaves = leafCache[concept.getNodeIndex()];
    if (refLeaves != null && refLeaves.get() != null) {
        return refLeaves.get();
    }
    // not in cache - compute recursively
    HashSet<Integer> leaves = new HashSet<Integer>();
    leafCache[concept.getNodeIndex()] = new SoftReference<HashSet<Integer>>(leaves);
    if (concept.isLeaf()) {
        // for leaves, just add the concept id
        leaves.add(concept.getNodeIndex());
    } else {
        IntrinsicICInfo icInfo = icInfoMap.get(concept.getConceptID());
        // have we already computed the leaf count for this node?
        // if yes, then we can ignore previously visited nodes
        // if no, then compute it now and revisit previously visited nodes
        // if we have to
        boolean needLeaves = (icInfo != null && icInfo.getLeafCount() == 0);
        HashSet<Integer> visitedNodesLocal = visitedNodes;
        if (needLeaves || visitedNodesLocal == null) {
            // allocate a set to keep track of nodes we've already visited
            // so that we don't revisit them. if we have already computed
            // this node's leaf count then we reuse whatever the caller gave
            // us if non null, else allocate a new one.
            // if we haven't already computed this node's leaf count,
            // allocate a new set to avoid duplications in the traversal for
            // this node
            visitedNodesLocal = new HashSet<Integer>();
        }
        // for inner nodes, recurse
        for (ConcRel child : concept.getChildren()) {
            // if we've already visited a node, then don't bother adding
            // that node's leaves - we already have them
            if (!visitedNodesLocal.contains(child.getNodeIndex())) {
                leaves.addAll(getLeaves(child, leafCache, icInfoMap, cg, w, visitedNodesLocal));
            }
        }
        // add this node to the set of visited nodes so we know not to
        // revisit. This is only of importance if the caller gave us
        // a non-empty set.
        if (visitedNodes != null && visitedNodes != visitedNodesLocal) {
            visitedNodes.add(concept.getNodeIndex());
            visitedNodes.addAll(visitedNodesLocal);
        }
        // update the leaf count if we haven't done so already
        if (needLeaves) {
            icInfo.setLeafCount(leaves.size());
            // output leaves if desired
            if (w != null) {
                w.write(concept.getConceptID());
                w.write("\t");
                w.write(Integer.toString(leaves.size()));
                w.write("\t");
                Iterator<Integer> iter = leaves.iterator();
                while (iter.hasNext()) {
                    w.write(cg.getConceptList().get(iter.next()).getConceptID());
                    w.write(" ");
                }
                w.newLine();
            }
        }
    }
    return leaves;
}

From source file:org.codehaus.enunciate.modules.docs.DocumentationDeploymentModule.java

/**
 * Builds the base output directory./*from  ww w  . ja  v a2 s. co m*/
 */
protected void buildBase() throws IOException {
    Enunciate enunciate = getEnunciate();
    File buildDir = getDocsBuildDir();
    buildDir.mkdirs();
    if (this.base == null) {
        InputStream discoveredBase = DocumentationDeploymentModule.class
                .getResourceAsStream("/META-INF/enunciate/docs-base.zip");
        if (discoveredBase == null) {
            debug("Default base to be used for documentation base.");
            enunciate.extractBase(loadDefaultBase(), buildDir);

            URL discoveredCss = DocumentationDeploymentModule.class
                    .getResource("/META-INF/enunciate/css/style.css");
            if (discoveredCss != null) {
                enunciate.copyResource(discoveredCss, new File(new File(buildDir, "css"), "style.css"));
            } else if (this.css != null) {
                enunciate.copyFile(enunciate.resolvePath(this.css),
                        new File(new File(buildDir, "css"), "style.css"));
            }
        } else {
            debug("Discovered documentation base at /META-INF/enunciate/docs-base.zip");
            enunciate.extractBase(discoveredBase, buildDir);
        }
    } else {
        File baseFile = enunciate.resolvePath(this.base);
        if (baseFile.isDirectory()) {
            debug("Directory %s to be used as the documentation base.", baseFile);
            enunciate.copyDir(baseFile, buildDir);
        } else {
            debug("Zip file %s to be extracted as the documentation base.", baseFile);
            enunciate.extractBase(new FileInputStream(baseFile), buildDir);
        }
    }

    for (SchemaInfo schemaInfo : getModel().getNamespacesToSchemas().values()) {
        if (schemaInfo.getProperty("file") != null) {
            File from = (File) schemaInfo.getProperty("file");
            String filename = schemaInfo.getProperty("filename") != null
                    ? (String) schemaInfo.getProperty("filename")
                    : from.getName();
            File to = new File(getDocsBuildDir(), filename);
            enunciate.copyFile(from, to);
        }
    }

    for (WsdlInfo wsdlInfo : getModel().getNamespacesToWSDLs().values()) {
        if (wsdlInfo.getProperty("file") != null) {
            File from = (File) wsdlInfo.getProperty("file");
            String filename = wsdlInfo.getProperty("filename") != null
                    ? (String) wsdlInfo.getProperty("filename")
                    : from.getName();
            File to = new File(getDocsBuildDir(), filename);
            enunciate.copyFile(from, to);
        }
    }

    File wadlFile = getModelInternal().getWadlFile();
    if (wadlFile != null) {
        enunciate.copyFile(wadlFile, new File(getDocsBuildDir(), wadlFile.getName()));
    }

    HashSet<String> explicitArtifacts = new HashSet<String>();
    TreeSet<Artifact> downloads = new TreeSet<Artifact>();
    for (DownloadConfig download : this.downloads) {
        if (download.getArtifact() != null) {
            explicitArtifacts.add(download.getArtifact());
        } else if (download.getFile() != null) {
            File downloadFile = enunciate.resolvePath(download.getFile());

            debug("File %s to be added as an extra download.", downloadFile.getAbsolutePath());
            DownloadBundle downloadArtifact = new DownloadBundle(getName(), downloadFile.getName(),
                    downloadFile);

            if (download.getName() != null) {
                downloadArtifact.setName(download.getName());
            }

            if (download.getDescription() != null) {
                downloadArtifact.setDescription(download.getDescription());
            }

            downloads.add(downloadArtifact);
        }
    }

    for (Artifact artifact : enunciate.getArtifacts()) {
        if (((artifact instanceof NamedArtifact) && (includeDefaultDownloads))
                || (explicitArtifacts.contains(artifact.getId()))) {
            if (artifact.isPublic()) {
                downloads.add(artifact);
            }

            debug("Artifact %s to be added as an extra download.", artifact.getId());
            explicitArtifacts.remove(artifact.getId());
        }
    }

    if (explicitArtifacts.size() > 0) {
        for (String artifactId : explicitArtifacts) {
            warn("WARNING: Unknown artifact '%s'.  Will not be available for download.", artifactId);
        }
    }

    for (Artifact download : downloads) {
        debug("Exporting %s to directory %s.", download.getId(), buildDir);
        download.exportTo(buildDir, enunciate);
    }

    Set<String> additionalCssFiles = new HashSet<String>();
    for (String additionalCss : getAdditionalCss()) {
        File additionalCssFile = enunciate.resolvePath(additionalCss);
        debug("File %s to be added as an additional css file.", additionalCss);
        enunciate.copyFile(additionalCssFile, new File(buildDir, additionalCssFile.getName()));
        additionalCssFiles.add(additionalCssFile.getName());
    }

    EnunciateFreemarkerModel model = getModel();
    model.put("downloads", downloads);
    model.put("additionalCssFiles", additionalCssFiles);
}

From source file:com.intel.ssg.dcst.panthera.parse.SkinDriver.java

private void doAuthorization(BaseSemanticAnalyzer sem) throws HiveException, AuthorizationException {
    HashSet<ReadEntity> inputs = sem.getInputs();
    HashSet<WriteEntity> outputs = sem.getOutputs();
    SessionState ss = SessionState.get();
    HiveOperation op = ss.getHiveOperation();
    Hive db = sem.getDb();/*from   ww w  . j  a v  a 2s  . c om*/
    if (op != null) {
        if (op.equals(HiveOperation.CREATETABLE_AS_SELECT) || op.equals(HiveOperation.CREATETABLE)) {
            ss.getAuthorizer().authorize(db.getDatabase(SessionState.get().getCurrentDatabase()), null,
                    HiveOperation.CREATETABLE_AS_SELECT.getOutputRequiredPrivileges());
        } else {
            if (op.equals(HiveOperation.IMPORT)) {
                ImportSemanticAnalyzer isa = (ImportSemanticAnalyzer) sem;
                if (!isa.existsTable()) {
                    ss.getAuthorizer().authorize(db.getDatabase(SessionState.get().getCurrentDatabase()), null,
                            HiveOperation.CREATETABLE_AS_SELECT.getOutputRequiredPrivileges());
                }
            }
        }
        if (outputs != null && outputs.size() > 0) {
            for (WriteEntity write : outputs) {

                if (write.getType() == WriteEntity.Type.PARTITION) {
                    Partition part = db.getPartition(write.getTable(), write.getPartition().getSpec(), false);
                    if (part != null) {
                        ss.getAuthorizer().authorize(write.getPartition(), null,
                                op.getOutputRequiredPrivileges());
                        continue;
                    }
                }

                if (write.getTable() != null) {
                    ss.getAuthorizer().authorize(write.getTable(), null, op.getOutputRequiredPrivileges());
                }
            }

        }
    }

    if (inputs != null && inputs.size() > 0) {

        Map<Table, List<String>> tab2Cols = new HashMap<Table, List<String>>();
        Map<Partition, List<String>> part2Cols = new HashMap<Partition, List<String>>();

        Map<String, Boolean> tableUsePartLevelAuth = new HashMap<String, Boolean>();
        for (ReadEntity read : inputs) {
            Table tbl = read.getTable();
            if ((read.getPartition() != null) || (tbl.isPartitioned())) {
                String tblName = tbl.getTableName();
                if (tableUsePartLevelAuth.get(tblName) == null) {
                    boolean usePartLevelPriv = (tbl.getParameters().get("PARTITION_LEVEL_PRIVILEGE") != null
                            && ("TRUE".equalsIgnoreCase(tbl.getParameters().get("PARTITION_LEVEL_PRIVILEGE"))));
                    if (usePartLevelPriv) {
                        tableUsePartLevelAuth.put(tblName, Boolean.TRUE);
                    } else {
                        tableUsePartLevelAuth.put(tblName, Boolean.FALSE);
                    }
                }
            }
        }

        if (op.equals(HiveOperation.CREATETABLE_AS_SELECT) || op.equals(HiveOperation.QUERY)) {
            SemanticAnalyzer querySem = (SemanticAnalyzer) sem;
            ParseContext parseCtx = querySem.getParseContext();
            Map<TableScanOperator, Table> tsoTopMap = parseCtx.getTopToTable();

            for (Map.Entry<String, Operator<? extends OperatorDesc>> topOpMap : querySem.getParseContext()
                    .getTopOps().entrySet()) {
                Operator<? extends OperatorDesc> topOp = topOpMap.getValue();
                if (topOp instanceof TableScanOperator && tsoTopMap.containsKey(topOp)) {
                    TableScanOperator tableScanOp = (TableScanOperator) topOp;
                    Table tbl = tsoTopMap.get(tableScanOp);
                    List<Integer> neededColumnIds = tableScanOp.getNeededColumnIDs();
                    List<FieldSchema> columns = tbl.getCols();
                    List<String> cols = new ArrayList<String>();
                    if (neededColumnIds != null && neededColumnIds.size() > 0) {
                        for (int i = 0; i < neededColumnIds.size(); i++) {
                            cols.add(columns.get(neededColumnIds.get(i)).getName());
                        }
                    } else {
                        for (int i = 0; i < columns.size(); i++) {
                            cols.add(columns.get(i).getName());
                        }
                    }
                    //map may not contain all sources, since input list may have been optimized out
                    //or non-existent tho such sources may still be referenced by the TableScanOperator
                    //if it's null then the partition probably doesn't exist so let's use table permission
                    if (tbl.isPartitioned() && tableUsePartLevelAuth.get(tbl.getTableName()) == Boolean.TRUE) {
                        String alias_id = topOpMap.getKey();

                        PrunedPartitionList partsList = PartitionPruner.prune(tableScanOp, parseCtx, alias_id);
                        Set<Partition> parts = partsList.getPartitions();
                        for (Partition part : parts) {
                            List<String> existingCols = part2Cols.get(part);
                            if (existingCols == null) {
                                existingCols = new ArrayList<String>();
                            }
                            existingCols.addAll(cols);
                            part2Cols.put(part, existingCols);
                        }
                    } else {
                        List<String> existingCols = tab2Cols.get(tbl);
                        if (existingCols == null) {
                            existingCols = new ArrayList<String>();
                        }
                        existingCols.addAll(cols);
                        tab2Cols.put(tbl, existingCols);
                    }
                }
            }
        }

        // cache the results for table authorization
        Set<String> tableAuthChecked = new HashSet<String>();
        for (ReadEntity read : inputs) {
            Table tbl = read.getTable();
            if (read.getPartition() != null) {
                Partition partition = read.getPartition();
                tbl = partition.getTable();
                // use partition level authorization
                if (tableUsePartLevelAuth.get(tbl.getTableName()) == Boolean.TRUE) {
                    List<String> cols = part2Cols.get(partition);
                    if (cols != null && cols.size() > 0) {
                        ss.getAuthorizer().authorize(partition.getTable(), partition, cols,
                                op.getInputRequiredPrivileges(), null);
                    } else {
                        ss.getAuthorizer().authorize(partition, op.getInputRequiredPrivileges(), null);
                    }
                    continue;
                }
            }

            // if we reach here, it means it needs to do a table authorization
            // check, and the table authorization may already happened because of other
            // partitions
            if (tbl != null && !tableAuthChecked.contains(tbl.getTableName())
                    && !(tableUsePartLevelAuth.get(tbl.getTableName()) == Boolean.TRUE)) {
                List<String> cols = tab2Cols.get(tbl);
                if (cols != null && cols.size() > 0) {
                    ss.getAuthorizer().authorize(tbl, null, cols, op.getInputRequiredPrivileges(), null);
                } else {
                    ss.getAuthorizer().authorize(tbl, op.getInputRequiredPrivileges(), null);
                }
                tableAuthChecked.add(tbl.getTableName());
            }
        }

    }
}

From source file:org.gcaldaemon.gui.config.MainConfig.java

public final String[] getCalendarPaths() {
    try {//from  w  ww.j ava 2  s.  c om
        HashSet set = new HashSet();
        FileSync[] configs = getFileSyncConfigs();

        // Scan directories
        HashSet dirs = new HashSet();
        int i;
        FileSync config;
        File file, dir;
        for (i = 0; i < configs.length; i++) {
            config = configs[i];
            if (config.icalPath != null && config.icalPath.endsWith(".ics")) {
                if (config.icalPath.indexOf("*.ics") != -1) {
                    continue;
                }
                if (config.icalPath.indexOf("Application Support") != -1) {
                    continue;
                }
                file = new File(config.icalPath);
                dir = file.getParentFile();
                if (dir.isDirectory() && dir.canRead() && !dirs.contains(dir)) {
                    dirs.add(dir);
                    getCalendarPaths(set, dir, true);
                }
            }
        }

        // Scan folders of iCal3
        getICalendar3Paths(set, dirs);

        // Scan folders of iCal4
        getICalendar4Paths(set, dirs);

        // Scan folders of Evolution
        getEvolutionPaths(set, dirs);

        // Add configured paths
        for (i = 0; i < configs.length; i++) {
            config = configs[i];
            if (config.icalPath != null && config.icalPath.endsWith(".ics")
                    && !containsPath(set, config.icalPath)) {
                set.add(config.icalPath);
            }
        }
        String[] array = new String[set.size()];
        set.toArray(array);
        Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
        return array;
    } catch (Exception anyException) {
    }
    return null;
}

From source file:eionet.cr.harvest.BaseHarvest.java

/**
 * Deletes sources with permanent errors after batch harvesting.
 *
 * @throws DAOException/*from  w  w  w .  j  av  a2  s. c  o  m*/
 *             if deleting fails
 */
private void deleteErroneousSources() throws DAOException {
    LOGGER.debug(loggerMsg("Checking sources that need removal"));
    HashSet<String> sourcesToDelete = new HashSet<String>();

    boolean sourceInError = false;

    // if the source or redirected sources are in erroneous state, delete them while batch harvesting
    if (!isOnDemandHarvest) {
        // check only the current (last redirected) source if there were redirections.
        // If it was failed delete redirected sources as well
        if (getContextSourceDTO().isPermanentError()) {
            if (!getContextSourceDTO().isPrioritySource()) {
                LOGGER.debug(getContextSourceDTO().getUrl() + "  will be deleted as a non-priority source "
                        + "with permanent error");
                sourcesToDelete.add(getContextSourceDTO().getUrl());
                sourceInError = true;

            }
        } else if (getContextSourceDTO().getCountUnavail() >= 5) {
            if (!getContextSourceDTO().isPrioritySource()) {
                LOGGER.debug(getContextSourceDTO().getUrl() + "  will be deleted as a non-priority source "
                        + "with unavailability >= 5");
                sourcesToDelete.add(getContextSourceDTO().getUrl());
                sourceInError = true;
            }
        }
        if (sourceInError) {
            for (HarvestSourceDTO dto : redirectedHarvestSources) {
                // delete redirected source if not in queue and not priority source
                LOGGER.debug(dto.getUrl() + "  is a redirected source will be deleted.");
                if (!dto.isPrioritySource()) {
                    sourcesToDelete.add(dto.getUrl());
                }
            }
        }
        LOGGER.debug(loggerMsg("sources to be removed count=" + sourcesToDelete.size()));
        getHarvestSourceDAO().removeHarvestSources(sourcesToDelete);
    }

}

From source file:edu.ku.brc.dbsupport.MySQLDMBSUserMgr.java

@Override
public List<String> getDatabaseListForUser(final String username) {
    String[] permsArray = new String[] { "SELECT", "DELETE", "UPDATE", "INSERT", "LOCK TABLES", };
    HashSet<String> permsHash = new HashSet<String>();
    Collections.addAll(permsHash, permsArray);

    ArrayList<String> dbNames = new ArrayList<String>();
    try {/* w ww.  j  a  v  a 2  s  .c o m*/
        if (connection != null) {
            String userStr = String.format("'%s'@'%s'", username, hostName);
            String sql = "SHOW GRANTS";
            for (Object obj : BasicSQLUtils.querySingleCol(connection, sql)) {
                boolean isAllDBs = false;
                String data = (String) obj;
                String dbName = null;
                System.out.println("->[" + data + "]");
                if (StringUtils.contains(data, userStr)) {
                    // get database name
                    String[] toks = StringUtils.split(data, '`');
                    if (toks.length > 2) {
                        dbName = toks[1];
                    }
                } else if (StringUtils.contains(data, "ON *.* TO")) {
                    //dbNames.add(obj.toString());   
                    isAllDBs = true;
                }

                // get permissions

                String permsStr = StringUtils.substringBetween(data, "GRANT ", " ON");
                String[] pToks = StringUtils.split(permsStr, ',');

                if (pToks != null) {
                    if (pToks.length == 1 && pToks[0].equalsIgnoreCase("ALL PRIVILEGES") && isAllDBs) {
                        dbNames.addAll(getDatabaseList());

                    } else if (pToks.length >= permsHash.size()) {
                        int cnt = 0;
                        for (String p : pToks) {
                            if (permsHash.contains(p.trim())) {
                                cnt++;
                            }
                        }

                        if (cnt == permsHash.size()) {
                            if (isAllDBs) {
                                dbNames.addAll(getDatabaseList());
                                break;

                            } else if (dbName != null) {
                                dbNames.add(dbName);
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return dbNames;
}