Example usage for java.util EnumMap put

List of usage examples for java.util EnumMap put

Introduction

In this page you can find the example usage for java.util EnumMap put.

Prototype

public V put(K key, V value) 

Source Link

Document

Associates the specified value with the specified key in this map.

Usage

From source file:com.adobe.acs.commons.mcp.impl.processes.asset.AssetIngestor.java

@SuppressWarnings("squid:S2445")
private void increment(EnumMap<ReportColumns, Object> row, ReportColumns col, long amt) {
    if (row != null) {
        synchronized (row) {
            row.put(col, (Long) row.getOrDefault(col, 0) + amt);
        }// w w  w . jav a 2  s .com
    }
}

From source file:it.units.malelab.sse.MyGeneticAlgorithm.java

private EnumMap<Evaluator.ResultType, Double> mean(List<EnumMap<Evaluator.ResultType, Double>> statsList) {
    EnumMap<Evaluator.ResultType, Double> meanStats = new EnumMap<>(Evaluator.ResultType.class);
    for (Evaluator.ResultType type : Evaluator.ResultType.values()) {
        double s = 0;
        double c = 0;
        for (EnumMap<Evaluator.ResultType, Double> stats : statsList) {
            if (stats.containsKey(type)) {
                s = s + stats.get(type);
                c = c + 1;//from   ww w. j a va2  s.c o m
            }
        }
        if (c > 0) {
            meanStats.put(type, s / c);
        }
    }
    return meanStats;
}

From source file:org.jodconverter.document.DocumentFormat.java

/**
 * Creates a new read-only document format with the specified name, extension and mime-type.
 *
 * @param name The name of the format.//w  ww  . j ava2  s.com
 * @param extensions The file name extensions of the format.
 * @param mediaType The media type (mime type) of the format.
 * @param inputFamily The DocumentFamily of the document.
 * @param loadProperties The properties required to load(open) a document of this format.
 * @param storeProperties The properties required to store(save) a document of this format to a
 *     document of another family.
 * @param unmodifiable {@code true} if the created document format cannot be modified after
 *     creation, {@code false} otherwise.
 */
private DocumentFormat(final String name, final Collection<String> extensions, final String mediaType,
        final DocumentFamily inputFamily, final Map<String, Object> loadProperties,
        final Map<DocumentFamily, Map<String, Object>> storeProperties, final boolean unmodifiable) {

    this.name = name;
    this.extensions = new ArrayList<>(extensions);
    this.mediaType = mediaType;
    this.inputFamily = inputFamily;
    this.loadProperties = Optional.ofNullable(loadProperties)
            // Create a copy of the map.
            .map(HashMap<String, Object>::new)
            // Make the map read only if required.
            .map(mapCopy -> unmodifiable ? Collections.unmodifiableMap(mapCopy) : mapCopy).orElse(null);
    this.storeProperties = Optional.ofNullable(storeProperties)
            // Create a copy of the map.
            .map(map -> {
                final EnumMap<DocumentFamily, Map<String, Object>> familyMap = new EnumMap<>(
                        DocumentFamily.class);
                map.forEach((family, propMap) -> familyMap.put(family,
                        unmodifiable ? Collections.unmodifiableMap(new HashMap<>(propMap))
                                : new HashMap<>(propMap)));
                return familyMap;
            })
            // Make the map read only if required.
            .map(mapCopy -> unmodifiable ? Collections.unmodifiableMap(mapCopy) : mapCopy).orElse(null);
}

From source file:com.techcavern.pircbotz.UserChannelDao.java

