Example usage for java.util Map.Entry get

List of usage examples for java.util Map.Entry get

Introduction

In this page you can find the example usage for java.util Map.Entry get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.terremark.handlers.CloudApiAuthenticationHandler.java

/**
 * Builds a formatted string a Terremark specific headers (excluding x-tmrk-authorization).
 *
 * @param request Client request./* w  w  w .ja v a  2s  .c o  m*/
 * @return Formatted string of Terremark specific headers and values.
 */
private static String getCanonicalizedHeaders(final ClientRequest request) {
    final Map<String, String> headers = new TreeMap<String, String>();

    for (final Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        final String headerName = entry.getKey().toLowerCase();

        if (!headerName.startsWith(TERREMARK_HEADER_PREFIX)
                || TERREMARK_AUTHORIZATION_HEADER.equals(headerName)) {
            continue;
        }

        if (entry.getValue() != null && entry.getValue().size() > 0) {
            headers.put(headerName, entry.getValue().get(0));
        }
    }

    final StringBuilder builder = new StringBuilder();
    for (final Map.Entry<String, String> entry : headers.entrySet()) {
        builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
    }

    if (builder.length() < 1) {
        builder.append('\n');
    }

    return builder.toString();
}

From source file:org.slc.sli.api.resources.util.ResourceUtil.java

/**
 * Helper method to convert MultivaluedMap to a Map
 * //  w ww. j a va2 s.  c  o m
 * @param map
 * @return
 */
public static Map<String, String> convertToMap(Map<String, List<String>> map) {
    Map<String, String> results = new HashMap<String, String>();

    if (map != null) {
        for (Map.Entry<String, List<String>> e : map.entrySet()) {
            results.put(e.getKey(), e.getValue().get(0));
        }
    }

    return results;
}

From source file:com.ebay.cloud.cms.service.resources.impl.QueryResource.java

public static void parseQueryParameters(MultivaluedMap<String, String> params, QueryContext context) {
    String paramName = "";
    String paramVal = "";
    try {/*  w  w w.  j a va2 s  .  co m*/
        for (Map.Entry<String, List<String>> paramEntry : params.entrySet()) {
            CheckConditions.checkNotNull(paramEntry.getKey());

            paramName = paramEntry.getKey();
            CheckConditions.checkArgument(!paramEntry.getValue().isEmpty(), "%s has empty value", paramName);
            paramVal = paramEntry.getValue().get(0);
            QueryParameterEnum paraEnum = null;
            try {
                paraEnum = QueryParameterEnum.valueOf(paramName);
            } catch (Exception e) {
                continue;// ignore the non-query parameter
            }
            switch (paraEnum) {
            case explain:
                context.setExplain(Boolean.valueOf(paramVal));
                break;
            case sortOn:
                for (String f : paramVal.split(",")) {
                    context.addSortOn(f.trim());
                }
                break;
            case sortOrder:
                for (String f : paramVal.split(",")) {
                    context.addSortOrder(SortOrder.valueOf(f.trim()));
                }
                break;
            case limit:
                int[] limits = extractIntArray(paramVal, Integer.MAX_VALUE);
                context.setLimits(limits);
                break;
            case skip:
                int[] skips = extractIntArray(paramVal, 0);
                context.setSkips(skips);
                break;
            case maxFetch:
                context.setMaxFetch(Integer.valueOf(paramVal));
                break;
            case hint:
                context.setHint(Integer.valueOf(paramVal));
                break;
            case allowFullTableScan:
                context.setAllowFullTableScan(Boolean.valueOf(paramVal));
                break;
            case cursor:
                String param = extractCursorValue(paramVal);
                context.setCursorString(param);
                break;
            default:
                break;
            }
        }
    } catch (Throwable t) {
        throw new BadParamException(t, "Bad Parameter (" + paramName + " : " + paramVal + ")");
    }

}

From source file:org.opencb.opencga.server.rest.OpenCGAWSServer.java

/**
 * Builds the query and the queryOptions based on the query parameters.
 *
 * @param params Map of parameters.//w ww . j  a va 2s. co m
 * @param getParam Method that returns the QueryParams object based on the key.
 * @param query Query where parameters parsing the getParam function will be inserted.
 * @param queryOptions QueryOptions where parameters not parsing the getParam function will be inserted.
 */
