Example usage for java.util Map hashCode

List of usage examples for java.util Map hashCode

Introduction

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

Prototype

int hashCode();

Source Link

Document

Returns the hash code value for this map.

Usage

From source file:nl.nn.adapterframework.webcontrol.api.ShowConfigurationStatus.java

@GET
@RolesAllowed({ "ObserverAccess", "IbisTester" })
@Path("/adapters/{name}")
@Produces(MediaType.APPLICATION_JSON)/*  ww w . j  a v  a 2s.c o  m*/
public Response getAdapter(@PathParam("name") String name) throws ApiException {
    initBase(servletConfig);

    Adapter adapter = (Adapter) ibisManager.getRegisteredAdapter(name);

    if (adapter == null) {
        throw new ApiException("Adapter not found!");
    }

    Map<String, Object> adapterInfo = mapAdapter(adapter);
    adapterInfo.put("receivers", mapAdapterReceivers(adapter));
    adapterInfo.put("pipes", mapAdapterPipes(adapter));
    adapterInfo.put("messages", mapAdapterMessages(adapter));

    Response.ResponseBuilder response = null;

    //Calculate the ETag on last modified date of user resource 
    EntityTag etag = new EntityTag(adapterInfo.hashCode() + "");

    //Verify if it matched with etag available in http request
    response = request.evaluatePreconditions(etag);

    //If ETag matches the response will be non-null; 
    if (response != null) {
        return response.tag(etag).build();
    }

    response = Response.status(Response.Status.CREATED).entity(adapterInfo).tag(etag);
    return response.build();
}

From source file:org.apache.pig.data.SchemaTuple.java

protected int hashCodePiece(int hash, Map<String, Object> v, boolean isNull) {
    return isNull ? hash : 31 * hash + v.hashCode();
}

From source file:org.apache.tez.dag.api.client.DAGStatus.java

@Override
public int hashCode() {
    // Source explicitly exclude from hashCode
    final int prime = 44017;
    int result = 1;
    result = prime + getState().hashCode();

    List<String> diagnostics = getDiagnostics();
    Progress dagProgress = getDAGProgress();
    Map<String, Progress> vProgress = getVertexProgress();
    TezCounters counters = getDAGCounters();

    result = prime * result + ((diagnostics == null) ? 0 : diagnostics.hashCode());
    result = prime * result + ((dagProgress == null) ? 0 : dagProgress.hashCode());
    result = prime * result + ((vProgress == null) ? 0 : vProgress.hashCode());
    result = prime * result + ((counters == null) ? 0 : counters.hashCode());

    return result;
}

From source file:org.betaconceptframework.astroboa.console.filter.HttpSessionRepositoryContextIntegrationFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    HttpSession httpSession = null;//  w  w w.  ja  v  a  2s.  c  o m

    try {
        httpSession = request.getSession(false);
    } catch (IllegalStateException ignored) {
    }

    boolean httpSessionExistedAtStartOfRequest = httpSession != null;

    Map<String, AstroboaClientContext> clientContextMapBeforeChainExecution = readClientContextMapFromSession(
            httpSession);
    AstroboaClientContext activeClientContextBeforeChainExecution = readActiveClientContextFromSession(
            httpSession);

    // Make the HttpSession null, as we don't want to keep a reference to it lying
    // around in case chain.doFilter() invalidates it.
    httpSession = null;

    int contextHashBeforeChainExecution = 0;

    if (clientContextMapBeforeChainExecution != null) {
        contextHashBeforeChainExecution = clientContextMapBeforeChainExecution.hashCode();
    }

    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

    // Create a wrapper that will eagerly update the session with the repository context
    // if anything in the chain does a sendError() or sendRedirect().
    // See SEC-398

    OnRedirectUpdateSessionResponseWrapper responseWrapper = new OnRedirectUpdateSessionResponseWrapper(
            response, request, httpSessionExistedAtStartOfRequest, contextHashBeforeChainExecution);

    // Proceed with chain

    try {
        // This is the only place in this class where RepositoryContextHolder.setContext() is called
        AstroboaClientContextHolder.setClientContextMap(clientContextMapBeforeChainExecution);
        AstroboaClientContextHolder.setActiveClientContext(activeClientContextBeforeChainExecution);

        filterChain.doFilter(request, responseWrapper);
    } finally {
        // This is the only place in this class where RepositoryContextHolder.getContext() is called
        Map<String, AstroboaClientContext> clientContextMapAfterChainExecution = AstroboaClientContextHolder
                .getClientContextMap();
        AstroboaClientContext activeClientContextAfterChainExecution = AstroboaClientContextHolder
                .getActiveClientContext();

        // Crucial removal of RepositoryContextHolder contents - do this before anything else.
        AstroboaClientContextHolder.clearContext();

        request.removeAttribute(FILTER_APPLIED);

        // storeRepositoryContextInSession() might already be called by the response wrapper
        // if something in the chain called sendError() or sendRedirect(). This ensures we only call it
        // once per request.
        if (!responseWrapper.isSessionUpdateDone()) {
            storeClientContextInSession(clientContextMapAfterChainExecution,
                    activeClientContextAfterChainExecution, request, httpSessionExistedAtStartOfRequest,
                    contextHashBeforeChainExecution);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("RepositoryContextHolder now cleared, as request processing completed");
        }
    }
}

