Example usage for java.util Collections synchronizedMap

List of usage examples for java.util Collections synchronizedMap

Introduction

In this page you can find the example usage for java.util Collections synchronizedMap.

Prototype

public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m) 

Source Link

Document

Returns a synchronized (thread-safe) map backed by the specified map.

Usage

From source file:org.opendaylight.controller.cluster.datastore.ShardManagerTest.java

@Test
public void testPerShardDatastoreContext() throws Exception {
    LOG.info("testPerShardDatastoreContext starting");
    final DatastoreContextFactory mockFactory = newDatastoreContextFactory(
            datastoreContextBuilder.shardElectionTimeoutFactor(5).build());

    Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build())
            .shardElectionTimeoutFactor(6).build()).when(mockFactory).getShardDatastoreContext("default");

    Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build())
            .shardElectionTimeoutFactor(7).build()).when(mockFactory).getShardDatastoreContext("topology");

    final MockConfiguration mockConfig = new MockConfiguration() {
        @Override/*w w  w. j ava  2  s  .c o  m*/
        public Collection<String> getMemberShardNames(String memberName) {
            return Arrays.asList("default", "topology");
        }

        @Override
        public Collection<String> getMembersFromShardName(String shardName) {
            return Arrays.asList("member-1");
        }
    };

    final TestActorRef<MessageCollectorActor> defaultShardActor = actorFactory.createTestActor(
            Props.create(MessageCollectorActor.class), actorFactory.generateActorId("default"));
    final TestActorRef<MessageCollectorActor> topologyShardActor = actorFactory.createTestActor(
            Props.create(MessageCollectorActor.class), actorFactory.generateActorId("topology"));

    final Map<String, Entry<ActorRef, DatastoreContext>> shardInfoMap = Collections
            .synchronizedMap(new HashMap<String, Entry<ActorRef, DatastoreContext>>());
    shardInfoMap.put("default",
            new AbstractMap.SimpleEntry<ActorRef, DatastoreContext>(defaultShardActor, null));
    shardInfoMap.put("topology",
            new AbstractMap.SimpleEntry<ActorRef, DatastoreContext>(topologyShardActor, null));

    final PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
    final CountDownLatch newShardActorLatch = new CountDownLatch(2);
    class LocalShardManager extends ShardManager {
        public LocalShardManager(AbstractBuilder<?> builder) {
            super(builder);
        }

        @Override
        protected ActorRef newShardActor(SchemaContext schemaContext, ShardInformation info) {
            Entry<ActorRef, DatastoreContext> entry = shardInfoMap.get(info.getShardName());
            ActorRef ref = null;
            if (entry != null) {
                ref = entry.getKey();
                entry.setValue(info.getDatastoreContext());
            }

            newShardActorLatch.countDown();
            return ref;
        }
    }

    final Creator<ShardManager> creator = new Creator<ShardManager>() {
        private static final long serialVersionUID = 1L;

        @Override
        public ShardManager create() throws Exception {
            return new LocalShardManager(new GenericBuilder<LocalShardManager>(LocalShardManager.class)
                    .datastoreContextFactory(mockFactory).primaryShardInfoCache(primaryShardInfoCache)
                    .configuration(mockConfig));
        }
    };

    JavaTestKit kit = new JavaTestKit(getSystem());

    final ActorRef shardManager = actorFactory
            .createActor(Props.create(new DelegatingShardManagerCreator(creator))
                    .withDispatcher(Dispatchers.DefaultDispatcherId()));

    shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), kit.getRef());

    assertEquals("Shard actors created", true, newShardActorLatch.await(5, TimeUnit.SECONDS));
    assertEquals("getShardElectionTimeoutFactor", 6,
            shardInfoMap.get("default").getValue().getShardElectionTimeoutFactor());
    assertEquals("getShardElectionTimeoutFactor", 7,
            shardInfoMap.get("topology").getValue().getShardElectionTimeoutFactor());

    DatastoreContextFactory newMockFactory = newDatastoreContextFactory(
            datastoreContextBuilder.shardElectionTimeoutFactor(5).build());
    Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build())
            .shardElectionTimeoutFactor(66).build()).when(newMockFactory).getShardDatastoreContext("default");

    Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build())
            .shardElectionTimeoutFactor(77).build()).when(newMockFactory).getShardDatastoreContext("topology");

    shardManager.tell(newMockFactory, kit.getRef());

    DatastoreContext newContext = MessageCollectorActor.expectFirstMatching(defaultShardActor,
            DatastoreContext.class);
    assertEquals("getShardElectionTimeoutFactor", 66, newContext.getShardElectionTimeoutFactor());

    newContext = MessageCollectorActor.expectFirstMatching(topologyShardActor, DatastoreContext.class);
    assertEquals("getShardElectionTimeoutFactor", 77, newContext.getShardElectionTimeoutFactor());

    LOG.info("testPerShardDatastoreContext ending");
}

