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.microsoft.azure.storage.core.Utility.java

/**
 * Logs the HttpURLConnection request. If an exception is encountered, logs nothing.
 * //from   w  w  w . j a va 2  s .c  o  m
 * @param conn
 *            The HttpURLConnection to serialize.
 * @param opContext 
 *            The operation context which provides the logger.
 */
public static void logHttpRequest(HttpURLConnection conn, OperationContext opContext) throws IOException {
    if (Logger.shouldLog(opContext)) {
        try {
            StringBuilder bld = new StringBuilder();

            bld.append(conn.getRequestMethod());
            bld.append(" ");
            bld.append(conn.getURL());
            bld.append("\n");

            // The Authorization header will not appear due to a security feature in HttpURLConnection
            for (Map.Entry<String, List<String>> header : conn.getRequestProperties().entrySet()) {
                if (header.getKey() != null) {
                    bld.append(header.getKey());
                    bld.append(": ");
                }

                for (int i = 0; i < header.getValue().size(); i++) {
                    bld.append(header.getValue().get(i));
                    if (i < header.getValue().size() - 1) {
                        bld.append(",");
                    }
                }
                bld.append('\n');
            }

            Logger.trace(opContext, bld.toString());
        } catch (Exception e) {
            // Do nothing
        }
    }
}

From source file:org.wso2.carbon.identity.provisioning.AbstractOutboundProvisioningConnector.java

/**
 * @param attributeMap/*from   w w w . java  2 s .  c o  m*/
 * @return claimValues
 */
protected Map<String, String> getSingleValuedClaims(Map<ClaimMapping, List<String>> attributeMap) {

    Map<String, String> claimValues = new HashMap<>();

    for (Map.Entry<ClaimMapping, List<String>> entry : attributeMap.entrySet()) {
        ClaimMapping mapping = entry.getKey();
        if (mapping.getRemoteClaim() != null && mapping.getRemoteClaim().getClaimUri() != null) {
            String claimUri = mapping.getRemoteClaim().getClaimUri();

            if (!(IdentityProvisioningConstants.GROUP_CLAIM_URI.equals(claimUri)
                    || IdentityProvisioningConstants.PASSWORD_CLAIM_URI.equals(claimUri)
                    || IdentityProvisioningConstants.USERNAME_CLAIM_URI.equals(claimUri))) {
                if (entry.getValue() != null && entry.getValue().get(0) != null) {
                    claimValues.put(claimUri, entry.getValue().get(0));
                } else {
                    claimValues.put(claimUri, mapping.getDefaultValue());
                }
            }
        }
    }

    return claimValues;
}

From source file:de.themoep.timedscripts.TimedScriptCommand.java

