Example usage for com.google.common.collect Sets newHashSetWithExpectedSize

List of usage examples for com.google.common.collect Sets newHashSetWithExpectedSize

Introduction

In this page you can find the example usage for com.google.common.collect Sets newHashSetWithExpectedSize.

Prototype

public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) 

Source Link

Document

Creates a HashSet instance, with a high enough initial table size that it should hold expectedSize elements without resizing.

Usage

From source file:com.mortardata.pig.storage.DynamoDBStorage.java

/** HELPERS 
 * @throws IOException **///from   w  w  w. j  a  va 2 s. c  o m

private void checkPigSchemaForDynamo(ResourceSchema schema) throws IOException {
    // extract field names
    Set<String> fieldNames = Sets.newHashSetWithExpectedSize(schema.getFields().length);
    for (ResourceFieldSchema field : schema.getFields()) {
        String fieldName = field.getName();
        if (fieldNames.contains(fieldName)) {
            throw new IOException(
                    "Schema cannot contain duplicated field name. Found duplicated: " + fieldName);
        }
        if (field.getType() == DataType.MAP || field.getType() == DataType.TUPLE
                || field.getType() == DataType.BAG) {
            throw new IOException(
                    "DynamoDBStorage can not store map, tuple, or bag types.  Found one in field name: "
                            + fieldName);
        }
        fieldNames.add(fieldName);
    }

    // ensure that Dynamo table primary keys are found in field names
    DescribeTableResult describe = describeDynamoTable();
    KeySchema dynamoKeySchema = describe.getTable().getKeySchema();
    if (dynamoKeySchema.getHashKeyElement() != null) {
        String expectedFieldName = dynamoKeySchema.getHashKeyElement().getAttributeName();
        if (!fieldNames.contains(expectedFieldName)) {
            throw new IOException("Dynamo table " + this.tableName + " hash primary key [" + expectedFieldName
                    + "] not found in " + " pig schema fields: " + fieldNames);
        }
    }
    if (dynamoKeySchema.getRangeKeyElement() != null) {
        String expectedFieldName = dynamoKeySchema.getRangeKeyElement().getAttributeName();
        if (!fieldNames.contains(expectedFieldName)) {
            throw new IOException("Dynamo table " + this.tableName + " range secondary key ["
                    + expectedFieldName + "] not found in " + " pig schema fields: " + fieldNames);
        }
    }
}

From source file:com.google.devtools.build.android.ResourceShrinker.java

/**
 * Remove resources (already identified by {@link #shrink(Path)}).
 *
 * <p>This task will copy all remaining used resources over from the full resource directory to a
 * new reduced resource directory. However, it can't just delete the resources, because it has no
 * way to tell aapt to continue to use the same id's for the resources. When we re-run aapt on the
 * stripped resource directory, it will assign new id's to some of the resources (to fill the
 * gaps) which means the resource id's no longer match the constants compiled into the dex files,
 * and as a result, the app crashes at runtime. <p> Therefore, it needs to preserve all id's by
 * actually keeping all the resource names. It can still save a lot of space by making these
 * resources tiny; e.g. all strings are set to empty, all styles, arrays and plurals are set to
 * not contain any children, and most importantly, all file based resources like bitmaps and
 * layouts are replaced by simple resource aliases which just point to @null.
 *
 * @param destination directory to copy resources into; if null, delete resources in place
 *//*from   www . ja  v  a2s.co  m*/
