Example usage for java.util Map containsValue

List of usage examples for java.util Map containsValue

Introduction

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

Prototype

boolean containsValue(Object value);

Source Link

Document

Returns true if this map maps one or more keys to the specified value.

Usage

From source file:com.funambol.server.engine.Sync4jStrategy.java

/**
 * Converts the parentKey of the given item from LUID to GUID
 * (the server syncsource needs the GUID) using the given mapping
 * @param mapping the mapping//from w  w w.  j a  v  a  2 s. com
 * @param item the item
 */
protected void fixParent(Map mapping, SyncItem item) {

    SyncItemKey parentKey = item.getParentKey();
    if (mapping == null) {
        return;
    }
    if (parentKey != null) {
        String sParentKey = parentKey.getKeyAsString();
        //
        // We have to transform the LUID in GUID
        //
        if (mapping.containsValue(sParentKey)) {

            Iterator itMap = mapping.keySet().iterator();
            String key = null;
            String value = null;
            while (itMap.hasNext()) {
                key = (String) itMap.next(); // GUID
                value = (String) mapping.get(key); // LUID
                if (value.equals(sParentKey)) {
                    parentKey.setKeyValue(key);
                }
            }
        }
    }
}

From source file:com.redsqirl.CanvasBean.java

public void paste() throws RemoteException {
    logger.info("paste");
    String error = null;/*from w w w.  j  av a  2s. c  o m*/
    if (wfCopyBuffer != null && getDf() != null) {
        error = getworkFlowInterface().copy(wfCopyBuffer.getDfCloneId(), wfCopyBuffer.getElementsToCopy(),
                getNameWorkflow());
        if (error == null) {
            Iterator<String> elIt = getDf().getComponentIds().iterator();
            Map<String, String> idMapWf = idMap.get(getNameWorkflow());
            StringBuffer ans = new StringBuffer();
            while (elIt.hasNext()) {
                String elCur = elIt.next();
                if (!idMapWf.containsValue(elCur)) {
                    idMapWf.put(elCur, elCur);
                    ans = ans.append("," + elCur);
                }
            }
            if (ans.length() > 0) {
                setIdsToPaste(ans.substring(1));
                logger.info(getIdsToPaste());
            }
        }
    }

    displayErrorMessage(error, "PASTE");

}

From source file:com.funambol.foundation.items.dao.PIMContactDAO.java

/**
 * Checks if contact and potential twin have phone numbers in common.
 *
 * @param contactPhones the list of contact's phone numbers
 * @param twinPhones the map of twin's phone numbers
 *
 * @return <b>true</b> if contact and twin have at least one phone numbers
 *         in common, <b>false</b> otherwise
 *///from w  w w.  java2s.co  m
private boolean haveContactAndTwinPhoneNumbersInCommon(List<Phone> contactPhones,
        Map<Integer, String> twinPhones) {

    //no phone number to process
    if (contactPhones.isEmpty() || twinPhones.isEmpty())
        return false;

    for (Phone phone : contactPhones) {
        String contactPhone = phone.getPropertyValueAsString();
        if (twinPhones.containsValue(contactPhone)) {
            return true;
        }
    }

    return false;
}

From source file:org.etudes.mneme.impl.ImportTextServiceImpl.java

/**
 * Process if it is recognized as an match question.
 * //from   ww  w  .java  2  s . c  o  m
 * @param pool
 *         The pool to hold the question.
 * @param lines
 *         The lines to process.
 * @return true if successfully recognized and processed, false if not.
 * 
 * @throws AssessmentPermissionException
 */