From source file:com.icesoft.faces.context.BridgeExternalContext.java

protected void recreateParameterAndCookieMaps() {
    requestParameterMap = Collections.synchronizedMap(new HashMap());
    requestParameterValuesMap = Collections.synchronizedMap(new HashMap());
    requestCookieMap = Collections.synchronizedMap(new HashMap());
    responseCookieMap = Collections.synchronizedMap(new HashMap());
    requestHeaderMap = Collections.synchronizedMap(new HashMap());
    requestHeaderValuesMap = Collections.synchronizedMap(new HashMap());
}

From source file:org.kuali.kpme.tklm.time.detail.web.ActionFormUtils.java

public static Map<String, String> getPayPeriodsMap(List<CalendarEntry> payPeriods, String viewPrincipal) {
    // use linked map to keep the order of the pay periods
    Map<String, String> pMap = Collections.synchronizedMap(new LinkedHashMap<String, String>());
    if (payPeriods == null || payPeriods.isEmpty()) {
        return pMap;
    }//from  w w w.ja va2  s .c  o m
    payPeriods.removeAll(Collections.singletonList(null));
    Collections.sort(payPeriods); // sort the pay period list by getBeginPeriodDate
    Collections.reverse(payPeriods); // newest on top
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    for (CalendarEntry pce : payPeriods) {
        // Check if service date of user is after the Calendar entry
        DateTime asOfDate = pce.getEndPeriodFullDateTime().minusDays(1);
        PrincipalHRAttributes principalHRAttributes = null;
        String formattedBeginDate = HrConstants.DateTimeFormats.BASIC_DATE_FORMAT
                .print(pce.getBeginPeriodFullDateTime());
        String formattedEndDate = HrConstants.DateTimeFormats.BASIC_DATE_FORMAT
                .print(pce.getEndPeriodFullDateTime().minusMillis(1));
        String formattedRange = formattedBeginDate + " - " + formattedEndDate;

        if (viewPrincipal != null) {
            principalHRAttributes = HrServiceLocator.getPrincipalHRAttributeService()
                    .getPrincipalCalendar(viewPrincipal, asOfDate.toLocalDate());
        } else {
            pMap.put(pce.getHrCalendarEntryId(), formattedRange);
        }

        if (principalHRAttributes != null && pce != null && pce.getHrCalendarEntryId() != null
                && pce.getBeginPeriodFullDateTime() != null && pce.getEndPeriodFullDateTime() != null) {
            LocalDate startCalDate = principalHRAttributes.getServiceLocalDate();
            if (startCalDate != null) {
                if (!(pce.getBeginPeriodFullDateTime().compareTo(startCalDate.toDateTimeAtStartOfDay()) < 0)) {
                    //pMap.put(pce.getHrCalendarEntriesId(), sdf.format(pce.getBeginPeriodDate()) + " - " + sdf.format(pce.getEndPeriodDate()));
                    //getting one millisecond of the endperioddate to match the actual pay period. i.e. pay period end at the 11:59:59:59...PM of that day
                    pMap.put(pce.getHrCalendarEntryId(), formattedRange);
                }
            } else {
                pMap.put(pce.getHrCalendarEntryId(), formattedRange);
            }
        }

    }

    return pMap;
}

From source file:com.alkacon.opencms.documentcenter.CategoryTree.java

/**
 * Returns a list of all categories sorted ascending by their position in the 
 * category tree.<p>//from   w ww  .  j  a  v a 2 s  .  co  m
 * 
 * The tree contains the main-categories, plus the sub-categories of all opened 
 * categories.<p>
 * 
 * @return a list of all categories
 */
