Example usage for java.util Map clear

List of usage examples for java.util Map clear

Introduction

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

Prototype

void clear();

Source Link

Document

Removes all of the mappings from this map (optional operation).

Usage

From source file:com.hypersocket.client.HypersocketClient.java

public void login() throws IOException, UserCancelledException {

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

    /**//from ww  w  . j  a  v  a  2 s  .  co  m
     * Reset authentication with client scheme
     */
    //      String json = transport.post("logon", params);

    int maxAttempts = 3;
    int attempts = maxAttempts;
    boolean attemptedCached = false;
    List<Prompt> prompts = new ArrayList<Prompt>();

    if (cachedUsername != null && cachedPassword != null) {
        params.put("username", cachedUsername);
        params.put("password", cachedPassword);
        attemptedCached = true;
    }

    while (!isLoggedOn()) {

        if (attempts == 0) {
            if (log.isInfoEnabled()) {
                log.info(String.format("%s too many authentication attempts", transport.getHost()));
            }
            disconnect(false);
            throw new IOException("Too many failed authentication attempts");
        }

        String json = transport.post("logon/hypersocketClient", params);

        params.clear();
        boolean success = processLogon(json, params, prompts);
        if (!success) {
            if (!attemptedCached) {
                attempts--;
            }
            attemptedCached = false;
        }
        if (!isLoggedOn() && prompts.size() > 0) {

            // If failed, and it's not the very first attempt (i.e. the one that triggers username and password entry), show an error
            if (!success) {
                showError("Incorrect username or password.");
            }

            Map<String, String> results = showLogin(this, prompts, attempts, success);

            if (results != null) {

                params.putAll(results);

                if (params.containsKey("username")) {
                    cachedUsername = params.get("username");
                }
                if (params.containsKey("password")) {
                    cachedPassword = params.get("password");
                }

            } else {
                if (log.isInfoEnabled()) {
                    log.info(String.format("%s user cancelled authentication", transport.getHost()));
                }
                disconnect(false);
                throw new UserCancelledException("User has cancelled authentication");
            }
        }
    }

    if (log.isInfoEnabled()) {
        log.info("Logon complete sessionId=" + getSessionId());
    }

    postLogin();

    onConnected();
}

From source file:asterix.parser.classad.ClassAd.java

public void getComponents(Map<CaseInsensitiveString, ExprTree> attrs) {
    attrs.clear();
    for (Entry<CaseInsensitiveString, ExprTree> attr : this.attrList.entrySet()) {
        attrs.put(attr.getKey(), attr.getValue());
    }//from  ww w  .  j a va 2s .c  o m
}

From source file:com.youanmi.scrm.smp.facade.org.OrgInfoFacade.java

/**
 * //w ww . ja  v  a 2  s . c o  m
 * @Description: ?orgName??
 * @author li.jinwen
 * @email lijinwen@youanmi.com
 * @date 2017213 ?2:14:04
 * @param orgName
 * @return
 */
public boolean uniqueneOrgName(String orgName, Long orgId) {
    // 1?????????
    Map<String, Object> params = new HashMap<>();
    params.put("orgId", orgId);
    params.put("orgName", orgName);
    params.put("orgLevel", 1);
    boolean b = orgInfoService.uniqueneOrgParams(params);
    // 2????????
    params.clear();
    params.put("orgId", orgId);
    params.put("orgName", orgName);
    params.put("topOrgId", orgId);// topOrgId=orgId
    params.put("notOrgType", 2);
    boolean c = orgInfoService.uniqueneOrgParams(params);
    return b && c;
}

From source file:com.caspida.plugins.graph.EntityGraphNeo4jPlugin.java

/**
 * Nodes and edges are merged in two different API calls because node creation
 * returns the nodes hashes to nodeId map
 *
 * Adding nodeId to the edge request speeds up the process of edge creation
 * because the lookUp of nodes by nodeId is much faster then going with the index
 *
 * {/*from   w ww  .  j  a  v  a 2s.  c  o m*/
 *   containers : [
 *     {
 *       "labels" : ["a", "b"],
 *       "header" : [<Array of properties names. All edge rels array will
 *                   follow the same order>]
 *       "relmap" : {
 *         "hash1" : {
 *           "id" : <e1>,
 *           "rels" : [
 *             [<hash2>, <e2>, <relationship>, <conditional probability>,
 *             <joint probability>, <mutual information>]
 *           ],
 *         }
 *         ...
 *       }
 *     }
 *   ]
 * }
 * @param graphDb
 * @param json
 * @return
 */