From source file:org.betaconceptframework.astroboa.console.filter.HttpSessionRepositoryContextIntegrationFilter.java

/**
 * Stores the supplied repository context in the session (if available) and if it has changed since it was
 * set at the start of the request.//w  w  w. j a  v a 2s. c o  m
 *
 * @param clientContextMapAfterChainExecution the context object obtained from the RepositoryContextHolder after the request has
 *        been processed by the filter chain. RepositoryContextHolder.getContext() cannot be used to obtain
 *        the context as it has already been cleared by the time this method is called.
 * @param request the request object (used to obtain the session, if one exists).
 * @param httpSessionExistedAtStartOfRequest indicates whether there was a session in place before the
 *        filter chain executed. If this is true, and the session is found to be null, this indicates that it was
 *        invalidated during the request and a new session will now be created.
 * @param contextHashBeforeChainExecution the hashcode of the context before the filter chain executed.
 *        The context will only be stored if it has a different hashcode, indicating that the context changed
 *        during the request.
 *
 */
private void storeClientContextInSession(Map<String, AstroboaClientContext> clientContextMapAfterChainExecution,
        AstroboaClientContext activeClientContextAfterChainExecution, HttpServletRequest request,
        boolean httpSessionExistedAtStartOfRequest, int contextHashBeforeChainExecution) {
    HttpSession httpSession = null;

    try {
        httpSession = request.getSession(false);
    } catch (IllegalStateException ignored) {
    }

    if (httpSession == null) {
        if (httpSessionExistedAtStartOfRequest) {
            if (logger.isDebugEnabled()) {
                logger.debug("HttpSession is now null, but was not null at start of request; "
                        + "session was invalidated, so do not create a new session");
            }
        }
    }

    // If HttpSession exists, store current RepositoryContextHolder contents but only if
    // the RepositoryContext has actually changed (see JIRA SEC-37)
    if (httpSession != null && (clientContextMapAfterChainExecution == null
            || clientContextMapAfterChainExecution.hashCode() != contextHashBeforeChainExecution)) {
        httpSession.setAttribute(ASTROBOA_CLIENT_CONTEXT_MAP_KEY, clientContextMapAfterChainExecution);
        httpSession.setAttribute(ACTIVE_ASTROBOA_CLIENT_CONTEXT_KEY, activeClientContextAfterChainExecution);

        if (logger.isDebugEnabled()) {
            logger.debug("AstroboaClientContext map: '" + clientContextMapAfterChainExecution
                    + ", and AstroboaClientContext stored to HttpSession");
        }
    }
}

From source file:org.jasig.portlet.calendar.mvc.controller.AjaxCalendarController.java