public List getCategoryTree() {

    List result = null;
    CmsCategory category = null;
    String parentFolder = null;
    List treeList = null;
    boolean addToResult = false;

    try {
        // create a new tree map
        m_treeMap = Collections.synchronizedMap(new HashMap());

        // add all selected categories to the tree        
        addSelectedCategories();

        // add all opened categories to the tree
        addOpenedCategories();

        // add all folders having the "category" property set to tree
        addCategoryFolders();

        // turn the tree map into a List in DFS order
        treeList = toList(new CmsCategory("", "", m_rootFolder));
        if (treeList == null) {
            // the tree is empty...
            return Collections.EMPTY_LIST;
        } else {
            // tree[0] is the root folder and can be skipped from the result tree
            if (treeList.size() > 1) {
                treeList = treeList.subList(1, treeList.size());
            }
        }

        // build the final result tree. this is to include only sub-trees
        // in the result that either have a parent folder being opened, 
        // or a "sibling" node in the tree that is selected
        result = new ArrayList();
        for (int i = 0, n = treeList.size(); i < n; i++) {

            category = (CmsCategory) treeList.get(i);
            parentFolder = CmsResource.getParentFolder(category.getCmsResource());

            // add the category to the result if it is a main category
            addToResult = (category.getDepth() == 0);
            // or if it is a sub-folder/category of an opened category
            addToResult |= m_openedCategoryList.contains(parentFolder);
            // and if it's folder depth is below the max. folder depth
            addToResult &= CmsResource.getPathLevel(category.getCmsResource()) <= m_maxTreeDepth;

            if (addToResult) {
                result.add(category);
            }
        }
    } catch (Exception e) {

        if (LOG.isErrorEnabled()) {
            LOG.error("Error building category tree", e);
        }
    }

    return result;
}

From source file:com.alkacon.opencms.v8.documentcenter.CategoryTree.java

/**
 * Returns a list of all categories sorted ascending by their position in the 
 * category tree.<p>/*from w  w  w  .j  av a  2  s  .  c  om*/
 * 
 * The tree contains the main-categories, plus the sub-categories of all opened 
 * categories.<p>
 * 
 * @return a list of all categories
 */
public List<CmsCategory> getCategoryTree() {

    List<CmsCategory> result = null;
    CmsCategory category = null;
    String parentFolder = null;
    List<CmsCategory> treeList = null;
    boolean addToResult = false;

    try {
        // create a new tree map
        m_treeMap = Collections.synchronizedMap(new HashMap<String, List<CmsCategory>>());

        // add all selected categories to the tree        
        addSelectedCategories();

        // add all opened categories to the tree
        addOpenedCategories();

        // add all folders having the "category" property set to tree
        addCategoryFolders();

        // turn the tree map into a List in DFS order
        treeList = toList(new CmsCategory("", "", m_rootFolder));
        if (treeList == null) {
            // the tree is empty...
            return Collections.emptyList();
        } else {
            // tree[0] is the root folder and can be skipped from the result tree
            if (treeList.size() > 1) {
                treeList = treeList.subList(1, treeList.size());
            }
        }

        // build the final result tree. this is to include only sub-trees
        // in the result that either have a parent folder being opened, 
        // or a "sibling" node in the tree that is selected
        result = new ArrayList<CmsCategory>();
        for (int i = 0, n = treeList.size(); i < n; i++) {

            category = treeList.get(i);
            parentFolder = CmsResource.getParentFolder(category.getCmsResource());

            // add the category to the result if it is a main category
            addToResult = (category.getDepth() == 0);
            // or if it is a sub-folder/category of an opened category
            addToResult |= m_openedCategoryList.contains(parentFolder);
            // and if it's folder depth is below the max. folder depth
            addToResult &= CmsResource.getPathLevel(category.getCmsResource()) <= m_maxTreeDepth;

            if (addToResult) {
                result.add(category);
            }
        }
    } catch (Exception e) {

        if (LOG.isErrorEnabled()) {
            LOG.error("Error building category tree", e);
        }
    }

    return result;
}

From source file:com.appbase.androidquery.callback.BitmapAjaxCallback.java

private static Map<String, Bitmap> getBCache() {
    if (bigCache == null) {
        bigCache = Collections.synchronizedMap(new BitmapCache(BIG_MAX, BIG_PIXELS, BIG_TPIXELS));
    }//from w  w w.  j  a v a 2s .com
    return bigCache;
}

From source file:org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerTest.java