protected boolean processTextMatching(Pool pool, String[] lines) throws AssessmentPermissionException {
    /* 1. if the choices start with '[' then it may be a matching question
       2. choice and match. choices should be equal or greater by one than matches*/
    if (lines.length < 3)
        return false;

    boolean first = true;
    boolean blankMatch = false;
    boolean foundQuestionAttributes = false;
    boolean foundDrawMatch = false;
    String feedback = null;
    String hints = null;
    boolean isSurvey = false;
    String distractor = null;
    Map<String, String> choicePairs = new LinkedHashMap<String, String>();
    Map<String, String> drawChoicePairs = new LinkedHashMap<String, String>();

    boolean drawMatchNumberFormatEstablished = false, numberFormatEstablished = false;

    NumberingType drawMatchNumberingType = null, numberingType = null;

    for (String line : lines) {
        // ignore first line as first line is question text
        if (first) {
            first = false;
            continue;
        }

        // draw choices
        if (!line.startsWith("[")) {
            String lower = line.toLowerCase();
            // get feedback, hints, reason, survey. Ignore the line if the key is not found
            if (lower.startsWith(feedbackKey1) || lower.startsWith(feedbackKey2)) {
                String[] parts = StringUtil.splitFirst(line, ":");
                if (parts.length > 1)
                    feedback = parts[1].trim();
                foundQuestionAttributes = true;
            } else if (lower.startsWith(hintKey)) {
                String[] parts = StringUtil.splitFirst(line, ":");
                if (parts.length > 1)
                    hints = parts[1].trim();
                foundQuestionAttributes = true;
            } else if (lower.equalsIgnoreCase(surveyKey)) {
                isSurvey = true;
                foundQuestionAttributes = true;
            }

            //after finding feedback or hints or reason or survey, ignore paired lists
            if (foundQuestionAttributes)
                continue;

            if (drawChoicePairs.size() < choicePairs.size()) {
                String[] drawMatch = line.trim().split("\\s+");

                if (drawMatch.length > 1) {
                    //check to see if the relation match starts with a character or digit with optional dot
                    if (!drawMatchNumberFormatEstablished) {
                        drawMatchNumberingType = establishNumberingType(drawMatch[0]);

                        if (drawMatchNumberingType == NumberingType.none)
                            continue;

                        drawMatchNumberFormatEstablished = true;
                    }
                    if (validateNumberingType(drawMatch[0], drawMatchNumberingType)) {
                        String key, value;
                        if (drawMatch[0].endsWith("."))
                            key = drawMatch[0].substring(0, drawMatch[0].length() - 1);
                        else
                            key = drawMatch[0].substring(0, drawMatch[0].length());

                        value = line.substring(drawMatch[0].length() + 1);

                        if ((StringUtil.trimToNull(value) == null) || (StringUtil.trimToNull(key) == null))
                            continue;

                        if (drawChoicePairs.containsKey(key) || drawChoicePairs.containsValue(value))
                            return false;

                        drawChoicePairs.put(key, value);

                        foundDrawMatch = true;
                    }
                }
            }
            continue;

        } else {
            // once draw matches found no more matching paired lists are added
            if (foundDrawMatch || foundQuestionAttributes)
                continue;
        }

        if (line.indexOf("]") == -1)
            continue;

        // choice
        String choiceValue = line.substring(line.indexOf("[") + 1, line.indexOf("]")).trim();

        String matchLine = line.substring(line.indexOf("]") + 1).trim();

        String[] match = matchLine.trim().split("\\s+");

        // distractor
        if (match.length < 2) {
            if (!blankMatch && match.length == 1) {
                distractor = choiceValue;

                blankMatch = true;
                continue;
            } else
                return false;
        }

        if (match.length > 1) {
            //check to see if paired lists counter starts with a character or digit with optional dot
            if (!numberFormatEstablished) {
                numberingType = establishNumberingType(match[0]);

                if (numberingType == NumberingType.none)
                    continue;

                numberFormatEstablished = true;
            }
            if (validateNumberingType(match[0], numberingType)) {
                String value = choiceValue;
                String key = line.substring(line.indexOf("]") + 1).substring(match[0].length() + 1).trim();

                if ((StringUtil.trimToNull(value) == null) || (StringUtil.trimToNull(key) == null))
                    continue;

                if (choicePairs.containsKey(key) || choicePairs.containsValue(value))
                    return false;

                choicePairs.put(key, value);
            }
        }

    }

    if (choicePairs.size() < 2)
        return false;

    // create the question
    Question question = this.questionService.newQuestion(pool, "mneme:Match");
    MatchQuestionImpl m = (MatchQuestionImpl) (question.getTypeSpecificQuestion());

    // set the text
    String text = lines[0].trim();
    String clean;
    if (text.matches("^\\d+\\.\\s.*")) {
        String[] parts = StringUtil.splitFirst(text, ".");
        if (parts.length > 1) {
            text = parts[1].trim();
            clean = Validator.escapeHtml(text);
        } else
            return false;
    } else
        clean = Validator.escapeHtml(text);

    question.getPresentation().setText(clean);

    // set the # pairs
    m.consolidate("INIT:" + choicePairs.size());

    // set the pair values
    List<MatchQuestionImpl.MatchQuestionPair> pairs = m.getPairs();
    String value;
    int index = 0;
    for (String key : choicePairs.keySet()) {
        clean = Validator.escapeHtml(key);
        pairs.get(index).setMatch(clean);

        if (drawChoicePairs.size() > 0) {
            value = choicePairs.get(key);
            value = drawChoicePairs.get(value);
        } else
            value = choicePairs.get(key);

        if (StringUtil.trimToNull(value) == null)
            return false;

        clean = Validator.escapeHtml(value);
        pairs.get(index).setChoice(clean);

        index++;
    }

    if (distractor != null)
        m.setDistractor(distractor);

    // add feedback
    if (StringUtil.trimToNull(feedback) != null) {
        question.setFeedback(Validator.escapeHtml(feedback));
    }

    // add hints
    if (StringUtil.trimToNull(hints) != null) {
        question.setHints(Validator.escapeHtml(hints));
    }

    // survey
    question.setIsSurvey(isSurvey);

    // save
    question.getTypeSpecificQuestion().consolidate("");
    this.questionService.saveQuestion(question);

    return true;
}

From source file:com.zimbra.cs.db.DbMailItem.java

public static List<Integer> getDumpsterItems(Mailbox mbox, int lastSync, int folderId, int maxTrack)
        throws ServiceException {
    List<Integer> result = new ArrayList<>();
    DbConnection conn = mbox.getOperationConnection();
    PreparedStatement stmt = null;
    ResultSet rs = null;/*  w ww  .  ja va 2 s  . c o m*/
    try {
        stmt = conn.prepareStatement(
                "SELECT id, prev_folders, folder_id, mod_metadata FROM " + getMailItemTableName(mbox, true)
                        + " WHERE " + IN_THIS_MAILBOX_AND + "mod_metadata > ? " + " ORDER BY id");
        Db.getInstance().enableStreaming(stmt);
        int pos = 1;
        pos = setMailboxId(stmt, mbox, pos);
        stmt.setLong(pos++, lastSync);
        rs = stmt.executeQuery();

        while (rs.next()) {
            int id = rs.getInt(1);
            String prevFolders = rs.getString(2);
            int curFolderId = rs.getInt(3);
            int modseq = rs.getInt(4);
            if (lastSync < modseq && curFolderId == folderId) {
                result.add(id);
                continue;
            }
            if (StringUtil.isNullOrEmpty(prevFolders)) {
                continue;
            }
            //e.g. "101:2;110:5"
            String[] mappings = prevFolders.split(";");
            Map<Integer, Integer> modseq2folders = new HashMap<>();
            for (String info : mappings) {
                String[] meta = info.split(":");
                modseq2folders.put(Integer.parseInt(meta[0]), Integer.parseInt(meta[1]));
            }
            if (!modseq2folders.containsValue(folderId)) {
                continue;
            }
            int index = 0;
            while (index < mappings.length && index < maxTrack) {
                String md2id = mappings[index++];
                String[] pair = md2id.split(":");
                int md = Integer.parseInt(pair[0]);
                if (lastSync < md) {
                    if (folderId == Integer.parseInt(pair[1])) {
                        result.add(id);
                        break;
                    }
                }
            }
        }
        return result;
    } catch (SQLException e) {
        throw ServiceException.FAILURE("reading mail_item_dumpster since modseq: " + lastSync, e);
    } finally {
        DbPool.closeResults(rs);
        DbPool.closeStatement(stmt);
    }
}