@Synchronized("accessLock")
public UserChannelDaoSnapshot createSnapshot() {
    //Create snapshots of all users and channels
    ImmutableMap.Builder<U, UserSnapshot> userSnapshotBuilder = ImmutableMap.builder();
    for (U curUser : userNickMap.values())
        userSnapshotBuilder.put(curUser, curUser.createSnapshot());
    ImmutableMap<U, UserSnapshot> userSnapshotMap = userSnapshotBuilder.build();
    ImmutableMap.Builder<C, ChannelSnapshot> channelSnapshotBuilder = ImmutableMap.builder();
    for (C curChannel : channelNameMap.values())
        channelSnapshotBuilder.put(curChannel, curChannel.createSnapshot());
    ImmutableMap<C, ChannelSnapshot> channelSnapshotMap = channelSnapshotBuilder.build();

    //Make snapshots of the relationship maps using the above user and channel snapshots
    UserChannelMapSnapshot mainMapSnapshot = mainMap.createSnapshot(userSnapshotMap, channelSnapshotMap);
    EnumMap<UserLevel, UserChannelMap<UserSnapshot, ChannelSnapshot>> levelsMapSnapshot = Maps
            .newEnumMap(UserLevel.class);
    for (Map.Entry<UserLevel, UserChannelMap<U, C>> curLevel : levelsMap.entrySet())
        levelsMapSnapshot.put(curLevel.getKey(),
                curLevel.getValue().createSnapshot(userSnapshotMap, channelSnapshotMap));
    ImmutableBiMap.Builder<String, UserSnapshot> userNickMapSnapshotBuilder = ImmutableBiMap.builder();
    for (Map.Entry<String, U> curNick : userNickMap.entrySet())
        userNickMapSnapshotBuilder.put(curNick.getKey(), curNick.getValue().createSnapshot());
    ImmutableBiMap.Builder<String, ChannelSnapshot> channelNameMapSnapshotBuilder = ImmutableBiMap.builder();
    for (Map.Entry<String, C> curName : channelNameMap.entrySet())
        channelNameMapSnapshotBuilder.put(curName.getKey(), curName.getValue().createSnapshot());
    ImmutableSortedSet.Builder<UserSnapshot> privateUserSnapshotBuilder = ImmutableSortedSet.naturalOrder();
    for (User curUser : privateUsers)
        privateUserSnapshotBuilder.add(curUser.createSnapshot());

    //Finally can create the snapshot object
    UserChannelDaoSnapshot daoSnapshot = new UserChannelDaoSnapshot(bot, locale, mainMapSnapshot,
            levelsMapSnapshot, userNickMapSnapshotBuilder.build(), channelNameMapSnapshotBuilder.build(),
            privateUserSnapshotBuilder.build());

    //Tell UserSnapshots and ChannelSnapshots what the new backing dao is
    for (UserSnapshot curUserSnapshot : userSnapshotMap.values())
        curUserSnapshot.setDao(daoSnapshot);
    for (ChannelSnapshot curChannelSnapshot : channelSnapshotMap.values())
        curChannelSnapshot.setDao(daoSnapshot);

    //Finally//from   w w w  . j  a v a 2  s .co  m
    return daoSnapshot;
}

From source file:org.sonar.java.checks.verifier.CheckVerifier.java

protected void collectExpectedIssues(String comment, int line) {
    String expectedStart = getExpectedIssueTrigger();
    if (comment.startsWith(expectedStart)) {
        String cleanedComment = StringUtils.remove(comment, expectedStart);

        EnumMap<IssueAttribute, String> attr = new EnumMap<>(IssueAttribute.class);
        String expectedMessage = StringUtils.substringBetween(cleanedComment, "{{", "}}");
        if (StringUtils.isNotEmpty(expectedMessage)) {
            attr.put(IssueAttribute.MESSAGE, expectedMessage);
        }/*from  w  w w . j av a2  s  .c om*/
        int expectedLine = line;
        String attributesSubstr = extractAttributes(comment, attr);

        cleanedComment = StringUtils
                .stripEnd(StringUtils.remove(StringUtils.remove(cleanedComment, "[[" + attributesSubstr + "]]"),
                        "{{" + expectedMessage + "}}"), " \t");
        if (StringUtils.startsWith(cleanedComment, "@")) {
            final int lineAdjustment;
            final char firstChar = cleanedComment.charAt(1);
            final int endIndex = cleanedComment.indexOf(' ');
            if (endIndex == -1) {
                lineAdjustment = Integer.parseInt(cleanedComment.substring(2));
            } else {
                lineAdjustment = Integer.parseInt(cleanedComment.substring(2, endIndex));
            }
            if (firstChar == '+') {
                expectedLine += lineAdjustment;
            } else if (firstChar == '-') {
                expectedLine -= lineAdjustment;
            } else {
                Fail.fail("Use only '@+N' or '@-N' to shifts messages.");
            }
        }
        updateEndLine(expectedLine, attr);
        expected.put(expectedLine, attr);
    }
}

From source file:org.openecomp.sdc.be.externalapi.servlet.AssetsDataServlet.java

@GET
@Path("/{assetType}/{uuid}/metadata")
@Produces(MediaType.APPLICATION_JSON)/*from www  .  j  ava2  s. com*/
@ApiOperation(value = "Fetch metadata of asset by uuid", httpMethod = "GET", notes = "Returns metadata of asset", response = Response.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Assets Fetched"),
        @ApiResponse(code = 401, message = "Authorization required"),
        @ApiResponse(code = 403, message = "Restricted operation"),
        @ApiResponse(code = 404, message = "Asset not found") })