private void removeUnused(Path destination) throws IOException, ParserConfigurationException, SAXException {
    assert unused != null; // should always call analyze() first
    int resourceCount = unused.size() * 4; // *4: account for some resource folder repetition
    Set<File> skip = Sets.newHashSetWithExpectedSize(resourceCount);
    Set<File> rewrite = Sets.newHashSetWithExpectedSize(resourceCount);
    for (Resource resource : unused) {
        if (resource.declarations != null) {
            for (File file : resource.declarations) {
                String folder = file.getParentFile().getName();
                ResourceFolderType folderType = ResourceFolderType.getFolderType(folder);
                if (folderType != null && folderType != ResourceFolderType.VALUES) {
                    logger.fine("Deleted unused resource " + file);
                    assert skip != null;
                    skip.add(file);
                } else {
                    // Can't delete values immediately; there can be many resources
                    // in this file, so we have to process them all
                    rewrite.add(file);
                }
            }
        }
    }
    // Special case the base values.xml folder
    File values = new File(mergedResourceDir.toFile(), FD_RES_VALUES + File.separatorChar + "values.xml");
    boolean valuesExists = values.exists();
    if (valuesExists) {
        rewrite.add(values);
    }
    Map<File, String> rewritten = Maps.newHashMapWithExpectedSize(rewrite.size());
    // Delete value resources: Must rewrite the XML files
    for (File file : rewrite) {
        String xml = Files.toString(file, UTF_8);
        Document document = XmlUtils.parseDocument(xml, true);
        Element root = document.getDocumentElement();
        if (root != null && TAG_RESOURCES.equals(root.getTagName())) {
            List<String> removed = Lists.newArrayList();
            stripUnused(root, removed);
            logger.info("Removed " + removed.size() + " unused resources from " + file + ":\n  "
                    + Joiner.on(", ").join(removed));
            String formatted = XmlPrettyPrinter.prettyPrint(document, xml.endsWith("\n"));
            rewritten.put(file, formatted);
        }
    }
    if (valuesExists) {
        String xml = rewritten.get(values);
        if (xml == null) {
            xml = Files.toString(values, UTF_8);
        }
        Document document = XmlUtils.parseDocument(xml, true);
        Element root = document.getDocumentElement();
        for (Resource resource : resources) {
            if (resource.type == ResourceType.ID && !resource.hasDefault) {
                Element item = document.createElement(TAG_ITEM);
                item.setAttribute(ATTR_TYPE, resource.type.getName());
                item.setAttribute(ATTR_NAME, resource.name);
                root.appendChild(item);
            } else if (!resource.reachable && !resource.hasDefault
                    && resource.type != ResourceType.DECLARE_STYLEABLE && resource.type != ResourceType.STYLE
                    && resource.type != ResourceType.PLURALS && resource.type != ResourceType.ARRAY
                    && resource.isRelevantType()) {
                Element item = document.createElement(TAG_ITEM);
                item.setAttribute(ATTR_TYPE, resource.type.getName());
                item.setAttribute(ATTR_NAME, resource.name);
                root.appendChild(item);
                String s = "@null";
                item.appendChild(document.createTextNode(s));
            }
        }
        String formatted = XmlPrettyPrinter.prettyPrint(document, xml.endsWith("\n"));
        rewritten.put(values, formatted);
    }
    filteredCopy(mergedResourceDir.toFile(), destination, skip, rewritten);
}

From source file:com.android.tools.lint.checks.OverrideDetector.java

@SuppressWarnings("rawtypes") // ASM5 API
@Override/*from w w  w  .j  av  a  2s . co m*/
public void checkClass(@NonNull ClassContext context, @NonNull ClassNode classNode) {
    if (!context.getProject().getReportIssues()) {
        // If this is a library project not being analyzed, ignore it
        return;
    }

    List methodList = classNode.methods;
    if (context.getPhase() == 1) {
        for (Object m : methodList) {
            MethodNode method = (MethodNode) m;
            int access = method.access;
            // Only record non-static package private methods
            if ((access & (ACC_STATIC | ACC_PRIVATE | ACC_PROTECTED | ACC_PUBLIC)) != 0) {
                continue;
            }

            // Ignore constructors too
            if (CONSTRUCTOR_NAME.equals(method.name)) {
                continue;
            }

            String owner = classNode.name;
            Set<String> methods = mPackagePrivateMethods.get(owner);
            if (methods == null) {
                methods = Sets.newHashSetWithExpectedSize(methodList.size());
                mPackagePrivateMethods.put(owner, methods);
            }
            methods.add(method.name + method.desc);
        }
    } else {
        assert context.getPhase() == 2;
        Map<String, Location> methods = mLocations.get(classNode.name);
        if (methods == null) {
            // No locations needed from this class
            return;
        }

        for (Object m : methodList) {
            MethodNode method = (MethodNode) m;

            String signature = method.name + method.desc;
            if (methods.containsKey(signature)) {
                if (context.getDriver().isSuppressed(ISSUE, classNode, method, null)) {
                    Map<String, String> errors = mErrors.get(classNode.name);
                    if (errors != null) {
                        errors.remove(signature);
                    }
                    continue;
                }

                Location location = context.getLocation(method, classNode);
                methods.put(signature, location);
                String description = ClassContext.createSignature(classNode.name, method.name, method.desc);
                location.setClientData(description);
            }
        }
    }
}

