下面列出了com.google.common.collect.Iterators#asEnumeration ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testTraverseOnMockBundle() {
List<String> structure = Arrays.asList(
"i18n/messages.properties",
"i18n/messages_fr.properties"
);
Enumeration<String> paths = Iterators.asEnumeration(structure.iterator());
Bundle bundle = mock(Bundle.class);
when(bundle.getEntryPaths(anyString())).thenReturn(paths);
when(bundle.getEntry("i18n/messages.properties"))
.thenReturn(this.getClass().getClassLoader().getResource("i18n/messages.properties"));
when(bundle.getEntry("i18n/messages_fr.properties"))
.thenReturn(this.getClass().getClassLoader().getResource("i18n/messages_fr.properties"));
List<I18nExtension> list;
list = ExtenderUtils.analyze("/i18n/", bundle);
assertThat(list.size()).isEqualTo(2);
assertThat(list.get(0).locale()).isEqualTo(InternationalizationService.DEFAULT_LOCALE);
assertThat(list.get(0).get("welcome")).isEqualTo("hello");
assertThat(list.get(0).get("lang")).isEqualTo("english");
assertThat(list.get(1).locale()).isEqualTo(Locale.FRENCH);
assertThat(list.get(1).get("welcome")).isEqualTo("bonjour");
assertThat(list.get(1).get("lang")).isEqualTo("français");
}
public static Bundle getMockBundle() {
List<String> structure = Arrays.asList(
"/i18n/messages.properties",
"/i18n/messages_fr.properties"
);
Enumeration<String> paths = Iterators.asEnumeration(structure.iterator());
Bundle bundle = mock(Bundle.class);
when(bundle.getEntryPaths(anyString())).thenReturn(paths);
when(bundle.getEntry("/i18n/messages.properties"))
.thenReturn(InternationalizationServiceSingletonTest.class.getClassLoader()
.getResource("i18n/messages.properties"));
when(bundle.getEntry("/i18n/messages_fr.properties"))
.thenReturn(InternationalizationServiceSingletonTest.class.getClassLoader()
.getResource("i18n/messages_fr.properties"));
return bundle;
}
@Override
public Enumeration<String> getKeys() {
if(bundle.isEmpty()) {
return parent != null ? parent.getKeys() : Collections.<String>emptyEnumeration();
}
return Iterators.asEnumeration(bundle.keySet().iterator());
}
/**
* Tests the {@link AsyncReadResultProcessor#processAll} method.
*/
@Test
public void testProcessAll() throws Exception {
// Pre-generate some entries.
ArrayList<byte[]> entries = new ArrayList<>();
int totalLength = generateEntries(entries);
// Setup an entry provider supplier.
AtomicInteger currentIndex = new AtomicInteger();
StreamSegmentReadResult.NextEntrySupplier supplier = (offset, length) -> {
int idx = currentIndex.getAndIncrement();
if (idx == entries.size() - 1) {
// Future read result.
Supplier<BufferView> entryContentsSupplier = () -> new ByteArraySegment(entries.get(idx));
return new TestFutureReadResultEntry(offset, length, entryContentsSupplier, executorService());
} else if (idx >= entries.size()) {
return null;
}
// Normal read.
return new CacheReadResultEntry(offset, entries.get(idx), 0, entries.get(idx).length);
};
// Fetch all the data and compare with expected.
@Cleanup
StreamSegmentReadResult rr = new StreamSegmentReadResult(0, totalLength, supplier, "");
val result = AsyncReadResultProcessor.processAll(rr, executorService(), TIMEOUT);
val actualData = result.get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS).getReader();
val expectedData = new SequenceInputStream(Iterators.asEnumeration(entries.stream().map(ByteArrayInputStream::new).iterator()));
AssertExtensions.assertStreamEquals("Unexpected data read back.", expectedData, actualData, totalLength);
}
@Override
public InputStream getReader() {
// Use the collector to create a list of ByteArrayInputStreams and then return them as combined.
ArrayList<ByteArrayInputStream> streams = new ArrayList<>();
collect((array, offset, length) -> streams.add(new ByteArrayInputStream(array, offset, length)), this.length);
return new SequenceInputStream(Iterators.asEnumeration(streams.iterator()));
}
/**
* Tests {@link CompositeBufferView#getReader()}.
*/
@Test
public void testGetReader() throws IOException {
val components = createComponents();
val cb = BufferView.wrap(components);
val expectedSize = components.stream().mapToInt(BufferView::getLength).sum();
val expected = new SequenceInputStream(Iterators.asEnumeration(components.stream().map(BufferView::getReader).iterator()));
val actual = cb.getReader();
AssertExtensions.assertStreamEquals("", expected, actual, expectedSize);
}
@Override
public InputStream getReader(int offset, int length) {
Preconditions.checkArgument(offset >= 0, "offset must be a non-negative number.");
Preconditions.checkArgument(length >= 0, "length must be a non-negative number.");
Preconditions.checkArgument(offset + length <= this.length, "offset+length must be non-negative and less than or equal to the length of the array.");
ArrayList<ByteArrayInputStream> streams = new ArrayList<>();
// Adjust the index based on the first entry offset.
offset += this.firstArrayOffset;
// Find the array which contains the starting offset.
for (byte[] array : this.arrays) {
if (offset >= array.length) {
// Not interested in this array
offset -= array.length;
continue;
}
// Figure out how much of this array we need to extract.
int arrayLength = Math.min(length, array.length - offset);
streams.add(new ByteArrayInputStream(array, offset, arrayLength));
offset = 0;
// Reduce the requested length by the amount of data we copied.
length -= arrayLength;
if (length <= 0) {
// We've reached the end.
break;
}
}
return new SequenceInputStream(Iterators.asEnumeration(streams.iterator()));
}
@Test
public void testTraverseOnEmptyBundle() {
List<String> structure = Arrays.asList();
Enumeration<String> paths = Iterators.asEnumeration(structure.iterator());
Bundle bundle = mock(Bundle.class);
when(bundle.getEntryPaths(anyString())).thenReturn(paths);
List<I18nExtension> list;
list = ExtenderUtils.analyze("/i18n/", bundle);
assertThat(list.size()).isEqualTo(0);
}
/**
* Creates the log output directory and concatenates logging.properties files together to
* configure or re-configure LogManager.
*/
public static synchronized void setupLogging(LogConfigSetup logConfigSetup) throws IOException {
// Bug JDK-6244047: The default FileHandler does not handle the directory not existing,
// so we have to create it before any log statements actually run.
Files.createDirectories(logConfigSetup.getLogDir());
if (logConfigSetup.getRotateLog()) {
try {
deleteOldLogFiles(logConfigSetup);
} catch (IOException e) {
System.err.format("Error deleting old log files (ignored): %s\n", e.getMessage());
}
}
ImmutableList.Builder<InputStream> inputStreamsBuilder = ImmutableList.builder();
if (!LogConfigPaths.MAIN_PATH.isPresent()) {
System.err.format(
"Error: Couldn't read system property %s (it should be set by buck_common or buck.cmd)\n",
LogConfigPaths.BUCK_CONFIG_STRING_TEMPLATE_FILE_PROPERTY);
} else {
if (!addInputStreamForTemplate(
LogConfigPaths.MAIN_PATH.get(), logConfigSetup, inputStreamsBuilder)) {
System.err.format(
"Error: Couldn't open logging properties file %s\n", LogConfigPaths.MAIN_PATH.get());
}
}
// We ignore the return value for these files; they don't need to exist.
addInputStreamForPath(LogConfigPaths.PROJECT_PATH, inputStreamsBuilder);
addInputStreamForPath(LogConfigPaths.LOCAL_PATH, inputStreamsBuilder);
// Concatenate each of the files together and read them in as a single properties file
// for log settings.
try (InputStream is =
new SequenceInputStream(Iterators.asEnumeration(inputStreamsBuilder.build().iterator()))) {
LogManager.getLogManager().readConfiguration(is);
}
}
@Override
public void run(final BaragonAgentConfiguration config, final Environment environment) {
if (!config.isEnableCorsFilter()) {
return;
}
final Filter corsFilter = new CrossOriginFilter();
final FilterConfig corsFilterConfig = new FilterConfig() {
@Override
public String getFilterName() {
return FILTER_NAME;
}
@Override
public ServletContext getServletContext() {
return null;
}
@Override
public String getInitParameter(final String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return Iterators.asEnumeration(Collections.<String>emptyIterator());
}
};
try {
corsFilter.init(corsFilterConfig);
} catch (final Exception e) {
throw Throwables.propagate(e);
}
environment.servlets().addFilter(FILTER_NAME, corsFilter).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
@Override
public void run(final BaragonConfiguration config, final Environment environment) {
if (!config.isEnableCorsFilter()) {
return;
}
final Filter corsFilter = new CrossOriginFilter();
final FilterConfig corsFilterConfig = new FilterConfig() {
@Override
public String getFilterName() {
return FILTER_NAME;
}
@Override
public ServletContext getServletContext() {
return null;
}
@Override
public String getInitParameter(final String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return Iterators.asEnumeration(Collections.<String>emptyIterator());
}
};
try {
corsFilter.init(corsFilterConfig);
} catch (final Exception e) {
throw Throwables.propagate(e);
}
environment.servlets().addFilter(FILTER_NAME, corsFilter).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
@Override
public InputStream getReader() {
return new SequenceInputStream(Iterators.asEnumeration(this.components.stream().map(BufferView::getReader).iterator()));
}
@Override
public Enumeration<String> getParameterNames ()
{
return Iterators.asEnumeration ( getParameterMap ().keySet ().iterator () );
}
@Override
public void run(final SingularityConfiguration config, final Environment environment) {
CorsConfiguration corsConfiguration = config.getCors();
if (!config.isEnableCorsFilter() && !corsConfiguration.isEnabled()) {
return;
}
final Filter corsFilter = new CrossOriginFilter();
final FilterConfig corsFilterConfig = new FilterConfig() {
@Override
public String getFilterName() {
return FILTER_NAME;
}
@Override
public ServletContext getServletContext() {
return null;
}
@Override
public String getInitParameter(final String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return Iterators.asEnumeration(Collections.<String>emptyIterator());
}
};
try {
corsFilter.init(corsFilterConfig);
} catch (final Exception e) {
throw new RuntimeException(e);
}
FilterRegistration.Dynamic filter = environment
.servlets()
.addFilter(FILTER_NAME, corsFilter);
filter.setInitParameter(
CrossOriginFilter.ALLOWED_ORIGINS_PARAM,
corsConfiguration.getAllowedOrigins()
);
filter.setInitParameter(
CrossOriginFilter.ALLOWED_HEADERS_PARAM,
corsConfiguration.getAllowedHeaders()
);
filter.setInitParameter(
CrossOriginFilter.ALLOWED_METHODS_PARAM,
corsConfiguration.getAllowedMethods()
);
filter.setInitParameter(
CrossOriginFilter.ALLOW_CREDENTIALS_PARAM,
corsConfiguration.isAllowCredentials() ? "true" : "false"
);
filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}