@ResourceMapping
public ModelAndView getEventList(ResourceRequest request, ResourceResponse response) throws Exception {

    // Pull parameters out of the resourceId
    final String resourceId = request.getResourceID();
    final String[] resourceIdTokens = resourceId.split("-");
    final String startDate = resourceIdTokens[0];
    final int days = Integer.parseInt(resourceIdTokens[1]);
    final boolean refresh = resourceIdTokens.length > 2 ? Boolean.valueOf(resourceIdTokens[2]) : false;

    final long startTime = System.currentTimeMillis();
    final List<String> errors = new ArrayList<String>();
    final Map<String, Object> model = new HashMap<String, Object>();
    final PortletSession session = request.getPortletSession();
    // get the user's configured time zone
    final String timezone = (String) session.getAttribute("timezone");
    final DateTimeZone tz = DateTimeZone.forID(timezone);

    // get the period for this request
    final Interval interval = DateUtil.getInterval(startDate, days, request);

    final Set<CalendarDisplayEvent> calendarEvents = helper.getEventList(errors, interval, request);

    int index = 0;
    final Set<JsonCalendarEventWrapper> events = new TreeSet<JsonCalendarEventWrapper>();
    for (CalendarDisplayEvent e : calendarEvents) {
        events.add(new JsonCalendarEventWrapper(e, index++));
    }/*w ww  .  ja  v  a2s.c  o m*/

    /*
     * Transform the event set into a map keyed by day.  This code is 
     * designed to separate events by day according to the user's configured
     * time zone.  This ensures that we keep complicated time-zone handling
     * logic out of the JavaScript.
     * 
     * Events are keyed by a string uniquely representing the date that is 
     * still orderable.  So that we can display a more user-friendly date
     * name, we also create a map representing date display names for each
     * date keyed in this response.
     */

    // define a DateFormat object that uniquely identifies dates in a way 
    // that can easily be ordered 
    DateTimeFormatter orderableDf = new DateTimeFormatterBuilder().appendYear(4, 4).appendLiteral("-")
            .appendMonthOfYear(2).appendLiteral("-").appendDayOfMonth(2).toFormatter().withZone(tz);

    // define a DateFormat object that can produce user-facing display 
    // names for dates
    DateTimeFormatter displayDf = new DateTimeFormatterBuilder().appendDayOfWeekText().appendLiteral(" ")
            .appendMonthOfYearText().appendLiteral(" ").appendDayOfMonth(1).toFormatter().withZone(tz);

    // define "today" and "tomorrow" so we can display these specially in the
    // user interface
    DateMidnight now = new DateMidnight(tz);
    String today = orderableDf.print(now);
    String tomorrow = orderableDf.print(now.plusDays(1));

    Map<String, String> dateDisplayNames = new HashMap<String, String>();
    Map<String, List<JsonCalendarEventWrapper>> eventsByDay = new LinkedHashMap<String, List<JsonCalendarEventWrapper>>();
    for (JsonCalendarEventWrapper event : events) {
        String day = orderableDf.print(event.getEvent().getDayStart());

        // if we haven't seen this day before, add entries to the event
        // and date name maps
        if (!eventsByDay.containsKey(day)) {

            // add a list for this day to the eventsByDay map
            eventsByDay.put(day, new ArrayList<JsonCalendarEventWrapper>());

            // Add an appropriate day name for this date to the date names
            // map.  If the day appears to be today or tomorrow display a 
            // special string value.  Otherwise, use the user-facing date
            // format object
            if (today.equals(day)) {
                dateDisplayNames.put(day, "Today");
            } else if (tomorrow.equals(day)) {
                dateDisplayNames.put(day, "Tomorrow");
            } else {
                dateDisplayNames.put(day, displayDf.print(event.getEvent().getDayStart()));
            }
        }

        // add the event to the by-day map
        eventsByDay.get(day).add(event);
    }

    if (log.isTraceEnabled()) {
        log.trace("Prepared the following eventsByDay collection for user '" + request.getRemoteUser() + "':"
                + eventsByDay);
    }

    model.put("dateMap", eventsByDay);
    model.put("dateNames", dateDisplayNames);
    model.put("viewName", "jsonView");
    model.put("errors", errors);

    String etag = String.valueOf(model.hashCode());
    String requestEtag = request.getETag();

    // if the request ETag matches the hash for this response, send back
    // an empty response indicating that cached content should be used
    if (!refresh && request.getETag() != null && etag.equals(requestEtag)) {
        if (log.isTraceEnabled()) {
            log.trace("Sending an empty response (due to matched ETag and " + "refresh=false) for user '"
                    + request.getRemoteUser() + "'");
        }
        response.getCacheControl().setExpirationTime(1);
        response.getCacheControl().setETag(etag);
        response.getCacheControl().setUseCachedContent(true);
        response.setProperty(ResourceResponse.HTTP_STATUS_CODE,
                Integer.toString(HttpServletResponse.SC_NOT_MODIFIED));
        // returning null appears to cause the response to be committed
        // before returning to the portal, so just use an empty view
        return new ModelAndView("empty", Collections.<String, String>emptyMap());
    }

    if (log.isTraceEnabled()) {
        log.trace("Sending a full response for user '" + request.getRemoteUser() + "' and refresh=" + refresh);
    }

    // create new content with new validation tag
    response.getCacheControl().setETag(etag);
    response.getCacheControl().setExpirationTime(1);

    long overallTime = System.currentTimeMillis() - startTime;
    log.debug("AjaxCalendarController took " + overallTime + " ms to produce JSON model");

    return new ModelAndView("json", model);
}