From source file:com.cinchapi.common.base.AnyStrings.java

/**
 * Efficiently escape inner occurrences of each of the {@code characters}
 * within the {@code string}, if necessary.
 * <p>/*  w  w w .  j a va  2 s  .  c  o m*/
 * Escaped characters are prepended with the backslash ('\') character.
 * </p>
 * <p>
 * An "inner occurrence" for a character is one that is not at the head or
 * tail of the string.
 * </p>
 * 
 * @param string the string to escape
 * @param characters the characters to escape within the {@code string}
 * @return the escaped {@code string}
 */
public static String escapeInner(String string, char... characters) {
    char c = '\0';
    char pchar = '\0';
    StringBuilder sb = null;
    Set<Character> chars = null;
    if (characters.length == 1) {
        c = characters[0];
    } else {
        chars = Sets.newHashSetWithExpectedSize(characters.length);
        for (char ch : characters) {
            chars.add(ch);
        }
    }
    char[] schars = string.toCharArray();
    int offset = 0;
    int i = 0;
    while (i < schars.length) {
        if (i > 0 && i < schars.length - 1) {
            char schar = schars[i];
            if (pchar != '\\' && ((c != '\0' && c == schar) || (chars != null && chars.contains(schar)))) {
                sb = MoreObjects.firstNonNull(sb, new StringBuilder());
                sb.append(schars, offset, i - offset);
                sb.append('\\');
                char escaped = Characters.getEscapedCharOrNullLiteral(schar);
                if (escaped != '0') {
                    sb.append(escaped);
                } else {
                    sb.append(schar);
                }
                offset = i + 1;
            }
            pchar = schar;
        }
        ++i;
    }
    if (sb != null) {
        sb.append(schars, offset, i - offset);
        return sb.toString();
    } else {
        return string;
    }
}

From source file:com.android.tools.lint.checks.LayoutConsistencyDetector.java

private void checkConsistentIds(@NonNull String layout, @NonNull List<Pair<File, Map<String, String>>> files) {
    int layoutCount = files.size();
    assert layoutCount >= 2;

    Map<File, Set<String>> idMap = getIdMap(files, layoutCount);
    Set<String> inconsistent = getInconsistentIds(idMap);
    if (inconsistent.isEmpty()) {
        return;//from w  ww  . j  a  v  a2  s .co m
    }

    if (mLocations == null) {
        mLocations = Maps.newHashMap();
    }
    if (mErrorMessages == null) {
        mErrorMessages = Maps.newHashMap();
    }

    // Map from each id, to a list of layout folders it is present in
    int idCount = inconsistent.size();
    Map<String, List<String>> presence = Maps.newHashMapWithExpectedSize(idCount);
    Set<String> allLayouts = Sets.newHashSetWithExpectedSize(layoutCount);
    for (Map.Entry<File, Set<String>> entry : idMap.entrySet()) {
        File file = entry.getKey();
        String folder = file.getParentFile().getName();
        allLayouts.add(folder);
        Set<String> ids = entry.getValue();
        for (String id : ids) {
            List<String> list = presence.get(id);
            if (list == null) {
                list = Lists.newArrayListWithExpectedSize(layoutCount);
                presence.put(id, list);
            }
            list.add(folder);
        }
    }

    // Compute lookup maps which will be used in phase 2 to initialize actual
    // locations for the id references

    Map<String, List<Location>> map = Maps.newHashMapWithExpectedSize(idCount);
    mLocations.put(layout, map);
    Map<String, String> messages = Maps.newHashMapWithExpectedSize(idCount);
    mErrorMessages.put(layout, messages);
    for (String id : inconsistent) {
        map.put(id, null); // The locations will be filled in during the second phase

        // Determine presence description for this id
        String message;
        List<String> layouts = presence.get(id);
        Collections.sort(layouts);

        Set<String> missingSet = new HashSet<String>(allLayouts);
        missingSet.removeAll(layouts);
        List<String> missing = new ArrayList<String>(missingSet);
        Collections.sort(missing);

        if (layouts.size() < layoutCount / 2) {
            message = String.format(
                    "The id \"%1$s\" in layout \"%2$s\" is only present in the following "
                            + "layout configurations: %3$s (missing from %4$s)",
                    id, layout, LintUtils.formatList(layouts, Integer.MAX_VALUE),
                    LintUtils.formatList(missing, Integer.MAX_VALUE));
        } else {
            message = String.format(
                    "The id \"%1$s\" in layout \"%2$s\" is missing from the following layout "
                            + "configurations: %3$s (present in %4$s)",
                    id, layout, LintUtils.formatList(missing, Integer.MAX_VALUE),
                    LintUtils.formatList(layouts, Integer.MAX_VALUE));
        }
        messages.put(id, message);
    }
}

From source file:com.opengamma.financial.analytics.model.swaption.deprecated.SwaptionBlackCurveSpecificFunctionDeprecated.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    final ValueProperties constraints = desiredValue.getConstraints();
    final Set<String> curveNames = constraints.getValues(ValuePropertyNames.CURVE);
    if (curveNames == null || curveNames.size() != 1) {
        s_logger.error("Did not specify a curve name for requirement {}", desiredValue);
        return null;
    }// www  .ja v  a2s  .c  o  m
    final Set<String> forwardCurveNames = constraints.getValues(YieldCurveFunction.PROPERTY_FORWARD_CURVE);
    if (forwardCurveNames == null || forwardCurveNames.size() != 1) {
        return null;
    }
    final Set<String> fundingCurveNames = constraints.getValues(YieldCurveFunction.PROPERTY_FUNDING_CURVE);
    if (fundingCurveNames == null || fundingCurveNames.size() != 1) {
        return null;
    }
    final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
    if (surfaceNames == null || surfaceNames.size() != 1) {
        return null;
    }
    final Set<String> curveCalculationMethods = constraints
            .getValues(ValuePropertyNames.CURVE_CALCULATION_METHOD);
    if (curveCalculationMethods == null || curveCalculationMethods.size() != 1) {
        return null;
    }
    final String forwardCurveName = forwardCurveNames.iterator().next();
    final String fundingCurveName = fundingCurveNames.iterator().next();
    final String curveName = curveNames.iterator().next();
    if (!(curveName.equals(forwardCurveName) || curveName.equals(fundingCurveName))) {
        s_logger.error(
                "Did not specify a curve to which this instrument is sensitive; asked for {}, {} and {} are allowed",
                new String[] { curveName, forwardCurveName, fundingCurveName });
        return null;
    }
    final String surfaceName = surfaceNames.iterator().next();
    final String curveCalculationMethod = curveCalculationMethods.iterator().next();
    final Set<ValueRequirement> requirements = Sets.newHashSetWithExpectedSize(4);
    final Currency currency = FinancialSecurityUtils.getCurrency(target.getSecurity());
    requirements.add(getCurveRequirement(forwardCurveName, forwardCurveName, fundingCurveName,
            curveCalculationMethod, currency));
    requirements.add(getCurveRequirement(fundingCurveName, forwardCurveName, fundingCurveName,
            curveCalculationMethod, currency));
    requirements.add(getVolatilityRequirement(surfaceName, currency));
    return requirements;
}