@Name(EntityGraphConstants.API_MERGE_ENTITY_EDGES)
@Description("Merge entity edges")
@PluginTarget(GraphDatabaseService.class)
public String mergeBehaviorGraphEdges(@Source GraphDatabaseService graphDb,
        @Description("") @Parameter(name = "data", optional = true) String json) {

    // Perform request validations
    if ((json == null) || (json.trim().isEmpty())) {
        throw new IllegalArgumentException("Invalid JSON provided for method : " + json);
    }

    logger.debug("Merge edges request data : {}", json);
    JSONObject relIds = new JSONObject();
    long numEdges = 0;
    JSONObject response = new JSONObject();
    try {
        JSONParser parser = new JSONParser();
        JSONObject request = (JSONObject) parser.parse(json);

        JSONArray header = (JSONArray) request.get(EntityGraphConstants.REQ_PROPERTY_HEADER_TAG);

        JSONObject relationsMap = (JSONObject) request
                .get(EntityGraphConstants.REQ_EDGE_MERGE_RELATIONSHIP_MAP_TAG);
        Map<Long, Map<String, Relationship>> eventRelationships = new HashMap<>();

        for (Object key : relationsMap.keySet()) {
            eventRelationships.clear();
            String eventHash = key.toString();
            JSONObject data = (JSONObject) relationsMap.get(key);
            Long eventId = null;

            Node e1 = null;
            if ((eventId == null) || (eventId < 0)) {
                e1 = UniqueEntityFactory.getOrCreateNode(graphDb, eventHash, null);
            } else {
                try (Transaction txn = graphDb.beginTx()) {
                    e1 = graphDb.getNodeById(eventId);
                }
            }

            List<UniqueEntityFactory.RelationshipRequestInfo> requestInfoList = new ArrayList<>();
            JSONArray relationships = (JSONArray) data
                    .get(EntityGraphConstants.REQ_EDGE_MERGE_RELATIONSHIPS_TAG);
            for (Object objectRel : relationships) {
                JSONArray rel = (JSONArray) objectRel;
                Map<String, Object> edgeProperties = getPropertiesFromHeaderAndArray(header, rel);
                Object tmp;
                tmp = edgeProperties.remove(EntityGraphConstants.REQ_EDGE_MERGE_END_NODE_HASH_TAG);
                String endNodeEventHash = (tmp != null) ? tmp.toString() : null;

                Long endNodeEventId = null;
                tmp = edgeProperties.remove(EntityGraphConstants.REQ_EDGE_MERGE_END_DB_ID_TAG);
                String relEventIdObj = (tmp != null) ? tmp.toString() : null;

                try {
                    endNodeEventId = (relEventIdObj != null) ? Long.parseLong(relEventIdObj.toString()) : null;
                } catch (NumberFormatException e) {
                    // ignore exception and do a lookup
                }

                tmp = edgeProperties.remove(EntityGraphConstants.REQ_EDGE_PROPS_RELNAME_KEY);
                String relationshipName = (tmp != null) ? tmp.toString() : null;

                requestInfoList.add(new UniqueEntityFactory.RelationshipRequestInfo(e1, endNodeEventId,
                        endNodeEventHash, relationshipName, edgeProperties));
            }

            UniqueEntityFactory.createBulkRelationships(graphDb, e1, requestInfoList);
            for (UniqueEntityFactory.RelationshipRequestInfo rri : requestInfoList) {
                String relKey = rri.getDescr();
                Relationship relationship = rri.getRelationship();
                if ((relKey == null) || (relationship == null)) {
                    continue;
                }

                relIds.put(relKey, relationship.getId());
            }
            numEdges += requestInfoList.size();
        }

        response.put(EntityGraphConstants.RES_IDS_TAG, relIds);
    } catch (Throwable e) {
        logger.error("Failed to create entity graph : " + json, e);
        createErrorResponse(response, EntityGraphConstants.API_MERGE_ENTITY_EDGES,
                "Failed to merge entity graph", e);
    }

    return response.toJSONString();
}