private boolean runAction(CommandSender sender, Action action, TimedScript script, String[] args) {
    String perm = "timedscripts.command." + action.toString().toLowerCase();
    if (sender instanceof Player && !sender.hasPermission(perm)) {
        sender.sendMessage(ChatColor.RED + "You don't have the permissions " + perm);
        return true;
    }//from   ww  w .  java  2s  .  c o m
    if (action == Action.EDIT) {
        if (args.length == 0) {
            return false;
        }
        try {
            EditAction editAction = EditAction.valueOf(args[0].toUpperCase());
            try {
                if (args.length == 1) {
                    sender.sendMessage(ChatColor.RED + "Usage: " + editAction.getUsage());
                    return true;
                }
                double time = Double.valueOf(args[1]);

                List<String> argList = new ArrayList<String>();
                argList.addAll(Arrays.asList(args).subList(2, args.length));
                if (!runEditAction(sender, editAction, time, script,
                        argList.toArray(new String[argList.size()]))) {
                    sender.sendMessage(ChatColor.RED + "Usage: " + editAction.getUsage());
                }

            } catch (NumberFormatException e) {
                sender.sendMessage(
                        ChatColor.RED + "Error: " + args[1] + " is not a valid double number input!");
                sender.sendMessage(ChatColor.RED + "Usage: " + editAction.getUsage());
            }
        } catch (IllegalArgumentException e) {
            sender.sendMessage(ChatColor.RED + "The edit action " + args[0].toUpperCase() + " is unknown!");
            return false;
        }

    } else if (action == Action.RUN) {
        if (sender instanceof Player && !((Player) sender).getUniqueId().equals(script.getCreatorId())
                && !sender.hasPermission("timedscripts.command.run." + script.getName().toLowerCase())) {
            sender.sendMessage(ChatColor.RED
                    + "You don't have the permissions to run this script! (TimedScripts.command.run."
                    + script.getName().toLowerCase() + ")");
            return true;
        }
        CommandSender runAs = sender;
        Map<String, String> vars = new HashMap<String, String>();
        if (args.length > 0 && sender instanceof Player && !sender
                .hasPermission("timedscripts.command.runwithvars." + script.getName().toLowerCase())) {
            sender.sendMessage(ChatColor.RED
                    + "You don't have the permissions to run this script with variables! (TimedScripts.command.runwithvars."
                    + script.getName().toLowerCase() + ")");
            return true;
        }
        String currentVar = "";
        StringBuilder currentValue = new StringBuilder();
        int inQuotes = 0;
        for (String arg : args) {
            if ((inQuotes > 0 && !arg.contains("=")) || inQuotes > 1) {
                if (arg.endsWith("\"")) {
                    inQuotes = 0;
                    arg = arg.substring(0, arg.length() - 1);
                } else {
                    inQuotes++;
                }
                currentValue.append(" ").append(arg);
                if (inQuotes == 0) {
                    vars.put(currentVar.toLowerCase(), currentValue.toString());
                    currentValue = new StringBuilder();
                }
            } else {
                if (!arg.contains("=")) {
                    sender.sendMessage(ChatColor.YELLOW + arg + ChatColor.RED
                            + " does not use the correct variable syntax of var=value!");
                    return false;
                }
                String[] var = arg.split("=");
                if (var.length > 0 && var[1].startsWith("\"") && !var[1].endsWith("\"")) {
                    inQuotes = 1;
                    currentVar = var[0];
                    currentValue.append(var[1].substring(1));
                } else if ("sender".equalsIgnoreCase(var[0])) {
                    if ("console".equalsIgnoreCase(var[1]) && (!(sender instanceof Player))
                            || sender.hasPermission("timedscripts.command.runasconsole")) {
                        runAs = plugin.getServer().getConsoleSender();
                    } else if (!(sender instanceof Player)
                            || sender.hasPermission("timedscripts.command.runasother")) {
                        runAs = plugin.getServer().getPlayer(var[1]);
                        if (runAs == null) {
                            sender.sendMessage(ChatColor.RED + "Could not find a player with the name "
                                    + ChatColor.YELLOW + args[0]);
                            return true;
                        }
                    }
                } else {
                    vars.put(var[0].toLowerCase(), var.length > 0 ? var[1] : "");
                }
            }
        }

        sender.sendMessage(ChatColor.GREEN + "Started script " + ChatColor.YELLOW + script.getName());
        plugin.getScriptManager().runScript(runAs, script, vars);

    } else if (action == Action.INFO) {
        int commandCount = 0;
        for (List<TimedCommand> commands : script.getCommands().values()) {
            commandCount += commands.size();
        }
        List<String> msg = new ArrayList<String>();
        msg.add(ChatColor.AQUA + "Info for script " + ChatColor.YELLOW + script.getName() + ChatColor.AQUA
                + ":");
        if (!plugin.getConfig().getString("webinterface", "").isEmpty()) {
            msg.add(ChatColor.AQUA + "Link: " + ChatColor.YELLOW
                    + plugin.getConfig().getString("webinterface", "").replace("%script%", script.getName()));
        }
        msg.add(ChatColor.AQUA + "Creator: " + ChatColor.YELLOW + script.getCreatorName() + ChatColor.AQUA + "("
                + script.getCreatorId() + ")");
        msg.add(ChatColor.AQUA + "Contains " + ChatColor.YELLOW + commandCount + ChatColor.AQUA + " command"
                + (commandCount != 1 ? "s" : "") + " at " + ChatColor.YELLOW + script.getCommands().size()
                + ChatColor.AQUA + " different times!");

        sender.sendMessage(msg.toArray(new String[msg.size()]));

    } else if (action == Action.VIEW) {
        if (script.getCommands().size() == 0) {
            sender.sendMessage(ChatColor.RED + "The script " + ChatColor.YELLOW + script.getName()
                    + ChatColor.RED + " does not have any commands defined yet!");
            return true;
        }
        List<String> commandList = new ArrayList<String>();
        double time = -1;
        if (args.length > 0) {
            try {
                time = Double.valueOf(args[0]);
                List<TimedCommand> commands = script.getCommands(time);
                if (commands == null || commands.size() == 0) {
                    sender.sendMessage(ChatColor.RED + "The script " + ChatColor.YELLOW + script.getName()
                            + ChatColor.RED + " does not have any commands at " + ChatColor.YELLOW + time);
                    return true;
                }
                for (int i = 0; i < commands.size(); i++) {
                    TimedCommand command = commands.get(i);
                    commandList.add(ChatColor.GRAY + "#" + i + " " + ChatColor.WHITE + Utils.formatTime(time)
                            + ": " + ChatColor.GRAY + command);
                }
            } catch (NumberFormatException e) {
                sender.sendMessage(
                        ChatColor.RED + "Error: " + args[0] + " is not a valid double number input!");
                return true;
            }
        } else {
            for (Map.Entry<Double, List<TimedCommand>> entry : script.getCommands().entrySet()) {
                for (int i = 0; i < entry.getValue().size(); i++) {
                    TimedCommand command = entry.getValue().get(i);
                    commandList.add(ChatColor.GRAY + "#" + i + " " + ChatColor.DARK_GRAY
                            + Utils.formatTime(entry.getKey()) + ": " + ChatColor.GRAY + command);
                }
            }
        }
        sender.sendMessage(ChatColor.AQUA + "Commands of " + ChatColor.YELLOW + script.getName()
                + ChatColor.AQUA + (time == -1 ? ":" : " at " + Utils.formatTime(time) + ":"));
        sender.sendMessage(commandList.toArray(new String[commandList.size()]));

    } else if (action == Action.SAVE) {
        if (script.save()) {
            sender.sendMessage(ChatColor.GREEN + "Script " + ChatColor.YELLOW + script.getName()
                    + ChatColor.GREEN + " saved!");
        } else {
            sender.sendMessage(ChatColor.RED + "An error occurred while saving the script " + script.getName()
                    + "! Please take a look at the exception in the log.");
        }

    } else if (action == Action.DELETE) {
        if (plugin.getScriptManager().deleteScript(script)) {
            sender.sendMessage(ChatColor.GREEN + "Script " + ChatColor.YELLOW + script.getName()
                    + ChatColor.GREEN + " deleted!");
        } else {
            sender.sendMessage(ChatColor.RED + "An error occurred while deleting the script " + script.getName()
                    + "! Please take a look at the exception in the log.");
        }

    } else if (action == Action.STOP) {
        if (plugin.getScriptManager().stopScript(script)) {
            sender.sendMessage(ChatColor.YELLOW + "Script " + script.getName() + " stopped!");
        } else {
            sender.sendMessage(ChatColor.YELLOW + "Script " + script.getName() + " was not running!");
        }
    } else if (action == Action.RELOAD) {
        plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> {
            if (plugin.getScriptManager().loadScript(script.getName()) != null) {
                sender.sendMessage(ChatColor.GREEN + script.getName() + " reloaded!");
            } else {
                sender.sendMessage(ChatColor.RED + script.getName()
                        + " could not be loaded? Please take a look at the log");
            }
        });
    } else {
        sender.sendMessage(ChatColor.RED + "Action " + action + " is not implemented yet!");
    }
    return true;
}