From source file:de.themoep.simpleteampvp.games.SimpleTeamPvPGame.java

/**
 * Balance the teams//from  w w w .j  a  va  2  s.  com
 * @return <tt>true</tt> if game is in GameState.JOINING and players can be balanced
 */
public boolean balance() {
    if (getState() != GameState.JOINING)
        return false;

    plugin.getServer()
            .broadcastMessage(ChatColor.GREEN + "Ausbalancieren und Auffllen der Teams gestartet...");

    Map<Player, String> beforeBalance = new HashMap<>();
    List<Player> playersToJoin = new ArrayList<>();
    for (Player player : plugin.getServer().getOnlinePlayers()) {
        if (player.hasPermission(SimpleTeamPvP.BYPASS_PERM) || player.getGameMode() == GameMode.CREATIVE
                || player.getGameMode() == GameMode.SPECTATOR)
            continue;
        TeamInfo team = getTeam(player);
        if (team == null) {
            if (config.getRandomRegion() == null || config.getRandomRegion().contains(player.getLocation()))
                playersToJoin.add(player);
            beforeBalance.put(player, "");
        } else {
            beforeBalance.put(player, team.getName());
        }
    }
    plugin.getLogger().log(Level.INFO, "Players to join: " + playersToJoin.size());

    int totalPlayers = playersToJoin.size();
    for (TeamInfo team : config.getTeams().values()) {
        totalPlayers += team.getSize();
    }
    plugin.getLogger().log(Level.INFO, "Number of teams: " + config.getTeams().size());
    double perfectSize = (double) totalPlayers / (double) config.getTeams().size();

    plugin.getLogger().log(Level.INFO, "perfectSize: " + perfectSize);

    if (plugin.getServerTags() != null) {
        // Team key -> Tag
        Map<String, String> teamTags = new HashMap<>();

        for (TeamInfo team : config.getTeams().values()) {

            Map<String, Integer> tags = new HashMap<>();
            for (String playerName : team.getScoreboardTeam().getEntries()) {
                Player player = plugin.getServer().getPlayer(playerName);
                if (player == null)
                    continue;

                String tag = "no server";
                ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player);
                if (serverInfo != null) {
                    tag = serverInfo.getTag();
                }
                if (!tags.containsKey(tag)) {
                    tags.put(tag, 0);
                }
                tags.put(tag, tags.get(tag) + 1);
            }

            String teamTag = "no server";
            int tagCount = 0;
            for (Map.Entry<String, Integer> entry : tags.entrySet()) {
                if (entry.getValue() > tagCount) {
                    tagCount = entry.getValue();
                    teamTag = entry.getKey();
                }
            }

            teamTags.put(team.getName(), teamTag);
        }

        for (TeamInfo team : config.getTeams().values()) {
            // Filter out players that come from another server than the majority of the team
            // and remove them as long as the team is larger than the perfect size
            for (String playerName : team.getScoreboardTeam().getEntries()) {
                if (team.getSize() <= perfectSize + 0.5)
                    break;

                Player player = plugin.getServer().getPlayer(playerName);
                if (player == null)
                    continue;

                String tag = "no server";
                ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player);
                if (serverInfo != null) {
                    tag = serverInfo.getTag();
                }

                if (tag.equals(teamTags.get(team.getName())))
                    continue;

                plugin.getLogger().log(Level.INFO,
                        "[ST] Removed " + player.getName() + " from " + team.getName() + " (Step 1)");

                team.removePlayer(player);
                playersToJoin.add(player);
            }

            // Team still larger than the perfect size? Remove last joined player
            Deque<String> teamMates = new ArrayDeque<>(team.getScoreboardTeam().getEntries());
            while (team.getSize() > perfectSize + 0.5) {
                String name = teamMates.peekLast();
                Player player = plugin.getServer().getPlayer(name);
                if (player == null)
                    continue;

                team.removePlayer(player);
                plugin.getLogger().log(Level.INFO,
                        "[ST] Removed " + player.getName() + " from " + team.getName() + " (Step 2)");
                teamMates.pollLast();
                playersToJoin.add(player);
            }
        }

        // Add rest of players to teams from their server
        Iterator<Player> playerIterator = playersToJoin.iterator();
        while (playerIterator.hasNext()) {
            Player player = playerIterator.next();
            ServerInfo serverInfo = plugin.getServerTags().getPlayerServer(player);
            if (serverInfo != null && teamTags.containsValue(serverInfo.getTag())) {
                for (TeamInfo team : config.getTeams().values()) {
                    if (team.getSize() < perfectSize - 0.5 && teamTags.containsKey(team.getName())
                            && teamTags.get(team.getName()).equals(serverInfo.getTag())) {
                        team.addPlayer(player);
                        plugin.getLogger().log(Level.INFO,
                                "[ST] Added " + player.getName() + " to " + team.getName());
                        playerIterator.remove();
                        break;
                    }
                }
            }
        }
        plugin.getLogger().log(Level.INFO, "Players to join after servertags: " + playersToJoin.size());
    }

    // Remove players from teams that have more than the perfect size
    for (TeamInfo team : config.getTeams().values()) {
        for (String playerName : team.getScoreboardTeam().getEntries()) {
            if (team.getSize() <= perfectSize + 0.5)
                break;

            Player player = plugin.getServer().getPlayer(playerName);
            if (player == null)
                continue;

            plugin.getLogger().log(Level.INFO, "Removed " + player.getName() + " from " + team.getName());

            team.removePlayer(player);
            playersToJoin.add(player);
        }
    }

    Iterator<Player> playerIterator = playersToJoin.iterator();
    for (TeamInfo team : config.getTeams().values()) {
        while (playerIterator.hasNext()) {
            if (team.getSize() >= perfectSize - 0.5)
                break;

            Player player = playerIterator.next();
            team.addPlayer(player);
            plugin.getLogger().log(Level.INFO, "Added " + player.getName() + " to " + team.getName());
            playerIterator.remove();
        }
    }

    if (playerIterator.hasNext()) {
        plugin.getLogger().log(Level.INFO, "Adding " + playersToJoin.size()
                + " remaining players to teams according to their player count:");

        List<TeamInfo> teams = new ArrayList<>(config.getTeams().values());
        teams.sort((t1, t2) -> Integer.compare(t2.getSize(), t1.getSize()));

        for (TeamInfo team : teams) {
            while (playerIterator.hasNext()) {
                if (team.getSize() > perfectSize)
                    break;

                Player player = playerIterator.next();
                team.addPlayer(player);
                plugin.getLogger().log(Level.INFO,
                        "Added remaining player " + player.getName() + " to " + team.getName());
                playerIterator.remove();
            }
        }
    }

    if (playerIterator.hasNext()) {
        plugin.getLogger().log(Level.INFO,
                "Adding " + playersToJoin.size() + " remaining players to totally random teams:");
        Random r = new Random();
        List<TeamInfo> teams = new ArrayList<>(config.getTeams().values());
        while (playerIterator.hasNext()) {
            Player player = playerIterator.next();
            TeamInfo team = teams.get(r.nextInt(teams.size()));
            team.addPlayer(player);
            plugin.getLogger().log(Level.INFO,
                    "Added player " + player.getName() + " to " + team.getName() + " by random");
            playerIterator.remove();
        }
    }
    plugin.getLogger().log(Level.INFO, "All players joined! (" + playersToJoin.size() + ")");

    for (Map.Entry<Player, String> entry : beforeBalance.entrySet()) {
        TeamInfo team = getTeam(entry.getKey());
        if (team != null && !team.getName().equals(entry.getValue())) {
            Player player = null;
            for (Iterator<String> it = team.getScoreboardTeam().getEntries().iterator(); player == null
                    && it.hasNext();) {
                player = plugin.getServer().getPlayer(it.next());
            }
            if (player != null && team.getJoinRegion().contains(player.getLocation())) {
                entry.getKey().teleport(player);
            } else {
                entry.getKey().teleport(team.getJoinRegion().calculateMiddle().getLocation());
            }
        }
    }

    plugin.getServer().broadcastMessage(ChatColor.GREEN + "Teams ausbalanciert und aufgefllt!");

    state = GameState.WAITING;
    return true;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private boolean processLinkedObjectsBeforePersist(Map<Object, IdHolder> newIdByOldId, INakedObject o,
        Set<PropertyDescriptor> linkedObjects, ObjectsToPersist toPersist)
        throws IllegalAccessException, InvocationTargetException, ClassNotFoundException,
        IntrospectionException, PersistenceException, InstantiationException {
    if (linkedObjects != null && !linkedObjects.isEmpty()) {
        for (PropertyDescriptor pd : linkedObjects) {
            INakedObject no = (INakedObject) pd.getReadMethod().invoke(o, StorageService.emptyArg);
            if (no != null) {
                Class<? extends INakedObject> linkedClass = no.getClass();
                String linkedClassName = linkedClass.getName();
                Set<PropertyDescriptor> loIds = idsByClassName.get(linkedClassName);
                com.hiperf.common.ui.shared.util.Id loId = getId(no, loIds);
                if (loId.isLocal()) {
                    INakedObject newObj = linkedClass.newInstance();
                    int i = 0;
                    for (Object id : loId.getFieldValues()) {
                        if ((id instanceof Long && ((Long) id).longValue() < 0) || (id instanceof String
                                && ((String) id).startsWith(PersistenceManager.SEQ_PREFIX))) {
                            IdHolder ids = newIdByOldId.get(id);
                            if (ids == null)
                                return false;
                            else
                                id = ids.getId();
                        }/*  w  w  w .  j av  a2s.  c  o m*/
                        setIdField(loIds, loId, newObj, i, id);
                        i++;
                    }
                    setObject(o, pd, newObj);
                } else if (!newIdByOldId
                        .containsValue(new IdHolder(loId.getFieldValues().get(0), linkedClassName))
                        && toPersist.getUpdatedObjects() != null
                        && toPersist.getUpdatedObjects().containsKey(linkedClassName)
                        && toPersist.getUpdatedObjects().get(linkedClassName).get(loId) != null) {
                    INakedObject newObj = linkedClass.newInstance();
                    int i = 0;
                    for (Object id : loId.getFieldValues()) {
                        setIdField(loIds, loId, newObj, i, id);
                        i++;
                    }
                    setObject(o, pd, newObj);
                }
            }
        }
    }
    return true;
}