From source file:org.n52.sos.encode.AbstractSensorMLEncoder.java

/**
 * Convert SOS sosOfferings to map with key == identifier and value = name
 * @param featureOfInterestFieldName /*from  w w  w  .  j a  v  a  2 s.  c o m*/
 * 
 * @param map
 *            .values() SOS sosOfferings
 * @return Set with identifier, name.
 */
protected Set<SweText> convertFeaturesToSet(final Map<String, AbstractFeature> map) {
    final Set<SweText> featureSet = Sets.newHashSetWithExpectedSize(map.values().size());
    for (final AbstractFeature abstractFeature : map.values()) {
        SweText sweText = new SweText();
        sweText.setValue(abstractFeature.getIdentifier());
        for (CodeType name : abstractFeature.getName()) {
            sweText.addName(name);
        }
        if (abstractFeature.isSetDescription()) {
            sweText.setDescription(abstractFeature.getDescription());
        }
        featureSet.add(sweText);
    }
    return featureSet;
}

From source file:org.gradoop.util.AsciiGraphLoader.java

/**
 * Returns edges by their given variables.
 *
 * @param variables variables used in GDL script
 * @return edges//w  ww . ja  va2 s. co m
 */
public Collection<E> getEdgesByVariables(String... variables) {
    Collection<E> result = Sets.newHashSetWithExpectedSize(variables.length);
    for (String variable : variables) {
        E edge = edgeCache.get(variable);
        if (edge != null) {
            result.add(edge);
        }
    }
    return result;
}

