下面列出了java.util.Map#Entry ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Create a new SQL statement instance.
* <p>
* This will parse the SQL statement for named parameters, and record the information for expanding
* it later on.
*
* @param sql The SQL statement to process.
* @return The statement, or {@code null} if the provided SQL as {@code null}.
*/
public static Statement statement(final String sql, final Object... values) {
if (sql == null) {
return null;
}
final String sqlFormatted = String.format(sql, values);
final Pattern pattern = DEFAULT_PATTERN;
final Matcher m = pattern.matcher(sqlFormatted);
int idx = 0;
final StringBuilder sb = new StringBuilder();
final List<Map.Entry<String, Integer>> mappings = new ArrayList<>();
while (m.find()) {
m.appendReplacement(sb, "${pre}?");
mappings.add(new SimpleImmutableEntry<>(m.group("name"), idx));
idx++;
}
m.appendTail(sb);
return new Statement(sb.toString(), mappings);
}
private FutureGroup<Map<ByteArray, byte[]>> internalMultiGet(final List<byte[]> keys, final boolean readOnlySafe,
final int retriesLeft, final Throwable lastCause) {
final Map<Region, List<byte[]>> regionMap = this.pdClient
.findRegionsByKeys(keys, ApiExceptionHelper.isInvalidEpoch(lastCause));
final List<CompletableFuture<Map<ByteArray, byte[]>>> futures = Lists.newArrayListWithCapacity(regionMap.size());
final Errors lastError = lastCause == null ? null : Errors.forException(lastCause);
for (final Map.Entry<Region, List<byte[]>> entry : regionMap.entrySet()) {
final Region region = entry.getKey();
final List<byte[]> subKeys = entry.getValue();
final RetryCallable<Map<ByteArray, byte[]>> retryCallable = retryCause -> internalMultiGet(subKeys,
readOnlySafe, retriesLeft - 1, retryCause);
final MapFailoverFuture<ByteArray, byte[]> future = new MapFailoverFuture<>(retriesLeft, retryCallable);
internalRegionMultiGet(region, subKeys, readOnlySafe, future, retriesLeft, lastError, this.onlyLeaderRead);
futures.add(future);
}
return new FutureGroup<>(futures);
}
/**
* This method starts at a given node, traverses all namespace mappings,
* and assembles a list of all prefixes that (for the given node) maps
* to _ANY_ namespace URI. Used by literal result elements to determine
*/
public Set<Map.Entry<String, String>> getNamespaceScope(SyntaxTreeNode node) {
Map<String, String> all = new HashMap<>();
while (node != null) {
Map<String, String> mapping = node.getPrefixMapping();
if (mapping != null) {
for( String prefix : mapping.keySet()) {
if (!all.containsKey(prefix)) {
all.put(prefix, mapping.get(prefix));
}
}
}
node = node.getParent();
}
return all.entrySet();
}
public static Object executeCommand( String commandId, Map paramMap )
throws NotDefinedException, ExecutionException,
ParameterValueConversionException, NotEnabledException,
NotHandledException
{
Command cmd = CommandUtils.getCommand( commandId );
List paramList = new ArrayList( );
if ( paramMap != null )
{
for ( Iterator iter = paramMap.entrySet( ).iterator( ); iter.hasNext( ); )
{
Map.Entry entry = (Entry) iter.next( );
String paramId = entry.getKey( ).toString( );
Object value = entry.getValue( );
if ( value != null )
{
paramList.add( createParameter( cmd, paramId, value ) );
}
}
}
if ( paramList.size( ) > 0 )
{
ParameterizedCommand paramCommand = new ParameterizedCommand( cmd,
(Parameterization[]) paramList.toArray( new Parameterization[paramList.size( )] ) );
return getHandlerService( ).executeCommand( paramCommand, null );
}
else
{
return getHandlerService( ).executeCommand( commandId, null );
}
}
public void testPutAbsentOnExisting() {
OpenIntToFieldHashMap<Fraction> map = createFromJavaMap(field);
int size = javaMap.size();
for (Map.Entry<Integer, Fraction> mapEntry : generateAbsent().entrySet()) {
map.put(mapEntry.getKey(), mapEntry.getValue());
assertEquals(++size, map.size());
assertEquals(mapEntry.getValue(), map.get(mapEntry.getKey()));
}
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
Object value = entry.getValue();
LeafNode<K, V> p = m.getEntry(entry.getKey());
return p != null && AdaptiveRadixTree.valEquals(p.getValue(), value);
}
/**
* Build a LazyFetchGroupMetadata based on the attributes defined for the
* PersistentClass
*
* @param mappedEntity The entity definition
*
* @return The built LazyFetchGroupMetadata
*/
public static LazyAttributesMetadata from(PersistentClass mappedEntity) {
final Map<String, LazyAttributeDescriptor> lazyAttributeDescriptorMap = new LinkedHashMap<>();
final Map<String, Set<String>> fetchGroupToAttributesMap = new HashMap<>();
int i = -1;
int x = 0;
final Iterator itr = mappedEntity.getPropertyClosureIterator();
while ( itr.hasNext() ) {
i++;
final Property property = (Property) itr.next();
if ( property.isLazy() ) {
final LazyAttributeDescriptor lazyAttributeDescriptor = LazyAttributeDescriptor.from( property, i, x++ );
lazyAttributeDescriptorMap.put( lazyAttributeDescriptor.getName(), lazyAttributeDescriptor );
final Set<String> attributeSet = fetchGroupToAttributesMap.computeIfAbsent(
lazyAttributeDescriptor.getFetchGroupName(),
k -> new LinkedHashSet<>()
);
attributeSet.add( lazyAttributeDescriptor.getName() );
}
}
if ( lazyAttributeDescriptorMap.isEmpty() ) {
return new LazyAttributesMetadata( mappedEntity.getEntityName() );
}
for ( Map.Entry<String, Set<String>> entry : fetchGroupToAttributesMap.entrySet() ) {
entry.setValue( Collections.unmodifiableSet( entry.getValue() ) );
}
return new LazyAttributesMetadata(
mappedEntity.getEntityName(),
Collections.unmodifiableMap( lazyAttributeDescriptorMap ),
Collections.unmodifiableMap( fetchGroupToAttributesMap )
);
}
/** Identifies entities in the contents of the object at the given GCS {@code path}. */
public static void analyzeEntitiesFile(String gcsUri) throws Exception {
// [START language_entities_gcs]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
// set the GCS Content URI path to the file to be analyzed
Document doc =
Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
AnalyzeEntitiesRequest request =
AnalyzeEntitiesRequest.newBuilder()
.setDocument(doc)
.setEncodingType(EncodingType.UTF16)
.build();
AnalyzeEntitiesResponse response = language.analyzeEntities(request);
// Print the response
for (Entity entity : response.getEntitiesList()) {
System.out.printf("Entity: %s\n", entity.getName());
System.out.printf("Salience: %.3f\n", entity.getSalience());
System.out.println("Metadata: ");
for (Map.Entry<String, String> entry : entity.getMetadataMap().entrySet()) {
System.out.printf("%s : %s", entry.getKey(), entry.getValue());
}
for (EntityMention mention : entity.getMentionsList()) {
System.out.printf("Begin offset: %d\n", mention.getText().getBeginOffset());
System.out.printf("Content: %s\n", mention.getText().getContent());
System.out.printf("Type: %s\n\n", mention.getType());
}
}
}
// [END language_entities_gcs]
}
public final String toJSONString() {
JSONObject jsonObject = new JSONObject();
try {
for (Map.Entry<String, String> entry : headersMap.entrySet()) {
jsonObject.put(entry.getKey(), entry.getValue());
}
} catch (JSONException e) {
OkLogger.printStackTrace(e);
}
return jsonObject.toString();
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<K,V> e = (Map.Entry<K,V>) o;
Entry<K,V> candidate = getEntry(e.getKey());
return candidate != null && candidate.equals(e);
}
/**
* Copies the key/value mappings in <tt>map</tt> into this map.
* Note that this will be a <b>deep</b> copy, as storage is by
* primitive value.
*
* @param map a <code>Map</code> value
*/
@Override // GemStoneAddition
public void putAll(Map map) {
Iterator it = map.entrySet().iterator();
for (int i = map.size(); i-- > 0;) {
Map.Entry e = (Map.Entry)it.next();
this.put(e.getKey(), e.getValue());
}
}
public String selectBrokerAddr() {
String value = this.brokerAddrs.get(MixAll.MASTER_ID);
if (null == value) {
for (Map.Entry<Long, String> entry : this.brokerAddrs.entrySet()) {
return entry.getValue();
}
}
return value;
}
/**
* Returns all {@link Field} values the user selected.
*/
public List<Field> getSelectedFields() {
List<Field> selectedList = new ArrayList<>();
for (Map.Entry<Field, State> entry : fieldStates.entrySet()) {
if (entry.getValue().checked) {
selectedList.add(entry.getKey());
}
}
return selectedList;
}
public void testRemove() {
OpenIntToDoubleHashMap map = createFromJavaMap();
int mapSize = javaMap.size();
assertEquals(mapSize, map.size());
for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) {
map.remove(mapEntry.getKey());
assertEquals(--mapSize, map.size());
assertTrue(Double.isNaN(map.get(mapEntry.getKey())));
}
/* Ensure that put and get still work correctly after removals */
assertPutAndGet(map);
}
Entry(Map.Entry ent, Object value) {
this.ent = ent;
this.value = value;
}
public static void register(ScalarFunctionModule module) {
for (Map.Entry<DataType, String> function : CastFunctionResolver.GEO_FUNCTION_MAP.entrySet()) {
module.register(function.getValue(), new GeoResolver(function.getKey(), function.getValue()));
}
}
public void writeNode(Node node, StringBuilder xmlDump, boolean includeMeta) {
Split splitNode = (Split) node;
writeNode("split", splitNode, xmlDump, includeMeta);
int type = splitNode.getType();
if (type != 0) {
xmlDump.append("type=\"" + type + "\" ");
}
if (splitNode.getConstraints().isEmpty()) {
endNode(xmlDump);
} else {
xmlDump.append(">" + EOL);
if (includeMeta) {
writeMetaData(splitNode, xmlDump);
}
xmlDump.append(" <constraints>" + EOL);
for (Map.Entry<ConnectionRef, Constraint> entry: splitNode.getConstraints().entrySet()) {
ConnectionRef connection = entry.getKey();
Constraint constraint = entry.getValue();
xmlDump.append(" <constraint "
+ "toNodeId=\"" + connection.getNodeId() + "\" "
+ "toType=\"" + connection.getToType() + "\" ");
String name = constraint.getName();
if (name != null && !"".equals(name)) {
xmlDump.append("name=\"" + XmlDumper.replaceIllegalChars(constraint.getName()) + "\" ");
}
int priority = constraint.getPriority();
if (priority != 0) {
xmlDump.append("priority=\"" + constraint.getPriority() + "\" ");
}
xmlDump.append("type=\"" + constraint.getType() + "\" ");
String dialect = constraint.getDialect();
if (dialect != null && !"".equals(dialect)) {
xmlDump.append("dialect=\"" + dialect + "\" ");
}
String constraintString = constraint.getConstraint();
if (constraintString != null) {
xmlDump.append(">" + XmlDumper.replaceIllegalChars(constraintString) + "</constraint>" + EOL);
} else {
xmlDump.append("/>" + EOL);
}
}
xmlDump.append(" </constraints>" + EOL);
endNode("split", xmlDump);
}
}
/**
* Calls the {@link FeedParser} on a sample RSS file and checks that there are
* 3 {@link ParseResult} entries including the below 2 links:
* <ul>
* <li>http://www-scf.usc.edu/~mattmann/</li>
* <li>http://www.nutch.org</li>
* </ul>
*
*
* @throws ProtocolNotFound
* If the {@link Protocol}Layer cannot be loaded (required to fetch
* the {@link Content} for the RSS file).
* @throws ParseException
* If the {@link Parser}Layer cannot be loaded.
*/
public void testParseFetchChannel() throws ProtocolNotFound, ParseException {
String urlString;
Protocol protocol;
Content content;
ParseResult parseResult;
Configuration conf = NutchConfiguration.create();
for (int i = 0; i < sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
urlString = urlString.replace('\\', '/');
protocol = new ProtocolFactory(conf).getProtocol(urlString);
content = protocol.getProtocolOutput(new Text(urlString),
new CrawlDatum()).getContent();
parseResult = new ParseUtil(conf).parseByExtensionId("feed", content);
assertEquals(3, parseResult.size());
boolean hasLink1 = false, hasLink2 = false, hasLink3=false;
for (Iterator<Map.Entry<Text, Parse>> j = parseResult.iterator(); j
.hasNext();) {
Map.Entry<Text, Parse> entry = j.next();
if (entry.getKey().toString().equals(
"http://www-scf.usc.edu/~mattmann/")) {
hasLink1 = true;
} else if (entry.getKey().toString().equals("http://www.nutch.org/")) {
hasLink2 = true;
}
else if(entry.getKey().toString().equals(urlString)){
hasLink3 = true;
}
assertNotNull(entry.getValue());
assertNotNull(entry.getValue().getData());
}
if (!hasLink1 || !hasLink2 || !hasLink3) {
fail("Outlinks read from sample rss file are not correct!");
}
}
}
@Override
public void write(org.apache.blur.thirdparty.thrift_0_9_0.protocol.TProtocol prot, CommandDescriptor struct) throws org.apache.blur.thirdparty.thrift_0_9_0.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetCommandName()) {
optionals.set(0);
}
if (struct.isSetDescription()) {
optionals.set(1);
}
if (struct.isSetRequiredArguments()) {
optionals.set(2);
}
if (struct.isSetOptionalArguments()) {
optionals.set(3);
}
if (struct.isSetReturnType()) {
optionals.set(4);
}
if (struct.isSetVersion()) {
optionals.set(5);
}
oprot.writeBitSet(optionals, 6);
if (struct.isSetCommandName()) {
oprot.writeString(struct.commandName);
}
if (struct.isSetDescription()) {
oprot.writeString(struct.description);
}
if (struct.isSetRequiredArguments()) {
{
oprot.writeI32(struct.requiredArguments.size());
for (Map.Entry<String, ArgumentDescriptor> _iter300 : struct.requiredArguments.entrySet())
{
oprot.writeString(_iter300.getKey());
_iter300.getValue().write(oprot);
}
}
}
if (struct.isSetOptionalArguments()) {
{
oprot.writeI32(struct.optionalArguments.size());
for (Map.Entry<String, ArgumentDescriptor> _iter301 : struct.optionalArguments.entrySet())
{
oprot.writeString(_iter301.getKey());
_iter301.getValue().write(oprot);
}
}
}
if (struct.isSetReturnType()) {
oprot.writeString(struct.returnType);
}
if (struct.isSetVersion()) {
oprot.writeString(struct.version);
}
}
/**
* Writes multiple mappings.
* <p>
* The writes may represent a mix of brand new values and updates to existing values.
* <p>
* By using a {@link BulkCacheWritingException} implementors can report partial success. Any other exception will
* be thrown back to the {@code Cache} user through a {@link BulkCacheWritingException} indicating a complete failure.
*
* @param entries the mappings to write
*
* @throws BulkCacheWritingException in case of partial success
* @throws Exception in case no values could be written
*/
default void writeAll(Iterable<? extends Map.Entry<? extends K, ? extends V>> entries) throws BulkCacheWritingException, Exception {
for (Map.Entry<? extends K, ? extends V> entry : entries) {
write(entry.getKey(), entry.getValue());
}
}