From source file:com.redhat.rhn.frontend.xmlrpc.system.SystemHandler.java

/**
 * Set server details.//from   w  ww  .  jav a 2  s.  com
 *
 * @param loggedInUser The current user
 * @param serverId ID of server to lookup details for.
 * @param details Map of (optional) system details to be set.
 * @return 1 on success, exception thrown otherwise.
 *
 * @xmlrpc.doc Set server details. All arguments are optional and will only be modified
 * if included in the struct.
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param_desc("int", "serverId", "ID of server to lookup details for.")
 * @xmlrpc.param
 *      #struct("server details")
 *          #prop_desc("string", "profile_name", "System's profile name")
 *          #prop_desc("string", "base_entitlement", "System's base entitlement label.
 *                      (enterprise_entitled or sw_mgr_entitled)")
 *           #prop_desc("boolean", "auto_errata_update", "True if system has
 *                          auto errata updates enabled")
 *           #prop_desc("string", "description", "System description")
 *           #prop_desc("string", "address1", "System's address line 1.")
 *           #prop_desc("string", "address2", "System's address line 2.")
 *           #prop("string", "city")
 *           #prop("string", "state")
 *           #prop("string", "country")
 *           #prop("string", "building")
 *           #prop("string", "room")
 *           #prop("string", "rack")
 *     #struct_end()
 *
 *  @xmlrpc.returntype #return_int_success()
 */
