1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.jxpath.util;
19
20 import org.apache.commons.jxpath.BasicNodeSet;
21 import org.apache.commons.jxpath.ExtendedKeyManager;
22 import org.apache.commons.jxpath.JXPathContext;
23 import org.apache.commons.jxpath.KeyManager;
24 import org.apache.commons.jxpath.NodeSet;
25 import org.apache.commons.jxpath.Pointer;
26 import org.apache.commons.jxpath.ri.InfoSetUtil;
27
28 /**
29 * Utility class.
30 *
31 * @since JXPath 1.3
32 */
33 public class KeyManagerUtils {
34
35 /**
36 * Adapt KeyManager to implement ExtendedKeyManager.
37 */
38 private static final class SingleNodeExtendedKeyManager implements ExtendedKeyManager {
39
40 private final KeyManager delegate;
41
42 /**
43 * Constructs a new SingleNodeExtendedKeyManager.
44 *
45 * @param delegate KeyManager to wrap
46 */
47 public SingleNodeExtendedKeyManager(final KeyManager delegate) {
48 this.delegate = delegate;
49 }
50
51 @Override
52 public NodeSet getNodeSetByKey(final JXPathContext context, final String key, final Object value) {
53 final Pointer pointer = delegate.getPointerByKey(context, key, InfoSetUtil.stringValue(value));
54 final BasicNodeSet result = new BasicNodeSet();
55 result.add(pointer);
56 return result;
57 }
58
59 @Override
60 public Pointer getPointerByKey(final JXPathContext context, final String keyName, final String keyValue) {
61 return delegate.getPointerByKey(context, keyName, keyValue);
62 }
63 }
64
65 /**
66 * Gets an ExtendedKeyManager from the specified KeyManager.
67 *
68 * @param keyManager to adapt, if necessary
69 * @return {@code keyManager} if it implements ExtendedKeyManager or a basic single-result ExtendedKeyManager that delegates to {@code keyManager}.
70 */
71 public static ExtendedKeyManager getExtendedKeyManager(final KeyManager keyManager) {
72 return keyManager instanceof ExtendedKeyManager ? (ExtendedKeyManager) keyManager : new SingleNodeExtendedKeyManager(keyManager);
73 }
74
75 /**
76 * Constructs a new instance.
77 *
78 * @deprecated Will be private in the next major version.
79 */
80 @Deprecated
81 public KeyManagerUtils() {
82 // empty
83 }
84 }