From source file:com.amazonaws.http.UrlHttpClient.java

@SuppressWarnings("checkstyle:emptyblock")
HttpResponse createHttpResponse(final HttpRequest request, final HttpURLConnection connection)
        throws IOException {
    // connection.setDoOutput(true);
    final String statusText = connection.getResponseMessage();
    final int statusCode = connection.getResponseCode();
    InputStream content = connection.getErrorStream();
    if (content == null) {
        // HEAD method doesn't have a body
        if (!"HEAD".equals(request.getMethod())) {
            try {
                content = connection.getInputStream();
            } catch (final IOException ioe) {
                // getInputStream() can throw an exception when there is no
                // input stream.
            }//from  www  .  j  av a 2 s .c  o m
        }
    }

    final HttpResponse.Builder builder = HttpResponse.builder().statusCode(statusCode).statusText(statusText)
            .content(content);
    for (final Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        // skip null field that stores connection status
        if (header.getKey() == null) {
            continue;
        }
        // No AWS service return a list of header values, so it's safe to
        // take the first one.
        builder.header(header.getKey(), header.getValue().get(0));
    }

    return builder.build();
}

From source file:com.healthcit.cacure.model.admin.GeneratedModuleDataDetail.java

/**
 * Purges the given key from all collection which keep track of unique keys
 *///from   w w w.j av  a 2 s.c o m