public Integer setDetails(User loggedInUser, Integer serverId, Map<String, Object> details) {

    // confirm that the user only provided valid keys in the map
    Set<String> validKeys = new HashSet<String>();
    validKeys.add("profile_name");
    validKeys.add("base_entitlement");
    validKeys.add("auto_errata_update");
    validKeys.add("address1");
    validKeys.add("address2");
    validKeys.add("city");
    validKeys.add("state");
    validKeys.add("country");
    validKeys.add("building");
    validKeys.add("room");
    validKeys.add("rack");
    validKeys.add("description");
    validateMap(validKeys, details);

    Server server = null;
    try {
        server = SystemManager.lookupByIdAndUser(new Long(serverId.longValue()), loggedInUser);
    } catch (LookupException e) {
        throw new NoSuchSystemException();
    }

    if (details.containsKey("profile_name")) {
        String name = (String) details.get("profile_name");
        name = StringUtils.trim(name);
        validateProfileName(name);
        server.setName(name);
    }

    if (details.containsKey("description")) {
        server.setDescription((String) details.get("description"));
    }

    if (details.containsKey("base_entitlement")) {
        // Raise exception if user attempts to set base entitlement but isn't an org
        // admin:
        if (!loggedInUser.hasRole(RoleFactory.ORG_ADMIN)) {
            throw new PermissionCheckFailureException();
        }

        String selectedEnt = (String) details.get("base_entitlement");
        Entitlement base = EntitlementManager.getByName(selectedEnt);
        if (base != null) {
            server.setBaseEntitlement(base);
        } else if (selectedEnt.equals("unentitle")) {
            SystemManager.removeAllServerEntitlements(server.getId());
        }
    }

    if (details.containsKey("auto_errata_update")) {
        Boolean autoUpdate = (Boolean) details.get("auto_errata_update");

        if (autoUpdate.booleanValue()) {
            if (server.getAutoUpdate().equals("N")) {
                // schedule errata update only it if the value has changed
                ActionManager.scheduleAllErrataUpdate(loggedInUser, server, new Date());
            }
            server.setAutoUpdate("Y");
        } else {
            server.setAutoUpdate("N");
        }
    }

    if (server.getLocation() == null) {
        Location l = new Location();
        server.setLocation(l);
        l.setServer(server);
    }

    if (details.containsKey("address1")) {
        server.getLocation().setAddress1((String) details.get("address1"));
    }
    if (details.containsKey("address2")) {
        server.getLocation().setAddress2((String) details.get("address2"));
    }
    if (details.containsKey("city")) {
        server.getLocation().setCity((String) details.get("city"));
    }
    if (details.containsKey("state")) {
        server.getLocation().setState((String) details.get("state"));
    }
    if (details.containsKey("country")) {
        String country = (String) details.get("country");
        Map<String, String> map = LocalizationService.getInstance().availableCountries();
        if (country.length() > 2 || !map.containsValue(country)) {
            throw new UnrecognizedCountryException(country);
        }
        server.getLocation().setCountry(country);
    }
    if (details.containsKey("building")) {
        server.getLocation().setBuilding((String) details.get("building"));
    }
    if (details.containsKey("room")) {
        server.getLocation().setRoom((String) details.get("room"));
    }
    if (details.containsKey("rack")) {
        server.getLocation().setRack((String) details.get("rack"));
    }

    return 1;
}

From source file:org.talend.designer.core.ui.editor.nodes.Node.java