protected static void parseQueryParams(Map<String, List<String>> params,
        Function<String, org.opencb.commons.datastore.core.QueryParam> getParam, ObjectMap query,
        QueryOptions queryOptions) {
    for (Map.Entry<String, List<String>> entry : params.entrySet()) {
        String param = entry.getKey();
        int indexOf = param.indexOf('.');
        param = indexOf > 0 ? param.substring(0, indexOf) : param;

        if (getParam.apply(param) != null) {
            query.put(entry.getKey(), entry.getValue().get(0));
        } else {
            queryOptions.add(param, entry.getValue().get(0));
        }

        // Exceptions
        if (param.equalsIgnoreCase("status")) {
            query.put("status.name", entry.getValue().get(0));
            query.remove("status");
            queryOptions.remove("status");
        }

        if (param.equalsIgnoreCase("sid")) {
            query.remove("sid");
            queryOptions.remove("sid");
        }
    }
    logger.debug("parseQueryParams: Query {}, queryOptions {}", query.safeToString(),
            queryOptions.safeToString());
}

From source file:eu.europa.ec.fisheries.uvms.exchange.search.SearchFieldMapper.java

/**
 * Created the complete search SQL with joins and sets the values based on
 * the criterias/*from  ww  w  .  j a  v  a 2  s  .  c  o m*/
 *
 * @param criterias
 * @param dynamic
 * @return
 * @throws ParseException
 */
private static String createSearchSql(List<SearchValue> criterias, boolean dynamic) throws ParseException {

    String OPERATOR = " OR ";
    if (dynamic) {
        OPERATOR = " AND ";
    }

    StringBuilder builder = new StringBuilder();
    HashMap<ExchangeSearchField, List<SearchValue>> orderedValues = combineSearchFields(criterias);

    if (!orderedValues.isEmpty()) {

        builder.append("WHERE ");

        boolean first = true;
        for (Map.Entry<ExchangeSearchField, List<SearchValue>> criteria : orderedValues.entrySet()) {

            if (first) {
                first = false;
            } else {
                builder.append(OPERATOR);
            }

            if (criteria.getValue().size() == 1) {
                SearchValue searchValue = criteria.getValue().get(0);
                builder.append(" ( ").append(buildTableAliasname(searchValue.getField()))
                        .append(setParameter(searchValue))
                        //   .append(" OR ").append(buildTableAliasname(searchValue.getField())).append(" IS NULL ")
                        .append(" ) ");
            } else if (criteria.getValue().size() > 1) {
                builder.append(" ( ").append(buildTableAliasname(criteria.getKey())).append(" IN (:")
                        .append(criteria.getKey().getSQLReplacementToken()).append(") ")
                        // .append(" OR ").append(buildTableAliasname(criteria.getKey())).append(" IS NULL ")
                        .append(" ) ");
            }
        }
    }

    return builder.toString();
}

From source file:com.linkedin.helix.tools.ClusterStateVerifier.java

public static boolean verifyFileBasedClusterStates(String file, String instanceName,
        StateModelFactory<StateModel> stateModelFactory) {
    ClusterView clusterView = ClusterViewSerializer.deserialize(new File(file));
    boolean ret = true;
    int nonOfflineStateNr = 0;

    // ideal_state for instance with name $instanceName
    Map<String, String> instanceIdealStates = new HashMap<String, String>();
    for (ZNRecord idealStateItem : clusterView.getPropertyList(PropertyType.IDEALSTATES)) {
        Map<String, Map<String, String>> idealStates = idealStateItem.getMapFields();

        for (Map.Entry<String, Map<String, String>> entry : idealStates.entrySet()) {
            if (entry.getValue().containsKey(instanceName)) {
                String state = entry.getValue().get(instanceName);
                instanceIdealStates.put(entry.getKey(), state);
            }/*from   w  w  w . ja  v  a 2 s .com*/
        }
    }

    Map<String, StateModel> currentStateMap = stateModelFactory.getStateModelMap();

    if (currentStateMap.size() != instanceIdealStates.size()) {
        LOG.warn("Number of current states (" + currentStateMap.size() + ") mismatch "
                + "number of ideal states (" + instanceIdealStates.size() + ")");
        return false;
    }

    for (Map.Entry<String, String> entry : instanceIdealStates.entrySet()) {

        String stateUnitKey = entry.getKey();
        String idealState = entry.getValue();

        if (!idealState.equalsIgnoreCase("offline")) {
            nonOfflineStateNr++;
        }

        if (!currentStateMap.containsKey(stateUnitKey)) {
            LOG.warn("Current state does not contain " + stateUnitKey);
            // return false;
            ret = false;
            continue;
        }

        String curState = currentStateMap.get(stateUnitKey).getCurrentState();
        if (!idealState.equalsIgnoreCase(curState)) {
            LOG.info("State mismatch--unit_key:" + stateUnitKey + " cur:" + curState + " ideal:" + idealState
                    + " instance_name:" + instanceName);
            // return false;
            ret = false;
            continue;
        }
    }

    if (ret == true) {
        System.out.println(instanceName + ": verification succeed");
        LOG.info(instanceName + ": verification succeed (" + nonOfflineStateNr + " states)");
    }

    return ret;
}