public void purgeQuestionCombinations(Map<String, JSONObject> uniqueKey, String entityId, int entityDocId,
        int docId) {
    for (Map.Entry<String, JSONObject> entry : uniqueKey.entrySet()) {
        String key = GeneratedModuleDataDetail.getTwoPartMapKey(entry.getKey(),
                entry.getValue().get(ANSWERVALUE_VALUE).toString());

        uniquePerAllModuleQuestionCombinations.get(key).remove(docId);

        uniquePerEntityModuleQuestionCombinations.get(key).remove(entityDocId);

        uniquePerEntityQuestionCombinations.get(key).remove(entityId);
    }
}

From source file:com.epam.catgenome.manager.protein.ProteinSequenceManager.java

/**
 * Load protein sequence for gene track, taking into account variations.
 *
 * @param psVariationQuery query//  www.ja va  2s  . c  o  m
 * @param referenceId      reference id
 * @return list of possible protein sequence tracks
 * @throws GeneReadingException   if error occurred during working with reference or gene files
 */
@Transactional(propagation = Propagation.REQUIRED)
public Track<MrnaProteinSequenceVariants> loadProteinSequenceWithVariations(
        final ProteinSequenceVariationQuery psVariationQuery, final Long referenceId)
        throws GeneReadingException {
    TrackQuery trackQuery = psVariationQuery.getTrackQuery();
    Track<ProteinSequence> track = Query2TrackConverter.convertToTrack(trackQuery);
    Chromosome chromosome = trackHelper.validateTrack(track);
    Track<Gene> geneTrack = gffManager.loadGenes(Query2TrackConverter.convertToTrack(trackQuery), false);

    // Check if variations changes CDS.
    Map<Gene, List<Gene>> mrnaToCdsMap = psReconstructionManager.loadCds(geneTrack, chromosome, false);
    Set<Gene> allCds = new HashSet<>();
    mrnaToCdsMap.values().stream().forEach(allCds::addAll);
    Map<Variation, List<Gene>> intersections = findIntersections(psVariationQuery.getVariations(), allCds);

    // Change mRNA according to variations and load new protein sequences.
    Map<Gene, List<List<Sequence>>> cdsToNucleotidesMap;
    try {
        cdsToNucleotidesMap = psReconstructionManager.loadNucleotidesForReferenceVariationCds(chromosome,
                referenceId, intersections);
    } catch (IOException e) {
        throw new GeneReadingException(geneTrack, e);
    }

    HashMap<Gene, List<Gene>> mrnaToVarCdsMap = makeMrnaToVarCdsMap(mrnaToCdsMap, allCds, cdsToNucleotidesMap);
    Map<Gene, List<List<ProteinSequenceEntry>>> mrnaToAminoAcidsMap = loadProteinSequencesByVarCds(
            mrnaToVarCdsMap, cdsToNucleotidesMap, referenceId, geneTrack, chromosome);

    Map<String, List<List<ProteinSequence>>> blocks = new HashMap<>(mrnaToAminoAcidsMap.size());
    for (Map.Entry<Gene, List<List<ProteinSequenceEntry>>> mrnaToAminoAcidsEntry : mrnaToAminoAcidsMap
            .entrySet()) {
        List<List<ProteinSequenceEntry>> psEntryList = mrnaToAminoAcidsEntry.getValue();
        List<List<ProteinSequence>> lst = new ArrayList<>();
        for (List<ProteinSequenceEntry> psEntry : psEntryList) {
            lst.add(psEntry.stream().map(ProteinSequence::new).collect(Collectors.toList()));
        }
        String transcriptId = mrnaToAminoAcidsEntry.getKey().getAttributes().get(TRANSCRIPT_ID_FILED);
        if (StringUtils.isNotEmpty(transcriptId)) {
            blocks.put(transcriptId, lst);
        }

    }

    Track<MrnaProteinSequenceVariants> result = new Track<>();
    result.setBlocks(Collections.singletonList(
            new MrnaProteinSequenceVariants(track.getStartIndex(), track.getEndIndex(), blocks)));

    return result;
}

