Example usage for java.util Map remove

List of usage examples for java.util Map remove

Introduction

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

Prototype

V remove(Object key);

Source Link

Document

Removes the mapping for a key from this map if it is present (optional operation).

Usage

From source file:edu.wisc.my.portlets.bookmarks.web.EditFolderFormController.java

/**
 * @see org.springframework.web.portlet.mvc.SimpleFormController#onSubmitAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse, java.lang.Object, org.springframework.validation.BindException)
 *///ww  w  .  j a v  a2  s .  c  o m
@Override
protected void onSubmitAction(ActionRequest request, ActionResponse response, Object command,
        BindException errors) throws Exception {
    final String targetParentPath = StringUtils.defaultIfEmpty(request.getParameter("folderPath"), null);
    final String targetEntryPath = StringUtils.defaultIfEmpty(request.getParameter("idPath"), null);

    //User edited bookmark
    final Folder commandFolder = (Folder) command;

    //Get the BookmarkSet from the store
    final BookmarkSet bs = this.bookmarkSetRequestResolver.getBookmarkSet(request, false);
    if (bs == null) {
        throw new IllegalArgumentException("No BookmarkSet exists for request='" + request + "'");
    }

    //Get the target parent folder
    final IdPathInfo targetParentPathInfo = FolderUtils.getEntryInfo(bs, targetParentPath);
    if (targetParentPathInfo == null || targetParentPathInfo.getTarget() == null) {
        throw new IllegalArgumentException("The specified parent Folder does not exist. BaseFolder='" + bs
                + "' and idPath='" + targetParentPath + "'");
    }

    final Folder targetParent = (Folder) targetParentPathInfo.getTarget();
    final Map<Long, Entry> targetChildren = targetParent.getChildren();

    //Get the original bookmark & it's parent folder
    final IdPathInfo originalBookmarkPathInfo = FolderUtils.getEntryInfo(bs, targetEntryPath);
    if (targetParentPathInfo == null || originalBookmarkPathInfo.getTarget() == null) {
        throw new IllegalArgumentException("The specified Folder does not exist. BaseFolder='" + bs
                + "' and idPath='" + targetEntryPath + "'");
    }

    final Folder originalParent = originalBookmarkPathInfo.getParent();
    final Folder orignalFolder = (Folder) originalBookmarkPathInfo.getTarget();

    //If moving the bookmark
    if (targetParent.getId() != originalParent.getId()) {
        final Map<Long, Entry> originalChildren = originalParent.getChildren();
        originalChildren.remove(orignalFolder.getId());

        commandFolder.setCreated(orignalFolder.getCreated());
        commandFolder.setModified(new Date());
        commandFolder.setChildren(orignalFolder.getChildren());

        //Hibernate doesn't let us move already persisted objects, need to clone the tree to allow for the object to be re-added
        final Folder clonedCommandFolder = FolderUtils.deepCloneFolder(commandFolder, false);

        targetChildren.put(clonedCommandFolder.getId(), clonedCommandFolder);
    }
    //If just updaing the bookmark
    //TODO should the formBackingObject be smarter on form submits for editBookmark and return the targeted bookmark?
    else {
        orignalFolder.setModified(new Date());
        orignalFolder.setName(commandFolder.getName());
        orignalFolder.setNote(commandFolder.getNote());
    }

    //Persist the changes to the BookmarkSet 
    this.bookmarkStore.storeBookmarkSet(bs);
}

From source file:org.springframework.restdocs.payload.FieldValidator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void removeField(List<String> segments, int depth, Map<String, Object> payloadPortion) {
    String key = segments.get(depth);
    if (depth == segments.size() - 1) {
        payloadPortion.remove(key);
    } else {//w w  w . j av  a2 s.  co  m
        Object candidate = payloadPortion.get(key);
        if (candidate instanceof Map) {
            Map map = (Map<?, ?>) candidate;
            removeField(segments, depth + 1, map);
            if (map.isEmpty()) {
                payloadPortion.remove(key);
            }
        }
    }
}

From source file:com.javaeeeee.dropbookmarks.resources.BookmarksResource.java

/**
 * A method to remove null and empty values from the change map. Necessary
 * if not fields in the changed object are filled.
 *
 * @param changeMap map of object field values.
 *//* w  w  w .  j  a  v a2  s.c o m*/
protected void purgeMap(final Map<String, String> changeMap) {
    changeMap.remove("id");
    changeMap.entrySet().removeIf(entry -> Strings.isNullOrEmpty(entry.getValue()));
}

From source file:edu.mayo.cts2.framework.webapp.rest.view.NoPathParamRedirectView.java

protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    for (String paramToRemove : this.paramsToRemove) {
        model.remove(paramToRemove);
    }//from  w  w w . ja  v a  2 s  .  c  o  m

    super.renderMergedOutputModel(model, request, response);
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.AccessConfirmationController.java

/**
 * Request the user confirmation for the resources enabled for the requesting client
 * @param model/*from   ww w  .ja v  a2s. c o m*/
 * @return
 * @throws Exception
 */
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model) throws Exception {
    AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
    // load client information given the client credentials obtained from the request
    ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
    ClientAppInfo info = ClientAppInfo.convert(client.getAdditionalInformation());
    List<Resource> resources = new ArrayList<Resource>();

    Set<String> all = client.getScope();
    Set<String> requested = clientAuth.getScope();
    if (requested == null || requested.isEmpty()) {
        requested = all;
    } else {
        requested = new HashSet<String>(requested);
        for (Iterator<String> iterator = requested.iterator(); iterator.hasNext();) {
            String r = iterator.next();
            if (!all.contains(r))
                iterator.remove();
        }
    }

    for (String rUri : requested) {
        try {
            Resource r = resourceRepository.findByResourceUri(rUri);
            // ask the user only for the resources associated to the user role and not managed by this client
            if (r.getAuthority().equals(AUTHORITY.ROLE_USER)
                    && !clientAuth.getClientId().equals(r.getClientId())) {
                resources.add(r);
            }
        } catch (Exception e) {
            logger.error("Error reading resource with uri " + rUri + ": " + e.getMessage());
        }
    }
    model.put("resources", resources);
    model.put("auth_request", clientAuth);
    model.put("clientName", info.getName());
    return new ModelAndView("access_confirmation", model);
}

From source file:com.centurylink.mdw.util.AuthUtils.java

/**
 * @return true if no authentication at all or authentication is successful
 *///  ww  w  .  j a  v  a  2 s .  co m
public static boolean checkBasicAuthenticationHeader(Map<String, String> headers) {

    String authorizationHeader = headers.get(Listener.AUTHORIZATION_HEADER_NAME);
    if (authorizationHeader == null)
        authorizationHeader = headers.get(Listener.AUTHORIZATION_HEADER_NAME.toLowerCase());

    if (authorizationHeader != null) {
        authorizationHeader = authorizationHeader.replaceFirst("Basic ", "");

        byte[] valueDecoded = Base64.decodeBase64(authorizationHeader.getBytes());
        authorizationHeader = new String(valueDecoded);

        String[] creds = authorizationHeader.split(":");
        String user = creds[0];
        String pass = creds[1];

        try {
            if (AuthConstants.getOAuthTokenLocation() != null) {
                oauthAuthenticate(user, pass);
            } else {
                ldapAuthenticate(user, pass);
            }

            /**
             * Authentication passed so take credentials out
             * of the metadata and just put user name in.
             */
            headers.remove(Listener.AUTHORIZATION_HEADER_NAME);
            headers.remove(Listener.AUTHORIZATION_HEADER_NAME.toLowerCase());
            headers.put(Listener.AUTHENTICATED_USER_HEADER, user);
            if (logger.isDebugEnabled()) {
                logger.debug("authentication successful for user '" + user + "'");
            }
        } catch (Exception ex) {
            headers.remove(Listener.AUTHORIZATION_HEADER_NAME);
            headers.remove(Listener.AUTHORIZATION_HEADER_NAME.toLowerCase());
            headers.put(Listener.AUTHENTICATION_FAILED,
                    "Authentication failed for '" + user + "' " + ex.getMessage());
            logger.severeException("Authentication failed for user '" + user + "'" + ex.getMessage(), ex);
            return false;
        }
    }
    return true;
}

From source file:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java

/**
 * ???/*  w  w  w  .  jav  a  2s .c o  m*/
 */
public static boolean isValidAgent(String facilityId) {
    boolean valid = false;

    try {
        _agentCacheLock.readLock();

        Map<String, AgentInfo> agentMap = getAgentCache();

        AgentInfo agentInfo = agentMap.get(facilityId);
        if (agentInfo != null) {
            valid = agentInfo.isValid();
        }
    } finally {
        _agentCacheLock.readUnlock();
    }

    if (!valid) {
        try {
            _agentCacheLock.writeLock();

            HashMap<String, AgentInfo> agentMap = getAgentCache();
            agentMap.remove(facilityId);
            storeAgentCache(agentMap);
        } finally {
            _agentCacheLock.writeUnlock();
        }
    }

    return valid;
}

From source file:com.wrmsr.wava.transform.Transforms.java