From source file:net.metanotion.multitenant.adminapp.Manager.java

/** This method generates the appropriate predicate to be used by a
{@link net.metanotion.web.concrete.ObjectPrefixDispatcher} to verify whether an HTTP request against a tenant
instance by the currently authenticated user is allowed based on the user's status as either a tenant admin or
tenant owner. This predicated does NOT verify specific ooperations permitted only to owners or verify that the user
has provided their password for operations that require a password to initiate.
   @param adminDS the data source for the administrative web application database.
   @return The predicate to use with the {@link net.metanotion.web.concrete.ObjectPrefixDispatcher}
*///w w  w. ja v  a  2  s  . c o m
public static Predicate<Map.Entry<Object, RequestObject>, Exception> tenantUserPermissionPredicate(
        final DataSource adminDS) {
    return new Predicate<Map.Entry<Object, RequestObject>, Exception>() {
        @Override
        public void eval(final Map.Entry<Object, RequestObject> requestInfo) throws Exception {
            logger.debug("auth check on tid {} for uid {}", requestInfo.getKey(), requestInfo.getValue());
            final long tid = Long.parseLong(requestInfo.getValue().get(Constants.TENANT_ID).toString());
            final UserToken user = ((Unknown) requestInfo.getKey()).lookupInterface(UserToken.class);
            try (final Connection conn = adminDS.getConnection()) {
                if (tenantQueries.checkAuth(conn, user.getID(), tid).size() == 0) {
                    throw new SecurityException("Invalid tenant for user.");
                }
            }
        }
    };
}

From source file:org.apache.storm.utils.ServerUtils.java

public static double getEstimatedTotalHeapMemoryRequiredByTopo(Map<String, Object> topoConf,
        StormTopology topology) throws InvalidTopologyException {
    Map<String, Integer> componentParallelism = getComponentParallelism(topoConf, topology);
    double totalMemoryRequired = 0.0;

    for (Map.Entry<String, Map<String, Double>> entry : ResourceUtils.getBoltsResources(topology, topoConf)
            .entrySet()) {//from   ww w.  j  a va2s.c  o m
        int parallelism = componentParallelism.getOrDefault(entry.getKey(), 1);
        double memoryRequirement = entry.getValue().get(Config.TOPOLOGY_COMPONENT_RESOURCES_ONHEAP_MEMORY_MB);
        totalMemoryRequired += memoryRequirement * parallelism;
    }

    for (Map.Entry<String, Map<String, Double>> entry : ResourceUtils.getSpoutsResources(topology, topoConf)
            .entrySet()) {
        int parallelism = componentParallelism.getOrDefault(entry.getKey(), 1);
        double memoryRequirement = entry.getValue().get(Config.TOPOLOGY_COMPONENT_RESOURCES_ONHEAP_MEMORY_MB);
        totalMemoryRequired += memoryRequirement * parallelism;
    }
    return totalMemoryRequired;
}

From source file:org.jsfr.json.BenchmarkParseLargeJsonWithoutStreaming.java

@Benchmark
public void benchmarkRawGson(Blackhole blackhole) {
    JsonObject root = gson.fromJson(json, JsonObject.class);
    JsonObject builders = root.getAsJsonObject("builders");
    for (Map.Entry<String, JsonElement> entry : builders.entrySet()) {
        JsonElement value = entry.getValue().getAsJsonObject().getAsJsonObject("properties").get("branch");
        blackhole.consume(value);//from   ww  w  .j  a v  a  2s .c  o m
        LOGGER.trace("json element: {}", value);
    }
}

From source file:com.espertech.esperio.db.core.DMLStatement.java

public void execute(Connection connection, EventBean eventBean) {
    PreparedStatement statement = null;
    try {/*w  ww .j av  a 2s .  c o m*/
        if ((ExecutionPathDebugLog.isDebugEnabled) && (log.isDebugEnabled())) {
            log.debug("Executing '" + dmlSQL + ")");
        }
        statement = connection.prepareStatement(dmlSQL);
        for (Map.Entry<Integer, BindingEntry> entry : bindings.entrySet()) {
            Object value = entry.getValue().getGetter().get(eventBean);
            statement.setObject(entry.getKey(), value);
        }

        int rows = statement.executeUpdate();
        if ((ExecutionPathDebugLog.isDebugEnabled) && (log.isDebugEnabled())) {
            log.debug("Execution yielded " + rows + " rows");
        }
    } catch (SQLException ex) {
        String message = "Failed to invoke : " + dmlSQL + " :" + ex.getMessage();
        log.error(message, ex);
        storeExceptionHandler.handle(message, ex);
        throw new StoreExceptionDBRel(message, ex);
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
        }
    }
}