From source file:org.jasig.portlet.newsreader.mvc.portlet.reader.AjaxNewsController.java

@ResourceMapping
public ModelAndView getJSONFeeds(ResourceRequest request, ResourceResponse response) throws Exception {
    log.debug("handleAjaxRequestInternal (AjaxNewsController)");

    Map<String, Object> model = new HashMap<String, Object>();

    String setName = request.getPreferences().getValue("newsSetName", "default");
    NewsSet set = setCreationService.getNewsSet(setName, request);
    List<NewsConfiguration> feeds = new ArrayList<NewsConfiguration>();
    feeds.addAll(set.getNewsConfigurations());
    Collections.sort(feeds);//from   w ww  . j  av  a  2 s.c  om

    JSONArray jsonFeeds = new JSONArray();
    List<String> knownFeeds = new ArrayList<String>();
    for (NewsConfiguration feed : feeds) {
        if (feed.isDisplayed()) {
            JSONObject jsonFeed = new JSONObject();
            jsonFeed.put("id", feed.getId());
            jsonFeed.put("name", feed.getNewsDefinition().getName());
            jsonFeeds.add(jsonFeed);
            knownFeeds.add(String.valueOf(feed.getId()));
        }
    }
    model.put("feeds", jsonFeeds);

    PortletPreferences prefs = request.getPreferences();
    String activeateNews = request.getParameter("activeateNews");
    if (activeateNews != null) {
        prefs.setValue("activeFeed", activeateNews);
        prefs.store();
    }

    int page = Integer.parseInt(request.getParameter("page"));

    // only bother to fetch the active feed
    String activeFeed = request.getPreferences().getValue("activeFeed", null);

    // if the current active feed no longer exists in the news set, unset it
    if (!knownFeeds.contains(activeFeed)) {
        activeFeed = null;
    }

    // if no active feed is currently set, use the first feed in the list
    if (activeFeed == null && jsonFeeds.size() > 0) {
        activeFeed = ((JSONObject) jsonFeeds.get(0)).getString("id");
        prefs.setValue("activeFeed", activeateNews);
        prefs.store();
    }

    if (activeFeed != null) {
        NewsConfiguration feedConfig = newsStore.getNewsConfiguration(Long.valueOf(activeFeed));
        model.put("activeFeed", feedConfig.getId());
        log.debug("On render Active feed is " + feedConfig.getId());

        model.put("page", page);

        try {
            // get an instance of the adapter for this feed
            INewsAdapter adapter = (INewsAdapter) applicationContext
                    .getBean(feedConfig.getNewsDefinition().getClassName());
            // retrieve the feed from this adaptor
            NewsFeed sharedFeed = adapter.getSyndFeed(feedConfig, page);
            if (sharedFeed != null) {
                List<NewsFeedItem> items = sharedFeed.getEntries();
                for (int i = 0; i < items.size(); i++) {
                    NewsFeedItem item = items.get(i);
                    if (item.getLink() == null && item.getFullStory() != null) {
                        PortletURL link = response.createRenderURL();
                        link.setParameter("action", "fullStory");
                        link.setParameter("activeFeed", feedConfig.getId().toString());
                        link.setParameter("itemIndex", String.valueOf(i));
                        link.setParameter("page", Integer.toString(page));
                        item.setLink(link.toString());
                    }
                }

                model.put("feed", sharedFeed);
            } else {
                log.warn("Failed to get feed from adapter.");
                model.put("message", "The news \"" + feedConfig.getNewsDefinition().getName()
                        + "\" is currently unavailable.");
            }

        } catch (NoSuchBeanDefinitionException ex) {
            log.error("News class instance could not be found: " + ex.getMessage());
            model.put("message",
                    "The news \"" + feedConfig.getNewsDefinition().getName() + "\" is currently unavailable.");
        } catch (NewsException ex) {
            log.warn(ex);
            model.put("message",
                    "The news \"" + feedConfig.getNewsDefinition().getName() + "\" is currently unavailable.");
        } catch (Exception ex) {
            log.error(ex);
            model.put("message",
                    "The news \"" + feedConfig.getNewsDefinition().getName() + "\" is currently unavailable.");
        }
    } else {
        //display message saying "Select the news you wish to read"
        model.put("message", "Select the news you wish to read.");
    }

    log.debug("forwarding to /ajaxFeedList");

    String etag = String.valueOf(model.hashCode());
    String requestEtag = request.getETag();

    // if the request ETag matches the hash for this response, send back
    // an empty response indicating that cached content should be used
    if (request.getETag() != null && etag.equals(requestEtag)) {
        response.getCacheControl().setExpirationTime(1);
        response.getCacheControl().setUseCachedContent(true);
        // returning null appears to cause the response to be committed
        // before returning to the portal, so just use an empty view
        return new ModelAndView("empty", Collections.<String, String>emptyMap());
    }

    // create new content with new validation tag
    response.getCacheControl().setETag(etag);
    response.getCacheControl().setExpirationTime(1);

    return new ModelAndView("json", model);
}