From source file:com.opengamma.financial.analytics.model.horizon.deprecated.InterestRateFutureOptionConstantSpreadThetaFunctionDeprecated.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    final Set<String> forwardCurves = desiredValue.getConstraints()
            .getValues(YieldCurveFunction.PROPERTY_FORWARD_CURVE);
    if (forwardCurves == null || forwardCurves.size() != 1) {
        return null;
    }/*from   ww w .  j a v  a2 s  .c  o m*/
    final Set<String> fundingCurves = desiredValue.getConstraints()
            .getValues(YieldCurveFunction.PROPERTY_FUNDING_CURVE);
    if (fundingCurves == null || fundingCurves.size() != 1) {
        return null;
    }
    final Set<String> curveCalculationMethodNames = desiredValue.getConstraints()
            .getValues(ValuePropertyNames.CURVE_CALCULATION_METHOD);
    if (curveCalculationMethodNames == null || curveCalculationMethodNames.size() != 1) {
        return null;
    }
    final Set<String> surfaceNames = desiredValue.getConstraints().getValues(ValuePropertyNames.SURFACE);
    if (surfaceNames == null || surfaceNames.size() != 1) {
        return null;
    }
    final String forwardCurveName = forwardCurves.iterator().next();
    final String fundingCurveName = fundingCurves.iterator().next();
    final String curveCalculationMethod = curveCalculationMethodNames.iterator().next();
    final String surfaceName = surfaceNames.iterator().next() + "_"
            + InterestRateFutureOptionBlackFunctionDeprecated.getFutureOptionPrefix(target);
    final Set<ValueRequirement> requirements = Sets.newHashSetWithExpectedSize(4);
    final Currency currency = FinancialSecurityUtils.getCurrency(target.getTrade().getSecurity());
    requirements.add(YieldCurveFunction.getCurveRequirement(currency, forwardCurveName, forwardCurveName,
            fundingCurveName, curveCalculationMethod));
    requirements.add(YieldCurveFunction.getCurveRequirement(currency, fundingCurveName, forwardCurveName,
            fundingCurveName, curveCalculationMethod));
    requirements.add(getVolatilityRequirement(surfaceName, currency));
    return requirements;

}

From source file:com.opengamma.financial.analytics.model.equity.variance.EquityVarianceSwapFunction.java

@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context,
        final ComputationTarget target, final ValueRequirement desiredValue) {
    final EquityVarianceSwapSecurity security = (EquityVarianceSwapSecurity) target.getSecurity();
    final Set<ValueRequirement> requirements = Sets.newHashSetWithExpectedSize(4);
    ValueRequirement requirement;/* w  w  w  .  ja va2s  .  c  o m*/
    requirements.add(getDiscountCurveRequirement(security));
    requirements.add(getSpotRequirement(security));
    requirements.add(getVolatilitySurfaceRequirement(security));
    requirement = getTimeSeriesRequirement(context, security);
    if (requirement == null) {
        return null;
    }
    requirements.add(requirement);
    return requirements;
}