From source file:com.esd.ps.EmployerController.java

/**
 * 1. 2.?/*from w ww.  j ava  2 s .c om*/
 * 
 * @param packName
 * @param taskLvl
 * @param packLockTime
 * @param markTimeMethod
 * @param session
 * @return
 */
@RequestMapping(value = "/unzip", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> unzip(String packName, String noteId, int taskType, int taskLvl, int packLockTime,
        int markTimeMethod, HttpSession session) {
    System.out.println("?!!!");
    Map<String, Object> map = new HashMap<String, Object>();
    int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
    int employerId = Integer.parseInt(session.getAttribute(Constants.EMPLOYER_ID).toString());
    String url = employerService.getUploadUrlByEmployerId(employerId);
    File fold = new File(url);
    if (!fold.exists()) {
        map.clear();
        map.put(Constants.MESSAGE, MSG_FOLD_NOT_EXIST);
        return map;
    }
    File file = new File(url + Constants.SLASH + packName);
    if (!file.exists()) {
        map.clear();
        map.put(Constants.MESSAGE, MSG_PACK_NOT_EXIST);
        return map;
    }
    packWithBLOBs packWithBLOBs = new packWithBLOBs();
    try {
        if (packService.getCountPackByPackName(packName) > 0) {
            map.clear();
            map.put(Constants.MESSAGE, MSG_PACK_EXIST);
            return map;
        }
        boolean flag = false;
        if (file.isDirectory()) {
            File[] f = file.listFiles();
            if (f.length > 0) {
                flag = true;
            }
        } else {
            ZipFile zip = new ZipFile(url + Constants.SLASH + packName);
            if (zip.size() > 1) {
                flag = true;
            }
        }
        if (flag) {

            packWithBLOBs
                    .setEmployerId(Integer.parseInt(session.getAttribute(Constants.EMPLOYER_ID).toString()));
            // packWithBLOBs.setPackFile(pack.getBytes());
            packWithBLOBs.setPackName(packName);
            packWithBLOBs.setDownCount(0);
            packWithBLOBs.setPackLockTime((packLockTime * 3600000));
            packWithBLOBs.setPackStatus(0);
            packWithBLOBs.setUnzip(0);
            packWithBLOBs.setNoteId(noteId);
            packWithBLOBs.setTaskMarkTimeId(markTimeMethod);
            markTimeMethod markTimeMethod1 = markTimeMethodService.getByPrimaryKey(markTimeMethod);
            packWithBLOBs.setTaskMarkTimeName(markTimeMethod1.getName());
            packWithBLOBs.setPackType(taskType);
            packWithBLOBs.setPackLvl(taskLvl);
            packWithBLOBs.setVersion(1);
            packWithBLOBs.setCreateId(userId);
            packWithBLOBs.setCreateTime(new Date());
            StackTraceElement[] items = Thread.currentThread().getStackTrace();
            packWithBLOBs.setCreateMethod(items[1].toString());
            packService.insertSelective(packWithBLOBs);
        } else {
            map.clear();
            map.put(Constants.MESSAGE, MSG_FOLD_NOT_EXIST);
            return map;
        }
        // ??TaskService
        if (file.isDirectory()) {
            storeDataFold(packName, taskLvl, url, userId, new Date());
        } else {
            storeDataZIP(packName, taskLvl, url, userId, new Date());
        }

    } catch (IOException e) {
        map.clear();
        map.put(Constants.MESSAGE, MSG_PACK_ERROR);
        return map;
    }
    map.clear();
    map.put(Constants.MESSAGE, MSG_FINISH);
    return map;
}

From source file:com.gst.portfolio.shareaccounts.service.ShareAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public CommandProcessingResult closeShareAccount(Long accountId, JsonCommand jsonCommand) {
    try {//from   w w w.  ja  va2s  .co  m
        ShareAccount account = this.shareAccountRepository.findOneWithNotFoundDetection(accountId);
        Map<String, Object> changes = this.accountDataSerializer.validateAndClose(jsonCommand, account);
        if (!changes.isEmpty()) {
            this.shareAccountRepository.save(account);
            final String noteText = jsonCommand.stringValueOfParameterNamed("note");
            if (StringUtils.isNotBlank(noteText)) {
                final Note note = Note.shareNote(account, noteText);
                changes.put("note", noteText);
                this.noteRepository.save(note);
            }
            ShareAccountTransaction transaction = (ShareAccountTransaction) changes
                    .get(ShareAccountApiConstants.requestedshares_paramname);
            transaction = account.getShareAccountTransaction(transaction);
            Set<ShareAccountTransaction> transactions = new HashSet<>();
            transactions.add(transaction);
            this.journalEntryWritePlatformService
                    .createJournalEntriesForShares(populateJournalEntries(account, transactions));
            changes.clear();
            changes.put(ShareAccountApiConstants.requestedshares_paramname, transaction.getId());

        }
        return new CommandProcessingResultBuilder() //
                .withCommandId(jsonCommand.commandId()) //
                .withEntityId(accountId) //
                .with(changes) //
                .build();
    } catch (DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(jsonCommand, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Handles dynamic changes to a qa.data.Array instance without having a complete replacement; expects a 
 * serverId, propertyName, type (one of "add", "remove", "order"), start, end, and optional array of items 
 * @param jp//from w  w w . jav  a  2s .c o  m
 * @throws ServletException
 * @throws IOException
 */
protected void cmdEditArray(JsonParser jp) throws ServletException, IOException {
    // Get the basics
    int serverId = getFieldValue(jp, "serverId", Integer.class);
    String propertyName = getFieldValue(jp, "propertyName", String.class);
    String action = getFieldValue(jp, "type", String.class);
    Integer start = null;
    Integer end = null;

    if (!action.equals("replaceAll")) {
        start = getFieldValue(jp, "start", Integer.class);
        end = getFieldValue(jp, "end", Integer.class);
    }

    // Get our info
    Proxied serverObject = getProxied(serverId);
    ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(serverObject.getClass());
    ProxyProperty prop = getProperty(type, propertyName);

    if (prop.getPropertyClass().isMap()) {
        Map items = null;

        // Get the optional array of items
        if (jp.nextToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("items")
                && jp.nextToken() == JsonToken.START_OBJECT) {

            items = readMap(jp, prop.getPropertyClass().getKeyClass(), prop.getPropertyClass().getJavaType());
        }

        // Quick logging
        if (log.isInfoEnabled()) {
            String str = "";
            if (items != null)
                for (Object key : items.keySet()) {
                    if (str.length() > 0)
                        str += ", ";
                    str += String.valueOf(key) + "=" + String.valueOf(items.get(key));
                }
            log.info("edit-array: property=" + prop + ", type=" + action + ", start=" + start + ", end=" + end
                    + str);
        }

        if (action.equals("replaceAll")) {
            Map map = (Map) prop.getValue(serverObject);
            if (map == null) {
                try {
                    map = (Map) prop.getPropertyClass().getCollectionClass().newInstance();
                } catch (Exception e) {
                    throw new IllegalArgumentException(e.getMessage(), e);
                }
                prop.setValue(serverObject, map);
            }
            map.clear();
            map.putAll(items);
        } else
            throw new IllegalArgumentException("Unsupported action in cmdEditArray: " + action);

        // Because collection properties are objects and we change them without the serverObject's
        //   knowledge, we have to make sure we notify other trackers ourselves
        ProxyManager.propertyChanged(serverObject, propertyName, items, null);

        jp.nextToken();
    } else {
        // NOTE: items is an Array!!  But because it may be an array of primitive types, we have
        //   to use java.lang.reflect.Array to access members because we cannot cast arrays of
        //   primitives to Object[]
        Object items = null;

        // Get the optional array of items
        if (jp.nextToken() == JsonToken.FIELD_NAME && jp.getCurrentName().equals("items")
                && jp.nextToken() == JsonToken.START_ARRAY) {

            items = readArray(jp, prop.getPropertyClass().getJavaType());
        }
        int itemsLength = Array.getLength(items);

        // Quick logging
        if (log.isInfoEnabled()) {
            String str = "";
            if (items != null)
                for (int i = 0; i < itemsLength; i++) {
                    if (str.length() != 0)
                        str += ", ";
                    str += Array.get(items, i);
                }
            log.info("edit-array: property=" + prop + ", type=" + action + ", start=" + start + ", end=" + end
                    + str);
        }

        if (action.equals("replaceAll")) {
            if (prop.getPropertyClass().isCollection()) {
                Collection list = (Collection) prop.getValue(serverObject);
                if (list == null) {
                    try {
                        list = (Collection) prop.getPropertyClass().getCollectionClass().newInstance();
                    } catch (Exception e) {
                        throw new IllegalArgumentException(e.getMessage(), e);
                    }
                    prop.setValue(serverObject, list);
                }
                list.clear();
                if (items != null)
                    for (int i = 0; i < itemsLength; i++)
                        list.add(Array.get(items, i));

                // Because collection properties are objects and we change them without the serverObject's
                //   knowledge, we have to make sure we notify other trackers ourselves
                ProxyManager.propertyChanged(serverObject, propertyName, list, null);
            } else {
                prop.setValue(serverObject, items);
            }
        } else
            throw new IllegalArgumentException("Unsupported action in cmdEditArray: " + action);

        jp.nextToken();
    }
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

@Override
public boolean updateClassroom(String roomId, String name, String description, Date begin, Date end,
        VCConfiguration config) {/*from   w  w  w .j a v a2s  .c  om*/
    if (!existsClassroom(roomId, config))
        return false;
    if (!loginAdmin())
        throw new AssertException(
                "Cannot login to Adobe Connect. Please check module configuration and that Adobe Connect is available.");

    String scoId = getScoIdFor(roomId);
    if (scoId == null)
        return false;

    // formatter for begin and end
    SimpleDateFormat sd = new SimpleDateFormat(DATE_FORMAT);

    Map<String, String> parameters = new HashMap<String, String>();
    // update meeting configuration
    parameters.put("action", "sco-update");
    parameters.put("sco-id", scoId);
    if (begin != null)
        parameters.put("date-begin", sd.format(begin));
    if (end != null)
        parameters.put("date-end", sd.format(end));
    String templateId = ((AdobeConnectConfiguration) config).getTemplateKey();
    if (templateId != null && !templateId.equals(DEFAULT_TEMPLATE))
        parameters.put("source-sco-id", templateId);
    Document responseDoc = getResponseDocument(sendRequest(parameters));
    if (!evaluateOk(responseDoc))
        return false;

    // adjust permissions
    parameters.clear();
    parameters.put("action", "permissions-update");
    parameters.put("acl-id", scoId);
    parameters.put("principal-id", "public-access");
    if (((AdobeConnectConfiguration) config).isGuestAccessAllowed())
        parameters.put("permission-id", "view-hidden");
    else
        parameters.put("permission-id", "remove");
    responseDoc = getResponseDocument(sendRequest(parameters));
    if (!evaluateOk(responseDoc))
        return false;

    logout();
    return true;
}

From source file:is.idega.idegaweb.egov.gumbo.webservice.client.business.DOFWSClientRealWebservice.java

public boolean emptyCache() {
    Map cache = getCache(GUMBO_FISHING_AREAS_CACHE, 0l);
    if (cache != null) {
        cache.clear();
    }/*from   w  w  w  .ja v  a  2 s. c  o m*/

    return true;
}

From source file:com.circle.utils.XMLSerializer.java

/**
 * Adds a namespace declaration to an element.<br>
 * Any previous values are discarded. If the elementName param is null or
 * blank, the namespace declaration will be added to the root element.
 *
 * @param prefix namespace prefix//  w  w w.j  a v  a 2  s .c om
 * @param uri namespace uri
 * @param elementName name of target element
 */
public void setNamespace(String prefix, String uri, String elementName) {
    if (StringUtils.isBlank(uri)) {
        return;
    }
    if (prefix == null) {
        prefix = "";
    }
    if (StringUtils.isBlank(elementName)) {
        rootNamespace.clear();
        rootNamespace.put(prefix.trim(), uri.trim());
    } else {
        Map nameSpaces = (Map) namespacesPerElement.get(elementName);
        if (nameSpaces == null) {
            nameSpaces = new TreeMap();
            namespacesPerElement.put(elementName, nameSpaces);
        }
        nameSpaces.clear();
        nameSpaces.put(prefix, uri);
    }
}