From source file:org.xwiki.office.viewer.internal.AbstractOfficeViewer.java

/**
 * @param attachmentReference reference to the attachment to be viewed
 * @param viewParameters implementation specific view parameters
 * @return a key to cache the view of the specified attachment
 *//*from  ww  w.  j a  v a 2s .co  m*/
private String getCacheKey(AttachmentReference attachmentReference, Map<String, String> viewParameters) {
    return serializer.serialize(attachmentReference) + '/' + viewParameters.hashCode();
}

From source file:org.xwiki.office.viewer.internal.DefaultOfficeResourceViewer.java

/**
 * Processes all the image blocks in the given XDOM and changes image URL to point to a temporary file for those
 * images that are view artifacts./*from ww w  . j  av  a  2s  . c o  m*/
 * 
 * @param xdom the XDOM whose image blocks are to be processed
 * @param artifacts specify which of the image blocks should be processed; only the image blocks that were generated
 *            during the office import process should be processed
 * @param ownerDocumentReference specifies the document that owns the office file
 * @param resourceReference a reference to the office file that is being viewed; this reference is used to compute
 *            the path to the temporary directory holding the image artifacts
 * @param parameters the build parameters. Note that currently only {@code filterStyles} is supported and if "true"
 *            it means that styles will be filtered to the maximum and the focus will be put on importing only the
 * @return the set of temporary files corresponding to image artifacts
 */
private Set<File> processImages(XDOM xdom, Map<String, byte[]> artifacts,
        DocumentReference ownerDocumentReference, String resourceReference, Map<String, ?> parameters) {
    // Process all image blocks.
    Set<File> temporaryFiles = new HashSet<File>();
    List<ImageBlock> imgBlocks = xdom.getBlocks(new ClassBlockMatcher(ImageBlock.class), Block.Axes.DESCENDANT);
    for (ImageBlock imgBlock : imgBlocks) {
        String imageReference = imgBlock.getReference().getReference();

        // Check whether there is a corresponding artifact.
        if (artifacts.containsKey(imageReference)) {
            try {
                List<String> resourcePath = Arrays.asList(String.valueOf(parameters.hashCode()),
                        imageReference);
                TemporaryResourceReference temporaryResourceReference = new TemporaryResourceReference(
                        MODULE_NAME, resourcePath, ownerDocumentReference);

                // Write the image into a temporary file.
                File tempFile = this.temporaryResourceStore.createTemporaryFile(temporaryResourceReference,
                        new ByteArrayInputStream(artifacts.get(imageReference)));

                // Create a URL image reference which links to above temporary image file.
                String temporaryResourceURL = this.urlTemporaryResourceReferenceSerializer
                        .serialize(temporaryResourceReference).serialize();
                ResourceReference urlImageReference = new ResourceReference(temporaryResourceURL,
                        ResourceType.PATH);
                urlImageReference.setTyped(true);

                // Replace the old image block with a new one that uses the above URL image reference.
                Block newImgBlock = new ImageBlock(urlImageReference, false, imgBlock.getParameters());
                imgBlock.getParent().replaceChild(Arrays.asList(newImgBlock), imgBlock);

                // Make sure the new image block is not inside an ExpandedMacroBlock whose's content syntax doesn't
                // support relative path resource references (we use relative paths to refer the temporary files).
                maybeFixExpandedMacroAncestor(newImgBlock);

                // Collect the temporary file so that it can be cleaned up when the view is disposed from cache.
                temporaryFiles.add(tempFile);
            } catch (Exception ex) {
                String message = "Error while processing artifact image [%s].";
                this.logger.error(String.format(message, imageReference), ex);
            }
        }
    }

    return temporaryFiles;
}