From source file:cn.afterturn.easypoi.excel.export.base.ExportCommonService.java

/**
 * ??//from w  w w .j a v a  2s .  c o m
 */
public void sortAllParams(List<ExcelExportEntity> excelParams) {
    // ?,group ?,??
    // groupName?,?
    Map<String, List<ExcelExportEntity>> groupMap = new HashMap<String, List<ExcelExportEntity>>();
    for (int i = excelParams.size() - 1; i > -1; i--) {
        // ??
        if (excelParams.get(i).getList() != null) {
            Collections.sort(excelParams.get(i).getList());
        } else if (StringUtils.isNoneEmpty(excelParams.get(i).getGroupName())) {
            if (!groupMap.containsKey(excelParams.get(i).getGroupName())) {
                groupMap.put(excelParams.get(i).getGroupName(), new ArrayList<ExcelExportEntity>());
            }
            groupMap.get(excelParams.get(i).getGroupName()).add(excelParams.get(i));
            excelParams.remove(i);
        }
    }
    Collections.sort(excelParams);
    if (groupMap.size() > 0) {
        // group ?
        for (Iterator it = groupMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, List<ExcelExportEntity>> entry = (Map.Entry) it.next();
            Collections.sort(entry.getValue());
            // ?excelParams
            boolean isInsert = false;
            String groupName = "START";
            for (int i = 0; i < excelParams.size(); i++) {
                // groupName ,
                if (excelParams.get(i).getOrderNum() > entry.getValue().get(0).getOrderNum()
                        && !groupName.equals(excelParams.get(i).getGroupName())) {
                    if (StringUtils.isNotEmpty(excelParams.get(i).getGroupName())) {
                        groupName = excelParams.get(i).getGroupName();
                    }
                    excelParams.addAll(i, entry.getValue());
                    isInsert = true;
                    break;
                } else if (!groupName.equals(excelParams.get(i).getGroupName())
                        && StringUtils.isNotEmpty(excelParams.get(i).getGroupName())) {
                    groupName = excelParams.get(i).getGroupName();
                }
            }
            //???
            if (!isInsert) {
                excelParams.addAll(entry.getValue());
            }
        }
    }
}

From source file:eu.delving.sip.FileStoreImpl.java