public static Node uniquifyLabels(Node root, Supplier<Name> nameSupplier) {
    Map<Name, Name> remappedNames = new HashMap<>();
    return root.accept(new Visitor<Void, Node>() {
        @Override//from w  w w  .j  a  v a 2 s  .  c  o  m
        protected Node visitNode(Node node, Void context) {
            return reconstructNode(node,
                    node.getChildren().stream().map(c -> c.accept(this, context)).iterator());
        }

        private Node processNamedNode(Node node, Name name, BiFunction<Name, Node, Node> ctor, Void context) {
            Name prevName = remappedNames.get(name);
            Name newName = prevName == null ? name : nameSupplier.get();
            remappedNames.put(name, newName);
            Node child = Iterables.getOnlyElement(node.getChildren());
            Node ret = ctor.apply(newName, child.accept(this, context));
            if (prevName == null) {
                remappedNames.remove(name);
            } else {
                remappedNames.put(name, prevName);
            }
            return ret;
        }

        @Override
        public Node visitBreak(Break node, Void context) {
            return new Break(requireNonNull(remappedNames.get(node.getTarget())),
                    node.getValue().accept(this, context));
        }

        @Override
        public Node visitBreakTable(BreakTable node, Void context) {
            return new BreakTable(
                    node.getTargets().stream().map(remappedNames::get).map(Objects::requireNonNull).collect(
                            toImmutableList()),
                    requireNonNull(remappedNames.get(node.getDefaultTarget())),
                    node.getCondition().accept(this, context));
        }

        @Override
        public Node visitLabel(Label node, Void context) {
            return processNamedNode(node, node.getName(), Label::new, context);
        }

        @Override
        public Node visitLoop(Loop node, Void context) {
            return processNamedNode(node, node.getName(), Loop::new, context);
        }
    }, null);
}

From source file:com.github.dactiv.fear.service.test.config.DataDictionaryServiceTest.java

@Test
public void testSaveDataDictionary() {
    Map<String, Object> dataDictionary = configService.getDataDictionary(1);

    dataDictionary.remove("id");
    dataDictionary.put("name", "?");
    dataDictionary.put("code", "RESET");
    dataDictionary.put("state", "reset");

    int before = countRowsInTable("tb_data_dictionary");
    configService.saveDataDictionary(dataDictionary);
    int after = countRowsInTable("tb_data_dictionary");

    assertEquals(before + 1, after);//from   ww w . j a va  2  s  .c  o  m

    dataDictionary.put("name", "???");
    dataDictionary.put("value", "4");

    before = countRowsInTable("tb_data_dictionary");
    configService.saveDataDictionary(dataDictionary);
    after = countRowsInTable("tb_data_dictionary");

    assertEquals(before, after);

    Integer id = Casts.cast(dataDictionary.get("id"), Integer.class);
    dataDictionary = configService.getDataDictionary(id);

    assertEquals(dataDictionary.get("name"), "???");
    assertEquals(dataDictionary.get("value"), "4");

}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.issues.tasklets.IssuesLastRunExtractorTasklet.java

/**
 * {@inheritDoc}/* w  ww.j a  va  2s.com*/
 * @see org.springframework.batch.core.step.tasklet.Tasklet#execute(org.springframework.batch.core.StepContribution, org.springframework.batch.core.scope.context.ChunkContext)
 */
@Override
public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext)
        throws Exception {

    final StepContext stepContext = chunkContext.getStepContext();
    final String jobName = stepContext.getJobName();
    final JobParameters jobParams = stepContext.getStepExecution().getJobParameters();
    final Map<String, JobParameter> currParams = new HashMap<String, JobParameter>(jobParams.getParameters());
    currParams.remove("run.id");

    Date lastJobRun = null;

    final List<JobInstance> jobInstances = jobExplorer.getJobInstances(jobName, 0, 1000);
    for (final JobInstance jobInstance : jobInstances) {
        final List<JobExecution> jobExecutions = jobExplorer.getJobExecutions(jobInstance);
        for (final JobExecution jobExecution : jobExecutions) {

            final JobParameters oldJobParams = jobExecution.getJobParameters();
            final Map<String, JobParameter> oldParams = new HashMap<String, JobParameter>(
                    oldJobParams.getParameters());
            oldParams.remove("run.id");

            if (ExitStatus.COMPLETED.equals(jobExecution.getExitStatus()) && oldParams.equals(currParams)) {

                if (lastJobRun == null || lastJobRun.before(jobExecution.getStartTime())) {
                    lastJobRun = jobExecution.getStartTime();
                }
            }
        }
    }

    if (lastJobRun != null) {
        stepContext.getStepExecution().getExecutionContext().put("mantis.update.last_job_run", lastJobRun);
    }

    stepContext.getStepExecution().getExecutionContext().put("mantis.update.current_job_run",
            Calendar.getInstance());

    return RepeatStatus.FINISHED;
}