List of usage examples for java.net URI equals
public boolean equals(Object ob)
From source file:net.sourceforge.dita4publishers.tools.dxp.DxpFileOrganizingBosVisitor.java
public void visit(BoundedObjectSet bos) throws Exception { // If there is a root map, then everything is // handled relative to it and there may not be a need // for a manifest, otherwise we need to generate // a manifest map or reorganize the files to put // everything below the root map. BosMember rootMember = bos.getRoot(); if (rootMember != null && rootMember instanceof DitaMapBosMemberImpl) { this.rootMap = rootMember; } else {// w w w . jav a 2 s . c o m this.rootMap = constructDxpManifestMap(bos); } this.rootMapUri = rootMap.getEffectiveUri(); try { this.baseUri = AddressingUtil.getParent(rootMapUri); } catch (URISyntaxException e) { throw new BosException("URI syntax exception calculating base URI for root map: " + e.getMessage()); } catch (MalformedURLException e) { throw new BosException("MalformedURLException calculating base URI for root map: " + e.getMessage()); } catch (IOException e) { throw new BosException("IOException calculating base URI for root map: " + e.getMessage()); } this.rewriteRequired = false; for (BosMember member : bos.getMembers()) { if (member.equals(rootMap)) continue; URI memberUri = member.getEffectiveUri(); URI memberBase = null; try { memberBase = AddressingUtil.getParent(memberUri); } catch (URISyntaxException e) { throw new BosException( "URI syntax exception: " + e.getMessage() + " getting base URI for member " + member); } catch (MalformedURLException e) { throw new BosException( "MalformedURLException: " + e.getMessage() + " getting base URI for member " + member); } catch (IOException e) { throw new BosException("IOException: " + e.getMessage() + " getting base URI for member " + member); } URI relativeUri = baseUri.relativize(memberUri); boolean isAbsolute = relativeUri.isAbsolute(); if (isAbsolute || relativeUri.toString().startsWith("..") || relativeUri.toString().startsWith("/") || memberBase.equals(baseUri)) { // URI is not below the root map, need to rewrite it. rewriteRequired = true; try { URL newUrl = new URL(baseUri.toURL(), "dependencies/" + member.getFileName()); member.setEffectiveUri(newUrl.toURI()); } catch (MalformedURLException e) { throw new BosException("Malformed URL exception: " + e.getMessage() + " constructing new URL for member " + member); } catch (URISyntaxException e) { throw new BosException("URI syntax exception: " + e.getMessage() + " constructing new URI for member " + member); } } } if (rewriteRequired) { UriToUriPointerRewritingBosVisitor rewritingVisitor = new UriToUriPointerRewritingBosVisitor(); rewritingVisitor.visit(bos); } }
From source file:org.ambraproject.article.service.BrowseServiceImpl.java
/** * Get a VolumeInfo for the given id. This only works if the volume is in the current journal. * * @param id Volume ID//from w ww.j a v a 2 s .c o m * @return VolumeInfo */ @Transactional(readOnly = true) public VolumeInfo getVolumeInfo(URI id, String journalKey) { // Attempt to get the volume infos from the cached journal list... List<VolumeInfo> volumes = getVolumeInfosForJournal(journalService.getJournal(journalKey)); for (VolumeInfo vol : volumes) { if (id.equals(vol.getId())) { return vol; } } /* * If we have no luck with the cached journal list, attempt to load the volume re-using * loadVolumeInfos(); */ List<URI> l = new ArrayList<URI>(); l.add(id); List<VolumeInfo> vols = loadVolumeInfos(l); if ((vols != null) && (vols.size() > 0)) { return vols.get(0); } return null; }
From source file:eu.planets_project.tb.gui.backing.service.ServiceRecordBean.java
public PathwayMatrixEntry[][] getPathwayMatrix() { Set<URI> uriset = new HashSet<URI>(); if (sd != null) { for (MigrationPath mp : sd.getPaths()) { uriset.add(mp.getInputFormat()); uriset.add(mp.getOutputFormat()); }//from w w w. j a v a2 s .c o m } List<URI> uris = new ArrayList<URI>(uriset); // Build: PathwayMatrixEntry[][] matrix = new PathwayMatrixEntry[uris.size() + 1][uris.size() + 1]; matrix[0][0] = new PathwayMatrixEntry(null); for (int i = 0; i < uris.size(); i++) { URI outUri = uris.get(i); PathwayMatrixEntry iFormatEntry = new PathwayMatrixEntry( new FormatBean(ServiceBrowser.fr.getFormatForUri(outUri))); matrix[i + 1][0] = iFormatEntry; for (int j = 0; j < uris.size(); j++) { URI inUri = uris.get(j); if (i == 0) { PathwayMatrixEntry jFormatEntry = new PathwayMatrixEntry( new FormatBean(ServiceBrowser.fr.getFormatForUri(inUri))); matrix[0][j + 1] = jFormatEntry; } // Pathway: PathwayMatrixEntry entry = new PathwayMatrixEntry(); matrix[i + 1][j + 1] = entry; for (MigrationPath mp : sd.getPaths()) { if (inUri.equals(mp.getInputFormat()) && outUri.equals(mp.getOutputFormat())) { PathwayBean pathway = new PathwayBean(this, new FormatBean(ServiceBrowser.fr.getFormatForUri(inUri)), new FormatBean(ServiceBrowser.fr.getFormatForUri(outUri))); entry.setPathway(pathway); } } } } // Map to Lists: return matrix; }
From source file:org.jboss.pressgang.ccms.contentspec.client.Client.java
/** * Apply the server settings from the client configuration * file to the command and/or Content Spec Configuration. */// ww w. j a v a 2 s .c o m protected void applyServerSettings() { final Map<String, ServerConfiguration> servers = clientConfig.getServers(); // If there is no server specified and no server in the csprocessor.cfg then make sure a default server exists if (command.getServerUrl() == null && ((cspConfig == null || cspConfig.getServerUrl() == null) && command.loadFromCSProcessorCfg() || !command.loadFromCSProcessorCfg())) { // Check that a default exists in the configuration files or via command line arguments if (!servers.containsKey(Constants.DEFAULT_SERVER_NAME) && getServerUrl() == null && command.getServerUrl() == null) { final File configFile = new File(ClientUtilities.fixConfigLocation(command.getConfigLocation())); command.printErrorAndShutdown(Constants.EXIT_CONFIG_ERROR, ClientUtilities.getMessage("NO_DEFAULT_SERVER_FOUND_MSG", configFile.getAbsolutePath()), false); } else if (servers.containsKey(Constants.DEFAULT_SERVER_NAME) && !servers.get(Constants.DEFAULT_SERVER_NAME).getUrl().matches("^(http://|https://).*")) { if (!servers.containsKey(servers.get(Constants.DEFAULT_SERVER_NAME).getUrl())) { command.printErrorAndShutdown(Constants.EXIT_CONFIG_ERROR, ClientUtilities.getMessage("NO_SERVER_FOUND_FOR_DEFAULT_SERVER_MSG"), false); } else { final ServerConfiguration defaultConfig = servers.get(Constants.DEFAULT_SERVER_NAME); final ServerConfiguration config = servers.get(defaultConfig.getUrl()); defaultConfig.setUrl(config.getUrl()); if (config.getUsername() != null && !config.getUsername().equals("")) defaultConfig.setUsername(config.getUsername()); } } } // Set the URL String url = null; if (command.getServerUrl() != null) { // Check if the server url is a name defined in csprocessor.ini for (final Entry<String, ServerConfiguration> serversEntry : servers.entrySet()) { final String serverName = serversEntry.getKey(); // Ignore the default server for csprocessor.cfg configuration files if (!serverName.equals(Constants.DEFAULT_SERVER_NAME) && serverName.equals(command.getServerUrl())) { command.setServerUrl(serversEntry.getValue().getUrl()); break; } } url = ClientUtilities.fixHostURL(command.getServerUrl()); } else if (cspConfig != null && cspConfig.getServerUrl() != null && command.loadFromCSProcessorCfg()) { for (final Entry<String, ServerConfiguration> serversEntry : servers.entrySet()) { final String serverName = serversEntry.getKey(); // Ignore the default server for csprocessor.cfg configuration files if (serverName.equals(Constants.DEFAULT_SERVER_NAME)) continue; // Compare the urls try { final ServerConfiguration serverConfig = serversEntry.getValue(); URI serverUrl = new URI(ClientUtilities.fixHostURL(serverConfig.getUrl())); if (serverUrl.equals(new URI(ClientUtilities.fixHostURL(cspConfig.getServerUrl())))) { url = serverConfig.getUrl(); break; } } catch (URISyntaxException e) { break; } } // If no URL matched between the csprocessor.ini and csprocessor.cfg then print an error if (url == null && !firstRun) { JCommander.getConsole().println(""); printErrorAndShutdown(Constants.EXIT_CONFIG_ERROR, ClientUtilities.getMessage("ERROR_NO_SERVER_FOUND_MSG", cspConfig.getServerUrl()), false); } else if (url == null) { JCommander.getConsole().println(""); printErrorAndShutdown(Constants.EXIT_CONFIG_ERROR, ClientUtilities.getMessage("SETUP_CONFIG_MSG"), false); } } else { url = servers.get(Constants.DEFAULT_SERVER_NAME).getUrl(); } command.setServerUrl(url); // Good point to check for a shutdown allowShutdownToContinueIfRequested(); // Set the username if (command.getUsername() == null) { for (final Entry<String, ServerConfiguration> serversEntry : servers.entrySet()) { final String serverName = serversEntry.getKey(); final ServerConfiguration serverConfig = serversEntry.getValue(); if (serverName.equals(Constants.DEFAULT_SERVER_NAME) || servers.get(serverName).getUrl().isEmpty()) continue; try { URL serverUrl = new URL(serverConfig.getUrl()); if (serverUrl.equals(new URL(url))) { command.setUsername(serverConfig.getUsername()); } } catch (MalformedURLException e) { if (servers.get(Constants.DEFAULT_SERVER_NAME) != null) { command.setUsername(servers.get(Constants.DEFAULT_SERVER_NAME).getUsername()); } } } // If none were found for the server then use the default if ((command.getUsername() == null || command.getUsername().equals("")) && servers.get(Constants.DEFAULT_SERVER_NAME) != null) { command.setUsername(servers.get(Constants.DEFAULT_SERVER_NAME).getUsername()); } } if (cspConfig.getServerUrl() == null) { cspConfig.setServerUrl(url); } }
From source file:org.dita.dost.module.GenMapAndTopicListModule.java
/** * Add the given file the wait list if it has not been parsed. * //from w w w. jav a2 s . c o m * @param ref reference to absolute system path */ private void addToWaitList(final Reference ref) { final URI file = ref.filename; assert file.isAbsolute() && file.getFragment() == null; if (doneList.contains(file) || waitList.contains(ref) || file.equals(currentFile)) { return; } waitList.add(ref); }
From source file:org.wrml.runtime.DefaultModel.java
private void initKeySlots(final Model model, final Keys keys) { final SchemaLoader schemaLoader = getContext().getSchemaLoader(); final URI documentSchemaUri = schemaLoader.getDocumentSchemaUri(); URI uri = null;//from w w w.j a v a 2s . co m // Apply all of these Keys to the cached model (in case any Key values are "new"). for (final URI keyedSchemaUri : keys.getKeyedSchemaUris()) { final Object keyValue = keys.getValue(keyedSchemaUri); final Prototype keyedPrototype = schemaLoader.getPrototype(keyedSchemaUri); final SortedSet<String> keySlotNames = keyedPrototype.getDeclaredKeySlotNames(); if (keySlotNames.size() == 1) { if (documentSchemaUri.equals(keyedSchemaUri)) { // Save the document key slot (uri) for last so that the hypermedia engine has all other keys // available // (to auto-generate the Link href values). uri = (URI) keyValue; } else { setSlotValue(model, keySlotNames.first(), keyValue, keyedSchemaUri, false); } } else if (keyValue instanceof CompositeKey) { final CompositeKey compositeKey = (CompositeKey) keyValue; final Map<String, Object> keySlots = compositeKey.getKeySlots(); for (final String keySlotName : keySlots.keySet()) { setSlotValue(model, keySlotName, keySlots.get(keySlotName), keyedSchemaUri, false); } } } // See comment above regarding saving the uri key slot for last. if (uri != null) { setSlotValue(model, Document.SLOT_NAME_URI, uri, documentSchemaUri, false); } }
From source file:org.eclipse.b3.p2.maven.loader.Maven2RepositoryLoader.java
private MavenMetadata findNextComponent(IProgressMonitor monitor) throws CoreException { if (iteratorStack.isEmpty()) ///*from w ww. j a v a 2s . c o m*/ // All iterators exhausted // return null; UriIterator itor = iteratorStack.peek(); outer: while (itor.hasNext()) { URI uri = itor.next(); if (isFolder(uri)) { // This was a folder. Push it on the stack and // scan it. // for (UriIterator prev : iteratorStack) { if (uri.equals(prev.getRoot())) // // Circular reference detected. This iteration // cannot be used. // continue outer; } UriIterator subItor; try { subItor = new UriIterator(getTransport(), uri, folderExcludePattern, monitor); } catch (CoreException e) { LogUtils.warning(e.getMessage()); continue; } URI[] uris = subItor.getURIs(); int idx = uris.length; URI mavenMetadataURI = null; while (--idx >= 0) { URI subUri = uris[idx]; IPath subPath = Path.fromPortableString(subUri.getPath()); String name = subPath.lastSegment(); if (MAVEN_METADATA.equals(name) || MAVEN_METADATA_LOCAL.equals(name)) { mavenMetadataURI = subUri; break; } } if (mavenMetadataURI != null) { // This folder has a maven-metadata.xml document. Let's filter out // all sub folders that just reflect versions of that document since // we will visit them anyway in due course if needed. // List<String> versions; try { MavenMetadata md = new MavenMetadata( org.eclipse.emf.common.util.URI.createURI(mavenMetadataURI.toString())); versions = md.getMetaData().getVersioning().getVersions().getVersion(); } catch (Exception e) { LogUtils.warning(e.getMessage()); continue; } int top = uris.length; List<URI> uriList = new ArrayList<URI>(); for (idx = 0; idx < top; ++idx) { URI subUri = uris[idx]; IPath subPath = Path.fromPortableString(subUri.getPath()); String file = subPath.lastSegment(); if (!versions.contains(file)) uriList.add(subUri); } if (uriList.size() < top) subItor = new UriIterator(uri, folderExcludePattern, uriList.toArray(new URI[uriList.size()])); } iteratorStack.push(subItor); return findNextComponent(monitor); } try { IPath path = Path.fromPortableString(uri.getPath()); String file = path.lastSegment(); if (MAVEN_METADATA.equals(file) || MAVEN_METADATA_LOCAL.equals(file)) return new MavenMetadata(org.eclipse.emf.common.util.URI.createURI(uri.toString())); } catch (Exception e) { LogUtils.warning(e.getMessage()); } } // This iterator is exhausted. Pop it from the stack // iteratorStack.pop(); return findNextComponent(monitor); }
From source file:com.facebook.widget.GraphObjectAdapter.java
private void downloadProfilePicture(final String profileId, URI pictureURI, final ImageView imageView) { if (pictureURI == null) { return;/*from w w w. j av a 2 s .c om*/ } // If we don't have an imageView, we are pre-fetching this image to store in-memory because we // think the user might scroll to its corresponding list row. If we do have an imageView, we // only want to queue a download if the view's tag isn't already set to the URL (which would mean // it's already got the correct picture). boolean prefetching = imageView == null; if (prefetching || !pictureURI.equals(imageView.getTag())) { if (!prefetching) { // Setting the tag to the profile ID indicates that we're currently downloading the // picture for this profile; we'll set it to the actual picture URL when complete. imageView.setTag(profileId); imageView.setImageResource(getDefaultPicture()); } ImageRequest.Builder builder = new ImageRequest.Builder(context.getApplicationContext(), pictureURI) .setCallerTag(this).setCallback(new ImageRequest.Callback() { @Override public void onCompleted(ImageResponse response) { processImageResponse(response, profileId, imageView); } }); ImageRequest newRequest = builder.build(); pendingRequests.put(profileId, newRequest); ImageDownloader.downloadAsync(newRequest); } }
From source file:org.dita.dost.module.GenMapAndTopicListModule.java
/** * Convert absolute paths to relative temporary directory paths * @return map with relative keys and values *///from w ww .java2 s .com private Map<URI, Set<URI>> addMapFilePrefix(final Map<URI, Set<URI>> map) { final Map<URI, Set<URI>> res = new HashMap<>(); for (final Map.Entry<URI, Set<URI>> e : map.entrySet()) { final URI key = e.getKey(); final Set<URI> newSet = new HashSet<>(e.getValue().size()); for (final URI file : e.getValue()) { newSet.add(tempFileNameScheme.generateTempFileName(file)); } res.put(key.equals(ROOT_URI) ? key : tempFileNameScheme.generateTempFileName(key), newSet); } return res; }
From source file:com.linkedin.d2.balancer.simple.SimpleLoadBalancerTest.java
@Test(groups = { "small", "back-end" }) public void testLoadBalancerWithPartitionsSmoke() throws URISyntaxException, ServiceUnavailableException, InterruptedException, ExecutionException { for (int tryAgain = 0; tryAgain < 12; ++tryAgain) { Map<String, LoadBalancerStrategyFactory<? extends LoadBalancerStrategy>> loadBalancerStrategyFactories = new HashMap<String, LoadBalancerStrategyFactory<? extends LoadBalancerStrategy>>(); Map<String, TransportClientFactory> clientFactories = new HashMap<String, TransportClientFactory>(); List<String> prioritizedSchemes = new ArrayList<String>(); MockStore<ServiceProperties> serviceRegistry = new MockStore<ServiceProperties>(); MockStore<ClusterProperties> clusterRegistry = new MockStore<ClusterProperties>(); MockStore<UriProperties> uriRegistry = new MockStore<UriProperties>(); ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3()); clientFactories.put("http", new DoNothingClientFactory()); SimpleLoadBalancerState state = new SimpleLoadBalancerState(executorService, uriRegistry, clusterRegistry, serviceRegistry, clientFactories, loadBalancerStrategyFactories); SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS); FutureCallback<None> balancerCallback = new FutureCallback<None>(); loadBalancer.start(balancerCallback); balancerCallback.get();/* w w w . jav a2 s . c om*/ URI uri1 = URI.create("http://test.qa1.com:1234"); URI uri2 = URI.create("http://test.qa2.com:2345"); URI uri3 = URI.create("http://test.qa3.com:6789"); Map<URI, Double> uris = new HashMap<URI, Double>(); uris.put(uri1, 1d); uris.put(uri2, 1d); uris.put(uri3, 1d); Map<URI, Map<Integer, PartitionData>> partitionDesc = new HashMap<URI, Map<Integer, PartitionData>>(); Map<Integer, PartitionData> server1 = new HashMap<Integer, PartitionData>(); server1.put(0, new PartitionData(1d)); server1.put(1, new PartitionData(1d)); Map<Integer, PartitionData> server2 = new HashMap<Integer, PartitionData>(); server2.put(0, new PartitionData(1d)); Map<Integer, PartitionData> server3 = new HashMap<Integer, PartitionData>(); server3.put(1, new PartitionData(1d)); partitionDesc.put(uri1, server1); partitionDesc.put(uri2, server2); partitionDesc.put(uri3, server3); prioritizedSchemes.add("http"); int partitionMethod = tryAgain % 4; switch (partitionMethod) { case 0: clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 2))); break; case 1: clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(), new HashBasedPartitionProperties("id=(\\d+)", 2, HashBasedPartitionProperties.HashAlgorithm.valueOf("MODULO")))); break; case 2: clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(), new HashBasedPartitionProperties("id=(\\d+)", 2, HashBasedPartitionProperties.HashAlgorithm.valueOf("MD5")))); break; case 3: // test getRings with gap. here, no server serves partition 2 clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 4))); server3.put(3, new PartitionData(1d)); partitionDesc.put(uri3, server3); break; default: break; } serviceRegistry.put("foo", new ServiceProperties("foo", "cluster-1", "/foo", Arrays.asList("degrader"), Collections.<String, Object>emptyMap(), null, null, prioritizedSchemes, null)); uriRegistry.put("cluster-1", new UriProperties("cluster-1", partitionDesc)); if (partitionMethod == 3) { Map<Integer, Ring<URI>> ringMap = loadBalancer.getRings(URI.create("d2://foo")); assertEquals(ringMap.size(), 4); // the ring for partition 2 should be empty assertEquals(ringMap.get(2).toString(), new ConsistentHashRing<URI>(Collections.emptyList()).toString()); continue; } URI expectedUri1 = URI.create("http://test.qa1.com:1234/foo"); URI expectedUri2 = URI.create("http://test.qa2.com:2345/foo"); URI expectedUri3 = URI.create("http://test.qa3.com:6789/foo"); Set<URI> expectedUris = new HashSet<URI>(); expectedUris.add(expectedUri1); expectedUris.add(expectedUri2); expectedUris.add(expectedUri3); for (int i = 0; i < 1000; ++i) { int ii = i % 100; RewriteClient client = (RewriteClient) loadBalancer.getClient(new URIRequest("d2://foo/id=" + ii), new RequestContext()); String clientUri = client.getUri().toString(); HashFunction<String[]> hashFunction = null; String[] str = new String[1]; // test KeyMapper target host hint: request is always to target host regardless of what's in d2 URI and whether it's hash-based or range-based partitions RequestContext requestContextWithHint = new RequestContext(); KeyMapper.TargetHostHints.setRequestContextTargetHost(requestContextWithHint, uri1); RewriteClient hintedClient1 = (RewriteClient) loadBalancer .getClient(new URIRequest("d2://foo/id=" + ii), requestContextWithHint); String hintedUri1 = hintedClient1.getUri().toString(); Assert.assertEquals(hintedUri1, uri1.toString() + "/foo"); RewriteClient hintedClient2 = (RewriteClient) loadBalancer .getClient(new URIRequest("d2://foo/action=purge-all"), requestContextWithHint); String hintedUri2 = hintedClient2.getUri().toString(); Assert.assertEquals(hintedUri2, uri1.toString() + "/foo"); // end test KeyMapper target host hint if (partitionMethod == 2) { hashFunction = new MD5Hash(); } for (URI uri : expectedUris) { if (clientUri.contains(uri.toString())) { // check if only key belonging to partition 0 gets uri2 if (uri.equals(uri2)) { if (partitionMethod == 0) { assertTrue(ii < 50); } else if (partitionMethod == 1) { assertTrue(ii % 2 == 0); } else { str[0] = ii + ""; assertTrue(hashFunction.hash(str) % 2 == 0); } } // check if only key belonging to partition 1 gets uri3 if (uri.equals(uri3)) { if (partitionMethod == 0) { assertTrue(ii >= 50); } else if (partitionMethod == 1) { assertTrue(ii % 2 == 1); } else { str[0] = ii + ""; assertTrue(hashFunction.hash(str) % 2 == 1); } } } } } // two rings for two partitions Map<Integer, Ring<URI>> ringMap = loadBalancer.getRings(URI.create("d2://foo")); assertEquals(ringMap.size(), 2); if (partitionMethod != 2) { Set<String> keys = new HashSet<String>(); for (int j = 0; j < 50; j++) { if (partitionMethod == 0) { keys.add(j + ""); } else { keys.add(j * 2 + ""); } } // if it is range based partition, all keys from 0 ~ 49 belong to partition 0 according to the range definition // if it is modulo based partition, all even keys belong to partition 0 because the partition count is 2 // only from partition 0 MapKeyResult<Ring<URI>, String> mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys); Map<Ring<URI>, Collection<String>> keyToPartition = mapKeyResult.getMapResult(); assertEquals(keyToPartition.size(), 1); for (Ring<URI> ring : keyToPartition.keySet()) { assertEquals(ring, ringMap.get(0)); } // now also from partition 1 keys.add("51"); mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys); assertEquals(mapKeyResult.getMapResult().size(), 2); assertEquals(mapKeyResult.getUnmappedKeys().size(), 0); // now only from partition 1 keys.clear(); keys.add("99"); mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys); keyToPartition = mapKeyResult.getMapResult(); assertEquals(keyToPartition.size(), 1); assertEquals(mapKeyResult.getUnmappedKeys().size(), 0); for (Ring<URI> ring : keyToPartition.keySet()) { assertEquals(ring, ringMap.get(1)); } keys.add("100"); mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys); if (partitionMethod == 0) { // key out of range Collection<MapKeyResult.UnmappedKey<String>> unmappedKeys = mapKeyResult.getUnmappedKeys(); assertEquals(unmappedKeys.size(), 1); } try { loadBalancer.getClient(new URIRequest("d2://foo/id=100"), new RequestContext()); if (partitionMethod == 0) { // key out of range fail("Should throw ServiceUnavailableException caused by PartitionAccessException"); } } catch (ServiceUnavailableException e) { } } final CountDownLatch latch = new CountDownLatch(1); PropertyEventShutdownCallback callback = new PropertyEventShutdownCallback() { @Override public void done() { latch.countDown(); } }; state.shutdown(callback); if (!latch.await(60, TimeUnit.SECONDS)) { fail("unable to shutdown state"); } executorService.shutdownNow(); assertTrue(executorService.isShutdown(), "ExecutorService should have shut down!"); } }