@Test
public void testPerShardDatastoreContext() throws Exception {
    LOG.info("testPerShardDatastoreContext starting");
    final DatastoreContextFactory mockFactory = newDatastoreContextFactory(
            datastoreContextBuilder.shardElectionTimeoutFactor(5).build());

    Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build())
            .shardElectionTimeoutFactor(6).build()).when(mockFactory).getShardDatastoreContext("default");

    Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build())
            .shardElectionTimeoutFactor(7).build()).when(mockFactory).getShardDatastoreContext("topology");

    final MockConfiguration mockConfig = new MockConfiguration() {
        @Override//w  w  w  .  j a  v  a2 s.  c  o  m
        public Collection<String> getMemberShardNames(MemberName memberName) {
            return Arrays.asList("default", "topology");
        }

        @Override
        public Collection<MemberName> getMembersFromShardName(String shardName) {
            return members("member-1");
        }
    };

    final TestActorRef<MessageCollectorActor> defaultShardActor = actorFactory.createTestActor(
            Props.create(MessageCollectorActor.class), actorFactory.generateActorId("default"));
    final TestActorRef<MessageCollectorActor> topologyShardActor = actorFactory.createTestActor(
            Props.create(MessageCollectorActor.class), actorFactory.generateActorId("topology"));

    final Map<String, Entry<ActorRef, DatastoreContext>> shardInfoMap = Collections
            .synchronizedMap(new HashMap<String, Entry<ActorRef, DatastoreContext>>());
    shardInfoMap.put("default",
            new AbstractMap.SimpleEntry<ActorRef, DatastoreContext>(defaultShardActor, null));
    shardInfoMap.put("topology",
            new AbstractMap.SimpleEntry<ActorRef, DatastoreContext>(topologyShardActor, null));

    final PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
    final CountDownLatch newShardActorLatch = new CountDownLatch(2);
    class LocalShardManager extends ShardManager {
        public LocalShardManager(AbstractShardManagerCreator<?> creator) {
            super(creator);
        }

        @Override
        protected ActorRef newShardActor(SchemaContext schemaContext, ShardInformation info) {
            Entry<ActorRef, DatastoreContext> entry = shardInfoMap.get(info.getShardName());
            ActorRef ref = null;
            if (entry != null) {
                ref = entry.getKey();
                entry.setValue(info.getDatastoreContext());
            }

            newShardActorLatch.countDown();
            return ref;
        }
    }

    final Creator<ShardManager> creator = new Creator<ShardManager>() {
        private static final long serialVersionUID = 1L;

        @Override
        public ShardManager create() throws Exception {
            return new LocalShardManager(new GenericCreator<LocalShardManager>(LocalShardManager.class)
                    .datastoreContextFactory(mockFactory).primaryShardInfoCache(primaryShardInfoCache)
                    .configuration(mockConfig));
        }
    };

    JavaTestKit kit = new JavaTestKit(getSystem());

    final ActorRef shardManager = actorFactory
            .createActor(Props.create(new DelegatingShardManagerCreator(creator))
                    .withDispatcher(Dispatchers.DefaultDispatcherId()));

    shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), kit.getRef());

    assertEquals("Shard actors created", true, newShardActorLatch.await(5, TimeUnit.SECONDS));
    assertEquals("getShardElectionTimeoutFactor", 6,
            shardInfoMap.get("default").getValue().getShardElectionTimeoutFactor());
    assertEquals("getShardElectionTimeoutFactor", 7,
            shardInfoMap.get("topology").getValue().getShardElectionTimeoutFactor());

    DatastoreContextFactory newMockFactory = newDatastoreContextFactory(
            datastoreContextBuilder.shardElectionTimeoutFactor(5).build());
    Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build())
            .shardElectionTimeoutFactor(66).build()).when(newMockFactory).getShardDatastoreContext("default");

    Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build())
            .shardElectionTimeoutFactor(77).build()).when(newMockFactory).getShardDatastoreContext("topology");

    shardManager.tell(newMockFactory, kit.getRef());

    DatastoreContext newContext = MessageCollectorActor.expectFirstMatching(defaultShardActor,
            DatastoreContext.class);
    assertEquals("getShardElectionTimeoutFactor", 66, newContext.getShardElectionTimeoutFactor());

    newContext = MessageCollectorActor.expectFirstMatching(topologyShardActor, DatastoreContext.class);
    assertEquals("getShardElectionTimeoutFactor", 77, newContext.getShardElectionTimeoutFactor());

    LOG.info("testPerShardDatastoreContext ending");
}

From source file:com.appbase.androidquery.callback.BitmapAjaxCallback.java