public Response getAssetListByUuid(@PathParam("assetType") final String assetType,
        @PathParam("uuid") final String uuid, @Context final HttpServletRequest request) {

    Response response = null;
    ResponseFormat responseFormat = null;
    String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
    AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
    String requestURI = request.getRequestURI();
    String url = request.getMethod() + " " + requestURI;
    log.debug("Start handle request of {}", url);
    String serverBaseURL = request.getRequestURL().toString();

    EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(
            AuditingFieldsKeysEnum.class);
    ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
    additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
    additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
    additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
    additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);

    // Mandatory
    if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
        log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
        responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
        getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
        return buildErrorResponse(responseFormat);
    }

    try {
        ServletContext context = request.getSession().getServletContext();
        ElementBusinessLogic elementLogic = getElementBL(context);
        getAssetUtils(context);

        Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic
                .getCatalogComponentsByUuidAndAssetType(assetType, uuid);

        if (assetTypeData.isRight()) {
            log.debug("getAssetList: Asset Fetching Failed");
            responseFormat = assetTypeData.right().value();
            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);

            return buildErrorResponse(responseFormat);
        } else {
            log.debug("getAssetList: Asset Fetching Success");
            additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME,
                    assetTypeData.left().value().iterator().next().getName());
            Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils
                    .convertToAssetMetadata(assetTypeData.left().value(), serverBaseURL, true);
            if (resMetadata.isRight()) {
                log.debug("getAssetList: Asset conversion Failed");
                responseFormat = resMetadata.right().value();
                getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
                return buildErrorResponse(responseFormat);
            }
            Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
            responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
            getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);

            response = buildOkResponse(responseFormat, result);
            return response;
        }
    } catch (Exception e) {
        BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
        log.debug("getAssetList: Fetch list of assets failed with exception", e);
        return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
    }
}

From source file:org.artifactory.common.property.ArtifactorySystemProperties.java