public void checkLinks() {
    boolean isJoblet = false;
    if (PluginChecker.isJobLetPluginLoaded()) {
        IJobletProviderService service = (IJobletProviderService) GlobalServiceRegister.getDefault()
                .getService(IJobletProviderService.class);
        if (service != null && service.isJobletComponent(this)) {
            isJoblet = true;/*w  w w  .j  a  va 2 s  . c o  m*/
        }
    }
    // check not startable components not linked
    if (!(Boolean) getPropertyValue(EParameterName.STARTABLE.getName())) {
        if ((getCurrentActiveLinksNbInput(EConnectionType.FLOW_MAIN) == 0)
                && (getConnectorFromType(EConnectionType.FLOW_MAIN).getMinLinkInput() == 0)
                        & (getConnectorFromType(EConnectionType.FLOW_MAIN).getMaxLinkInput() != 0)) {
            String errorMessage = Messages.getString("Node.noInputLink"); //$NON-NLS-1$
            Problems.add(ProblemStatus.WARNING, this, errorMessage);
        }
        if ((getCurrentActiveLinksNbInput(EConnectionType.FLOW_MAIN) == 0)
                && (getCurrentActiveLinksNbInput(EConnectionType.FLOW_REF) > 0)) {
            String errorMessage = Messages.getString("Node.noRowMainLink"); //$NON-NLS-1$
            Problems.add(ProblemStatus.WARNING, this, errorMessage);
        }
    }

    // check not startable components not linked
    if ((getConnectorFromType(EConnectionType.FLOW_MAIN).getMaxLinkInput() == 0)
            && (getConnectorFromType(EConnectionType.FLOW_MAIN).getMaxLinkOutput() != 0)) {
        if ((getCurrentActiveLinksNbOutput(EConnectionType.FLOW_MAIN) == 0)
                && (getCurrentActiveLinksNbOutput(EConnectionType.FLOW_MERGE) == 0)
                && (getCurrentActiveLinksNbOutput(EConnectionType.FLOW_REF) == 0)
                && (getCurrentActiveLinksNbOutput(EConnectionType.ITERATE) == 0)) {
            String errorMessage = Messages.getString("Node.noOutputLink"); //$NON-NLS-1$
            Problems.add(ProblemStatus.WARNING, this, errorMessage);
        }
    }

    if (!isJoblet) {
        // Check if there's an output run after / before on a component that is
        // not a sub process start
        if (!isSubProcessStart() || (!(Boolean) getPropertyValue(EParameterName.STARTABLE.getName()))) {
            if ((getCurrentActiveLinksNbOutput(EConnectionType.ON_SUBJOB_OK) > 0)
                    || getCurrentActiveLinksNbOutput(EConnectionType.ON_SUBJOB_ERROR) > 0) {

                String errorMessage = Messages.getString("Node.errorMessage1"); //$NON-NLS-1$
                Problems.add(ProblemStatus.ERROR, this, errorMessage);
            }
        }

        // if (isSubProcessStart() && process.getMergelinkOrder(this) > 1) {
        // String errorMessage = "A component that is not a sub process start can not have any link run after / run
        // before in output.";
        // Problems.add(ProblemStatus.ERROR, this, errorMessage);
        // }

        // Check if there's an input run after / before on a component that is
        // not a sub process start
        if ((!isELTComponent() && !isSubProcessStart())
                || (!(Boolean) getPropertyValue(EParameterName.STARTABLE.getName()))) {
            if ((getCurrentActiveLinksNbInput(EConnectionType.ON_SUBJOB_OK) > 0)
                    || (getCurrentActiveLinksNbInput(EConnectionType.RUN_IF) > 0)
                    || (getCurrentActiveLinksNbInput(EConnectionType.ON_COMPONENT_OK) > 0)
                    || (getCurrentActiveLinksNbInput(EConnectionType.ON_COMPONENT_ERROR) > 0)
                    || (getCurrentActiveLinksNbInput(EConnectionType.STARTS) > 0)
            /*
             * http://jira.talendforge.org/browse/TESB-4858 Modified By LiXiaopeng 2012-2-13 ||
             * (getCurrentActiveLinksNbInput(EConnectionType.ROUTE_WHEN) > 0)
             */) {

                String errorMessage = Messages.getString("Node.errorMessage2"); //$NON-NLS-1$
                Problems.add(ProblemStatus.ERROR, this, errorMessage);
            }
        }

        if (isHL7Output()) {
            if (getIncomingConnections(EConnectionType.FLOW_MERGE).size() <= 0) {
                String errorMessage = Messages.getString("Node.hl7HaveNoMergeLink"); //$NON-NLS-1$
                Problems.add(ProblemStatus.ERROR, this, errorMessage);
            } else {
                List<Map<String, String>> maps = (List<Map<String, String>>) ElementParameterParser
                        .getObjectValue(this, "__SCHEMAS__"); //$NON-NLS-1$
                List<IMetadataTable> tables = this.getMetadataList();
                for (IConnection connection : getIncomingConnections(EConnectionType.FLOW_MERGE)) {
                    IMetadataTable metadataTable = connection.getMetadataTable();
                    // metadataTable.setLabel(connection.getUniqueName());
                    // String metadataTableName = metadataTable.getLabel();
                    String rowName = connection.getUniqueName();
                    String schemaName = null;
                    for (Map<String, String> map : maps) {
                        if (map.containsValue(rowName)) {
                            if (map.get("PARENT_ROW") != null && map.get("PARENT_ROW").equals(rowName)) { //$NON-NLS-1$ //$NON-NLS-2$
                                schemaName = map.get("SCHEMA"); //$NON-NLS-1$
                                // int first = schemaName.indexOf("_"); //$NON-NLS-1$
                                // int second = schemaName.lastIndexOf("_"); //$NON-NLS-1$
                                // if (first > 0 && first < second) {
                                // schemaName = schemaName.substring(first + 1, second);
                                break;
                                // }
                            }
                        }
                    }
                    for (IMetadataTable nodeTable : tables) {
                        if (nodeTable.getTableName() != null && nodeTable.getTableName().equals(schemaName)) {
                            if (!metadataTable.sameMetadataAs(nodeTable, IMetadataColumn.OPTIONS_NONE)) {
                                String errorMessage = Messages.getString("Node.schemaNotSynchronized"); //$NON-NLS-1$
                                Problems.add(ProblemStatus.ERROR, this, errorMessage);
                            }
                        }
                    }
                }
            }
        }
    }
    int tableOutLinkNum = 0;
    int tableRefOutLinkNum = 0;
    List<? extends IConnection> tableOutLinks = this.getOutgoingConnections(EConnectionType.TABLE);
    if (null != tableOutLinks) {
        tableOutLinkNum = tableOutLinks.size();
    }
    List<? extends IConnection> tableRefOutLinks = this.getOutgoingConnections(EConnectionType.TABLE_REF);
    if (null != tableRefOutLinks) {
        tableRefOutLinkNum = tableRefOutLinks.size();
    }
    int tableInLinkNum = 0;
    int tableRefInLinkNum = 0;
    List<? extends IConnection> tableInLinks = this.getIncomingConnections(EConnectionType.TABLE);
    if (null != tableInLinks) {
        tableInLinkNum = tableInLinks.size();
    }
    List<? extends IConnection> tableRefInLinks = this.getIncomingConnections(EConnectionType.TABLE_REF);
    if (null != tableRefInLinks) {
        tableRefInLinkNum = tableRefInLinks.size();
    }
    int jobletBuildConnectorNum = 0;
    // means this Node is an ELTDBMap, and it can use subQuery, so the check maybe a little different
    boolean subQueryMode = true;
    INodeConnector tableRefConnector = getConnectorFromType(EConnectionType.TABLE_REF);
    if (null != tableRefConnector) {
        if (tableRefConnector.getMaxLinkOutput() == 0) {
            subQueryMode = false;
        }
    }

    for (INodeConnector nodeConnector : listConnector) {
        if (!nodeConnector.getDefaultConnectionType().hasConnectionCategory(IConnectionCategory.USE_HASH)
                && nodeConnector.getDefaultConnectionType() != EConnectionType.FLOW_MERGE) {
            boolean needCheckOutput = true;
            boolean needCheckInput = true;
            int nbMaxOut;
            nbMaxOut = nodeConnector.getMaxLinkOutput();
            int nbMaxIn;
            nbMaxIn = nodeConnector.getMaxLinkInput();
            int nbMinOut;
            nbMinOut = nodeConnector.getMinLinkOutput();
            int nbMinIn;
            nbMinIn = nodeConnector.getMinLinkInput();
            int curLinkOut;
            curLinkOut = nodeConnector.getCurLinkNbOutput();
            int curLinkIn;
            curLinkIn = nodeConnector.getCurLinkNbInput();
            String typeName = nodeConnector.getMenuName();

            boolean isCheckingTableLink = false;

            if (subQueryMode) {
                if (nodeConnector.getDefaultConnectionType() == EConnectionType.TABLE) {
                    if (0 < tableRefOutLinkNum) {
                        needCheckOutput = false;
                        if (0 < tableOutLinkNum) {
                            Object[] errorParams = new String[] { EConnectionType.TABLE.getDefaultMenuName(),
                                    EConnectionType.TABLE_REF.getDefaultMenuName() };
                            String errorMessage = Messages.getString("Node.canNotMultiKindTableOutput", //$NON-NLS-1$
                                    errorParams);
                            Problems.add(ProblemStatus.ERROR, this, errorMessage);
                        }
                    }
                    if (0 < tableRefInLinkNum) {
                        needCheckInput = false;
                    }
                    isCheckingTableLink = true;
                    // A subjob can not have multi start node of ELTDBMap
                    if (this.getComponent().getName().endsWith("Map") && tableOutLinks != null) { //$NON-NLS-1$
                        for (IConnection iconn : tableOutLinks) {
                            INode newTarget = iconn.getTarget();
                            if (newTarget.isELTComponent()
                                    && newTarget.getComponent().getName().endsWith("Map")) { //$NON-NLS-1$
                                Object[] errorParams = new String[] { this.getLabel(), newTarget.getLabel(),
                                        EConnectionType.TABLE_REF.getDefaultMenuName() };
                                String errorMessage = Messages
                                        .getString("Node.ELTDBMap.canNotHaveMultiStartNode", errorParams); //$NON-NLS-1$
                                Problems.add(ProblemStatus.ERROR, this, errorMessage);
                            }
                        }
                    }
                } else if (nodeConnector.getDefaultConnectionType() == EConnectionType.TABLE_REF) {
                    if (0 < tableOutLinkNum) {
                        needCheckOutput = false;
                        if (0 < tableRefOutLinkNum) {
                            Object[] errorParams = new String[] { EConnectionType.TABLE.getDefaultMenuName(),
                                    EConnectionType.TABLE_REF.getDefaultMenuName() };
                            String errorMessage = Messages.getString("Node.canNotMultiKindTableOutput", //$NON-NLS-1$
                                    errorParams);
                            Problems.add(ProblemStatus.ERROR, this, errorMessage);
                        }
                    }
                    if (0 < tableInLinkNum) {
                        needCheckInput = false;
                    }
                    isCheckingTableLink = true;
                }
            }

            if (isCheckingTableLink) {
                typeName = EConnectionType.TABLE.getDefaultMenuName() + "/" //$NON-NLS-1$
                        + EConnectionType.TABLE_REF.getDefaultMenuName();
            }

            if (nodeConnector.getDefaultConnectionType() == EConnectionType.FLOW_MAIN) {
                typeName = "Row"; //$NON-NLS-1$
                if (isJoblet) {
                    if (nodeConnector.isBuiltIn()) {
                        jobletBuildConnectorNum++;
                    }
                    continue;
                }
            }
            if (needCheckOutput) {
                if (nbMaxOut != -1) {
                    if (curLinkOut > nbMaxOut) {
                        String errorMessage = Messages.getString("Node.tooMuchTypeOutput", typeName); //$NON-NLS-1$
                        Problems.add(ProblemStatus.WARNING, this, errorMessage);
                    }
                }
                if (nbMinOut != 0) {
                    if (curLinkOut < nbMinOut) {
                        String errorMessage = Messages.getString("Node.notEnoughTypeOutput", typeName); //$NON-NLS-1$
                        Problems.add(ProblemStatus.WARNING, this, errorMessage);
                    }
                }
            }

            // ingore input warning
            if (!isJoblet) {

                if (nbMaxIn != -1) {
                    if (curLinkIn > nbMaxIn) {
                        String errorMessage = Messages.getString("Node.tooMuchTypeInput", typeName); //$NON-NLS-1$
                        Problems.add(ProblemStatus.WARNING, this, errorMessage);
                    }
                }
                if (needCheckInput) {
                    if (nbMinIn != 0) {
                        if (curLinkIn < nbMinIn) {
                            String errorMessage = Messages.getString("Node.notEnoughTypeInput", typeName); //$NON-NLS-1$
                            Problems.add(ProblemStatus.WARNING, this, errorMessage);
                        }
                    }
                }
            }
        }
    }
    if (isJoblet) { // bug 12764
        List<? extends IConnection> outgoingConnections = this
                .getOutgoingConnections(EConnectionType.FLOW_MAIN);
        for (IConnection con : outgoingConnections) {
            INodeConnector connector = this.getConnectorFromName(con.getConnectorName());
            if (connector == null && con instanceof Connection) { // connector is lost.
                ((Connection) con).disconnect();
            }
        }

        String typeName = "Row"; //$NON-NLS-1$
        outgoingConnections = this.getOutgoingConnections(EConnectionType.FLOW_MAIN);
        if (outgoingConnections.size() > jobletBuildConnectorNum) {
            String errorMessage = Messages.getString("Node.tooMuchTypeOutput", typeName); //$NON-NLS-1$
            Problems.add(ProblemStatus.WARNING, this, errorMessage);
        } else if (outgoingConnections.size() < jobletBuildConnectorNum) {
            String errorMessage = Messages.getString("Node.notEnoughTypeOutput", typeName); //$NON-NLS-1$
            Problems.add(ProblemStatus.WARNING, this, errorMessage);
        }
    }
}