private Collection<File> findMappingFiles(File dir) {
    File[] files = dir.listFiles(new MappingFileFilter());
    Map<String, List<File>> map = new TreeMap<String, List<File>>();
    for (File file : files) {
        String prefix = getMetadataPrefix(file);
        if (prefix == null)
            continue;
        List<File> list = map.get(prefix);
        if (list == null) {
            map.put(prefix, list = new ArrayList<File>());
        }//from  w w w .j a  va2s  .com
        list.add(file);
    }
    List<File> mappingFiles = new ArrayList<File>();
    for (Map.Entry<String, List<File>> entry : map.entrySet()) {
        if (entry.getValue().size() == 1) {
            mappingFiles.add(entry.getValue().get(0));
        } else {
            mappingFiles.add(getMostRecent(entry.getValue().toArray(new File[entry.getValue().size()])));
        }
    }
    return mappingFiles;
}

From source file:org.openspaces.rest.space.ReplicationRESTController.java

public TopologySpec(Map ts) {
    this.name = (String) ts.get("name");

    List<Map<String, String>> inputedges = (List<Map<String, String>>) ts.get("edges");
    if (inputedges == null || inputedges.size() == 0)
        throw new RuntimeException("no replication pairs defined");
    for (Map<String, String> edge : inputedges) {
        TopologyEdge newedge = new TopologyEdge(edge.get("fromSite"), edge.get("fromSpace"), edge.get("toSite"),
                edge.get("toSpace"));
        edges.add(newedge);//from  ww  w. j a  va2s. com
    }

    Map<String, Map<String, String>> portmap = (Map<String, Map<String, String>>) ts.get("ports");
    if (portmap == null)
        portmap = new HashMap<String, Map<String, String>>();
    for (Map.Entry<String, Map<String, String>> entry : portmap.entrySet()) {
        List<Integer> plist = new ArrayList<Integer>();
        plist.add(Integer.parseInt(entry.getValue().get("discovery")));
        plist.add(Integer.parseInt(entry.getValue().get("data")));
        ports.put(entry.getKey(), plist);
    }
}

From source file:org.unitime.timetable.backup.SessionRestore.java

protected Object get(Class clazz, String id) {
    if (clazz.equals(String.class) || clazz.equals(StringType.class))
        return id;
    if (clazz.equals(Character.class) || clazz.equals(CharacterType.class))
        return (id == null || id.isEmpty() ? null : id.charAt(0));
    if (clazz.equals(Byte.class) || clazz.equals(ByteType.class))
        return Byte.valueOf(id);
    if (clazz.equals(Short.class) || clazz.equals(ShortType.class))
        return Short.valueOf(id);
    if (clazz.equals(Integer.class) || clazz.equals(IntegerType.class))
        return Integer.valueOf(id);
    if (clazz.equals(Long.class) || clazz.equals(LongType.class))
        return Long.valueOf(id);
    if (clazz.equals(Float.class) || clazz.equals(FloatType.class))
        return Float.valueOf(id);
    if (clazz.equals(Double.class) || clazz.equals(DoubleType.class))
        return Double.valueOf(id);
    if (clazz.equals(Boolean.class) || clazz.equals(BooleanType.class))
        return Boolean.valueOf(id);

    Map<String, Entity> entities = iEntities.get(clazz.getName());
    if (entities != null) {
        Entity entity = entities.get(id);
        if (entity != null)
            return entity.getObject();
    }//from   w ww.j  a  v a 2  s  . c o m
    for (Map.Entry<String, Map<String, Entity>> entry : iEntities.entrySet()) {
        Entity o = entry.getValue().get(id);
        if (o != null && clazz.isInstance(o.getObject()))
            return o.getObject();
    }
    if (clazz.equals(Session.class))
        return ((Entity) iEntities.get(Session.class.getName()).values().iterator().next()).getObject();
    if (clazz.equals(Student.class))
        return checkUnknown(clazz, id, iStudents.get(id));
    if (iIsClone)
        return checkUnknown(clazz, id,
                iHibSession.get(clazz, clazz.equals(ItypeDesc.class) ? (Serializable) Integer.valueOf(id)
                        : (Serializable) Long.valueOf(id)));
    return checkUnknown(clazz, id, null);
}