public void loadArtifactorySystemProperties(File systemPropertiesFile, File artifactoryPropertiesFile) {
    Properties combinedProperties = new Properties();
    if (systemPropertiesFile != null && systemPropertiesFile.exists()) {
        FileInputStream fis = null;
        try {//w ww  .j  av  a2 s.co m
            fis = new FileInputStream(systemPropertiesFile);
            combinedProperties.load(fis);
        } catch (Exception e) {
            throw new RuntimeException("Could not read default system properties from '"
                    + systemPropertiesFile.getAbsolutePath() + "'.", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    // load artifactory.properties (version and revision properties)
    if (artifactoryPropertiesFile != null && artifactoryPropertiesFile.exists()) {
        FileInputStream fis = null;
        try {
            // Load from file than override from the system props
            fis = new FileInputStream(artifactoryPropertiesFile);
            combinedProperties.load(fis);
        } catch (Exception e) {
            throw new RuntimeException("Could not read artifactory.properties from '"
                    + artifactoryPropertiesFile.getAbsolutePath() + "'.", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    // Override with System properties
    loadSystemProperties(combinedProperties);

    Set<String> setAsSystemProp = new HashSet<>();
    //Cleanup all non-artifactory system properties and set them as system properties
    for (Object key : combinedProperties.keySet()) {
        String propName = (String) key;
        String propValue = combinedProperties.getProperty(propName);
        if (!propName.startsWith(ConstantValues.SYS_PROP_PREFIX)) {
            // TODO: mainly for derby db properties, find another way of doing it
            System.setProperty(propName, propValue);
            setAsSystemProp.add(propName);
        }
    }
    for (String key : setAsSystemProp) {
        combinedProperties.remove(key);
    }

    substituteRepoKeys = fillRepoKeySubstitute(combinedProperties);

    //Test for deprecated properties and warn
    handleDeprecatedProps(combinedProperties);

    validateConstants(combinedProperties);

    // Use the EnumMap as much as possible
    EnumMap<ConstantValues, String> newArtifactoryProperties = new EnumMap<>(ConstantValues.class);
    for (ConstantValues constVal : ConstantValues.values()) {
        Object val = combinedProperties.remove(constVal.getPropertyName());
        if (val != null) {
            newArtifactoryProperties.put(constVal, (String) val);
        }
    }
    artifactoryProperties = newArtifactoryProperties;
    // TODO: Print a message when combined props is not empty as this should not happen.
    // It's probably a typo! But it's used for special security access values not declared in ConstantValues
    nonEnumArtifactoryProperties = combinedProperties;
    artifactoryBooleanProperties.clear();
    artifactoryLongProperties.clear();
}

From source file:org.libreplan.business.workingday.EffortDuration.java

public EnumMap<Granularity, Integer> decompose() {
    EnumMap<Granularity, Integer> result = new EnumMap<>(Granularity.class);
    int remainder = seconds;
    for (Granularity each : Granularity.fromMoreCoarseToLessCoarse()) {
        int value = each.convertFromSeconds(remainder);
        remainder -= value * each.toSeconds(1);
        result.put(each, value);
    }//from   ww w .  j  ava 2s .  c  o m
    assert remainder == 0;

    return result;
}

From source file:com.espertech.esper.schedule.TestScheduleSpec.java

public void testValidate() {
    // Test all units missing
    EnumMap<ScheduleUnit, SortedSet<Integer>> unitValues = new EnumMap<ScheduleUnit, SortedSet<Integer>>(
            ScheduleUnit.class);
    assertInvalid(unitValues);//from   w w  w .  ja va 2  s  . co m

    // Test one unit missing
    unitValues = (new ScheduleSpec()).getUnitValues();
    unitValues.remove(ScheduleUnit.HOURS);
    assertInvalid(unitValues);

    // Test all units are wildcards
    unitValues = (new ScheduleSpec()).getUnitValues();
    new ScheduleSpec(unitValues, null, null, null);

    // Test invalid value in month
    SortedSet<Integer> values = new TreeSet<Integer>();
    values.add(0);
    unitValues.put(ScheduleUnit.MONTHS, values);
    assertInvalid(unitValues);

    // Test valid value in month
    values = new TreeSet<Integer>();
    values.add(1);
    values.add(5);
    unitValues.put(ScheduleUnit.MONTHS, values);
    new ScheduleSpec(unitValues, null, null, null);
}

From source file:org.pircbotx.UserChannelDao.java

/**
 * Create an immutable snapshot (copy) of all of contained Users, Channels,
 * and mappings, VERY EXPENSIVE./*from   ww w . j  av a 2s .co  m*/
 *
 * @return Copy of entire model
 */
@Synchronized("accessLock")
public UserChannelDaoSnapshot createSnapshot() {
    //Create snapshots of all users and channels
    Map<U, UserSnapshot> userSnapshotMap = Maps.newHashMapWithExpectedSize(userNickMap.size());
    for (U curUser : userNickMap.values())
        userSnapshotMap.put(curUser, curUser.createSnapshot());
    Map<C, ChannelSnapshot> channelSnapshotMap = Maps.newHashMapWithExpectedSize(channelNameMap.size());
    for (C curChannel : channelNameMap.values())
        channelSnapshotMap.put(curChannel, curChannel.createSnapshot());

    //Make snapshots of the relationship maps using the above user and channel snapshots
    UserChannelMapSnapshot mainMapSnapshot = mainMap.createSnapshot(userSnapshotMap, channelSnapshotMap);
    EnumMap<UserLevel, UserChannelMap<UserSnapshot, ChannelSnapshot>> levelsMapSnapshot = Maps
            .newEnumMap(UserLevel.class);
    for (Map.Entry<UserLevel, UserChannelMap<U, C>> curLevel : levelsMap.entrySet())
        levelsMapSnapshot.put(curLevel.getKey(),
                curLevel.getValue().createSnapshot(userSnapshotMap, channelSnapshotMap));
    ImmutableBiMap.Builder<String, UserSnapshot> userNickMapSnapshotBuilder = ImmutableBiMap.builder();
    for (Map.Entry<String, U> curNickEntry : userNickMap.entrySet())
        userNickMapSnapshotBuilder.put(curNickEntry.getKey(), userSnapshotMap.get(curNickEntry.getValue()));
    ImmutableBiMap.Builder<String, ChannelSnapshot> channelNameMapSnapshotBuilder = ImmutableBiMap.builder();
    for (Map.Entry<String, C> curName : channelNameMap.entrySet())
        channelNameMapSnapshotBuilder.put(curName.getKey(), channelSnapshotMap.get(curName.getValue()));
    ImmutableBiMap.Builder<String, UserSnapshot> privateUserSnapshotBuilder = ImmutableBiMap.builder();
    for (Map.Entry<String, U> curNickEntry : privateUsers.entrySet())
        privateUserSnapshotBuilder.put(curNickEntry.getKey(), userSnapshotMap.get(curNickEntry.getValue()));

    //Finally can create the snapshot object
    UserChannelDaoSnapshot daoSnapshot = new UserChannelDaoSnapshot(bot, locale, mainMapSnapshot,
            levelsMapSnapshot, userNickMapSnapshotBuilder.build(), channelNameMapSnapshotBuilder.build(),
            privateUserSnapshotBuilder.build());

    //Tell UserSnapshots and ChannelSnapshots what the new backing dao is
    for (UserSnapshot curUserSnapshot : userSnapshotMap.values())
        curUserSnapshot.setDao(daoSnapshot);
    for (ChannelSnapshot curChannelSnapshot : channelSnapshotMap.values())
        curChannelSnapshot.setDao(daoSnapshot);

    //Finally
    return daoSnapshot;
}