From source file:org.exoplatform.services.jcr.ext.backup.impl.BackupManagerImpl.java

/**
 * Repository restore from backup./* ww  w. j  a  va 2s.  c  o  m*/
 *
 * @param log
 *          RepositoryBackupChainLog, the repository backup log
 * @param repositoryEntry
 *          RepositoryEntry, the repository entry
 * @param workspaceNamesCorrespondMap
 *          Map<String, String>, the map with correspondence workspace name in RepositoryEntry and RepositoryBackupChainLog.
 * @param asynchronous
 *          boolean, in 'true' then asynchronous restore.
 * @param removeJobOnceOver
 *          boolean, in 'true' then restore job well remove after restore.   
 * @throws BackupOperationException
 *           will be generate the exception BackupOperationException 
 * @throws BackupConfigurationException
 *           will be generate the exception BackupConfigurationException 
 * @throws RepositoryException
 *           will be generate the exception RepositoryException 
 * @throws RepositoryConfigurationException
 *           will be generate the exception RepositoryConfigurationException 
 */
private void restoreRepository(RepositoryBackupChainLog rblog, RepositoryEntry repositoryEntry,
        Map<String, String> workspaceNamesCorrespondMap, boolean asynchronous, boolean removeJobOnceOver)
        throws BackupOperationException, BackupConfigurationException, RepositoryException,
        RepositoryConfigurationException {
    // Checking repository exists. 
    try {
        repoService.getRepository(repositoryEntry.getName());
        throw new BackupConfigurationException(
                "Repository \"" + repositoryEntry.getName() + "\" is already exists.");
    } catch (RepositoryException e) {
        //OK. Repository with "repositoryEntry.getName" is not exists.
        if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + e.getMessage());
        }
    }

    Map<String, File> workspacesMapping = new HashedMap();

    Map<String, BackupChainLog> backups = new HashedMap();

    if (workspaceNamesCorrespondMap == null) {
        for (String path : rblog.getWorkspaceBackupsInfo()) {
            BackupChainLog bLog = new BackupChainLog(new File(path));
            backups.put(bLog.getBackupConfig().getWorkspace(), bLog);
        }

        if (!rblog.getSystemWorkspace().equals(repositoryEntry.getSystemWorkspaceName())) {
            throw new BackupConfigurationException(
                    "The backup to system workspace is not system workspace in repository entry: "
                            + rblog.getSystemWorkspace() + " is not equal "
                            + repositoryEntry.getSystemWorkspaceName());
        }

        if (backups.size() != repositoryEntry.getWorkspaceEntries().size()) {
            throw new BackupConfigurationException(
                    "The repository entry is contains more or less workspace entry than backups of workspace in "
                            + rblog.getLogFilePath());
        }

        for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries()) {
            if (!backups.containsKey(wsEntry.getName())) {
                throw new BackupConfigurationException("The workspace '" + wsEntry.getName()
                        + "' is not found in backup " + rblog.getLogFilePath());
            } else {
                workspacesMapping.put(wsEntry.getName(),
                        new File(backups.get(wsEntry.getName()).getLogFilePath()));
            }
        }
    } else {
        // Create map [new_ws_name : backupLog to that workspace].
        for (String path : rblog.getWorkspaceBackupsInfo()) {
            BackupChainLog bLog = new BackupChainLog(new File(path));

            if (!workspaceNamesCorrespondMap.containsKey(bLog.getBackupConfig().getWorkspace())) {
                throw new BackupConfigurationException(
                        "Can not found coresptonding workspace name to workspace '"
                                + bLog.getBackupConfig().getWorkspace() + "' in  "
                                + workspaceNamesCorrespondMap.keySet());
            }

            backups.put(workspaceNamesCorrespondMap.get(bLog.getBackupConfig().getWorkspace()), bLog);
        }

        // Checking system workspace.
        if (!repositoryEntry.getSystemWorkspaceName()
                .equals(workspaceNamesCorrespondMap.get(rblog.getSystemWorkspace()))) {
            throw new BackupConfigurationException(
                    "The backup to system workspace is not system workspace in repository entry: "
                            + repositoryEntry.getSystemWorkspaceName() + " is not equal "
                            + workspaceNamesCorrespondMap.get(rblog.getSystemWorkspace()));
        }

        // Checking count of corresponding workspaces.
        if (workspaceNamesCorrespondMap.size() != repositoryEntry.getWorkspaceEntries().size()) {
            throw new BackupConfigurationException(
                    "The repository entry is contains more or less workspace entry than backups of workspace in "
                            + rblog.getLogFilePath());
        }

        for (WorkspaceEntry wsEntry : repositoryEntry.getWorkspaceEntries()) {
            if (!workspaceNamesCorrespondMap.containsValue(wsEntry.getName())) {
                throw new BackupConfigurationException(
                        "The workspace '" + wsEntry.getName() + "' is not found workspaceNamesCorrespondMap  : "
                                + workspaceNamesCorrespondMap.values());
            } else if (!backups.containsKey(wsEntry.getName())) {
                throw new BackupConfigurationException("The workspace '" + wsEntry.getName()
                        + "' is not found in backup " + rblog.getLogFilePath());
            } else {
                workspacesMapping.put(wsEntry.getName(),
                        new File(backups.get(wsEntry.getName()).getLogFilePath()));
            }
        }
    }

    JobRepositoryRestore jobRepositoryRestore = new JobRepositoryRestore(repoService, this, repositoryEntry,
            workspacesMapping, new File(rblog.getLogFilePath()), removeJobOnceOver);

    restoreRepositoryJobs.add(jobRepositoryRestore);
    if (asynchronous) {
        jobRepositoryRestore.start();
    } else {
        jobRepositoryRestore.restore();
    }
}