private static Map<String, Bitmap> getSCache() {
    if (smallCache == null) {
        smallCache = Collections.synchronizedMap(new BitmapCache(SMALL_MAX, SMALL_PIXELS, 250000));
    }//from  www  .j a v a  2  s. co  m
    return smallCache;
}

From source file:uk.ac.ebi.ep.controller.SearchController.java

/**
 * Retrieves any previous searches stored in the application context.
 *
 * @param servletContext the application context.
 * @return a map of searches to results.
 *///from www. jav a2 s .  c  o  m
@SuppressWarnings("unchecked")
protected Map<String, SearchResults> getPreviousSearches(ServletContext servletContext) {
    Map<String, SearchResults> prevSearches = (Map<String, SearchResults>) servletContext
            .getAttribute(Attribute.prevSearches.name());
    if (prevSearches == null) {
        // Map implementation which maintains the order of access:
        prevSearches = Collections.synchronizedMap(
                new LinkedHashMap<String, SearchResults>(searchConfig.getSearchCacheSize(), 1, true));

        servletContext.setAttribute(Attribute.prevSearches.getName(), prevSearches);

    }
    return prevSearches;
}

From source file:com.collabnet.ccf.core.transformer.DynamicXsltProcessor.java

/**
 * Hook to perform any validation of the component properties required by
 * the implementation. Default behaviour should be a no-op.
 *//*w  w  w .  j  a v  a  2s  .com*/
@SuppressWarnings("unchecked")
public void validate(List exceptions) {
    // we have to make this map thread safe because it will be
    // updated asynchronously
    xsltFileNameTransformerMap = Collections.synchronizedMap(new HashMap<String, List<Transformer>>());
    if (isListenForFileUpdates()) {
        try {
            fsManager = VFS.getManager();
        } catch (FileSystemException e) {
            exceptions
                    .add(new ValidationException("could not initialize file manager: " + e.getMessage(), this));
            return;
        }
        fileMonitor = new DefaultFileMonitor(new FileListener() {
            public void fileChanged(org.apache.commons.vfs.FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileCreated(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }

            public void fileDeleted(FileChangeEvent arg0) throws Exception {
                xsltFileNameTransformerMap.clear();
            }
        });
    }

    String xsltDir = this.getXsltDir();
    String xsltFile = this.getXsltFile();
    if (!StringUtils.isEmpty(xsltDir)) {
        File xsltDirFile = new File(xsltDir);
        if (xsltDirFile.exists() && xsltDirFile.isDirectory()) {
            log.debug("xsltDir property " + xsltDir + " is a valid directory");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltDirFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltDir property " + xsltDir + " is not a valid directory: " + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.setRecursive(true);
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
            if (scriptProcessors.isEmpty()) {
                log.warn("No scripts supplied, so dynamic XSLT processor will not change data at all");
            }
        } else {
            exceptions.add(new ValidationException(
                    "xsltDir property " + xsltDir + " is not a valid directory...!", this));
            return;
        }
    } else if (!StringUtils.isEmpty(xsltFile)) {
        File xsltFileFile = new File(xsltFile);
        if (xsltFileFile.exists() && xsltFileFile.isFile()) {
            log.debug("xsltFile property " + xsltFile + " is a valid file");
            if (listenForFileUpdates) {
                FileObject fileObject = null;
                try {
                    fileObject = fsManager.resolveFile(xsltFileFile.getAbsolutePath());
                } catch (FileSystemException e) {
                    exceptions.add(new ValidationException(
                            "xsltFile property " + xsltFile + " is not a valid file...:" + e.getMessage(),
                            this));
                    return;
                }
                fileMonitor.addFile(fileObject);
                fileMonitor.start();
            }
        } else {
            exceptions.add(new ValidationException("xsltFile property " + xsltFile + " is not a valid file...!",
                    this));
            return;
        }
    }
    factory = TransformerFactory.newInstance();
    if (isOnlyAllowWhiteListedJavaFunctionCalls()) {
        try {
            secureFactory = TransformerFactory.newInstance();
            secureFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            secureFactory.setErrorListener(new XsltValidationErrorListener());
        } catch (TransformerConfigurationException e) {
            exceptions.add(new ValidationException(
                    "Setting secure processing feature on XSLT processor failed, bailing out since this feature is required by onlyAllowWhiteListedJavaFunctions property",
                    this));
            return;
        }
    }
}