repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/pool/EVCacheScheduledExecutor.java
package com.netflix.evcache.pool; import java.lang.management.ManagementFactory; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import javax.management.MBeanServer; import javax.management.ObjectName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.archaius.api.Property; import com.netflix.evcache.metrics.EVCacheMetricsFactory; import com.netflix.evcache.util.EVCacheConfig; import com.netflix.spectator.api.patterns.ThreadPoolMonitor; public class EVCacheScheduledExecutor extends ScheduledThreadPoolExecutor implements EVCacheScheduledExecutorMBean { private static final Logger log = LoggerFactory.getLogger(EVCacheScheduledExecutor.class); private final Property<Integer> maxAsyncPoolSize; private final Property<Integer> coreAsyncPoolSize; private final String name; public EVCacheScheduledExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, RejectedExecutionHandler handler, String name) { super(corePoolSize, handler); this.name = name; maxAsyncPoolSize = EVCacheConfig.getInstance().getPropertyRepository().get(name + "executor.max.size", Integer.class).orElse(maximumPoolSize); setMaximumPoolSize(maxAsyncPoolSize.get()); coreAsyncPoolSize = EVCacheConfig.getInstance().getPropertyRepository().get(name + "executor.core.size", Integer.class).orElse(corePoolSize); setCorePoolSize(coreAsyncPoolSize.get()); setKeepAliveTime(keepAliveTime, unit); final ThreadFactory asyncFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat( "EVCacheScheduledExecutor-" + name + "-%d").build(); setThreadFactory(asyncFactory); maxAsyncPoolSize.subscribe(this::setMaximumPoolSize); coreAsyncPoolSize.subscribe(i -> { setCorePoolSize(i); prestartAllCoreThreads(); }); setupMonitoring(name); ThreadPoolMonitor.attach(EVCacheMetricsFactory.getInstance().getRegistry(), this, EVCacheMetricsFactory.INTERNAL_EXECUTOR_SCHEDULED + "-" + name); } private void setupMonitoring(String name) { try { ObjectName mBeanName = ObjectName.getInstance("com.netflix.evcache:Group=ThreadPool,SubGroup="+name); MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); if (mbeanServer.isRegistered(mBeanName)) { if (log.isDebugEnabled()) log.debug("MBEAN with name " + mBeanName + " has been registered. Will unregister the previous instance and register a new one."); mbeanServer.unregisterMBean(mBeanName); } mbeanServer.registerMBean(this, mBeanName); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Exception", e); } } public void shutdown() { try { ObjectName mBeanName = ObjectName.getInstance("com.netflix.evcache:Group=ThreadPool,SubGroup="+name); MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); mbeanServer.unregisterMBean(mBeanName); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Exception", e); } super.shutdown(); } @Override public int getQueueSize() { return getQueue().size(); } }
3,546
42.256098
172
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/pool/EVCacheClient.java
package com.netflix.evcache.pool; import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.*; import java.util.zip.CRC32; import java.util.zip.Checksum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.archaius.api.Property; import com.netflix.evcache.EVCache; import com.netflix.evcache.EVCache.Call; import com.netflix.evcache.EVCacheConnectException; import com.netflix.evcache.EVCacheException; import com.netflix.evcache.EVCacheLatch; import com.netflix.evcache.EVCacheReadQueueException; import com.netflix.evcache.EVCacheSerializingTranscoder; import com.netflix.evcache.metrics.EVCacheMetricsFactory; import com.netflix.evcache.operation.EVCacheFutures; import com.netflix.evcache.operation.EVCacheItem; import com.netflix.evcache.operation.EVCacheItemMetaData; import com.netflix.evcache.operation.EVCacheLatchImpl; import com.netflix.evcache.pool.observer.EVCacheConnectionObserver; import com.netflix.evcache.util.EVCacheConfig; import com.netflix.evcache.util.KeyHasher; import com.netflix.evcache.util.KeyHasher.HashingAlgorithm; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Tag; import net.spy.memcached.CASValue; import net.spy.memcached.CachedData; import net.spy.memcached.ConnectionFactory; import net.spy.memcached.EVCacheMemcachedClient; import net.spy.memcached.EVCacheNode; import net.spy.memcached.MemcachedClient; import net.spy.memcached.MemcachedNode; import net.spy.memcached.NodeLocator; import net.spy.memcached.internal.ListenableFuture; import net.spy.memcached.internal.OperationCompletionListener; import net.spy.memcached.internal.OperationFuture; import net.spy.memcached.transcoders.Transcoder; import rx.Scheduler; import rx.Single; @SuppressWarnings({"rawtypes", "unchecked"}) @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "REC_CATCH_EXCEPTION", "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" }) public class EVCacheClient { private static final Logger log = LoggerFactory.getLogger(EVCacheClient.class); private final ConnectionFactory connectionFactory; private final EVCacheMemcachedClient evcacheMemcachedClient; private final List<InetSocketAddress> memcachedNodesInZone; private EVCacheConnectionObserver connectionObserver = null; private boolean shutdown = false; private final int id; private final String appName; private final String zone; private final ServerGroup serverGroup; private final EVCacheServerGroupConfig config; private final int maxWriteQueueSize; private final Property<Integer> readTimeout; private final Property<Integer> bulkReadTimeout; private final Property<Integer> maxReadQueueSize; private final Property<Boolean> ignoreInactiveNodes; private final Property<Boolean> enableChunking; private final Property<Boolean> hashKeyByServerGroup; private final Property<Boolean> shouldEncodeHashKey; private final Property<Integer> maxDigestBytes; private final Property<Integer> maxHashLength; private final Property<Integer> chunkSize, writeBlock; private final Property<String> encoderBase; private final ChunkTranscoder chunkingTranscoder; private final EVCacheSerializingTranscoder decodingTranscoder; private static final int SPECIAL_BYTEARRAY = (8 << 8); private final EVCacheClientPool pool; // private Counter addCounter = null; private final Property<Boolean> ignoreTouch; private List<Tag> tags; private final Map<String, Counter> counterMap = new ConcurrentHashMap<String, Counter>(); private final Property<String> hashingAlgo; protected final Counter operationsCounter; private final boolean isDuetClient; EVCacheClient(String appName, String zone, int id, EVCacheServerGroupConfig config, List<InetSocketAddress> memcachedNodesInZone, int maxQueueSize, Property<Integer> maxReadQueueSize, Property<Integer> readTimeout, Property<Integer> bulkReadTimeout, Property<Integer> opQueueMaxBlockTime, Property<Integer> operationTimeout, EVCacheClientPool pool, boolean isDuetClient) throws IOException { this.memcachedNodesInZone = memcachedNodesInZone; this.id = id; this.appName = appName; this.zone = zone; this.config = config; this.serverGroup = config.getServerGroup(); this.readTimeout = readTimeout; this.bulkReadTimeout = bulkReadTimeout; this.maxReadQueueSize = maxReadQueueSize; // this.operationTimeout = operationTimeout; this.pool = pool; this.isDuetClient = isDuetClient; final List<Tag> tagList = new ArrayList<Tag>(4); EVCacheMetricsFactory.getInstance().addAppNameTags(tagList, appName); tagList.add(new BasicTag(EVCacheMetricsFactory.CONNECTION_ID, String.valueOf(id))); tagList.add(new BasicTag(EVCacheMetricsFactory.SERVERGROUP, serverGroup.getName())); this.tags = Collections.<Tag>unmodifiableList(new ArrayList(tagList)); tagList.add(new BasicTag(EVCacheMetricsFactory.STAT_NAME, EVCacheMetricsFactory.POOL_OPERATIONS)); operationsCounter = EVCacheMetricsFactory.getInstance().getCounter(EVCacheMetricsFactory.INTERNAL_STATS, tagList); this.enableChunking = EVCacheConfig.getInstance().getPropertyRepository().get(this.serverGroup.getName()+ ".chunk.data", Boolean.class).orElseGet(appName + ".chunk.data").orElse(false); this.chunkSize = EVCacheConfig.getInstance().getPropertyRepository().get(this.serverGroup.getName() + ".chunk.size", Integer.class).orElseGet(appName + ".chunk.size").orElse(1180); this.writeBlock = EVCacheConfig.getInstance().getPropertyRepository().get(appName + "." + this.serverGroup.getName() + ".write.block.duration", Integer.class).orElseGet(appName + ".write.block.duration").orElse(25); this.chunkingTranscoder = new ChunkTranscoder(); this.maxWriteQueueSize = maxQueueSize; this.ignoreTouch = EVCacheConfig.getInstance().getPropertyRepository().get(appName + "." + this.serverGroup.getName() + ".ignore.touch", Boolean.class).orElseGet(appName + ".ignore.touch").orElse(false); this.connectionFactory = pool.getEVCacheClientPoolManager().getConnectionFactoryProvider().getConnectionFactory(this); this.connectionObserver = new EVCacheConnectionObserver(this); this.ignoreInactiveNodes = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".ignore.inactive.nodes", Boolean.class).orElse(true); this.evcacheMemcachedClient = new EVCacheMemcachedClient(connectionFactory, memcachedNodesInZone, readTimeout, this); this.evcacheMemcachedClient.addObserver(connectionObserver); this.decodingTranscoder = new EVCacheSerializingTranscoder(Integer.MAX_VALUE); decodingTranscoder.setCompressionThreshold(Integer.MAX_VALUE); this.hashKeyByServerGroup = EVCacheConfig.getInstance().getPropertyRepository().get(this.serverGroup.getName() + ".hash.key", Boolean.class).orElse(null); this.hashingAlgo = EVCacheConfig.getInstance().getPropertyRepository().get(this.serverGroup.getName() + ".hash.algo", String.class).orElseGet(appName + ".hash.algo").orElse("siphash24"); this.shouldEncodeHashKey = EVCacheConfig.getInstance().getPropertyRepository().get(this.serverGroup.getName() + ".hash.encode", Boolean.class).orElse(null); this.maxDigestBytes = EVCacheConfig.getInstance().getPropertyRepository().get(this.serverGroup.getName() + ".max.digest.bytes", Integer.class).orElse(null); this.maxHashLength = EVCacheConfig.getInstance().getPropertyRepository().get(this.serverGroup.getName() + ".max.hash.length", Integer.class).orElse(null); this.encoderBase = EVCacheConfig.getInstance().getPropertyRepository().get(this.serverGroup.getName() + ".hash.encoder", String.class).orElse("base64"); ping(); } public void ping() { try { final Map<SocketAddress, String> versions = getVersions(); for (Entry<SocketAddress, String> vEntry : versions.entrySet()) { if (log.isDebugEnabled()) log.debug("Host : " + vEntry.getKey() + " : " + vEntry.getValue()); } } catch (Throwable t) { log.error("Error while pinging the servers", t); } } public boolean isDuetClient() { return isDuetClient; } public Boolean shouldEncodeHashKey() { return this.shouldEncodeHashKey.get(); } public String getBaseEncoder() { return this.encoderBase.get(); } public Integer getMaxDigestBytes() { return this.maxDigestBytes.get(); } public Integer getMaxHashLength() { return this.maxHashLength.get(); } private Collection<String> validateReadQueueSize(Collection<String> canonicalKeys, EVCache.Call call) { if (evcacheMemcachedClient.getNodeLocator() == null) return canonicalKeys; final Collection<String> retKeys = new ArrayList<>(canonicalKeys.size()); for (String key : canonicalKeys) { final MemcachedNode node = evcacheMemcachedClient.getNodeLocator().getPrimary(key); if (node instanceof EVCacheNode) { final EVCacheNode evcNode = (EVCacheNode) node; if (!evcNode.isAvailable(call)) { continue; } final int size = evcNode.getReadQueueSize(); final boolean canAddToOpQueue = size < (maxReadQueueSize.get() * 2); // if (log.isDebugEnabled()) log.debug("Bulk Current Read Queue // Size - " + size + " for app " + appName + " & zone " + zone + // " ; node " + node); if (!canAddToOpQueue) { final String hostName; if(evcNode.getSocketAddress() instanceof InetSocketAddress) { hostName = ((InetSocketAddress)evcNode.getSocketAddress()).getHostName(); } else { hostName = evcNode.getSocketAddress().toString(); } incrementFailure(EVCacheMetricsFactory.READ_QUEUE_FULL, call, hostName); if (log.isDebugEnabled()) log.debug("Read Queue Full on Bulk Operation for app : " + appName + "; zone : " + zone + "; Current Size : " + size + "; Max Size : " + maxReadQueueSize.get() * 2); } else { retKeys.add(key); } } } return retKeys; } private void incrementFailure(String metric, EVCache.Call call) { incrementFailure(metric, call, null); } private void incrementFailure(String metric, EVCache.Call call, String host) { Counter counter = counterMap.get(metric); if(counter == null) { final List<Tag> tagList = new ArrayList<Tag>(6); tagList.addAll(tags); if(call != null) { tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, call.name())); switch(call) { case GET: case GETL: case GET_AND_TOUCH: case ASYNC_GET: case BULK: case GET_ALL: tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TYPE_TAG, EVCacheMetricsFactory.READ)); break; default : tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TYPE_TAG, EVCacheMetricsFactory.WRITE)); break; } } tagList.add(new BasicTag(EVCacheMetricsFactory.FAILURE_REASON, metric)); if(host != null) tagList.add(new BasicTag(EVCacheMetricsFactory.FAILED_HOST, host)); counter = EVCacheMetricsFactory.getInstance().getCounter(EVCacheMetricsFactory.INTERNAL_FAIL, tagList); counterMap.put(metric, counter); } counter.increment(); } public void reportWrongKeyReturned(String hostName) { incrementFailure(EVCacheMetricsFactory.WRONG_KEY_RETURNED, null, hostName); } private boolean ensureWriteQueueSize(MemcachedNode node, String key, EVCache.Call call) throws EVCacheException { if (node instanceof EVCacheNode) { final EVCacheNode evcNode = (EVCacheNode) node; int i = 0; while (true) { final int size = evcNode.getWriteQueueSize(); final boolean canAddToOpQueue = size < maxWriteQueueSize; if (log.isDebugEnabled()) log.debug("App : " + appName + "; zone : " + zone + "; key : " + key + "; WriteQSize : " + size); if (canAddToOpQueue) break; try { Thread.sleep(writeBlock.get()); } catch (InterruptedException e) { throw new EVCacheException("Thread was Interrupted", e); } if(i++ > 3) { final String hostName; if(evcNode.getSocketAddress() instanceof InetSocketAddress) { hostName = ((InetSocketAddress)evcNode.getSocketAddress()).getHostName(); } else { hostName = evcNode.getSocketAddress().toString(); } incrementFailure(EVCacheMetricsFactory.INACTIVE_NODE, call, hostName); if (log.isDebugEnabled()) log.debug("Node : " + evcNode + " for app : " + appName + "; zone : " + zone + " is not active. Will Fail Fast and the write will be dropped for key : " + key); evcNode.shutdown(); return false; } } } return true; } private boolean validateNode(String key, boolean _throwException, EVCache.Call call) throws EVCacheException, EVCacheConnectException { final MemcachedNode node = evcacheMemcachedClient.getEVCacheNode(key); // First check if the node is active if (node instanceof EVCacheNode) { final EVCacheNode evcNode = (EVCacheNode) node; final String hostName; if(evcNode.getSocketAddress() instanceof InetSocketAddress) { hostName = ((InetSocketAddress)evcNode.getSocketAddress()).getHostName(); } else { hostName = evcNode.getSocketAddress().toString(); } if (!evcNode.isAvailable(call)) { incrementFailure(EVCacheMetricsFactory.INACTIVE_NODE, call, hostName); if (log.isDebugEnabled()) log.debug("Node : " + node + " for app : " + appName + "; zone : " + zone + " is not active. Will Fail Fast so that we can fallback to Other Zone if available."); if (_throwException) throw new EVCacheConnectException("Connection for Node : " + node + " for app : " + appName + "; zone : " + zone + " is not active"); return false; } final int size = evcNode.getReadQueueSize(); final boolean canAddToOpQueue = size < maxReadQueueSize.get(); if (log.isDebugEnabled()) log.debug("Current Read Queue Size - " + size + " for app " + appName + " & zone " + zone + " and node : " + evcNode); if (!canAddToOpQueue) { incrementFailure(EVCacheMetricsFactory.READ_QUEUE_FULL, call, hostName); if (log.isDebugEnabled()) log.debug("Read Queue Full for Node : " + node + "; app : " + appName + "; zone : " + zone + "; Current Size : " + size + "; Max Size : " + maxReadQueueSize.get()); if (_throwException) throw new EVCacheReadQueueException("Read Queue Full for Node : " + node + "; app : " + appName + "; zone : " + zone + "; Current Size : " + size + "; Max Size : " + maxReadQueueSize.get()); return false; } } return true; } private <T> ChunkDetails<T> getChunkDetails(String key) { final List<String> firstKeys = new ArrayList<String>(2); firstKeys.add(key); final String firstKey = key + "_00"; firstKeys.add(firstKey); try { final Map<String, CachedData> metadataMap = evcacheMemcachedClient.asyncGetBulk(firstKeys, chunkingTranscoder, null) .getSome(readTimeout.get(), TimeUnit.MILLISECONDS, false, false); if (metadataMap.containsKey(key)) { return new ChunkDetails(null, null, false, metadataMap.get(key)); } else if (metadataMap.containsKey(firstKey)) { final ChunkInfo ci = getChunkInfo(firstKey, (String) decodingTranscoder.decode(metadataMap.get(firstKey))); if (ci == null) return null; final List<String> keys = new ArrayList<>(); for (int i = 1; i < ci.getChunks(); i++) { final String prefix = (i < 10) ? "0" : ""; keys.add(ci.getKey() + "_" + prefix + i); } return new ChunkDetails(keys, ci, true, null); } else { return null; } } catch (Exception e) { log.error(e.getMessage(), e); } return null; } private <T> Single<ChunkDetails<T>> getChunkDetails(String key, Scheduler scheduler) { final List<String> firstKeys = new ArrayList<>(2); firstKeys.add(key); final String firstKey = key + "_00"; firstKeys.add(firstKey); return evcacheMemcachedClient.asyncGetBulk(firstKeys, chunkingTranscoder, null) .getSome(readTimeout.get(), TimeUnit.MILLISECONDS, false, false, scheduler) .map(metadataMap -> { if (metadataMap.containsKey(key)) { return new ChunkDetails(null, null, false, metadataMap.get(key)); } else if (metadataMap.containsKey(firstKey)) { final ChunkInfo ci = getChunkInfo(firstKey, (String) decodingTranscoder.decode(metadataMap.get(firstKey))); if (ci == null) return null; final List<String> keys = new ArrayList<>(); for (int i = 1; i < ci.getChunks(); i++) { final String prefix = (i < 10) ? "0" : ""; keys.add(ci.getKey() + "_" + prefix + i); } return new ChunkDetails(keys, ci, true, null); } else { return null; } }); } private <T> T assembleChunks(String key, boolean touch, int ttl, Transcoder<T> tc, boolean hasZF) { try { final ChunkDetails<T> cd = getChunkDetails(key); if (cd == null) return null; if (!cd.isChunked()) { if (cd.getData() == null) return null; final Transcoder<T> transcoder = (tc == null ? (Transcoder<T>) evcacheMemcachedClient.getTranscoder() : tc); return transcoder.decode((CachedData) cd.getData()); } else { final List<String> keys = cd.getChunkKeys(); final ChunkInfo ci = cd.getChunkInfo(); final Map<String, CachedData> dataMap = evcacheMemcachedClient.asyncGetBulk(keys, chunkingTranscoder, null) .getSome(readTimeout.get(), TimeUnit.MILLISECONDS, false, false); if (dataMap.size() != ci.getChunks() - 1) { incrementFailure(EVCacheMetricsFactory.INCORRECT_CHUNKS, null); return null; } final byte[] data = new byte[(ci.getChunks() - 2) * ci.getChunkSize() + (ci.getLastChunk() == 0 ? ci .getChunkSize() : ci.getLastChunk())]; int index = 0; for (int i = 0; i < keys.size(); i++) { final String _key = keys.get(i); final CachedData _cd = dataMap.get(_key); if (log.isDebugEnabled()) log.debug("Chunk Key " + _key + "; Value : " + _cd); if (_cd == null) continue; final byte[] val = _cd.getData(); // If we expect a chunk to be present and it is null then return null immediately. if (val == null) return null; final int len = (i == keys.size() - 1) ? ((ci.getLastChunk() == 0 || ci.getLastChunk() > ci .getChunkSize()) ? ci.getChunkSize() : ci.getLastChunk()) : val.length; if (len != ci.getChunkSize() && i != keys.size() - 1) { incrementFailure(EVCacheMetricsFactory.INVALID_CHUNK_SIZE, null); if (log.isWarnEnabled()) log.warn("CHUNK_SIZE_ERROR : Chunks : " + ci.getChunks() + " ; " + "length : " + len + "; expectedLength : " + ci.getChunkSize() + " for key : " + _key); } if (len > 0) { try { System.arraycopy(val, 0, data, index, len); } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.append("ArrayCopyError - Key : " + _key + "; final data Size : " + data.length + "; copy array size : " + len + "; val size : " + val.length + "; key index : " + i + "; copy from : " + index + "; ChunkInfo : " + ci + "\n"); for (int j = 0; j < keys.size(); j++) { final String skey = keys.get(j); final byte[] sval = (byte[]) dataMap.get(skey).getData(); sb.append(skey + "=" + sval.length + "\n"); } if (log.isWarnEnabled()) log.warn(sb.toString(), e); throw e; } index += val.length; if (touch) evcacheMemcachedClient.touch(_key, ttl); } } final boolean checksumPass = checkCRCChecksum(data, ci, hasZF); if (!checksumPass) return null; final Transcoder<T> transcoder = (tc == null ? (Transcoder<T>) evcacheMemcachedClient.getTranscoder() : tc); return transcoder.decode(new CachedData(ci.getFlags(), data, Integer.MAX_VALUE)); } } catch (Exception e) { log.error(e.getMessage(), e); } return null; } private <T> Single<T> assembleChunks(String key, boolean touch, int ttl, Transcoder<T> tc, boolean hasZF, Scheduler scheduler) { return getChunkDetails(key, scheduler).flatMap(cd -> { if (cd == null) return Single.just(null); if (!cd.isChunked()) { if (cd.getData() == null) return Single.just(null); final Transcoder<T> transcoder = (tc == null ? (Transcoder<T>) evcacheMemcachedClient.getTranscoder() : tc); return Single.just(transcoder.decode((CachedData) cd.getData())); } else { final List<String> keys = cd.getChunkKeys(); final ChunkInfo ci = cd.getChunkInfo(); return evcacheMemcachedClient.asyncGetBulk(keys, chunkingTranscoder, null) .getSome(readTimeout.get(), TimeUnit.MILLISECONDS, false, false, scheduler) .map(dataMap -> { if (dataMap.size() != ci.getChunks() - 1) { incrementFailure(EVCacheMetricsFactory.INCORRECT_CHUNKS, null); return null; } final byte[] data = new byte[(ci.getChunks() - 2) * ci.getChunkSize() + (ci.getLastChunk() == 0 ? ci .getChunkSize() : ci.getLastChunk())]; int index = 0; for (int i = 0; i < keys.size(); i++) { final String _key = keys.get(i); final CachedData _cd = dataMap.get(_key); if (log.isDebugEnabled()) log.debug("Chunk Key " + _key + "; Value : " + _cd); if (_cd == null) continue; final byte[] val = _cd.getData(); // If we expect a chunk to be present and it is null then return null immediately. if (val == null) return null; final int len = (i == keys.size() - 1) ? ((ci.getLastChunk() == 0 || ci.getLastChunk() > ci .getChunkSize()) ? ci.getChunkSize() : ci.getLastChunk()) : val.length; if (len != ci.getChunkSize() && i != keys.size() - 1) { incrementFailure(EVCacheMetricsFactory.INVALID_CHUNK_SIZE, null); if (log.isWarnEnabled()) log.warn("CHUNK_SIZE_ERROR : Chunks : " + ci.getChunks() + " ; " + "length : " + len + "; expectedLength : " + ci.getChunkSize() + " for key : " + _key); } if (len > 0) { try { System.arraycopy(val, 0, data, index, len); } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.append("ArrayCopyError - Key : " + _key + "; final data Size : " + data.length + "; copy array size : " + len + "; val size : " + val.length + "; key index : " + i + "; copy from : " + index + "; ChunkInfo : " + ci + "\n"); for (int j = 0; j < keys.size(); j++) { final String skey = keys.get(j); final byte[] sval = (byte[]) dataMap.get(skey).getData(); sb.append(skey + "=" + sval.length + "\n"); } if (log.isWarnEnabled()) log.warn(sb.toString(), e); throw e; } System.arraycopy(val, 0, data, index, len); index += val.length; if (touch) evcacheMemcachedClient.touch(_key, ttl); } } final boolean checksumPass = checkCRCChecksum(data, ci, hasZF); if (!checksumPass) return null; final Transcoder<T> transcoder = (tc == null ? (Transcoder<T>) evcacheMemcachedClient.getTranscoder() : tc); return transcoder.decode(new CachedData(ci.getFlags(), data, Integer.MAX_VALUE)); }); } }); } private boolean checkCRCChecksum(byte[] data, final ChunkInfo ci, boolean hasZF) { if (data == null || data.length == 0) return false; final Checksum checksum = new CRC32(); checksum.update(data, 0, data.length); final long currentChecksum = checksum.getValue(); final long expectedChecksum = ci.getChecksum(); if (log.isDebugEnabled()) log.debug("CurrentChecksum : " + currentChecksum + "; ExpectedChecksum : " + expectedChecksum + " for key : " + ci.getKey()); if (currentChecksum != expectedChecksum) { if (!hasZF) { if (log.isWarnEnabled()) log.warn("CHECKSUM_ERROR : Chunks : " + ci.getChunks() + " ; " + "currentChecksum : " + currentChecksum + "; expectedChecksum : " + expectedChecksum + " for key : " + ci.getKey()); incrementFailure(EVCacheMetricsFactory.CHECK_SUM_ERROR, null); } return false; } return true; } private ChunkInfo getChunkInfo(String firstKey, String metadata) { if (metadata == null) return null; final String[] metaItems = metadata.split(":"); if (metaItems.length != 5) return null; final String key = firstKey.substring(0, firstKey.length() - 3); final ChunkInfo ci = new ChunkInfo(Integer.parseInt(metaItems[0]), Integer.parseInt(metaItems[1]), Integer .parseInt(metaItems[2]), Integer.parseInt(metaItems[3]), key, Long .parseLong(metaItems[4])); return ci; } private <T> Map<String, T> assembleChunks(Collection<String> keyList, Transcoder<T> tc, boolean hasZF) { final List<String> firstKeys = new ArrayList<>(); for (String key : keyList) { firstKeys.add(key); firstKeys.add(key + "_00"); } try { final Map<String, CachedData> metadataMap = evcacheMemcachedClient.asyncGetBulk(firstKeys, chunkingTranscoder, null) .getSome(bulkReadTimeout.get(), TimeUnit.MILLISECONDS, false, false); if (metadataMap == null) return null; final Map<String, T> returnMap = new HashMap<>(keyList.size() * 2); for (String key : keyList) { if (metadataMap.containsKey(key)) { CachedData val = metadataMap.remove(key); returnMap.put(key, tc.decode(val)); } } final List<String> allKeys = new ArrayList<>(); final Map<ChunkInfo, SimpleEntry<List<String>, byte[]>> responseMap = new HashMap<>(); for (Entry<String, CachedData> entry : metadataMap.entrySet()) { final String firstKey = entry.getKey(); final String metadata = (String) decodingTranscoder.decode(entry.getValue()); if (metadata == null) continue; final ChunkInfo ci = getChunkInfo(firstKey, metadata); if (ci != null) { final List<String> ciKeys = new ArrayList<>(); for (int i = 1; i < ci.getChunks(); i++) { final String prefix = (i < 10) ? "0" : ""; final String _key = ci.getKey() + "_" + prefix + i; allKeys.add(_key); ciKeys.add(_key); } final byte[] data = new byte[(ci.getChunks() - 2) * ci.getChunkSize() + ci.getLastChunk()]; responseMap.put(ci, new SimpleEntry<>(ciKeys, data)); } } final Map<String, CachedData> dataMap = evcacheMemcachedClient.asyncGetBulk(allKeys, chunkingTranscoder, null) .getSome(bulkReadTimeout.get(), TimeUnit.MILLISECONDS, false, false); for (Entry<ChunkInfo, SimpleEntry<List<String>, byte[]>> entry : responseMap.entrySet()) { final ChunkInfo ci = entry.getKey(); final SimpleEntry<List<String>, byte[]> pair = entry.getValue(); final List<String> ciKeys = pair.getKey(); byte[] data = pair.getValue(); int index = 0; for (int i = 0; i < ciKeys.size(); i++) { final String _key = ciKeys.get(i); final CachedData cd = dataMap.get(_key); if (log.isDebugEnabled()) log.debug("Chunk Key " + _key + "; Value : " + cd); if (cd == null) continue; final byte[] val = cd.getData(); if (val == null) { data = null; break; } final int len = (i == ciKeys.size() - 1) ? ((ci.getLastChunk() == 0 || ci.getLastChunk() > ci .getChunkSize()) ? ci.getChunkSize() : ci.getLastChunk()) : val.length; try { System.arraycopy(val, 0, data, index, len); } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.append("ArrayCopyError - Key : " + _key + "; final data Size : " + data.length + "; copy array size : " + len + "; val size : " + val.length + "; key index : " + i + "; copy from : " + index + "; ChunkInfo : " + ci + "\n"); for (int j = 0; j < ciKeys.size(); j++) { final String skey = ciKeys.get(j); final byte[] sval = dataMap.get(skey).getData(); sb.append(skey + "=" + sval.length + "\n"); } if (log.isWarnEnabled()) log.warn(sb.toString(), e); throw e; } index += val.length; } final boolean checksumPass = checkCRCChecksum(data, ci, hasZF); if (data != null && checksumPass) { final CachedData cd = new CachedData(ci.getFlags(), data, Integer.MAX_VALUE); returnMap.put(ci.getKey(), tc.decode(cd)); } else { returnMap.put(ci.getKey(), null); } } return returnMap; } catch (Exception e) { log.error(e.getMessage(), e); } return null; } private <T> Single<Map<String, T>> assembleChunks(Collection<String> keyList, Transcoder<T> tc, boolean hasZF, Scheduler scheduler) { final List<String> firstKeys = new ArrayList<>(); for (String key : keyList) { firstKeys.add(key); firstKeys.add(key + "_00"); } return evcacheMemcachedClient.asyncGetBulk(firstKeys, chunkingTranscoder, null) .getSome(bulkReadTimeout.get(), TimeUnit.MILLISECONDS, false, false, scheduler) .flatMap(metadataMap -> { if (metadataMap == null) return null; final Map<String, T> returnMap = new HashMap<>(keyList.size() * 2); for (String key : keyList) { if (metadataMap.containsKey(key)) { CachedData val = metadataMap.remove(key); returnMap.put(key, tc.decode(val)); } } final List<String> allKeys = new ArrayList<>(); final Map<ChunkInfo, SimpleEntry<List<String>, byte[]>> responseMap = new HashMap<>(); for (Entry<String, CachedData> entry : metadataMap.entrySet()) { final String firstKey = entry.getKey(); final String metadata = (String) decodingTranscoder.decode(entry.getValue()); if (metadata == null) continue; final ChunkInfo ci = getChunkInfo(firstKey, metadata); if (ci != null) { final List<String> ciKeys = new ArrayList<>(); for (int i = 1; i < ci.getChunks(); i++) { final String prefix = (i < 10) ? "0" : ""; final String _key = ci.getKey() + "_" + prefix + i; allKeys.add(_key); ciKeys.add(_key); } final byte[] data = new byte[(ci.getChunks() - 2) * ci.getChunkSize() + ci.getLastChunk()]; responseMap.put(ci, new SimpleEntry<>(ciKeys, data)); } } return evcacheMemcachedClient.asyncGetBulk(allKeys, chunkingTranscoder, null) .getSome(bulkReadTimeout.get(), TimeUnit.MILLISECONDS, false, false, scheduler) .map(dataMap -> { for (Entry<ChunkInfo, SimpleEntry<List<String>, byte[]>> entry : responseMap.entrySet()) { final ChunkInfo ci = entry.getKey(); final SimpleEntry<List<String>, byte[]> pair = entry.getValue(); final List<String> ciKeys = pair.getKey(); byte[] data = pair.getValue(); int index = 0; for (int i = 0; i < ciKeys.size(); i++) { final String _key = ciKeys.get(i); final CachedData cd = dataMap.get(_key); if (log.isDebugEnabled()) log.debug("Chunk Key " + _key + "; Value : " + cd); if (cd == null) continue; final byte[] val = cd.getData(); if (val == null) { data = null; break; } final int len = (i == ciKeys.size() - 1) ? ((ci.getLastChunk() == 0 || ci.getLastChunk() > ci .getChunkSize()) ? ci.getChunkSize() : ci.getLastChunk()) : val.length; try { System.arraycopy(val, 0, data, index, len); } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.append("ArrayCopyError - Key : " + _key + "; final data Size : " + data.length + "; copy array size : " + len + "; val size : " + val.length + "; key index : " + i + "; copy from : " + index + "; ChunkInfo : " + ci + "\n"); for (int j = 0; j < ciKeys.size(); j++) { final String skey = ciKeys.get(j); final byte[] sval = dataMap.get(skey).getData(); sb.append(skey + "=" + sval.length + "\n"); } if (log.isWarnEnabled()) log.warn(sb.toString(), e); throw e; } index += val.length; } final boolean checksumPass = checkCRCChecksum(data, ci, hasZF); if (data != null && checksumPass) { final CachedData cd = new CachedData(ci.getFlags(), data, Integer.MAX_VALUE); returnMap.put(ci.getKey(), tc.decode(cd)); } else { returnMap.put(ci.getKey(), null); } } return returnMap; }); }); } private CachedData[] createChunks(CachedData cd, String key) { final int cSize = chunkSize.get(); if ((key.length() + 3) > cSize) throw new IllegalArgumentException("The chunksize " + cSize + " is smaller than the key size. Will not be able to proceed. key size = " + key.length()); final int len = cd.getData().length; /* the format of headers in memcached */ // Key size + 1 + Header( Flags (Characters Number) + Key (Characters Numbers) + 2 bytes ( \r\n ) + 4 bytes (2 spaces and 1 \r)) + Chunk Size + CAS Size // final int overheadSize = key.length() // Key Size // + 1 // Space // + 4 // Flags (Characters Number) // + 4 // Key (Characters Numbers) // + 2 // /r/n // + 4 // 2 spaces and 1 \r // + 48 // Header Size // + 8; // CAS final int overheadSize = key.length() + 71 + 3; // 3 because we will suffix _00, _01 ... _99; 68 is the size of the memcached header final int actualChunkSize = cSize - overheadSize; int lastChunkSize = len % actualChunkSize; final int numOfChunks = len / actualChunkSize + ((lastChunkSize > 0) ? 1 : 0) + 1; final CachedData[] chunkData = new CachedData[numOfChunks]; if (lastChunkSize == 0) lastChunkSize = actualChunkSize; final long sTime = System.nanoTime(); final Checksum checksum = new CRC32(); checksum.update(cd.getData(), 0, len); final long checkSumValue = checksum.getValue(); int srcPos = 0; if (log.isDebugEnabled()) log.debug("Ths size of data is " + len + " ; we will create " + (numOfChunks - 1) + " of " + actualChunkSize + " bytes. Checksum : " + checkSumValue + "; Checksum Duration : " + (System.nanoTime() - sTime)); chunkData[0] = decodingTranscoder.encode(numOfChunks + ":" + actualChunkSize + ":" + lastChunkSize + ":" + cd .getFlags() + ":" + checkSumValue); for (int i = 1; i < numOfChunks; i++) { int lengthOfArray = actualChunkSize; if (srcPos + actualChunkSize > len) { lengthOfArray = len - srcPos; } byte[] dest = new byte[actualChunkSize]; System.arraycopy(cd.getData(), srcPos, dest, 0, lengthOfArray); if (actualChunkSize > lengthOfArray) { for (int j = lengthOfArray; j < actualChunkSize; j++) { dest[j] = Character.UNASSIGNED;// Adding filler data } } srcPos += lengthOfArray; //chunkData[i] = decodingTranscoder.encode(dest); chunkData[i] = new CachedData(SPECIAL_BYTEARRAY, dest, Integer.MAX_VALUE); } EVCacheMetricsFactory.getInstance().getDistributionSummary(EVCacheMetricsFactory.INTERNAL_NUM_CHUNK_SIZE, getTagList()).record(numOfChunks); EVCacheMetricsFactory.getInstance().getDistributionSummary(EVCacheMetricsFactory.INTERNAL_CHUNK_DATA_SIZE, getTagList()).record(len); return chunkData; } /** * Retrieves all the chunks as is. This is mainly used for debugging. * * @param key * @return Returns all the chunks retrieved. * @throws EVCacheReadQueueException * @throws EVCacheException * @throws Exception */ public Map<String, CachedData> getAllChunks(String key) throws EVCacheReadQueueException, EVCacheException, Exception { try { final ChunkDetails<Object> cd = getChunkDetails(key); if(log.isDebugEnabled()) log.debug("Chunkdetails " + cd); if (cd == null) return null; if (!cd.isChunked()) { Map<String, CachedData> rv = new HashMap<String, CachedData>(); rv.put(key, (CachedData) cd.getData()); if(log.isDebugEnabled()) log.debug("Data : " + rv); return rv; } else { final List<String> keys = cd.getChunkKeys(); if(log.isDebugEnabled()) log.debug("Keys - " + keys); final Map<String, CachedData> dataMap = evcacheMemcachedClient.asyncGetBulk(keys, chunkingTranscoder, null) .getSome(readTimeout.get().intValue(), TimeUnit.MILLISECONDS, false, false); if(log.isDebugEnabled()) log.debug("Datamap " + dataMap); return dataMap; } } catch (Exception e) { log.error(e.getMessage(), e); } return null; } public long incr(String key, long by, long defaultVal, int timeToLive) throws EVCacheException { return evcacheMemcachedClient.incr(key, by, defaultVal, timeToLive); } public long decr(String key, long by, long defaultVal, int timeToLive) throws EVCacheException { return evcacheMemcachedClient.decr(key, by, defaultVal, timeToLive); } public <T> CompletableFuture<T> getAsync(String key, Transcoder<T> tc) { if(log.isDebugEnabled()) log.debug("fetching data getAsync {}", key); return evcacheMemcachedClient .asyncGet(key, tc, null) .getAsync(readTimeout.get(), TimeUnit.MILLISECONDS); } public <T> T get(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF, boolean chunked) throws Exception { if (chunked) { return assembleChunks(key, false, 0, tc, hasZF); } else { return evcacheMemcachedClient.asyncGet(key, tc, null).get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF); } } public <T> T get(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF) throws Exception { if (!validateNode(key, _throwException, Call.GET)) { if(ignoreInactiveNodes.get()) { incrementFailure(EVCacheMetricsFactory.IGNORE_INACTIVE_NODES, Call.GET); return pool.getEVCacheClientForReadExclude(serverGroup).get(key, tc, _throwException, hasZF, enableChunking.get()); } else { return null; } } return get(key, tc, _throwException, hasZF, enableChunking.get()); } public <T> Single<T> get(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF, boolean chunked, Scheduler scheduler) throws Exception { if (chunked) { return assembleChunks(key, _throwException, 0, tc, hasZF, scheduler); } else { return evcacheMemcachedClient.asyncGet(key, tc, null) .get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF, scheduler); } } public <T> Single<T> get(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF, Scheduler scheduler) { try { if (!validateNode(key, _throwException, Call.GET)) { if(ignoreInactiveNodes.get()) { incrementFailure(EVCacheMetricsFactory.IGNORE_INACTIVE_NODES, Call.GET); return pool.getEVCacheClientForReadExclude(serverGroup).get(key, tc, _throwException, hasZF, enableChunking.get(), scheduler); } else { return Single.just(null); } } return get(key, tc, _throwException, hasZF, enableChunking.get(), scheduler); } catch (Throwable e) { return Single.error(e); } } public <T> T getAndTouch(String key, Transcoder<T> tc, int timeToLive, boolean _throwException, boolean hasZF) throws Exception { EVCacheMemcachedClient _client = evcacheMemcachedClient; if (!validateNode(key, _throwException, Call.GET_AND_TOUCH)) { if(ignoreInactiveNodes.get()) { incrementFailure(EVCacheMetricsFactory.IGNORE_INACTIVE_NODES, Call.GET_AND_TOUCH); _client = pool.getEVCacheClientForReadExclude(serverGroup).getEVCacheMemcachedClient(); } else { return null; } } if (tc == null) tc = (Transcoder<T>) getTranscoder(); final T returnVal; if (enableChunking.get()) { return assembleChunks(key, false, 0, tc, hasZF); } else { if(ignoreTouch.get()) { returnVal = _client.asyncGet(key, tc, null).get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF); } else { final CASValue<T> value = _client.asyncGetAndTouch(key, timeToLive, tc).get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF); returnVal = (value == null) ? null : value.getValue(); } } return returnVal; } public <T> Single<T> getAndTouch(String key, Transcoder<T> transcoder, int timeToLive, boolean _throwException, boolean hasZF, Scheduler scheduler) { try { EVCacheMemcachedClient client = evcacheMemcachedClient; if (!validateNode(key, _throwException, Call.GET_AND_TOUCH)) { if(ignoreInactiveNodes.get()) { incrementFailure(EVCacheMetricsFactory.IGNORE_INACTIVE_NODES, Call.GET_AND_TOUCH); client = pool.getEVCacheClientForReadExclude(serverGroup).getEVCacheMemcachedClient(); } else { return null; } } final EVCacheMemcachedClient _client = client; final Transcoder<T> tc = (transcoder == null) ? (Transcoder<T>) getTranscoder(): transcoder; if (enableChunking.get()) { return assembleChunks(key, false, 0, tc, hasZF, scheduler); } else { return _client.asyncGetAndTouch(key, timeToLive, tc) .get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF, scheduler) .map(value -> (value == null) ? null : value.getValue()); } } catch (Throwable e) { return Single.error(e); } } public <T> Map<String, T> getBulk(Collection<String> _canonicalKeys, Transcoder<T> tc, boolean _throwException, boolean hasZF) throws Exception { final Collection<String> canonicalKeys = validateReadQueueSize(_canonicalKeys, Call.BULK); final Map<String, T> returnVal; try { if (tc == null) tc = (Transcoder<T>) getTranscoder(); if (enableChunking.get()) { returnVal = assembleChunks(_canonicalKeys, tc, hasZF); } else { returnVal = evcacheMemcachedClient.asyncGetBulk(canonicalKeys, tc, null) .getSome(bulkReadTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF); } } catch (Exception e) { if (_throwException) throw e; return Collections.<String, T> emptyMap(); } return returnVal; } public <T> CompletableFuture<Map<String, T>> getAsyncBulk(Collection<String> _canonicalKeys, Transcoder<T> tc) { final Collection<String> canonicalKeys = validateReadQueueSize(_canonicalKeys, Call.COMPLETABLE_FUTURE_GET_BULK); if (tc == null) tc = (Transcoder<T>) getTranscoder(); return evcacheMemcachedClient .asyncGetBulk(canonicalKeys, tc, null) .getAsyncSome(bulkReadTimeout.get(), TimeUnit.MILLISECONDS); } public <T> Single<Map<String, T>> getBulk(Collection<String> _canonicalKeys, final Transcoder<T> transcoder, boolean _throwException, boolean hasZF, Scheduler scheduler) { try { final Collection<String> canonicalKeys = validateReadQueueSize(_canonicalKeys, Call.BULK); final Transcoder<T> tc = (transcoder == null) ? (Transcoder<T>) getTranscoder() : transcoder; if (enableChunking.get()) { return assembleChunks(_canonicalKeys, tc, hasZF, scheduler); } else { return evcacheMemcachedClient.asyncGetBulk(canonicalKeys, tc, null) .getSome(bulkReadTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF, scheduler); } } catch (Throwable e) { return Single.error(e); } } public <T> Future<Boolean> append(String key, T value) throws Exception { if (enableChunking.get()) throw new EVCacheException( "This operation is not supported as chunking is enabled on this EVCacheClient."); final MemcachedNode node = evcacheMemcachedClient.getEVCacheNode(key); if (!ensureWriteQueueSize(node, key, Call.APPEND)) return getDefaultFuture(); return evcacheMemcachedClient.append(key, value); } public Future<Boolean> set(String key, CachedData value, int timeToLive) throws Exception { return _set(key, value, timeToLive, null); } public Future<Boolean> set(String key, CachedData cd, int timeToLive, EVCacheLatch evcacheLatch) throws Exception { return _set(key, cd, timeToLive, evcacheLatch); } @Deprecated public <T> Future<Boolean> set(String key, T value, int timeToLive) throws Exception { return set(key, value, timeToLive, null); } @Deprecated public <T> Future<Boolean> set(String key, T value, int timeToLive, EVCacheLatch evcacheLatch) throws Exception { final CachedData cd; if (value instanceof CachedData) { cd = (CachedData) value; } else { cd = getTranscoder().encode(value); } return _set(key, cd, timeToLive, evcacheLatch); } private Future<Boolean> _set(String key, CachedData value, int timeToLive, EVCacheLatch evcacheLatch) throws Exception { final MemcachedNode node = evcacheMemcachedClient.getEVCacheNode(key); if (!ensureWriteQueueSize(node, key, Call.SET)) { if (log.isInfoEnabled()) log.info("Node : " + node + " is not active. Failing fast and dropping the write event."); final ListenableFuture<Boolean, OperationCompletionListener> defaultFuture = (ListenableFuture<Boolean, OperationCompletionListener>) getDefaultFuture(); if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl && !isInWriteOnly()) ((EVCacheLatchImpl) evcacheLatch).addFuture(defaultFuture); return defaultFuture; } try { final int dataSize = ((CachedData) value).getData().length; if (enableChunking.get()) { if (dataSize > chunkSize.get()) { final CachedData[] cd = createChunks(value, key); final int len = cd.length; final OperationFuture<Boolean>[] futures = new OperationFuture[len]; for (int i = 0; i < cd.length; i++) { final String prefix = (i < 10) ? "0" : ""; futures[i] = evcacheMemcachedClient.set(key + "_" + prefix + i, timeToLive, cd[i], null, null); } // ensure we are deleting the unchunked key if it exists. // Ignore return value since it may not exist. evcacheMemcachedClient.delete(key); return new EVCacheFutures(futures, key, appName, serverGroup, evcacheLatch); } else { // delete all the chunks if they exist as the // data is moving from chunked to unchunked delete(key); return evcacheMemcachedClient.set(key, timeToLive, value, null, evcacheLatch); } } else { return evcacheMemcachedClient.set(key, timeToLive, value, null, evcacheLatch); } } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } private Boolean shouldHashKey() { return hashKeyByServerGroup.get(); } public HashingAlgorithm getHashingAlgorithm() { if (null == shouldHashKey()) { // hash key property is not set at the client level return null; } // return NO_HASHING if hashing is explicitly disabled at client level return shouldHashKey() ? KeyHasher.getHashingAlgorithmFromString(hashingAlgo.get()) : HashingAlgorithm.NO_HASHING; } public <T> Future<Boolean> appendOrAdd(String key, CachedData value, int timeToLive, EVCacheLatch evcacheLatch) throws Exception { final MemcachedNode node = evcacheMemcachedClient.getEVCacheNode(key); if (!ensureWriteQueueSize(node, key, Call.APPEND_OR_ADD)) { if (log.isInfoEnabled()) log.info("Node : " + node + " is not active. Failing fast and dropping the write event."); final ListenableFuture<Boolean, OperationCompletionListener> defaultFuture = (ListenableFuture<Boolean, OperationCompletionListener>) getDefaultFuture(); if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl && !isInWriteOnly()) ((EVCacheLatchImpl) evcacheLatch).addFuture(defaultFuture); return defaultFuture; } try { return evcacheMemcachedClient.asyncAppendOrAdd(key, timeToLive, value, evcacheLatch); } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } public Future<Boolean> replace(String key, CachedData cd, int timeToLive, EVCacheLatch evcacheLatch) throws Exception { return _replace(key, cd, timeToLive, evcacheLatch); } @Deprecated public <T> Future<Boolean> replace(String key, T value, int timeToLive, EVCacheLatch evcacheLatch) throws Exception { final CachedData cd; if (value instanceof CachedData) { cd = (CachedData) value; } else { cd = getTranscoder().encode(value); } return _replace(key, cd, timeToLive, evcacheLatch); } private Future<Boolean> _replace(String key, CachedData value, int timeToLive, EVCacheLatch evcacheLatch) throws Exception { final MemcachedNode node = evcacheMemcachedClient.getEVCacheNode(key); if (!ensureWriteQueueSize(node, key, Call.REPLACE)) { if (log.isInfoEnabled()) log.info("Node : " + node + " is not active. Failing fast and dropping the replace event."); final ListenableFuture<Boolean, OperationCompletionListener> defaultFuture = (ListenableFuture<Boolean, OperationCompletionListener>) getDefaultFuture(); if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl && !isInWriteOnly()) ((EVCacheLatchImpl) evcacheLatch).addFuture(defaultFuture); return defaultFuture; } try { final int dataSize = ((CachedData) value).getData().length; if (enableChunking.get() && dataSize > chunkSize.get()) { final CachedData[] cd = createChunks(value, key); final int len = cd.length; final OperationFuture<Boolean>[] futures = new OperationFuture[len]; for (int i = 0; i < cd.length; i++) { final String prefix = (i < 10) ? "0" : ""; futures[i] = evcacheMemcachedClient.replace(key + "_" + prefix + i, timeToLive, cd[i], null, null); } return new EVCacheFutures(futures, key, appName, serverGroup, evcacheLatch); } else { return evcacheMemcachedClient.replace(key, timeToLive, value, null, evcacheLatch); } } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } private Future<Boolean> _add(String key, int exp, CachedData value, EVCacheLatch latch) throws Exception { if (enableChunking.get()) throw new EVCacheException("This operation is not supported as chunking is enabled on this EVCacheClient."); final MemcachedNode node = evcacheMemcachedClient.getEVCacheNode(key); if (!ensureWriteQueueSize(node, key, Call.ADD)) return getDefaultFuture(); return evcacheMemcachedClient.add(key, exp, value, null, latch); } @Deprecated public <T> Future<Boolean> add(String key, int exp, T value) throws Exception { final CachedData cd; if (value instanceof CachedData) { cd = (CachedData) value; } else { cd = getTranscoder().encode(value); } return _add(key, exp, cd, null); } @Deprecated public <T> Future<Boolean> add(String key, int exp, T value, Transcoder<T> tc) throws Exception { final CachedData cd; if (value instanceof CachedData) { cd = (CachedData) value; } else { if(tc == null) { cd = getTranscoder().encode(value); } else { cd = tc.encode(value); } } return _add(key, exp, cd, null); } @Deprecated public <T> Future<Boolean> add(String key, int exp, T value, final Transcoder<T> tc, EVCacheLatch latch) throws Exception { final CachedData cd; if (value instanceof CachedData) { cd = (CachedData) value; } else { if(tc == null) { cd = getTranscoder().encode(value); } else { cd = tc.encode(value); } } return _add(key, exp, cd, latch); } public Future<Boolean> add(String key, int exp, CachedData value, EVCacheLatch latch) throws Exception { return _add(key, exp, value, latch); } public <T> Future<Boolean> touch(String key, int timeToLive) throws Exception { return touch(key, timeToLive, null); } public <T> Future<Boolean> touch(String key, int timeToLive, EVCacheLatch latch) throws Exception { if(ignoreTouch.get()) { final ListenableFuture<Boolean, OperationCompletionListener> sf = new SuccessFuture(); if (latch != null && latch instanceof EVCacheLatchImpl && !isInWriteOnly()) ((EVCacheLatchImpl) latch).addFuture(sf); return sf; } final MemcachedNode node = evcacheMemcachedClient.getEVCacheNode(key); if (!ensureWriteQueueSize(node, key, Call.TOUCH)) { final ListenableFuture<Boolean, OperationCompletionListener> defaultFuture = (ListenableFuture<Boolean, OperationCompletionListener>) getDefaultFuture(); if (latch != null && latch instanceof EVCacheLatchImpl && !isInWriteOnly()) ((EVCacheLatchImpl) latch).addFuture(defaultFuture); return defaultFuture; } if (enableChunking.get()) { final ChunkDetails<?> cd = getChunkDetails(key); if (cd.isChunked()) { final List<String> keys = cd.getChunkKeys(); OperationFuture<Boolean>[] futures = new OperationFuture[keys.size() + 1]; futures[0] = evcacheMemcachedClient.touch(key + "_00", timeToLive, latch); for (int i = 0; i < keys.size(); i++) { final String prefix = (i < 10) ? "0" : ""; final String _key = key + "_" + prefix + i; futures[i + 1] = evcacheMemcachedClient.touch(_key, timeToLive, latch); } return new EVCacheFutures(futures, key, appName, serverGroup, latch); } else { return evcacheMemcachedClient.touch(key, timeToLive, latch); } } else { return evcacheMemcachedClient.touch(key, timeToLive, latch); } } public <T> Future<T> asyncGet(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF) throws Exception { if (enableChunking.get()) throw new EVCacheException( "This operation is not supported as chunking is enabled on this EVCacheClient."); if (!validateNode(key, _throwException, Call.ASYNC_GET)) return null; if (tc == null) tc = (Transcoder<T>) getTranscoder(); return evcacheMemcachedClient.asyncGet(key, tc, null); } public Future<Boolean> delete(String key) throws Exception { return delete(key, null); } public Future<Boolean> delete(String key, EVCacheLatch latch) throws Exception { final MemcachedNode node = evcacheMemcachedClient.getEVCacheNode(key); if (!ensureWriteQueueSize(node, key, Call.DELETE)) { final ListenableFuture<Boolean, OperationCompletionListener> defaultFuture = (ListenableFuture<Boolean, OperationCompletionListener>) getDefaultFuture(); if (latch != null && latch instanceof EVCacheLatchImpl && !isInWriteOnly()) ((EVCacheLatchImpl) latch).addFuture(defaultFuture); return defaultFuture; } if (enableChunking.get()) { final ChunkDetails<?> cd = getChunkDetails(key); if (cd == null) { // Paranoid delete : cases where get fails and we ensure the first key is deleted just in case return evcacheMemcachedClient.delete(key + "_00", latch); } if (!cd.isChunked()) { return evcacheMemcachedClient.delete(key, latch); } else { final List<String> keys = cd.getChunkKeys(); OperationFuture<Boolean>[] futures = new OperationFuture[keys.size() + 1]; futures[0] = evcacheMemcachedClient.delete(key + "_00"); for (int i = 0; i < keys.size(); i++) { futures[i + 1] = evcacheMemcachedClient.delete(keys.get(i), null); } return new EVCacheFutures(futures, key, appName, serverGroup, latch); } } else { return evcacheMemcachedClient.delete(key, latch); } } public boolean removeConnectionObserver() { try { boolean removed = evcacheMemcachedClient.removeObserver(connectionObserver); if (removed) connectionObserver = null; return removed; } catch (Exception e) { return false; } } public boolean shutdown(long timeout, TimeUnit unit) { if(shutdown) return true; shutdown = true; try { evcacheMemcachedClient.shutdown(timeout, unit); } catch(Throwable t) { log.error("Exception while shutting down", t); } return true; } public EVCacheConnectionObserver getConnectionObserver() { return this.connectionObserver; } public ConnectionFactory getConnectionFactory() { return connectionFactory; } public String getAppName() { return appName; } public String getZone() { return zone; } public int getId() { return id; } public ServerGroup getServerGroup() { return serverGroup; } public String getServerGroupName() { return (serverGroup == null ? "NA" : serverGroup.getName()); } public boolean isShutdown() { return this.shutdown; } public boolean isInWriteOnly(){ return pool.isInWriteOnly(getServerGroup()); } public Map<SocketAddress, Map<String, String>> getStats(String cmd) { return evcacheMemcachedClient.getStats(cmd); } public Map<SocketAddress, String> execCmd(String cmd, String[] ips) { return evcacheMemcachedClient.execCmd(cmd, ips); } public Map<SocketAddress, String> getVersions() { return evcacheMemcachedClient.getVersions(); } public Future<Boolean> flush() { return evcacheMemcachedClient.flush(); } public Transcoder<Object> getTranscoder() { return evcacheMemcachedClient.getTranscoder(); } public ConnectionFactory getEVCacheConnectionFactory() { return this.connectionFactory; } public NodeLocator getNodeLocator() { return this.evcacheMemcachedClient.getNodeLocator(); } static class SuccessFuture implements ListenableFuture<Boolean, OperationCompletionListener> { @Override public boolean cancel(boolean mayInterruptIfRunning) { return true; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public Boolean get() throws InterruptedException, ExecutionException { return Boolean.TRUE; } @Override public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return Boolean.TRUE; } @Override public Future<Boolean> addListener(OperationCompletionListener listener) { return this; } @Override public Future<Boolean> removeListener(OperationCompletionListener listener) { return this; } } static class DefaultFuture implements ListenableFuture<Boolean, OperationCompletionListener> { public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public Boolean get() throws InterruptedException, ExecutionException { return Boolean.FALSE; } @Override public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return Boolean.FALSE; } @Override public Future<Boolean> addListener(OperationCompletionListener listener) { return this; } @Override public Future<Boolean> removeListener(OperationCompletionListener listener) { return this; } } private Future<Boolean> getDefaultFuture() { final Future<Boolean> defaultFuture = new DefaultFuture(); return defaultFuture; } public String toString() { return "App : " + appName + "; Zone : " + zone + "; Id : " + id + "; " + serverGroup.toString() + "; Nodes : " + memcachedNodesInZone.toString(); } public EVCacheMemcachedClient getEVCacheMemcachedClient() { return evcacheMemcachedClient; } public List<InetSocketAddress> getMemcachedNodesInZone() { return memcachedNodesInZone; } public int getMaxWriteQueueSize() { return maxWriteQueueSize; } public Property<Integer> getReadTimeout() { return readTimeout; } public Property<Integer> getBulkReadTimeout() { return bulkReadTimeout; } public Property<Integer> getMaxReadQueueSize() { return maxReadQueueSize; } public Property<Boolean> getEnableChunking() { return enableChunking; } public Property<Integer> getChunkSize() { return chunkSize; } public ChunkTranscoder getChunkingTranscoder() { return chunkingTranscoder; } public EVCacheSerializingTranscoder getDecodingTranscoder() { return decodingTranscoder; } public EVCacheClientPool getPool() { return pool; } public EVCacheServerGroupConfig getEVCacheConfig() { return config; } static class ChunkDetails<T> { final List<String> chunkKeys; final ChunkInfo chunkInfo; final boolean chunked; final T data; public ChunkDetails(List<String> chunkKeys, ChunkInfo chunkInfo, boolean chunked, T data) { super(); this.chunkKeys = chunkKeys; this.chunkInfo = chunkInfo; this.chunked = chunked; this.data = data; } public List<String> getChunkKeys() { return chunkKeys; } public ChunkInfo getChunkInfo() { return chunkInfo; } public boolean isChunked() { return chunked; } public T getData() { return data; } @Override public String toString() { return "ChunkDetails [chunkKeys=" + chunkKeys + ", chunkInfo=" + chunkInfo + ", chunked=" + chunked + ", data=" + data + "]"; } } static class ChunkInfo { final int chunks; final int chunkSize; final int lastChunk; final int flags; final String key; final long checksum; public ChunkInfo(int chunks, int chunkSize, int lastChunk, int flags, String firstKey, long checksum) { super(); this.chunks = chunks; this.chunkSize = chunkSize; this.lastChunk = lastChunk; this.flags = flags; this.key = firstKey; this.checksum = checksum; } public int getChunks() { return chunks; } public int getChunkSize() { return chunkSize; } public int getLastChunk() { return lastChunk; } public int getFlags() { return flags; } public String getKey() { return key; } public long getChecksum() { return checksum; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{\"chunks\":\""); builder.append(chunks); builder.append("\",\"chunkSize\":\""); builder.append(chunkSize); builder.append("\",\"lastChunk\":\""); builder.append(lastChunk); builder.append("\",\"flags\":\""); builder.append(flags); builder.append("\",\"key\":\""); builder.append(key); builder.append("\",\"checksum\":\""); builder.append(checksum); builder.append("\"}"); return builder.toString(); } } public int getWriteQueueLength() { final Collection<MemcachedNode> allNodes = evcacheMemcachedClient.getNodeLocator().getAll(); int size = 0; for(MemcachedNode node : allNodes) { if(node instanceof EVCacheNode) { size += ((EVCacheNode)node).getWriteQueueSize(); } } return size; } public int getReadQueueLength() { final Collection<MemcachedNode> allNodes = evcacheMemcachedClient.getNodeLocator().getAll(); int size = 0; for(MemcachedNode node : allNodes) { if(node instanceof EVCacheNode) { size += ((EVCacheNode)node).getReadQueueSize(); } } return size; } public List<Tag> getTagList() { return tags; } public Counter getOperationCounter() { return operationsCounter; } /** * Return the keys upto the limit. The key will be cannoicalized key( or hashed Key).<br> * <B> The keys are read into memory so make sure you have enough memory to read the specified number of keys<b> * @param limit - The number of keys that need to fetched from each memcached clients. * @return - the List of keys. */ public List<String> getAllKeys(final int limit) { final List<String> keyList = new ArrayList<String>(limit); byte[] array = new byte[EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".all.keys.reader.buffer.size.bytes", Integer.class).orElse(4*1024*1024).get()]; final int waitInSec = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".all.keys.reader.wait.duration.sec", Integer.class).orElse(60).get(); for(InetSocketAddress address : memcachedNodesInZone) { //final List<String> keyList = new ArrayList<String>(limit); Socket socket = null; PrintWriter printWriter = null; BufferedInputStream bufferedReader = null; try { socket = new Socket(address.getHostName(), address.getPort()); printWriter = new PrintWriter(socket.getOutputStream(), true); printWriter.print("lru_crawler metadump all \r\n"); printWriter.print("quit \r\n"); printWriter.flush(); bufferedReader = new BufferedInputStream(socket.getInputStream()); while(isDataAvailableForRead(bufferedReader, waitInSec, TimeUnit.SECONDS, socket)) { int read = bufferedReader.read(array); if (log.isDebugEnabled()) log.debug("Number of bytes read = " +read); if(read > 0) { StringBuilder b = new StringBuilder(); boolean start = true; for (int i = 0; i < read; i++) { if(array[i] == ' ') { start = false; if(b.length() > 4) keyList.add(URLDecoder.decode(b.substring(4), StandardCharsets.UTF_8.name())); b = new StringBuilder(); } if(start) b.append((char)array[i]); if(array[i] == '\n') { start = true; } if(keyList.size() >= limit) { if (log.isDebugEnabled()) log.debug("Record Limit reached. Will break and return"); return keyList; } } } else if (read < 0 ){ break; } } } catch (Exception e) { if(socket != null) { try { socket.close(); } catch (IOException e1) { log.error("Error closing socket", e1); } } log.error("Exception", e); } finally { if(bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e1) { log.error("Error closing bufferedReader", e1); } } if(printWriter != null) { try { printWriter.close(); } catch (Exception e1) { log.error("Error closing socket", e1); } } if(socket != null) { try { socket.close(); } catch (IOException e) { if (log.isDebugEnabled()) log.debug("Error closing socket", e); } } } } return keyList; } private boolean isDataAvailableForRead(BufferedInputStream bufferedReader, long timeout, TimeUnit unit, Socket socket) throws IOException { long expiry = System.currentTimeMillis() + unit.toMillis(timeout); int tryCount = 0; while(expiry > System.currentTimeMillis()) { if(log.isDebugEnabled()) log.debug("For Socket " + socket + " number of bytes available = " + bufferedReader.available() + " and try number is " + tryCount); if(bufferedReader.available() > 0) { return true; } if(tryCount++ < 5) { try { if(log.isDebugEnabled()) log.debug("Sleep for 100 msec"); Thread.sleep(100); } catch (InterruptedException e) { } } else { return false; } } return false; } public EVCacheItemMetaData metaDebug(String key) throws Exception { final EVCacheItemMetaData obj = evcacheMemcachedClient.metaDebug(key); if(log.isDebugEnabled()) log.debug("EVCacheItemMetaData : " + obj); return obj; } public <T> EVCacheItem<T> metaGet(String key, Transcoder<T> tc, boolean _throwException, boolean hasZF) throws Exception { final EVCacheItem<T> obj = evcacheMemcachedClient.asyncMetaGet(key, tc, null).get(readTimeout.get(), TimeUnit.MILLISECONDS, _throwException, hasZF); if (log.isDebugEnabled()) log.debug("EVCacheItem : " + obj); return obj; } public void addTag(String tagName, String tagValue) { final Tag tag = new BasicTag(tagName, tagValue); if(tags.contains(tag)) return; final List<Tag> tagList = new ArrayList<Tag>(tags); tagList.add(tag); this.tags = Collections.<Tag>unmodifiableList(new ArrayList(tagList)); } }
80,890
44.572394
223
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/pool/EVCacheClientPoolManager.java
package com.netflix.evcache.pool; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.archaius.api.Property; import com.netflix.evcache.EVCacheImpl; import com.netflix.evcache.EVCacheInMemoryCache; import com.netflix.evcache.connection.ConnectionFactoryBuilder; import com.netflix.evcache.connection.IConnectionBuilder; import com.netflix.evcache.event.EVCacheEventListener; import com.netflix.evcache.util.EVCacheConfig; import net.spy.memcached.transcoders.Transcoder; /** * A manager that holds Pools for each EVCache app. When this class is * initialized all the EVCache apps defined in the property evcache.appsToInit * will be initialized and added to the pool. If a service knows all the EVCache * app it uses, then it can define this property and pass a list of EVCache apps * that needs to be initialized. * * An EVCache app can also be initialized by Injecting * <code>EVCacheClientPoolManager</code> and calling <code> * initEVCache(<app name>) * </code> * * This typically should be done in the client libraries that need to initialize * an EVCache app. For Example VHSViewingHistoryLibrary in its initLibrary * initializes EVCACHE_VH by calling * * <pre> * {@literal @}Inject * public VHSViewingHistoryLibrary(EVCacheClientPoolManager instance,...) { * .... * instance.initEVCache("EVCACHE_VH"); * ... * } * </pre> * * @author smadappa * */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS", "DM_CONVERT_CASE", "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" }) @Singleton public class EVCacheClientPoolManager { /** * <b>NOTE : Should be the only static referenced variables</b> * **/ private static final Logger log = LoggerFactory.getLogger(EVCacheClientPoolManager.class); private volatile static EVCacheClientPoolManager instance; private final Property<Integer> defaultReadTimeout; private final Property<String> logEnabledApps; private final Property<Integer> defaultRefreshInterval; private final Map<String, EVCacheClientPool> poolMap = new ConcurrentHashMap<String, EVCacheClientPool>(); private final Map<EVCacheClientPool, ScheduledFuture<?>> scheduledTaskMap = new HashMap<EVCacheClientPool, ScheduledFuture<?>>(); private final EVCacheScheduledExecutor asyncExecutor; private final EVCacheExecutor syncExecutor; private final List<EVCacheEventListener> evcacheEventListenerList; private final IConnectionBuilder connectionFactoryProvider; private final EVCacheNodeList evcacheNodeList; private final EVCacheConfig evcConfig; @Inject public EVCacheClientPoolManager(IConnectionBuilder connectionFactoryprovider, EVCacheNodeList evcacheNodeList, EVCacheConfig evcConfig) { instance = this; this.connectionFactoryProvider = connectionFactoryprovider; this.evcacheNodeList = evcacheNodeList; this.evcConfig = evcConfig; this.evcacheEventListenerList = new CopyOnWriteArrayList<EVCacheEventListener>(); String clientCurrentInstanceId = null; if(clientCurrentInstanceId == null) clientCurrentInstanceId= System.getenv("EC2_INSTANCE_ID"); if(clientCurrentInstanceId == null) clientCurrentInstanceId= System.getenv("NETFLIX_INSTANCE_ID"); if(log.isInfoEnabled()) log.info("\nClient Current InstanceId from env = " + clientCurrentInstanceId); if(clientCurrentInstanceId == null && EVCacheConfig.getInstance().getPropertyRepository() != null) clientCurrentInstanceId = EVCacheConfig.getInstance().getPropertyRepository().get("EC2_INSTANCE_ID", String.class).orElse(null).get(); if(clientCurrentInstanceId == null && EVCacheConfig.getInstance().getPropertyRepository() != null) clientCurrentInstanceId = EVCacheConfig.getInstance().getPropertyRepository().get("NETFLIX_INSTANCE_ID", String.class).orElse(null).get(); if(clientCurrentInstanceId != null && !clientCurrentInstanceId.equalsIgnoreCase("localhost")) { this.defaultReadTimeout = EVCacheConfig.getInstance().getPropertyRepository().get("default.read.timeout", Integer.class).orElse(20); if(log.isInfoEnabled()) log.info("\nClient Current InstanceId = " + clientCurrentInstanceId + " which is probably a cloud location. The default.read.timeout = " + defaultReadTimeout); } else { //Assuming this is not in cloud so bump up the timeouts this.defaultReadTimeout = EVCacheConfig.getInstance().getPropertyRepository().get("default.read.timeout", Integer.class).orElse(750); if(log.isInfoEnabled()) log.info("\n\nClient Current InstanceId = " + clientCurrentInstanceId + ". Probably a non-cloud instance. The default.read.timeout = " + defaultReadTimeout + "\n\n"); } this.logEnabledApps = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheClientPoolManager.log.apps", String.class).orElse("*"); this.defaultRefreshInterval = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheClientPoolManager.refresh.interval", Integer.class).orElse(60); this.asyncExecutor = new EVCacheScheduledExecutor(Runtime.getRuntime().availableProcessors(),Runtime.getRuntime().availableProcessors(), 30, TimeUnit.SECONDS, new ThreadPoolExecutor.CallerRunsPolicy(), "scheduled"); asyncExecutor.prestartAllCoreThreads(); this.syncExecutor = new EVCacheExecutor(Runtime.getRuntime().availableProcessors(),Runtime.getRuntime().availableProcessors(), 30, TimeUnit.SECONDS, new ThreadPoolExecutor.CallerRunsPolicy(), "pool"); syncExecutor.prestartAllCoreThreads(); initAtStartup(); } public IConnectionBuilder getConnectionFactoryProvider() { return connectionFactoryProvider; } public void addEVCacheEventListener(EVCacheEventListener listener) { this.evcacheEventListenerList.add(listener); } public void addEVCacheEventListener(EVCacheEventListener listener, int index) { if(index < evcacheEventListenerList.size()) { this.evcacheEventListenerList.add(index, listener); } else { this.evcacheEventListenerList.add(listener); } } public void removeEVCacheEventListener(EVCacheEventListener listener) { this.evcacheEventListenerList.remove(listener); } public List<EVCacheEventListener> getEVCacheEventListeners() { return this.evcacheEventListenerList; } public EVCacheConfig getEVCacheConfig() { return this.evcConfig; } /** * @deprecated. Please use DependencyInjection (@Inject) to obtain * {@link EVCacheClientPoolManager}. The use of this can result in * unintended behavior where you will not be able to talk to evcache * instances. */ @Deprecated public static EVCacheClientPoolManager getInstance() { if (instance == null) { new EVCacheClientPoolManager(new ConnectionFactoryBuilder(), new SimpleNodeListProvider(), EVCacheConfig.getInstance()); if (!EVCacheConfig.getInstance().getPropertyRepository().get("evcache.use.simple.node.list.provider", Boolean.class).orElse(false).get()) { if(log.isDebugEnabled()) log.debug("Please make sure EVCacheClientPoolManager is injected first. This is not the appropriate way to init EVCacheClientPoolManager." + " If you are using simple node list provider please set evcache.use.simple.node.list.provider property to true.", new Exception()); } } return instance; } public void initAtStartup() { final String appsToInit = EVCacheConfig.getInstance().getPropertyRepository().get("evcache.appsToInit", String.class).orElse("").get(); if (appsToInit != null && appsToInit.length() > 0) { final StringTokenizer apps = new StringTokenizer(appsToInit, ","); while (apps.hasMoreTokens()) { final String app = getAppName(apps.nextToken()); if (log.isDebugEnabled()) log.debug("Initializing EVCache - " + app); initEVCache(app); } } } /** * Will init the given EVCache app call. If one is already initialized for * the given app method returns without doing anything. * * @param app * - name of the evcache app */ public final synchronized EVCacheClientPool initEVCache(String app) { return initEVCache(app, false); } public final synchronized EVCacheClientPool initEVCache(String app, boolean isDuet) { if (app == null || (app = app.trim()).length() == 0) throw new IllegalArgumentException("param app name null or space"); final String APP = getAppName(app); if (poolMap.containsKey(APP)) return poolMap.get(APP); final EVCacheClientPool pool = new EVCacheClientPool(APP, evcacheNodeList, asyncExecutor, this, isDuet); scheduleRefresh(pool); poolMap.put(APP, pool); return pool; } private void scheduleRefresh(EVCacheClientPool pool) { final ScheduledFuture<?> task = asyncExecutor.scheduleWithFixedDelay(pool, 30, defaultRefreshInterval.get(), TimeUnit.SECONDS); scheduledTaskMap.put(pool, task); } /** * Given the appName get the EVCacheClientPool. If the app is already * created then will return the existing instance. If not one will be * created and returned. * * @param _app * - name of the evcache app * @return the Pool for the give app. * @throws IOException */ public EVCacheClientPool getEVCacheClientPool(String _app) { final String app = getAppName(_app); final EVCacheClientPool evcacheClientPool = poolMap.get(app); if (evcacheClientPool != null) return evcacheClientPool; initEVCache(app); return poolMap.get(app); } public Map<String, EVCacheClientPool> getAllEVCacheClientPool() { return new HashMap<String, EVCacheClientPool>(poolMap); } @PreDestroy public void shutdown() { asyncExecutor.shutdown(); syncExecutor.shutdown(); for (EVCacheClientPool pool : poolMap.values()) { pool.shutdown(); } } public boolean shouldLog(String appName) { if ("*".equals(logEnabledApps.get())) return true; if (logEnabledApps.get().indexOf(appName) != -1) return true; return false; } public Property<Integer> getDefaultReadTimeout() { return defaultReadTimeout; } public Property<Integer> getDefaultRefreshInterval() { return defaultRefreshInterval; } public EVCacheScheduledExecutor getEVCacheScheduledExecutor() { return asyncExecutor; } public EVCacheExecutor getEVCacheExecutor() { return syncExecutor; } private String getAppName(String _app) { _app = _app.toUpperCase(); Boolean ignoreAlias = EVCacheConfig.getInstance().getPropertyRepository() .get("EVCacheClientPoolManager." + _app + ".ignoreAlias", Boolean.class) .orElseGet("EVCacheClientPoolManager.ignoreAlias") .orElse(false).get(); final String app = ignoreAlias ? _app : EVCacheConfig.getInstance().getPropertyRepository() .get("EVCacheClientPoolManager." + _app + ".alias", String.class) .orElse(_app).get().toUpperCase(); if (log.isDebugEnabled()) log.debug("Original App Name : " + _app + "; Alias App Name : " + app); if(app != null && app.length() > 0) return app.toUpperCase(); return _app; } private WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); private final Map<String, EVCacheInMemoryCache<?>> inMemoryMap = new ConcurrentHashMap<String, EVCacheInMemoryCache<?>>(); @SuppressWarnings("unchecked") public <T> EVCacheInMemoryCache<T> createInMemoryCache(Transcoder<T> tc, EVCacheImpl impl) { final String name = impl.getCachePrefix() == null ? impl.getAppName() : impl.getAppName() + impl.getCachePrefix(); EVCacheInMemoryCache<T> cache = (EVCacheInMemoryCache<T>) inMemoryMap.get(name); if(cache == null) { writeLock.lock(); if((cache = getInMemoryCache(name)) == null) { cache = new EVCacheInMemoryCache<T>(impl.getAppName(), tc, impl); inMemoryMap.put(name, cache); } writeLock.unlock(); } return cache; } @SuppressWarnings("unchecked") public <T> EVCacheInMemoryCache<T> getInMemoryCache(String appName) { return (EVCacheInMemoryCache<T>) inMemoryMap.get(appName); } }
13,386
45.162069
245
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/pool/observer/EVCacheConnectionObserverMBean.java
package com.netflix.evcache.pool.observer; import java.net.SocketAddress; import java.util.Set; public interface EVCacheConnectionObserverMBean { int getActiveServerCount(); Set<SocketAddress> getActiveServerNames(); int getInActiveServerCount(); Set<SocketAddress> getInActiveServerNames(); long getLostCount(); long getConnectCount(); }
370
18.526316
49
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/pool/observer/EVCacheConnectionObserver.java
package com.netflix.evcache.pool.observer; import java.lang.management.ManagementFactory; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.management.MBeanServer; import javax.management.ObjectName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.evcache.pool.EVCacheClient; import net.spy.memcached.ConnectionObserver; public class EVCacheConnectionObserver implements ConnectionObserver, EVCacheConnectionObserverMBean { private static final Logger log = LoggerFactory.getLogger(EVCacheConnectionObserver.class); private final EVCacheClient client; private long lostCount = 0; private long connectCount = 0; private final Set<SocketAddress> evCacheActiveSet; private final Set<SocketAddress> evCacheInActiveSet; private final Map<InetSocketAddress, Long> evCacheActiveStringSet; private final Map<InetSocketAddress, Long> evCacheInActiveStringSet; // private final Counter connectCounter, connLostCounter; public EVCacheConnectionObserver(EVCacheClient client) { this.client = client; this.evCacheActiveSet = Collections.newSetFromMap(new ConcurrentHashMap<SocketAddress, Boolean>()); this.evCacheInActiveSet = Collections.newSetFromMap(new ConcurrentHashMap<SocketAddress, Boolean>()); this.evCacheActiveStringSet = new ConcurrentHashMap<InetSocketAddress, Long>(); this.evCacheInActiveStringSet = new ConcurrentHashMap<InetSocketAddress, Long>(); // final ArrayList<Tag> tags = new ArrayList<Tag>(client.getTagList().size() + 3); // tags.addAll(client.getTagList()); // tags.add(new BasicTag(EVCacheMetricsFactory.CONFIG_NAME, EVCacheMetricsFactory.CONNECT )); // connectCounter = EVCacheMetricsFactory.getInstance().getCounter(EVCacheMetricsFactory.CONFIG, tags); // // tags.clear(); // tags.addAll(client.getTagList()); // tags.add(new BasicTag(EVCacheMetricsFactory.CONFIG_NAME, EVCacheMetricsFactory.DISCONNECT )); // connLostCounter = EVCacheMetricsFactory.getInstance().getCounter(EVCacheMetricsFactory.CONFIG, tags); setupMonitoring(false); } public void connectionEstablished(SocketAddress sa, int reconnectCount) { final String address = sa.toString(); evCacheActiveSet.add(sa); evCacheInActiveSet.remove(sa); final InetSocketAddress inetAdd = (InetSocketAddress) sa; evCacheActiveStringSet.put(inetAdd, Long.valueOf(System.currentTimeMillis())); evCacheInActiveStringSet.remove(inetAdd); if (log.isDebugEnabled()) log.debug(client.getAppName() + ":CONNECTION ESTABLISHED : To " + address + " was established after " + reconnectCount + " retries"); if(log.isTraceEnabled()) log.trace("Stack", new Exception()); // connectCounter.increment(); connectCount++; } public void connectionLost(SocketAddress sa) { final String address = sa.toString(); evCacheInActiveSet.add(sa); evCacheActiveSet.remove(sa); final InetSocketAddress inetAdd = (InetSocketAddress) sa; evCacheInActiveStringSet.put(inetAdd, Long.valueOf(System.currentTimeMillis())); evCacheActiveStringSet.remove(inetAdd); if (log.isDebugEnabled()) log.debug(client.getAppName() + ":CONNECTION LOST : To " + address); if(log.isTraceEnabled()) log.trace("Stack", new Exception()); lostCount++; // connLostCounter.increment(); } public int getActiveServerCount() { return evCacheActiveSet.size(); } public Set<SocketAddress> getActiveServerNames() { return evCacheActiveSet; } public int getInActiveServerCount() { return evCacheInActiveSet.size(); } public Set<SocketAddress> getInActiveServerNames() { return evCacheInActiveSet; } public long getLostCount() { return lostCount; } public long getConnectCount() { return connectCount; } public Map<InetSocketAddress, Long> getInActiveServers() { return evCacheInActiveStringSet; } public Map<InetSocketAddress, Long> getActiveServers() { return evCacheActiveStringSet; } private void setupMonitoring(boolean shutdown) { try { final ObjectName mBeanName = ObjectName.getInstance("com.netflix.evcache:Group=" + client.getAppName() + ",SubGroup=pool,SubSubGroup=" + client.getServerGroupName()+ ",SubSubSubGroup=" + client.getId()); final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); if (mbeanServer.isRegistered(mBeanName)) { if (log.isDebugEnabled()) log.debug("MBEAN with name " + mBeanName + " has been registered. Will unregister the previous instance and register a new one."); mbeanServer.unregisterMBean(mBeanName); } if (!shutdown) { mbeanServer.registerMBean(this, mBeanName); } } catch (Exception e) { if (log.isWarnEnabled()) log.warn(e.getMessage(), e); } } private void unRegisterInActiveNodes() { try { for (SocketAddress sa : evCacheInActiveSet) { final ObjectName mBeanName = ObjectName.getInstance("com.netflix.evcache:Group=" + client.getAppName() + ",SubGroup=pool" + ",SubSubGroup=" + client.getServerGroupName() + ",SubSubSubGroup=" + client.getId() + ",SubSubSubSubGroup=" + ((InetSocketAddress) sa).getHostName()); final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); if (mbeanServer.isRegistered(mBeanName)) { if (log.isDebugEnabled()) log.debug("MBEAN with name " + mBeanName + " has been registered. Will unregister the previous instance and register a new one."); mbeanServer.unregisterMBean(mBeanName); } } } catch (Exception e) { if (log.isWarnEnabled()) log.warn(e.getMessage(), e); } } public void shutdown() { unRegisterInActiveNodes(); setupMonitoring(true); } public String toString() { return "EVCacheConnectionObserver [" + "EVCacheClient=" + client + ", evCacheActiveSet=" + evCacheActiveSet + ", evCacheInActiveSet=" + evCacheInActiveSet + ", evCacheActiveStringSet=" + evCacheActiveStringSet + ", evCacheInActiveStringSet=" + evCacheInActiveStringSet + "]"; } public String getAppName() { return client.getAppName(); } public String getServerGroup() { return client.getServerGroup().toString(); } public int getId() { return client.getId(); } public EVCacheClient getClient() { return client; } }
7,118
38.994382
167
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/connection/IConnectionBuilder.java
package com.netflix.evcache.connection; import com.netflix.evcache.pool.EVCacheClient; import net.spy.memcached.ConnectionFactory; public interface IConnectionBuilder { ConnectionFactory getConnectionFactory(EVCacheClient client); }
241
21
65
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/connection/BaseAsciiConnectionFactory.java
package com.netflix.evcache.connection; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SocketChannel; import java.util.Collection; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import com.netflix.archaius.api.Property; import com.netflix.evcache.EVCacheTranscoder; import com.netflix.evcache.operation.EVCacheAsciiOperationFactory; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.EVCacheClientPool; import com.netflix.evcache.pool.EVCacheClientPoolManager; import com.netflix.evcache.pool.EVCacheKetamaNodeLocatorConfiguration; import com.netflix.evcache.pool.EVCacheNodeLocator; import com.netflix.evcache.util.EVCacheConfig; import net.spy.memcached.ConnectionObserver; import net.spy.memcached.DefaultConnectionFactory; import net.spy.memcached.DefaultHashAlgorithm; import net.spy.memcached.EVCacheConnection; import net.spy.memcached.FailureMode; import net.spy.memcached.HashAlgorithm; import net.spy.memcached.MemcachedConnection; import net.spy.memcached.MemcachedNode; import net.spy.memcached.NodeLocator; import net.spy.memcached.OperationFactory; import net.spy.memcached.ops.Operation; import net.spy.memcached.protocol.ascii.AsciiOperationFactory; import net.spy.memcached.protocol.ascii.EVCacheAsciiNodeImpl; import net.spy.memcached.transcoders.Transcoder; public class BaseAsciiConnectionFactory extends DefaultConnectionFactory { protected final String name; protected final String appName; protected final Property<Integer> operationTimeout; protected final long opMaxBlockTime; protected EVCacheNodeLocator locator; protected final long startTime; protected final EVCacheClient client; protected final Property<String> failureMode; BaseAsciiConnectionFactory(EVCacheClient client, int len, Property<Integer> _operationTimeout, long opMaxBlockTime) { super(len, DefaultConnectionFactory.DEFAULT_READ_BUFFER_SIZE, DefaultHashAlgorithm.KETAMA_HASH); this.opMaxBlockTime = opMaxBlockTime; this.operationTimeout = _operationTimeout; this.client = client; this.startTime = System.currentTimeMillis(); this.appName = client.getAppName(); this.failureMode = client.getPool().getEVCacheClientPoolManager().getEVCacheConfig().getPropertyRepository().get(this.client.getServerGroupName() + ".failure.mode", String.class).orElseGet(appName + ".failure.mode").orElse("Retry"); this.name = appName + "-" + client.getServerGroupName() + "-" + client.getId(); } public NodeLocator createLocator(List<MemcachedNode> list) { this.locator = new EVCacheNodeLocator(client, list, DefaultHashAlgorithm.KETAMA_HASH, new EVCacheKetamaNodeLocatorConfiguration(client)); return locator; } public EVCacheNodeLocator getEVCacheNodeLocator() { return this.locator; } public long getMaxReconnectDelay() { return super.getMaxReconnectDelay(); } public int getOpQueueLen() { return super.getOpQueueLen(); } public int getReadBufSize() { return super.getReadBufSize(); } public BlockingQueue<Operation> createOperationQueue() { return new ArrayBlockingQueue<Operation>(getOpQueueLen()); } public MemcachedConnection createConnection(List<InetSocketAddress> addrs) throws IOException { return new EVCacheConnection(name, getReadBufSize(), this, addrs, getInitialObservers(), getFailureMode(), getOperationFactory()); } public EVCacheAsciiOperationFactory getOperationFactory() { return new EVCacheAsciiOperationFactory(); } public MemcachedNode createMemcachedNode(SocketAddress sa, SocketChannel c, int bufSize) { boolean doAuth = false; final EVCacheAsciiNodeImpl node = new EVCacheAsciiNodeImpl(sa, c, bufSize, createReadOperationQueue(), createWriteOperationQueue(), createOperationQueue(), opMaxBlockTime, doAuth, getOperationTimeout(), getAuthWaitTime(), this, client, startTime); node.registerMonitors(); return node; } public long getOperationTimeout() { return operationTimeout.get(); } public BlockingQueue<Operation> createReadOperationQueue() { return super.createReadOperationQueue(); } public BlockingQueue<Operation> createWriteOperationQueue() { return super.createWriteOperationQueue(); } public Transcoder<Object> getDefaultTranscoder() { return new EVCacheTranscoder(); } public FailureMode getFailureMode() { try { return FailureMode.valueOf(failureMode.get()); } catch (IllegalArgumentException ex) { return FailureMode.Cancel; } } public HashAlgorithm getHashAlg() { return super.getHashAlg(); } public Collection<ConnectionObserver> getInitialObservers() { return super.getInitialObservers(); } public boolean isDaemon() { return EVCacheConfig.getInstance().getPropertyRepository().get("evcache.thread.daemon", Boolean.class).orElse(super.isDaemon()).get(); } public boolean shouldOptimize() { return EVCacheConfig.getInstance().getPropertyRepository().get("evcache.broadcast.ascii.connection.optimize", Boolean.class).orElse(true).get(); } public boolean isDefaultExecutorService() { return false; } public ExecutorService getListenerExecutorService() { return client.getPool().getEVCacheClientPoolManager().getEVCacheExecutor(); } public int getId() { return client.getId(); } public String getZone() { return client.getServerGroup().getZone(); } public String getServerGroupName() { return client.getServerGroup().getName(); } public String getReplicaSetName() { return client.getServerGroup().getName(); } public String getAppName() { return this.appName; } public String toString() { return name; } public EVCacheClientPoolManager getEVCacheClientPoolManager() { return this.client.getPool().getEVCacheClientPoolManager(); } public EVCacheClientPool getEVCacheClientPool() { return this.client.getPool(); } public EVCacheClient getEVCacheClient() { return this.client; } }
6,541
33.613757
240
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/connection/ConnectionFactoryBuilder.java
package com.netflix.evcache.connection; import com.netflix.archaius.api.Property; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.util.EVCacheConfig; import net.spy.memcached.ConnectionFactory; public class ConnectionFactoryBuilder implements IConnectionBuilder { public ConnectionFactoryBuilder() { } public ConnectionFactory getConnectionFactory(EVCacheClient client) { final String appName = client.getAppName(); final int maxQueueSize = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".max.queue.length", Integer.class).orElse(16384).get(); final Property<Integer> operationTimeout = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".operation.timeout", Integer.class).orElse(2500); final int opQueueMaxBlockTime = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".operation.QueueMaxBlockTime", Integer.class).orElse(10).get(); final boolean useBinary = EVCacheConfig.getInstance().getPropertyRepository().get("evcache.use.binary.protocol", Boolean.class).orElse(true).get(); if(useBinary) return new BaseConnectionFactory(client, maxQueueSize, operationTimeout, opQueueMaxBlockTime); else return new BaseAsciiConnectionFactory(client, maxQueueSize, operationTimeout, opQueueMaxBlockTime); } }
1,355
51.153846
170
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/connection/BaseConnectionFactory.java
package com.netflix.evcache.connection; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SocketChannel; import java.util.Collection; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import com.netflix.archaius.api.Property; import com.netflix.evcache.EVCacheTranscoder; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.EVCacheClientPool; import com.netflix.evcache.pool.EVCacheClientPoolManager; import com.netflix.evcache.pool.EVCacheKetamaNodeLocatorConfiguration; import com.netflix.evcache.pool.EVCacheNodeLocator; import com.netflix.evcache.util.EVCacheConfig; import net.spy.memcached.BinaryConnectionFactory; import net.spy.memcached.ConnectionObserver; import net.spy.memcached.DefaultHashAlgorithm; import net.spy.memcached.EVCacheConnection; import net.spy.memcached.FailureMode; import net.spy.memcached.HashAlgorithm; import net.spy.memcached.MemcachedConnection; import net.spy.memcached.MemcachedNode; import net.spy.memcached.NodeLocator; import net.spy.memcached.ops.Operation; import net.spy.memcached.protocol.binary.EVCacheNodeImpl; import net.spy.memcached.transcoders.Transcoder; public class BaseConnectionFactory extends BinaryConnectionFactory { protected final String name; protected final String appName; protected final Property<Integer> operationTimeout; protected final long opMaxBlockTime; protected EVCacheNodeLocator locator; protected final long startTime; protected final EVCacheClient client; protected final Property<String> failureMode; BaseConnectionFactory(EVCacheClient client, int len, Property<Integer> _operationTimeout, long opMaxBlockTime) { super(len, BinaryConnectionFactory.DEFAULT_READ_BUFFER_SIZE, DefaultHashAlgorithm.KETAMA_HASH); this.opMaxBlockTime = opMaxBlockTime; this.operationTimeout = _operationTimeout; this.client = client; this.startTime = System.currentTimeMillis(); this.appName = client.getAppName(); this.failureMode = client.getPool().getEVCacheClientPoolManager().getEVCacheConfig().getPropertyRepository().get(this.client.getServerGroupName() + ".failure.mode", String.class).orElseGet(appName + ".failure.mode").orElse("Retry"); this.name = appName + "-" + client.getServerGroupName() + "-" + client.getId(); } public NodeLocator createLocator(List<MemcachedNode> list) { this.locator = new EVCacheNodeLocator(client, list, DefaultHashAlgorithm.KETAMA_HASH, new EVCacheKetamaNodeLocatorConfiguration(client)); return locator; } public EVCacheNodeLocator getEVCacheNodeLocator() { return this.locator; } public long getMaxReconnectDelay() { return super.getMaxReconnectDelay(); } public int getOpQueueLen() { return super.getOpQueueLen(); } public int getReadBufSize() { return super.getReadBufSize(); } public BlockingQueue<Operation> createOperationQueue() { return new ArrayBlockingQueue<Operation>(getOpQueueLen()); } public MemcachedConnection createConnection(List<InetSocketAddress> addrs) throws IOException { return new EVCacheConnection(name, getReadBufSize(), this, addrs, getInitialObservers(), getFailureMode(), getOperationFactory()); } public MemcachedNode createMemcachedNode(SocketAddress sa, SocketChannel c, int bufSize) { boolean doAuth = false; final EVCacheNodeImpl node = new EVCacheNodeImpl(sa, c, bufSize, createReadOperationQueue(), createWriteOperationQueue(), createOperationQueue(), opMaxBlockTime, doAuth, getOperationTimeout(), getAuthWaitTime(), this, client, startTime); node.registerMonitors(); return node; } public long getOperationTimeout() { return operationTimeout.get(); } public BlockingQueue<Operation> createReadOperationQueue() { return super.createReadOperationQueue(); } public BlockingQueue<Operation> createWriteOperationQueue() { return super.createWriteOperationQueue(); } public Transcoder<Object> getDefaultTranscoder() { return new EVCacheTranscoder(); } public FailureMode getFailureMode() { try { return FailureMode.valueOf(failureMode.get()); } catch (IllegalArgumentException ex) { return FailureMode.Cancel; } } public HashAlgorithm getHashAlg() { return super.getHashAlg(); } public Collection<ConnectionObserver> getInitialObservers() { return super.getInitialObservers(); } public boolean isDaemon() { return EVCacheConfig.getInstance().getPropertyRepository().get("evcache.thread.daemon", Boolean.class).orElse(super.isDaemon()).get(); } public boolean shouldOptimize() { return EVCacheConfig.getInstance().getPropertyRepository().get("evcache.broadcast.base.connection.optimize", Boolean.class).orElse(true).get(); } public boolean isDefaultExecutorService() { return false; } public ExecutorService getListenerExecutorService() { return client.getPool().getEVCacheClientPoolManager().getEVCacheExecutor(); } public int getId() { return client.getId(); } public String getZone() { return client.getServerGroup().getZone(); } public String getServerGroupName() { return client.getServerGroup().getName(); } public String getReplicaSetName() { return client.getServerGroup().getName(); } public String getAppName() { return this.appName; } public String toString() { return name; } public EVCacheClientPoolManager getEVCacheClientPoolManager() { return this.client.getPool().getEVCacheClientPoolManager(); } public EVCacheClientPool getEVCacheClientPool() { return this.client.getPool(); } public EVCacheClient getEVCacheClient() { return this.client; } }
6,236
33.081967
240
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/dto/KeyMapDto.java
package com.netflix.evcache.dto; import com.netflix.evcache.EVCacheKey; import java.util.Map; public class KeyMapDto { Map<String, EVCacheKey> keyMap; boolean isKeyHashed; public KeyMapDto(Map<String, EVCacheKey> keyMap, boolean isKeyHashed) { this.keyMap = keyMap; this.isKeyHashed = isKeyHashed; } public Map<String, EVCacheKey> getKeyMap() { return keyMap; } public boolean isKeyHashed() { return isKeyHashed; } }
487
19.333333
75
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/dto/EVCacheResponseStatus.java
package com.netflix.evcache.dto; public class EVCacheResponseStatus { private String status; public EVCacheResponseStatus(String status) { this.status = status; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
329
17.333333
49
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/event/EVCacheEventListener.java
package com.netflix.evcache.event; import java.util.EventListener; import com.netflix.evcache.EVCacheException; public interface EVCacheEventListener extends EventListener { void onStart(EVCacheEvent e); void onComplete(EVCacheEvent e); void onError(EVCacheEvent e, Throwable t); boolean onThrottle(EVCacheEvent e) throws EVCacheException; }
364
21.8125
63
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/event/EVCacheEvent.java
package com.netflix.evcache.event; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.netflix.evcache.EVCache.Call; import com.netflix.evcache.metrics.EVCacheMetricsFactory; import com.netflix.evcache.EVCacheKey; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.EVCacheClientPool; import net.spy.memcached.CachedData; import net.spy.memcached.MemcachedNode; public class EVCacheEvent { public static final String CLIENTS = "clients"; private final Call call; private final String appName; private final String cacheName; private final EVCacheClientPool pool; private final long startTime; private long endTime = 0; private String status = EVCacheMetricsFactory.SUCCESS; private Collection<EVCacheClient> clients = null; private Collection<EVCacheKey> evcKeys = null; private int ttl = 0; private CachedData cachedData = null; private Map<Object, Object> data; public EVCacheEvent(Call call, String appName, String cacheName, EVCacheClientPool pool) { super(); this.call = call; this.appName = appName; this.cacheName = cacheName; this.pool = pool; this.startTime = System.currentTimeMillis(); } public Call getCall() { return call; } public String getAppName() { return appName; } public String getCacheName() { return cacheName; } public EVCacheClientPool getEVCacheClientPool() { return pool; } public Collection<EVCacheKey> getEVCacheKeys() { return evcKeys; } public void setEVCacheKeys(Collection<EVCacheKey> evcacheKeys) { this.evcKeys = evcacheKeys; } public int getTTL() { return ttl; } public void setTTL(int ttl) { this.ttl = ttl; } public CachedData getCachedData() { return cachedData; } public void setCachedData(CachedData cachedData) { this.cachedData = cachedData; } public Collection<EVCacheClient> getClients() { return clients; } public void setClients(Collection<EVCacheClient> clients) { this.clients = clients; } public void setAttribute(Object key, Object value) { if (data == null) data = new HashMap<Object, Object>(); data.put(key, value); } public Object getAttribute(Object key) { if (data == null) return null; return data.get(key); } public void setEndTime(long endTime) { this.endTime = endTime; } public long getEndTime() { return endTime; } public void setStatus(String status) { this.status = status; } public String getStatus() { return status; } /* * Will return the duration of the call if available else -1 */ public long getDurationInMillis() { if(endTime == 0) return -1; return endTime - startTime; } @Override public int hashCode() { return evcKeys.hashCode(); } /** * @deprecated replaced by {@link #getEVCacheKeys()} */ @Deprecated public Collection<String> getKeys() { if(evcKeys == null || evcKeys.size() == 0) return Collections.<String>emptyList(); final Collection<String> keyList = new ArrayList<String>(evcKeys.size()); for(EVCacheKey key : evcKeys) { keyList.add(key.getKey()); } return keyList; } /** * @deprecated replaced by {@link #setEVCacheKeys(Collection)} */ @Deprecated public void setKeys(Collection<String> keys) { } /** * @deprecated replaced by {@link #getEVCacheKeys()} */ @Deprecated public Collection<String> getCanonicalKeys() { if(evcKeys == null || evcKeys.size() == 0) return Collections.<String>emptyList(); final Collection<String> keyList = new ArrayList<String>(evcKeys.size()); for(EVCacheKey key : evcKeys) { keyList.add(key.getCanonicalKey()); } return keyList; } public Collection<MemcachedNode> getMemcachedNode(EVCacheKey evckey) { final Collection<MemcachedNode> nodeList = new ArrayList<MemcachedNode>(clients.size()); for(EVCacheClient client : clients) { String key = evckey.getDerivedKey(client.isDuetClient(), client.getHashingAlgorithm(), client.shouldEncodeHashKey(), client.getMaxDigestBytes(), client.getMaxHashLength(), client.getBaseEncoder()); nodeList.add(client.getNodeLocator().getPrimary(key)); } return nodeList; } /** * @deprecated replaced by {@link #setEVCacheKeys(Collection)} */ public void setCanonicalKeys(Collection<String> canonicalKeys) { } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EVCacheEvent other = (EVCacheEvent) obj; if (appName == null) { if (other.appName != null) return false; } else if (!appName.equals(other.appName)) return false; if (cacheName == null) { if (other.cacheName != null) return false; } else if (!cacheName.equals(other.cacheName)) return false; if (call != other.call) return false; if (evcKeys == null) { if (other.evcKeys != null) return false; } else if (!evcKeys.equals(other.evcKeys)) return false; return true; } public long getStartTime() { return this.startTime; } @Override public String toString() { return "EVCacheEvent [call=" + call + ", appName=" + appName + ", cacheName=" + cacheName + ", Num of Clients=" + clients.size() + ", evcKeys=" + evcKeys + ", ttl=" + ttl + ", event Time=" + (new Date(startTime)).toString() + ", cachedData=" + (cachedData != null ? "[ Flags : " + cachedData.getFlags() + "; Data Array length : " +cachedData.getData().length + "] " : "null") + ", Attributes=" + data + "]"; } }
6,371
27.070485
209
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/event/hotkey/HotKeyListener.java
package com.netflix.evcache.event.hotkey; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.netflix.archaius.api.Property; import com.netflix.evcache.EVCacheKey; import com.netflix.evcache.event.EVCacheEvent; import com.netflix.evcache.event.EVCacheEventListener; import com.netflix.evcache.pool.EVCacheClientPoolManager; import com.netflix.evcache.util.EVCacheConfig; /** * <p> * To enable throttling of requests on the client for keys that are sending too many requests in a short duration then set the below property * <code>EVCacheThrottler.throttle.hot.keys=true</code> * </p> * <br> * Hot keys can be throttled in 2 ways. * * <ol> * <li>If there are set of keys that are determined by an offline process or enabling debugging then we can set the following property (, separated) * * ex: <code><evcache appName>.throttle.keys=key1,key2</code> * This will throttle all operations for keys key1 and key2 * * </li><li>Another option is to dynamically figure based on metrics if a key is having a lot of operations. * At the start of every operation we add the key to an internal cache for a duration specified by <code>EVCacheThrottler.< evcache appName>.inmemory.expire.after.write.duration.ms</code> (default is 10 seconds). * If a key appears again within this duration we increment the value and release the key for <code>EVCacheThrottler.< evcache appName>.inmemory.expire.after.access.duration.ms</code> (default is 10 seconds). * Once the key count crosses <code>EVCacheThrottler.< evcache appName>.throttle.value</code> (default is 3) then the key will be throttled. YMMV so tune this based on your evcache app and client requests. * </li> * * @author smadappa * */ @Singleton public class HotKeyListener implements EVCacheEventListener { private static final Logger log = LoggerFactory.getLogger(HotKeyListener.class); private final Map<String, Property<Boolean>> throttleMap; private final Map<String, Cache<String, Integer>> cacheMap; private final Integer START_VAL = Integer.valueOf(1); private final Property<Boolean> enableThrottleHotKeys; private final EVCacheClientPoolManager poolManager; private final Map<String, Property<Set<String>>> throttleKeysMap; @Inject public HotKeyListener(EVCacheClientPoolManager poolManager) { this.poolManager = poolManager; this.throttleKeysMap = new ConcurrentHashMap<String, Property<Set<String>>>(); this.throttleMap = new ConcurrentHashMap<String, Property<Boolean>>(); cacheMap = new ConcurrentHashMap<String, Cache<String, Integer>>(); enableThrottleHotKeys = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler.throttle.hot.keys", Boolean.class).orElse(false); enableThrottleHotKeys.subscribe((i) -> setupHotKeyListener()); if(enableThrottleHotKeys.get()) setupHotKeyListener(); } private void setupHotKeyListener() { if(enableThrottleHotKeys.get()) { poolManager.addEVCacheEventListener(this); } else { poolManager.removeEVCacheEventListener(this); for(Cache<String, Integer> cache : cacheMap.values()) { cache.invalidateAll(); } } } private Cache<String, Integer> getCache(String appName) { Property<Boolean> throttleFlag = throttleMap.get(appName); if(throttleFlag == null) { throttleFlag = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".throttle.hot.keys", Boolean.class).orElse(false); throttleMap.put(appName, throttleFlag); } if(log.isDebugEnabled()) log.debug("Throttle hot keys : " + throttleFlag); if(!throttleFlag.get()) { return null; } Cache<String, Integer> cache = cacheMap.get(appName); if(cache != null) return cache; final Property<Integer> _cacheDuration = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".inmemory.expire.after.write.duration.ms", Integer.class).orElse(10000); final Property<Integer> _exireAfterAccessDuration = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".inmemory.expire.after.access.duration.ms", Integer.class).orElse(10000); final Property<Integer> _cacheSize = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".inmemory.cache.size", Integer.class).orElse(100); CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().recordStats(); if(_cacheSize.get() > 0) { builder = builder.maximumSize(_cacheSize.get()); } if(_exireAfterAccessDuration.get() > 0) { builder = builder.expireAfterAccess(_exireAfterAccessDuration.get(), TimeUnit.MILLISECONDS); } else if(_cacheDuration.get() > 0) { builder = builder.expireAfterWrite(_cacheDuration.get(), TimeUnit.MILLISECONDS); } cache = builder.build(); cacheMap.put(appName, cache); return cache; } public void onStart(final EVCacheEvent e) { if(!enableThrottleHotKeys.get()) return; final Cache<String, Integer> cache = getCache(e.getAppName()); if(cache == null) return; for(EVCacheKey evcKey : e.getEVCacheKeys()) { final String key = evcKey.getKey(); Integer val = cache.getIfPresent(key); if(val == null) { cache.put(key, START_VAL); } else { cache.put(key, Integer.valueOf(val.intValue() + 1)); } } } @Override public boolean onThrottle(final EVCacheEvent e) { if(!enableThrottleHotKeys.get()) return false; final String appName = e.getAppName(); Property<Set<String>> throttleKeysSet = throttleKeysMap.get(appName).orElse(Collections.emptySet()); if(throttleKeysSet.get().size() > 0) { if(log.isDebugEnabled()) log.debug("Throttle : " + throttleKeysSet); for(EVCacheKey evcKey : e.getEVCacheKeys()) { final String key = evcKey.getKey(); if(throttleKeysSet.get().contains(key)) { if(log.isDebugEnabled()) log.debug("Key : " + key + " is throttled"); return true; } } } final Cache<String, Integer> cache = getCache(appName); if(cache == null) return false; final Property<Integer> _throttleVal = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".throttle.value", Integer.class).orElse(3); for(EVCacheKey evcKey : e.getEVCacheKeys()) { final String key = evcKey.getKey(); Integer val = cache.getIfPresent(key); if(val.intValue() > _throttleVal.get()) { if(log.isDebugEnabled()) log.debug("Key : " + key + " has exceeded " + _throttleVal.get() + ". Will throttle this request"); return true; } } return false; } public void onComplete(EVCacheEvent e) { if(!enableThrottleHotKeys.get()) return; final String appName = e.getAppName(); final Cache<String, Integer> cache = getCache(appName); if(cache == null) return; for(EVCacheKey evcKey : e.getEVCacheKeys()) { final String key = evcKey.getKey(); Integer val = cache.getIfPresent(key); if(val != null) { cache.put(key, Integer.valueOf(val.intValue() - 1)); } } } public void onError(EVCacheEvent e, Throwable t) { if(!enableThrottleHotKeys.get()) return; final String appName = e.getAppName(); final Cache<String, Integer> cache = getCache(appName); if(cache == null) return; for(EVCacheKey evcKey : e.getEVCacheKeys()) { final String key = evcKey.getKey(); Integer val = cache.getIfPresent(key); if(val != null) { cache.put(key, Integer.valueOf(val.intValue() - 1)); } } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cacheMap == null) ? 0 : cacheMap.hashCode()); result = prime * result + ((throttleMap == null) ? 0 : throttleMap.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HotKeyListener other = (HotKeyListener) obj; if (cacheMap == null) { if (other.cacheMap != null) return false; } else if (!cacheMap.equals(other.cacheMap)) return false; if (throttleMap == null) { if (other.throttleMap != null) return false; } else if (!throttleMap.equals(other.throttleMap)) return false; return true; } }
9,489
41.177778
222
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/event/throttle/ThrottleListener.java
package com.netflix.evcache.event.throttle; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.archaius.api.Property; import com.netflix.evcache.EVCache.Call; import com.netflix.evcache.event.EVCacheEvent; import com.netflix.evcache.event.EVCacheEventListener; import com.netflix.evcache.pool.EVCacheClientPoolManager; import com.netflix.evcache.util.EVCacheConfig; /** * <p> * To enable throttling on operations the set the below property * <code>EVCacheThrottler.throttle.operations=true</code> * </p> * <p> * To throttle all operations specified in {@link Call} then add the {@link Call} (separated by comma(,)) to the below property.<br> * <code>&lt;EVCache appName&gt;.throttle.calls=&lt;comma separated list of calls&gt;</code><br> * <br> * EX: To throttle {@link Call.GET} and {@link Call.DELETE} operations for EVCACHE_CRS set the below property * <code>EVCACHE_CRS.throttle.calls=GET,DELETE</code> * * @author smadappa */ @Singleton public class ThrottleListener implements EVCacheEventListener { private static final Logger log = LoggerFactory.getLogger(ThrottleListener.class); private final Map<String, Property<Set<String>>> _ignoreOperationsMap; private final Property<Boolean> enableThrottleOperations; private final EVCacheClientPoolManager poolManager; @Inject public ThrottleListener(EVCacheClientPoolManager poolManager) { this.poolManager = poolManager; this._ignoreOperationsMap = new ConcurrentHashMap<String, Property<Set<String>>>(); enableThrottleOperations = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler.throttle.operations", Boolean.class).orElse(false); enableThrottleOperations.subscribe(i -> setupListener()); if(enableThrottleOperations.get()) setupListener(); } private void setupListener() { if(enableThrottleOperations.get()) { poolManager.addEVCacheEventListener(this); } else { poolManager.removeEVCacheEventListener(this); } } public void onStart(final EVCacheEvent e) { } @Override public boolean onThrottle(final EVCacheEvent e) { if(!enableThrottleOperations.get()) return false; final String appName = e.getAppName(); Property<Set<String>> throttleCalls = _ignoreOperationsMap.get(appName).orElse(Collections.emptySet()); if(throttleCalls.get().size() > 0 && throttleCalls.get().contains(e.getCall().name())) { if(log.isDebugEnabled()) log.debug("Call : " + e.getCall() + " is throttled"); return true; } return false; } public void onComplete(EVCacheEvent e) { } public void onError(EVCacheEvent e, Throwable t) { } }
2,963
34.285714
160
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/operation/EVCacheFutures.java
package com.netflix.evcache.operation; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.evcache.EVCacheLatch; import com.netflix.evcache.pool.ServerGroup; import net.spy.memcached.internal.ListenableFuture; import net.spy.memcached.internal.OperationCompletionListener; import net.spy.memcached.internal.OperationFuture; @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "DE_MIGHT_IGNORE", "EI_EXPOSE_REP2" }) public class EVCacheFutures implements ListenableFuture<Boolean, OperationCompletionListener>, OperationCompletionListener { private static final Logger log = LoggerFactory.getLogger(EVCacheFutures.class); private final OperationFuture<Boolean>[] futures; private final String app; private final ServerGroup serverGroup; private final String key; private final AtomicInteger completionCounter; private final EVCacheLatch latch; public EVCacheFutures(OperationFuture<Boolean>[] futures, String key, String app, ServerGroup serverGroup, EVCacheLatch latch) { this.futures = futures; this.app = app; this.serverGroup = serverGroup; this.key = key; this.latch = latch; this.completionCounter = new AtomicInteger(futures.length); if (latch != null && latch instanceof EVCacheLatchImpl) ((EVCacheLatchImpl) latch).addFuture(this); for (int i = 0; i < futures.length; i++) { final OperationFuture<Boolean> of = futures[i]; if (of.isDone()) { try { onComplete(of); } catch (Exception e) { } } else { of.addListener(this); } } } public boolean cancel(boolean mayInterruptIfRunning) { if(log.isDebugEnabled()) log.debug("Operation cancelled", new Exception()); for (OperationFuture<Boolean> future : futures) { future.cancel(); } return true; } @Override public boolean isCancelled() { for (OperationFuture<Boolean> future : futures) { if (future.isCancelled() == false) return false; } return true; } @Override public boolean isDone() { for (OperationFuture<Boolean> future : futures) { if (future.isDone() == false) return false; } return true; } @Override public Boolean get() throws InterruptedException, ExecutionException { for (OperationFuture<Boolean> future : futures) { if (future.get() == false) return false; } return true; } @Override public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { for (OperationFuture<Boolean> future : futures) { if (future.get(timeout, unit) == false) return false; } return true; } public String getKey() { return key; } public String getApp() { return app; } public String getZone() { return serverGroup.getZone(); } public String getServerGroupName() { return serverGroup.getName(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("EVCacheFutures [futures=["); for (OperationFuture<Boolean> future : futures) sb.append(future); sb.append("], app=").append(app).append(", ServerGroup=").append(serverGroup.toString()).append("]"); return sb.toString(); } @Override public void onComplete(OperationFuture<?> future) throws Exception { int val = completionCounter.decrementAndGet(); if (val == 0) { if (latch != null) latch.onComplete(future);// Pass the last future to get completed } } @Override public Future<Boolean> addListener(OperationCompletionListener listener) { return this; } @Override public Future<Boolean> removeListener(OperationCompletionListener listener) { return this; } }
4,321
30.318841
132
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/operation/EVCacheAsciiOperationFactory.java
package com.netflix.evcache.operation; import net.spy.memcached.protocol.ascii.AsciiOperationFactory; import net.spy.memcached.protocol.ascii.ExecCmdOperation; import net.spy.memcached.protocol.ascii.ExecCmdOperationImpl; import net.spy.memcached.protocol.ascii.MetaDebugOperation; import net.spy.memcached.protocol.ascii.MetaDebugOperationImpl; import net.spy.memcached.protocol.ascii.MetaGetOperation; import net.spy.memcached.protocol.ascii.MetaGetOperationImpl; import net.spy.memcached.protocol.ascii.MetaArithmeticOperationImpl; import net.spy.memcached.ops.Mutator; import net.spy.memcached.ops.MutatorOperation; import net.spy.memcached.ops.OperationCallback; public class EVCacheAsciiOperationFactory extends AsciiOperationFactory { public MetaDebugOperation metaDebug(String key, MetaDebugOperation.Callback cb) { return new MetaDebugOperationImpl(key, cb); } public MetaGetOperation metaGet(String key, MetaGetOperation.Callback cb) { return new MetaGetOperationImpl(key, cb); } public ExecCmdOperation execCmd(String cmd, ExecCmdOperation.Callback cb) { return new ExecCmdOperationImpl(cmd, cb); } public MutatorOperation mutate(Mutator m, String key, long by, long def, int exp, OperationCallback cb) { return new MetaArithmeticOperationImpl(m, key, by, def, exp, cb); } }
1,396
36.756757
85
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/operation/EVCacheItemMetaData.java
package com.netflix.evcache.operation; /** * <B><u>Meta </u></B> * <br> * The meta debug command is a human readable dump of all available internal * metadata of an item, minus the value.<br> * <br> * <b><i>me &lt;key&gt;r\n</i></b><br> * <br> * <key> means one key string.<br> * <br> * The response looks like:<br> * <br> * <b><i>ME &lt;key&gt; &lt;k&gt;=&lt;v&gt;*\r\nEN\r\n</i></b><br> * <br> * For Ex: <br> * <pre> * me img:bil:360465414627441161 ME img:bil:360465414627441161 exp=-549784 la=55016 cas=0 fetch=yes cls=5 size=237 EN </pre> * <br> * Each of the keys and values are the internal data for the item.<br> * <br> * exp = expiration time<br> * la = time in seconds since last access<br> * cas = CAS ID<br> * fetch = whether an item has been fetched before<br> * cls = slab class id<br> * size = total size in bytes<br> * <br> * @author smadappa * */ public class EVCacheItemMetaData { public long secondsLeftToExpire; public long secondsSinceLastAccess; public long cas; public boolean hasBeenFetchedAfterWrite; public int slabClass; public int sizeInBytes; public EVCacheItemMetaData() { super(); } public void setSecondsLeftToExpire(long secondsLeftToExpire) { this.secondsLeftToExpire = secondsLeftToExpire; } public void setSecondsSinceLastAccess(long secondsSinceLastAccess) { this.secondsSinceLastAccess = secondsSinceLastAccess; } public void setCas(long cas) { this.cas = cas; } public void setHasBeenFetchedAfterWrite(boolean hasBeenFetchedAfterWrite) { this.hasBeenFetchedAfterWrite = hasBeenFetchedAfterWrite; } public void setSlabClass(int slabClass) { this.slabClass = slabClass; } public void setSizeInBytes(int sizeInBytes) { this.sizeInBytes = sizeInBytes; } public long getSecondsLeftToExpire() { return secondsLeftToExpire; } public long getSecondsSinceLastAccess() { return secondsSinceLastAccess; } public long getCas() { return cas; } public boolean isHasBeenFetchedAfterWrite() { return hasBeenFetchedAfterWrite; } public int getSlabClass() { return slabClass; } public int getSizeInBytes() { return sizeInBytes; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (cas ^ (cas >>> 32)); result = prime * result + (hasBeenFetchedAfterWrite ? 1231 : 1237); result = prime * result + (int) (secondsLeftToExpire ^ (secondsLeftToExpire >>> 32)); result = prime * result + (int) (secondsSinceLastAccess ^ (secondsSinceLastAccess >>> 32)); result = prime * result + sizeInBytes; result = prime * result + slabClass; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EVCacheItemMetaData other = (EVCacheItemMetaData) obj; if (cas != other.cas) return false; if (hasBeenFetchedAfterWrite != other.hasBeenFetchedAfterWrite) return false; if (secondsLeftToExpire != other.secondsLeftToExpire) return false; if (secondsSinceLastAccess != other.secondsSinceLastAccess) return false; if (sizeInBytes != other.sizeInBytes) return false; if (slabClass != other.slabClass) return false; return true; } @Override public String toString() { return "EVCacheItemMetaData [secondsLeftToExpire=" + secondsLeftToExpire + ", secondsSinceLastAccess=" + secondsSinceLastAccess + ", cas=" + cas + ", hasBeenFetchedAfterWrite=" + hasBeenFetchedAfterWrite + ", slabClass=" + slabClass + ", sizeInBytes=" + sizeInBytes + "]"; } }
4,061
27.405594
116
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/operation/EVCacheItem.java
package com.netflix.evcache.operation; public class EVCacheItem<T> { private final EVCacheItemMetaData item; private T data = null; private int flag = 0; public EVCacheItem() { item = new EVCacheItemMetaData(); } public EVCacheItemMetaData getItemMetaData() { return item; } public T getData() { return data; } public void setData(T data) { this.data = data; } public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } @Override public String toString() { return "EVCacheItem [item=" + item + ", data=" + data + ", flag=" + flag + "]"; } }
710
17.230769
87
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/operation/EVCacheBulkGetFuture.java
package com.netflix.evcache.operation; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.*; import com.netflix.evcache.EVCacheGetOperationListener; import net.spy.memcached.internal.BulkGetCompletionListener; import net.spy.memcached.internal.CheckedOperationTimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.evcache.metrics.EVCacheMetricsFactory; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.ServerGroup; import com.netflix.evcache.util.EVCacheConfig; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import com.sun.management.GcInfo; import net.spy.memcached.MemcachedConnection; import net.spy.memcached.internal.BulkGetFuture; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationState; import rx.Scheduler; import rx.Single; /** * Future for handling results from bulk gets. * * Not intended for general use. * * types of objects returned from the GETBULK */ @SuppressWarnings("restriction") public class EVCacheBulkGetFuture<T> extends BulkGetFuture<T> { private static final Logger log = LoggerFactory.getLogger(EVCacheBulkGetFuture.class); private final Map<String, Future<T>> rvMap; private final Collection<Operation> ops; private final CountDownLatch latch; private final long start; private final EVCacheClient client; public EVCacheBulkGetFuture(Map<String, Future<T>> m, Collection<Operation> getOps, CountDownLatch l, ExecutorService service, EVCacheClient client) { super(m, getOps, l, service); rvMap = m; ops = getOps; latch = l; this.start = System.currentTimeMillis(); this.client = client; } public Map<String, T> getSome(long to, TimeUnit unit, boolean throwException, boolean hasZF) throws InterruptedException, ExecutionException { boolean status = latch.await(to, unit); if(log.isDebugEnabled()) log.debug("Took " + (System.currentTimeMillis() - start)+ " to fetch " + rvMap.size() + " keys from " + client); long pauseDuration = -1; List<Tag> tagList = null; Collection<Operation> timedoutOps = null; String statusString = EVCacheMetricsFactory.SUCCESS; try { if (!status) { boolean gcPause = false; tagList = new ArrayList<Tag>(7); tagList.addAll(client.getTagList()); tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, EVCacheMetricsFactory.BULK_OPERATION)); final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); final long vmStartTime = runtimeBean.getStartTime(); final List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean gcMXBean : gcMXBeans) { if (gcMXBean instanceof com.sun.management.GarbageCollectorMXBean) { final GcInfo lastGcInfo = ((com.sun.management.GarbageCollectorMXBean) gcMXBean).getLastGcInfo(); // If no GCs, there was no pause. if (lastGcInfo == null) { continue; } final long gcStartTime = lastGcInfo.getStartTime() + vmStartTime; if (gcStartTime > start) { gcPause = true; if (log.isDebugEnabled()) log.debug("Total duration due to gc event = " + lastGcInfo.getDuration() + " msec."); break; } } } // redo the same op once more since there was a chance of gc pause if (gcPause) { status = latch.await(to, unit); tagList.add(new BasicTag(EVCacheMetricsFactory.PAUSE_REASON, EVCacheMetricsFactory.GC)); if (log.isDebugEnabled()) log.debug("Retry status : " + status); if (status) { tagList.add(new BasicTag(EVCacheMetricsFactory.FETCH_AFTER_PAUSE, EVCacheMetricsFactory.YES)); } else { tagList.add(new BasicTag(EVCacheMetricsFactory.FETCH_AFTER_PAUSE, EVCacheMetricsFactory.NO)); } } else { tagList.add(new BasicTag(EVCacheMetricsFactory.PAUSE_REASON, EVCacheMetricsFactory.SCHEDULE)); } pauseDuration = System.currentTimeMillis() - start; if (log.isDebugEnabled()) log.debug("Total duration due to gc event = " + (System.currentTimeMillis() - start) + " msec."); } for (Operation op : ops) { if (op.getState() != OperationState.COMPLETE) { if (!status) { MemcachedConnection.opTimedOut(op); if(timedoutOps == null) timedoutOps = new HashSet<Operation>(); timedoutOps.add(op); } else { MemcachedConnection.opSucceeded(op); } } else { MemcachedConnection.opSucceeded(op); } } if (!status && !hasZF && (timedoutOps != null && timedoutOps.size() > 0)) statusString = EVCacheMetricsFactory.TIMEOUT; for (Operation op : ops) { if(op.isCancelled()) { if (hasZF) statusString = EVCacheMetricsFactory.CANCELLED; if (throwException) throw new ExecutionException(new CancellationException("Cancelled")); } if (op.hasErrored() && throwException) throw new ExecutionException(op.getException()); } Map<String, T> m = new HashMap<String, T>(); for (Map.Entry<String, Future<T>> me : rvMap.entrySet()) { m.put(me.getKey(), me.getValue().get()); } return m; } finally { if(pauseDuration > 0) { tagList.add(new BasicTag(EVCacheMetricsFactory.OPERATION_STATUS, statusString)); EVCacheMetricsFactory.getInstance().getPercentileTimer(EVCacheMetricsFactory.INTERNAL_PAUSE, tagList, Duration.ofMillis(EVCacheConfig.getInstance().getPropertyRepository().get(getApp() + ".max.read.duration.metric", Integer.class) .orElseGet("evcache.max.read.duration.metric").orElse(20).get().intValue())).record(pauseDuration, TimeUnit.MILLISECONDS); } } } public CompletableFuture<Map<String, T>> getSomeCompletableFuture(long to, TimeUnit unit, boolean throwException, boolean hasZF) { CompletableFuture<Map<String, T>> completableFuture = new CompletableFuture<>(); try { Map<String, T> value = getSome(to, unit, throwException, hasZF); completableFuture.complete(value); } catch (Exception e) { completableFuture.completeExceptionally(e); } return completableFuture; } public Single<Map<String, T>> observe() { return Single.create(subscriber -> addListener(future -> { try { subscriber.onSuccess(get()); } catch (Throwable e) { subscriber.onError(e); } }) ); } public <U> CompletableFuture<U> makeFutureWithTimeout(long timeout, TimeUnit units) { final CompletableFuture<U> future = new CompletableFuture<>(); return EVCacheOperationFuture.withTimeout(future, timeout, units); } public CompletableFuture<Map<String, T>> getAsyncSome(long timeout, TimeUnit units) { CompletableFuture<Map<String, T>> future = makeFutureWithTimeout(timeout, units); doAsyncGetSome(future); return future.handle((data, ex) -> { if (ex != null) { handleBulkException(); } return data; }); } public void handleBulkException() { ExecutionException t = null; for (Operation op : ops) { if (op.getState() != OperationState.COMPLETE) { if (op.isCancelled()) { throw new RuntimeException(new ExecutionException(new CancellationException("Cancelled"))); } else if (op.hasErrored()) { throw new RuntimeException(new ExecutionException(op.getException())); } else { op.timeOut(); MemcachedConnection.opTimedOut(op); t = new ExecutionException(new CheckedOperationTimeoutException("Checked Operation timed out.", op)); } } else { MemcachedConnection.opSucceeded(op); } } throw new RuntimeException(t); } public void doAsyncGetSome(CompletableFuture<Map<String, T>> promise) { this.addListener(future -> { try { Map<String, T> m = new HashMap<>(); Map<String, ?> result = future.get(); for (Map.Entry<String, ?> me : result.entrySet()) { m.put(me.getKey(), (T)me.getValue()); } promise.complete(m); } catch (Exception t) { promise.completeExceptionally(t); } }); } public Single<Map<String, T>> getSome(long to, TimeUnit units, boolean throwException, boolean hasZF, Scheduler scheduler) { return observe().timeout(to, units, Single.create(subscriber -> { try { final Collection<Operation> timedoutOps = new HashSet<Operation>(); for (Operation op : ops) { if (op.getState() != OperationState.COMPLETE) { MemcachedConnection.opTimedOut(op); timedoutOps.add(op); } else { MemcachedConnection.opSucceeded(op); } } //if (!hasZF && timedoutOps.size() > 0) EVCacheMetricsFactory.getInstance().increment(client.getAppName() + "-getSome-CheckedOperationTimeout", client.getTagList()); for (Operation op : ops) { if (op.isCancelled() && throwException) throw new ExecutionException(new CancellationException("Cancelled")); if (op.hasErrored() && throwException) throw new ExecutionException(op.getException()); } Map<String, T> m = new HashMap<String, T>(); for (Map.Entry<String, Future<T>> me : rvMap.entrySet()) { m.put(me.getKey(), me.getValue().get()); } subscriber.onSuccess(m); } catch (Throwable e) { subscriber.onError(e); } }), scheduler); } public String getZone() { return client.getServerGroupName(); } public ServerGroup getServerGroup() { return client.getServerGroup(); } public String getApp() { return client.getAppName(); } public Set<String> getKeys() { return Collections.unmodifiableSet(rvMap.keySet()); } public void signalComplete() { super.signalComplete(); } public boolean cancel(boolean ign) { if(log.isDebugEnabled()) log.debug("Operation cancelled", new Exception()); return super.cancel(ign); } public long getStartTime() { return start; } }
12,067
40.902778
246
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/operation/EVCacheFuture.java
package com.netflix.evcache.operation; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.ServerGroup; public class EVCacheFuture implements Future<Boolean> { private static final Logger log = LoggerFactory.getLogger(EVCacheFuture.class); private final Future<Boolean> future; private final String app; private final ServerGroup serverGroup; private final String key; private final EVCacheClient client; public EVCacheFuture(Future<Boolean> future, String key, String app, ServerGroup serverGroup) { this(future, key, app, serverGroup, null); } public EVCacheFuture(Future<Boolean> future, String key, String app, ServerGroup serverGroup, EVCacheClient client) { this.future = future; this.app = app; this.serverGroup = serverGroup; this.key = key; this.client = client; } public Future<Boolean> getFuture() { return future; } @Override public boolean cancel(boolean mayInterruptIfRunning) { if(log.isDebugEnabled()) log.debug("Operation cancelled", new Exception()); return future.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return future.isCancelled(); } @Override public boolean isDone() { return future.isDone(); } @Override public Boolean get() throws InterruptedException, ExecutionException { return future.get(); } @Override public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return future.get(timeout, unit); } public String getKey() { return key; } public String getApp() { return app; } public String getZone() { return serverGroup.getZone(); } public String getServerGroupName() { return serverGroup.getName(); } public EVCacheClient getEVCacheClient() { return client; } @Override public String toString() { return "EVCacheFuture [future=" + future + ", app=" + app + ", ServerGroup=" + serverGroup + ", EVCacheClient=" + client + "]"; } }
2,457
25.717391
121
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/operation/EVCacheOperationFuture.java
package com.netflix.evcache.operation; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; import net.spy.memcached.ops.OperationState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.evcache.EVCacheGetOperationListener; import com.netflix.evcache.metrics.EVCacheMetricsFactory; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.ServerGroup; import com.netflix.evcache.util.EVCacheConfig; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import com.sun.management.GcInfo; import net.spy.memcached.MemcachedConnection; import net.spy.memcached.internal.CheckedOperationTimeoutException; import net.spy.memcached.internal.OperationFuture; import net.spy.memcached.ops.Operation; import rx.Scheduler; import rx.Single; import rx.functions.Action0; /** * Managed future for operations. * * <p> * From an OperationFuture, application code can determine if the status of a * given Operation in an asynchronous manner. * * <p> * If for example we needed to update the keys "user:<userid>:name", * "user:<userid>:friendlist" because later in the method we were going to * verify the change occurred as expected interacting with the user, we can fire * multiple IO operations simultaneously with this concept. * * @param <T> * Type of object returned from this future. */ @SuppressWarnings("restriction") @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EXS_EXCEPTION_SOFTENING_HAS_CHECKED") public class EVCacheOperationFuture<T> extends OperationFuture<T> { private static final Logger log = LoggerFactory.getLogger(EVCacheOperationFuture.class); private static final class LazySharedExecutor { private static final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1, new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("evcache-timeout-%s") .setUncaughtExceptionHandler( (t, e) -> log.error( "{} timeout operation failed with exception: {}", t.getName(), e)) .build()); static { // We don't need to keep around all those cancellation tasks taking up memory once the // initial caller completes. executor.setRemoveOnCancelPolicy(true); } } private final CountDownLatch latch; private final AtomicReference<T> objRef; private Operation op; private final String key; private final long start; private final EVCacheClient client; public EVCacheOperationFuture(String k, CountDownLatch l, AtomicReference<T> oref, long opTimeout, ExecutorService service, EVCacheClient client) { super(k, l, oref, opTimeout, service); this.latch = l; this.objRef = oref; this.key = k; this.client = client; this.start = System.currentTimeMillis(); } public Operation getOperation() { return this.op; } public void setOperation(Operation to) { this.op = to; super.setOperation(to); } public String getApp() { return client.getAppName(); } public String getKey() { return key; } public String getZone() { return client.getZone(); } public ServerGroup getServerGroup() { return client.getServerGroup(); } public EVCacheClient getEVCacheClient() { return client; } public EVCacheOperationFuture<T> addListener(EVCacheGetOperationListener<T> listener) { super.addToListeners(listener); return this; } public EVCacheOperationFuture<T> removeListener(EVCacheGetOperationListener<T> listener) { super.removeFromListeners(listener); return this; } /** * Get the results of the given operation. * * As with the Future interface, this call will block until the results of * the future operation has been received. * * Note: If we detect there was GC pause and our operation was caught in * between we wait again to see if we will be successful. This is effective * as the timeout we specify is very low. * * @param duration * amount of time to wait * @param units * unit of time to wait * @param if * exeception needs to be thrown of null returned on a failed * operation * @param has * zone fallback * @return the operation results of this OperationFuture * @throws InterruptedException * @throws TimeoutException * @throws ExecutionException */ public T get(long duration, TimeUnit units, boolean throwException, boolean hasZF) throws InterruptedException, TimeoutException, ExecutionException { boolean status = latch.await(duration, units); if (!status) { status = handleGCPauseForGet(duration, units, throwException, hasZF); } if (status) MemcachedConnection.opSucceeded(op);// continuous timeout counter will be reset return objRef.get(); } private boolean handleGCPauseForGet(long duration, TimeUnit units, boolean throwException, boolean hasZF) throws InterruptedException, ExecutionException { boolean status; boolean gcPause = false; final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); final long vmStartTime = runtimeBean.getStartTime(); final List<GarbageCollectorMXBean> gcMXBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (GarbageCollectorMXBean gcMXBean : gcMXBeans) { if (gcMXBean instanceof com.sun.management.GarbageCollectorMXBean) { final GcInfo lastGcInfo = ((com.sun.management.GarbageCollectorMXBean) gcMXBean).getLastGcInfo(); // If no GCs, there was no pause due to GC. if (lastGcInfo == null) { continue; } final long gcStartTime = lastGcInfo.getStartTime() + vmStartTime; if (gcStartTime > start) { gcPause = true; final long gcDuration = lastGcInfo.getDuration(); final long pauseDuration = System.currentTimeMillis() - gcStartTime; if (log.isDebugEnabled()) { log.debug("Event Start Time = " + start + "; Last GC Start Time = " + gcStartTime + "; " + (gcStartTime - start) + " msec ago.\n" + "\nTotal pause duration due for this event = " + pauseDuration + " msec.\nTotal GC duration = " + gcDuration + " msec."); } break; } } } if (!gcPause && log.isDebugEnabled()) { log.debug("Total pause duration due to NON-GC event = " + (System.currentTimeMillis() - start) + " msec."); } // redo the same op once more since there was a chance of gc pause status = latch.await(duration, units); if (log.isDebugEnabled()) log.debug("re-await status : " + status); String statusString = EVCacheMetricsFactory.SUCCESS; final long pauseDuration = System.currentTimeMillis() - start; if (op != null && !status) { // whenever timeout occurs, continuous timeout counter will increase by 1. MemcachedConnection.opTimedOut(op); op.timeOut(); ExecutionException t = null; if(throwException && !hasZF) { if (op.isTimedOut()) { t = new ExecutionException(new CheckedOperationTimeoutException("Checked Operation timed out.", op)); statusString = EVCacheMetricsFactory.CHECKED_OP_TIMEOUT; } else if (op.isCancelled() && throwException) { t = new ExecutionException(new CancellationException("Cancelled"));statusString = EVCacheMetricsFactory.CANCELLED; } else if (op.hasErrored() ) { t = new ExecutionException(op.getException());statusString = EVCacheMetricsFactory.ERROR; } } if(t != null) throw t; //finally throw the exception if needed } final List<Tag> tagList = new ArrayList<Tag>(client.getTagList().size() + 4); tagList.addAll(client.getTagList()); tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, EVCacheMetricsFactory.GET_OPERATION)); tagList.add(new BasicTag(EVCacheMetricsFactory.PAUSE_REASON, gcPause ? EVCacheMetricsFactory.GC:EVCacheMetricsFactory.SCHEDULE)); tagList.add(new BasicTag(EVCacheMetricsFactory.FETCH_AFTER_PAUSE, status ? EVCacheMetricsFactory.YES:EVCacheMetricsFactory.NO)); tagList.add(new BasicTag(EVCacheMetricsFactory.OPERATION_STATUS, statusString)); EVCacheMetricsFactory.getInstance().getPercentileTimer(EVCacheMetricsFactory.INTERNAL_PAUSE, tagList, Duration.ofMillis(EVCacheConfig.getInstance().getPropertyRepository().get(getApp() + ".max.write.duration.metric", Integer.class).orElseGet("evcache.max.write.duration.metric").orElse(50).get().intValue())).record(pauseDuration, TimeUnit.MILLISECONDS); return status; } public Single<T> observe() { return Single.create(subscriber -> addListener((EVCacheGetOperationListener<T>) future -> { try { subscriber.onSuccess(get()); } catch (Throwable e) { subscriber.onError(e); } }) ); } static <T> CompletableFuture<T> withTimeout(CompletableFuture<T> future, long timeout, TimeUnit unit) { int timeoutSlots = getTimeoutSlots((int) timeout); // [DABP-2005] split timeout to timeoutSlots slots to not timeout during GC. long splitTimeout = Math.max(1, timeout / timeoutSlots); CompletableFuture<Void> chain = CompletableFuture.completedFuture(null); for (int i = 0; i < timeoutSlots; i++) { final int j = i; chain = chain.thenCompose(unused -> getNext(future, j, timeout, splitTimeout, unit, timeoutSlots)); } return future; } private static int getTimeoutSlots(int timeout) { if(log.isDebugEnabled()) log.debug("Timeout is {}", timeout); int timeoutSlots; int val = timeout /10; if (val == 0 ) { timeoutSlots = 1; } else if (val >= 1 && val < 5) { timeoutSlots = val; } else { timeoutSlots = 5; } if(log.isDebugEnabled()) log.debug("timeoutSlots is {}", timeoutSlots); return timeoutSlots; } private static<T> CompletableFuture<Void> getNext(CompletableFuture<T> future, final int j, long timeout, long splitTimeout, TimeUnit unit, int timeoutSlots) { CompletableFuture<Void> next = new CompletableFuture<>(); if (future.isDone()) { next.complete(null); } else { ScheduledFuture<?> scheduledTimeout; if (j < timeoutSlots - 1) { scheduledTimeout = LazySharedExecutor.executor.schedule( () -> { if(log.isDebugEnabled()) log.debug("Completing now for loop {} and timeout slot {}", j, timeoutSlots); next.complete(null); }, splitTimeout, TimeUnit.MILLISECONDS); } else { scheduledTimeout = LazySharedExecutor.executor.schedule( () -> { next.complete(null); if (future.isDone()) { return; } if(log.isDebugEnabled()) log.warn("Throwing timeout exception after {} {} with timeout slot {}", timeout, unit, timeoutSlots); future.completeExceptionally(new TimeoutException("Timeout after " + timeout)); }, splitTimeout, unit); } // If the completable future completes normally, don't bother timing it out. // Also cleans the ref for GC. future.whenComplete( (r, exp) -> { if (exp == null) { scheduledTimeout.cancel(false); if(log.isDebugEnabled()) log.debug("completing the future"); next.complete(null); } }); } return next; } public <U> CompletableFuture<U> makeFutureWithTimeout(long timeout, TimeUnit units) { final CompletableFuture<U> future = new CompletableFuture<>(); return withTimeout(future, timeout, units); } private void handleException() { if (log.isDebugEnabled()) log.debug("handling the timeout in handleTimeoutException"); if (op != null) { MemcachedConnection.opTimedOut(op); op.timeOut(); ExecutionException t = null; if (op.isTimedOut()) { if (log.isDebugEnabled()) log.debug("Checked Operation timed out with operation {}.", op); t = new ExecutionException(new CheckedOperationTimeoutException("Checked Operation timed out.", op)); } else if (op.isCancelled()) { if (log.isDebugEnabled()) log.debug("Cancelled with operation {}.", op); t = new ExecutionException(new CancellationException("Cancelled")); } else if (op.hasErrored()) { if (log.isDebugEnabled()) log.debug("Other exception with operation {}.", op); t = new ExecutionException(op.getException()); } throw new RuntimeException(t); } } public CompletableFuture<T> getAsync(long timeout, TimeUnit units) { CompletableFuture<T> future = makeFutureWithTimeout(timeout, units); doAsyncGet(future); return future.handle((data, ex) -> { if (ex != null) { handleException(); } return data; }); } private void doAsyncGet(CompletableFuture<T> cf) { EVCacheGetOperationListener<T> listener = future -> { try { T result = future.get(); cf.complete(result); } catch (Exception t) { cf.completeExceptionally(t); } }; this.addListener(listener); } public Single<T> get(long duration, TimeUnit units, boolean throwException, boolean hasZF, Scheduler scheduler) { return observe().timeout(duration, units, Single.create(subscriber -> { // whenever timeout occurs, continuous timeout counter will increase by 1. MemcachedConnection.opTimedOut(op); if (op != null) op.timeOut(); //if (!hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-CheckedOperationTimeout", DataSourceType.COUNTER).increment(); if (throwException) { subscriber.onError(new CheckedOperationTimeoutException("Timed out waiting for operation", op)); } else { if (isCancelled()) { //if (hasZF) EVCacheMetricsFactory.getCounter(appName, null, serverGroup.getName(), appName + "-get-Cancelled", DataSourceType.COUNTER).increment(); } subscriber.onSuccess(objRef.get()); } }), scheduler).doAfterTerminate(new Action0() { @Override public void call() { } } ); } public void signalComplete() { super.signalComplete(); } /** * Cancel this operation, if possible. * * @param ign not used * @deprecated * @return true if the operation has not yet been written to the network */ public boolean cancel(boolean ign) { if(log.isDebugEnabled()) log.debug("Operation cancelled", new Exception()); return super.cancel(ign); } /** * Cancel this operation, if possible. * * @return true if the operation has not yet been written to the network */ public boolean cancel() { if(log.isDebugEnabled()) log.debug("Operation cancelled", new Exception()); return super.cancel(); } public long getStartTime() { return start; } }
17,633
41.186603
362
java
EVCache
EVCache-master/evcache-core/src/main/java/com/netflix/evcache/operation/EVCacheLatchImpl.java
package com.netflix.evcache.operation; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.evcache.EVCacheLatch; import com.netflix.evcache.event.EVCacheEvent; import com.netflix.evcache.event.EVCacheEventListener; import com.netflix.evcache.metrics.EVCacheMetricsFactory; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.EVCacheClientPool; import com.netflix.evcache.pool.ServerGroup; import com.netflix.evcache.util.EVCacheConfig; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.Tag; import com.netflix.spectator.ipc.IpcStatus; import net.spy.memcached.internal.ListenableFuture; import net.spy.memcached.internal.OperationCompletionListener; import net.spy.memcached.internal.OperationFuture; import net.spy.memcached.ops.StatusCode; public class EVCacheLatchImpl implements EVCacheLatch, Runnable { private static final Logger log = LoggerFactory.getLogger(EVCacheLatchImpl.class); private final int expectedCompleteCount; private final CountDownLatch latch; private final List<Future<Boolean>> futures; private final Policy policy; private final int totalFutureCount; private final long start; private final String appName; private EVCacheEvent evcacheEvent = null; private boolean onCompleteDone = false; private int completeCount = 0; private int failureCount = 0; private String failReason = null; private ScheduledFuture<?> scheduledFuture; public EVCacheLatchImpl(Policy policy, int _count, String appName) { this.start = System.currentTimeMillis(); this.policy = policy; this.futures = new ArrayList<Future<Boolean>>(_count); this.appName = appName; this.totalFutureCount = _count; this.expectedCompleteCount = policyToCount(policy, _count); this.latch = new CountDownLatch(expectedCompleteCount); if (log.isDebugEnabled()) log.debug("Number of Futures = " + _count + "; Number of Futures that need to completed for Latch to be released = " + this.expectedCompleteCount); } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#await(long,java.util.concurrent.TimeUnit) */ @Override public boolean await(long timeout, TimeUnit unit) throws InterruptedException { if (log.isDebugEnabled()) log.debug("Current Latch Count = " + latch.getCount() + "; await for "+ timeout + " " + unit.name() + " appName : " + appName); final long start = log.isDebugEnabled() ? System.currentTimeMillis() : 0; final boolean awaitSuccess = latch.await(timeout, unit); if (log.isDebugEnabled()) log.debug("await success = " + awaitSuccess + " after " + (System.currentTimeMillis() - start) + " msec." + " appName : " + appName + ((evcacheEvent != null) ? " keys : " + evcacheEvent.getEVCacheKeys() : "")); return awaitSuccess; } /* * (non-Javadoc) * * @see * com.netflix.evcache.operation.EVCacheLatchI#addFuture(net.spy.memcached.internal.ListenableFuture) */ public void addFuture(ListenableFuture<Boolean, OperationCompletionListener> future) { future.addListener(this); if (future.isDone()) countDown(); this.futures.add(future); } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#isDone() */ @Override public boolean isDone() { if (latch.getCount() == 0) return true; return false; } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#countDown() */ public void countDown() { if (log.isDebugEnabled()) log.debug("Current Latch Count = " + latch.getCount() + "; Count Down."); latch.countDown(); } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#getPendingCount() */ @Override public int getPendingCount() { if (log.isDebugEnabled()) log.debug("Pending Count = " + latch.getCount()); return (int) latch.getCount(); } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#getCompletedCount() */ @Override public int getCompletedCount() { if (log.isDebugEnabled()) log.debug("Completed Count = " + completeCount); return completeCount; } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#getPendingFutures() */ @Override public List<Future<Boolean>> getPendingFutures() { final List<Future<Boolean>> returnFutures = new ArrayList<Future<Boolean>>(expectedCompleteCount); for (Future<Boolean> future : futures) { if (!future.isDone()) { returnFutures.add(future); } } return returnFutures; } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#getAllFutures() */ @Override public List<Future<Boolean>> getAllFutures() { return this.futures; } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#getCompletedFutures() */ @Override public List<Future<Boolean>> getCompletedFutures() { final List<Future<Boolean>> returnFutures = new ArrayList<Future<Boolean>>(expectedCompleteCount); for (Future<Boolean> future : futures) { if (future.isDone()) { returnFutures.add(future); } } return returnFutures; } private int policyToCount(Policy policy, int count) { if (policy == null || count == 0) return 0; switch (policy) { case NONE: return 0; case ONE: return 1; case QUORUM: if (count <= 2) return 1; else return (futures.size() / 2) + 1; case ALL_MINUS_1: if (count <= 2) return 1; else return count - 1; default: return count; } } public void setEVCacheEvent(EVCacheEvent e) { this.evcacheEvent = e; } /* * (non-Javadoc) * * @see * com.netflix.evcache.operation.EVCacheLatchI#onComplete(net.spy.memcached.internal.OperationFuture) */ @Override public void onComplete(OperationFuture<?> future) throws Exception { if (log.isDebugEnabled()) log.debug("BEGIN : onComplete - Calling Countdown. Completed Future = " + future + "; App : " + appName); countDown(); completeCount++; if(evcacheEvent != null) { if (log.isDebugEnabled()) log.debug(";App : " + evcacheEvent.getAppName() + "; Call : " + evcacheEvent.getCall() + "; Keys : " + evcacheEvent.getEVCacheKeys() + "; completeCount : " + completeCount + "; totalFutureCount : " + totalFutureCount +"; failureCount : " + failureCount); try { if(future.isDone() && future.get().equals(Boolean.FALSE)) { failureCount++; if(failReason == null) failReason = EVCacheMetricsFactory.getInstance().getStatusCode(future.getStatus().getStatusCode()); } } catch (Exception e) { failureCount++; if(failReason == null) failReason = IpcStatus.unexpected_error.name(); if(log.isDebugEnabled()) log.debug(e.getMessage(), e); } if(!onCompleteDone && getCompletedCount() >= getExpectedSuccessCount()) { if(evcacheEvent.getClients().size() > 0) { for(EVCacheClient client : evcacheEvent.getClients()) { final List<EVCacheEventListener> evcacheEventListenerList = client.getPool().getEVCacheClientPoolManager().getEVCacheEventListeners(); for (EVCacheEventListener evcacheEventListener : evcacheEventListenerList) { evcacheEventListener.onComplete(evcacheEvent); } onCompleteDone = true;//This ensures we fire onComplete only once break; } } } if(scheduledFuture != null) { final boolean futureCancelled = scheduledFuture.isCancelled(); if (log.isDebugEnabled()) log.debug("App : " + evcacheEvent.getAppName() + "; Call : " + evcacheEvent.getCall() + "; Keys : " + evcacheEvent.getEVCacheKeys() + "; completeCount : " + completeCount + "; totalFutureCount : " + totalFutureCount +"; failureCount : " + failureCount + "; futureCancelled : " + futureCancelled); if(onCompleteDone && !futureCancelled) { if(completeCount == totalFutureCount && failureCount == 0) { // all futures are completed final boolean status = scheduledFuture.cancel(true); run();//TODO: should we reschedule this method to run as part of EVCacheScheduledExecutor instead of running on the callback thread if (log.isDebugEnabled()) log.debug("Cancelled the scheduled task : " + status); } } } if (log.isDebugEnabled()) log.debug("App : " + evcacheEvent.getAppName() + "; Call : " + evcacheEvent.getCall() + "; Keys : " + evcacheEvent.getEVCacheKeys() + "; completeCount : " + completeCount + "; totalFutureCount : " + totalFutureCount +"; failureCount : " + failureCount); } if(totalFutureCount == completeCount) { final List<Tag> tags = new ArrayList<Tag>(5); EVCacheMetricsFactory.getInstance().addAppNameTags(tags, appName); if(evcacheEvent != null) tags.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, evcacheEvent.getCall().name())); tags.add(new BasicTag(EVCacheMetricsFactory.FAIL_COUNT, String.valueOf(failureCount))); tags.add(new BasicTag(EVCacheMetricsFactory.COMPLETE_COUNT, String.valueOf(completeCount))); if(failReason != null) tags.add(new BasicTag(EVCacheMetricsFactory.IPC_STATUS, failReason)); //tags.add(new BasicTag(EVCacheMetricsFactory.OPERATION, EVCacheMetricsFactory.CALLBACK)); EVCacheMetricsFactory.getInstance().getPercentileTimer(EVCacheMetricsFactory.INTERNAL_LATCH, tags, Duration.ofMillis(EVCacheConfig.getInstance().getPropertyRepository().get(getAppName() + ".max.write.duration.metric", Integer.class) .orElseGet("evcache.max.write.duration.metric").orElse(50).get().intValue())).record(System.currentTimeMillis()- start, TimeUnit.MILLISECONDS); } if (log.isDebugEnabled()) log.debug("END : onComplete - Calling Countdown. Completed Future = " + future + "; App : " + appName); } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#getFailureCount() */ @Override public int getFailureCount() { int fail = 0; for (Future<Boolean> future : futures) { try { if (future.isDone() && future.get().equals(Boolean.FALSE)) { fail++; } } catch (Exception e) { fail++; log.error(e.getMessage(), e); } } return fail; } /* * (non-Javadoc) * * @see * com.netflix.evcache.operation.EVCacheLatchI#getExpectedCompleteCount() */ @Override public int getExpectedCompleteCount() { return this.expectedCompleteCount; } /* * (non-Javadoc) * * @see * com.netflix.evcache.operation.EVCacheLatchI#getExpectedSuccessCount() */ @Override public int getExpectedSuccessCount() { return this.expectedCompleteCount; } /* * (non-Javadoc) * * @see com.netflix.evcache.operation.EVCacheLatchI#getSuccessCount() */ @Override public int getSuccessCount() { int success = 0; for (Future<Boolean> future : futures) { try { if (future.isDone() && future.get().equals(Boolean.TRUE)) { success++; } } catch (Exception e) { log.error(e.getMessage(), e); } } return success; } public String getAppName() { return appName; } public Policy getPolicy() { return this.policy; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{\"AppName\":\""); builder.append(getAppName()); builder.append("\",\"isDone\":\""); builder.append(isDone()); builder.append("\",\"Pending Count\":\""); builder.append(getPendingCount()); builder.append("\",\"Completed Count\":\""); builder.append(getCompletedCount()); builder.append("\",\"Pending Futures\":\""); builder.append(getPendingFutures()); builder.append("\",\"All Futures\":\""); builder.append(getAllFutures()); builder.append("\",\"Completed Futures\":\""); builder.append(getCompletedFutures()); builder.append("\",\"Failure Count\":\""); builder.append(getFailureCount()); builder.append("\",\"Success Count\":\""); builder.append(getSuccessCount()); builder.append("\",\"Excpected Success Count\":\""); builder.append(getExpectedSuccessCount()); builder.append("\"}"); return builder.toString(); } @Override public int getPendingFutureCount() { int count = 0; for (Future<Boolean> future : futures) { if (!future.isDone()) { count++; } } return count; } @Override public int getCompletedFutureCount() { int count = 0; for (Future<Boolean> future : futures) { if (future.isDone()) { count++; } } return count; } public boolean isFastFailure() { return (totalFutureCount == 0); } @SuppressWarnings("unchecked") @Override public void run() { if(evcacheEvent != null) { int failCount = 0, completeCount = 0; for (Future<Boolean> future : futures) { boolean fail = false; try { if(future.isDone()) { fail = future.get(0, TimeUnit.MILLISECONDS).equals(Boolean.FALSE); } else { long delayms = 0; if(scheduledFuture != null) { delayms = scheduledFuture.getDelay(TimeUnit.MILLISECONDS); } if(delayms < 0 ) delayms = 0;//making sure wait is not negative. It might be ok but as this is implementation dependent let us stick with 0 fail = future.get(delayms, TimeUnit.MILLISECONDS).equals(Boolean.FALSE); } } catch (Exception e) { fail = true; if(log.isDebugEnabled()) log.debug(e.getMessage(), e); } if (fail) { if(future instanceof EVCacheOperationFuture) { final EVCacheOperationFuture<Boolean> evcFuture = (EVCacheOperationFuture<Boolean>)future; final StatusCode code = evcFuture.getStatus().getStatusCode(); if(code != StatusCode.SUCCESS && code != StatusCode.ERR_NOT_FOUND && code != StatusCode.ERR_EXISTS) { List<ServerGroup> listOfFailedServerGroups = (List<ServerGroup>) evcacheEvent.getAttribute("FailedServerGroups"); if(listOfFailedServerGroups == null) { listOfFailedServerGroups = new ArrayList<ServerGroup>(failCount); evcacheEvent.setAttribute("FailedServerGroups", listOfFailedServerGroups); } listOfFailedServerGroups.add(evcFuture.getServerGroup()); failCount++; } } else { failCount++; } } else { completeCount++; } } if(log.isDebugEnabled()) log.debug("Fail Count : " + failCount); if(failCount > 0) { if(evcacheEvent.getClients().size() > 0) { for(EVCacheClient client : evcacheEvent.getClients()) { final List<EVCacheEventListener> evcacheEventListenerList = client.getPool().getEVCacheClientPoolManager().getEVCacheEventListeners(); if(log.isDebugEnabled()) log.debug("\nClient : " + client +"\nEvcacheEventListenerList : " + evcacheEventListenerList); for (EVCacheEventListener evcacheEventListener : evcacheEventListenerList) { evcacheEventListener.onError(evcacheEvent, null); } break; } } } final List<Tag> tags = new ArrayList<Tag>(5); EVCacheMetricsFactory.getInstance().addAppNameTags(tags, appName); if(evcacheEvent != null) tags.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, evcacheEvent.getCall().name())); //tags.add(new BasicTag(EVCacheMetricsFactory.OPERATION, EVCacheMetricsFactory.VERIFY)); tags.add(new BasicTag(EVCacheMetricsFactory.FAIL_COUNT, String.valueOf(failCount))); tags.add(new BasicTag(EVCacheMetricsFactory.COMPLETE_COUNT, String.valueOf(completeCount))); EVCacheMetricsFactory.getInstance().increment(EVCacheMetricsFactory.INTERNAL_LATCH_VERIFY, tags); } } @Override public int hashCode() { return ((evcacheEvent == null) ? 0 : evcacheEvent.hashCode()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EVCacheLatchImpl other = (EVCacheLatchImpl) obj; if (appName == null) { if (other.appName != null) return false; } else if (!appName.equals(other.appName)) return false; if (evcacheEvent == null) { if (other.evcacheEvent != null) return false; } else if (!evcacheEvent.equals(other.evcacheEvent)) return false; return true; } public void setScheduledFuture(ScheduledFuture<?> scheduledFuture) { this.scheduledFuture = scheduledFuture; } public void scheduledFutureValidation() { if(evcacheEvent != null) { final EVCacheClientPool pool = evcacheEvent.getEVCacheClientPool(); final ScheduledFuture<?> scheduledFuture = pool.getEVCacheClientPoolManager().getEVCacheScheduledExecutor().schedule(this, pool.getOperationTimeout().get(), TimeUnit.MILLISECONDS); setScheduledFuture(scheduledFuture); } else { if(log.isWarnEnabled()) log.warn("Future cannot be scheduled as EVCacheEvent is null!"); } } }
19,747
39.302041
338
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/EVCacheNodeMBean.java
package net.spy.memcached; public interface EVCacheNodeMBean extends EVCacheNode { }
86
16.4
55
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/EVCacheMemcachedNodeROImpl.java
package net.spy.memcached; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.Collection; import net.spy.memcached.ops.Operation; public class EVCacheMemcachedNodeROImpl implements MemcachedNode { private final MemcachedNode root; public EVCacheMemcachedNodeROImpl(MemcachedNode n) { super(); root = n; } public String toString() { return root.toString(); } public void addOp(Operation op) { throw new UnsupportedOperationException(); } public void insertOp(Operation op) { throw new UnsupportedOperationException(); } public void connected() { throw new UnsupportedOperationException(); } public void copyInputQueue() { throw new UnsupportedOperationException(); } public void fillWriteBuffer(boolean optimizeGets) { throw new UnsupportedOperationException(); } public void fixupOps() { throw new UnsupportedOperationException(); } public int getBytesRemainingToWrite() { return root.getBytesRemainingToWrite(); } public SocketChannel getChannel() { throw new UnsupportedOperationException(); } public Operation getCurrentReadOp() { throw new UnsupportedOperationException(); } public Operation getCurrentWriteOp() { throw new UnsupportedOperationException(); } public ByteBuffer getRbuf() { throw new UnsupportedOperationException(); } public int getReconnectCount() { return root.getReconnectCount(); } public int getSelectionOps() { return root.getSelectionOps(); } public SelectionKey getSk() { throw new UnsupportedOperationException(); } public SocketAddress getSocketAddress() { return root.getSocketAddress(); } public ByteBuffer getWbuf() { throw new UnsupportedOperationException(); } public boolean hasReadOp() { return root.hasReadOp(); } public boolean hasWriteOp() { return root.hasReadOp(); } public boolean isActive() { return root.isActive(); } public void reconnecting() { throw new UnsupportedOperationException(); } public void registerChannel(SocketChannel ch, SelectionKey selectionKey) { throw new UnsupportedOperationException(); } public Operation removeCurrentReadOp() { throw new UnsupportedOperationException(); } public Operation removeCurrentWriteOp() { throw new UnsupportedOperationException(); } public void setChannel(SocketChannel to) { throw new UnsupportedOperationException(); } public void setSk(SelectionKey to) { throw new UnsupportedOperationException(); } public void setupResend() { throw new UnsupportedOperationException(); } public void transitionWriteItem() { throw new UnsupportedOperationException(); } public int writeSome() throws IOException { throw new UnsupportedOperationException(); } public Collection<Operation> destroyInputQueue() { throw new UnsupportedOperationException(); } public void authComplete() { throw new UnsupportedOperationException(); } public void setupForAuth() { throw new UnsupportedOperationException(); } public int getContinuousTimeout() { throw new UnsupportedOperationException(); } public void setContinuousTimeout(boolean isIncrease) { throw new UnsupportedOperationException(); } public boolean isAuthenticated() { throw new UnsupportedOperationException(); } public long lastReadDelta() { throw new UnsupportedOperationException(); } public void completedRead() { throw new UnsupportedOperationException(); } public MemcachedConnection getConnection() { throw new UnsupportedOperationException(); } public void setConnection(MemcachedConnection connection) { throw new UnsupportedOperationException(); } }
4,223
22.864407
78
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/EVCacheMemcachedClient.java
package net.spy.memcached; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.archaius.api.Property; import com.netflix.evcache.EVCacheGetOperationListener; import com.netflix.evcache.EVCacheLatch; import com.netflix.evcache.metrics.EVCacheMetricsFactory; import com.netflix.evcache.operation.EVCacheAsciiOperationFactory; import com.netflix.evcache.operation.EVCacheBulkGetFuture; import com.netflix.evcache.operation.EVCacheItem; import com.netflix.evcache.operation.EVCacheItemMetaData; import com.netflix.evcache.operation.EVCacheLatchImpl; import com.netflix.evcache.operation.EVCacheOperationFuture; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.util.EVCacheConfig; import com.netflix.spectator.api.BasicTag; import com.netflix.spectator.api.DistributionSummary; import com.netflix.spectator.api.Tag; import com.netflix.spectator.api.Timer; import com.netflix.spectator.ipc.IpcStatus; import net.spy.memcached.internal.GetFuture; import net.spy.memcached.internal.OperationFuture; import net.spy.memcached.ops.ConcatenationType; import net.spy.memcached.ops.DeleteOperation; import net.spy.memcached.ops.GetAndTouchOperation; import net.spy.memcached.ops.GetOperation; import net.spy.memcached.ops.Mutator; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.ops.StatsOperation; import net.spy.memcached.ops.StatusCode; import net.spy.memcached.ops.StoreOperation; import net.spy.memcached.ops.StoreType; import net.spy.memcached.protocol.binary.BinaryOperationFactory; import net.spy.memcached.transcoders.Transcoder; import net.spy.memcached.util.StringUtils; import net.spy.memcached.protocol.ascii.ExecCmdOperation; import net.spy.memcached.protocol.ascii.MetaDebugOperation; import net.spy.memcached.protocol.ascii.MetaGetOperation; @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS", "SIC_INNER_SHOULD_BE_STATIC_ANON" }) public class EVCacheMemcachedClient extends MemcachedClient { private static final Logger log = LoggerFactory.getLogger(EVCacheMemcachedClient.class); private final String appName; private final Property<Integer> readTimeout; private final EVCacheClient client; private final Map<String, Timer> timerMap = new ConcurrentHashMap<String, Timer>(); private final Map<String, DistributionSummary> distributionSummaryMap = new ConcurrentHashMap<String, DistributionSummary>(); private Property<Long> mutateOperationTimeout; private final ConnectionFactory connectionFactory; private final Property<Integer> maxReadDuration, maxWriteDuration; private final Property<Boolean> enableDebugLogsOnWrongKey; public EVCacheMemcachedClient(ConnectionFactory cf, List<InetSocketAddress> addrs, Property<Integer> readTimeout, EVCacheClient client) throws IOException { super(cf, addrs); this.connectionFactory = cf; this.readTimeout = readTimeout; this.client = client; this.appName = client.getAppName(); this.maxWriteDuration = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".max.write.duration.metric", Integer.class).orElseGet("evcache.max.write.duration.metric").orElse(50); this.maxReadDuration = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".max.read.duration.metric", Integer.class).orElseGet("evcache.max.read.duration.metric").orElse(20); this.enableDebugLogsOnWrongKey = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".enable.debug.logs.on.wrongkey", Boolean.class).orElse(false); } public NodeLocator getNodeLocator() { return this.mconn.getLocator(); } public MemcachedNode getEVCacheNode(String key) { return this.mconn.getLocator().getPrimary(key); } public <T> GetFuture<T> asyncGet(final String key, final Transcoder<T> tc) { throw new UnsupportedOperationException("asyncGet"); } // Returns 'true' if keys don't match and logs & reports the error. // Returns 'false' if keys match. // TODO: Consider removing this code once we've fixed the Wrong key bug(s) private boolean isWrongKeyReturned(String original_key, String returned_key) { if (!original_key.equals(returned_key)) { // If they keys don't match, log the error along with the key owning host's information and stack trace. final String original_host = getHostNameByKey(original_key); final String returned_host = getHostNameByKey(returned_key); log.error("Wrong key returned. Key - " + original_key + " (Host: " + original_host + ") ; Returned Key " + returned_key + " (Host: " + returned_host + ")", new Exception()); client.reportWrongKeyReturned(original_host); // If we are configured to dynamically switch log levels to DEBUG on a wrong key error, do so here. if (enableDebugLogsOnWrongKey.get()) { System.setProperty("log4j.logger.net.spy.memcached", "DEBUG"); } return true; } return false; } public <T> EVCacheOperationFuture<T> asyncGet(final String key, final Transcoder<T> tc, EVCacheGetOperationListener<T> listener) { final CountDownLatch latch = new CountDownLatch(1); final EVCacheOperationFuture<T> rv = new EVCacheOperationFuture<T>(key, latch, new AtomicReference<T>(null), readTimeout.get().intValue(), executorService, client); final Operation op = opFact.get(key, new GetOperation.Callback() { private Future<T> val = null; public void receivedStatus(OperationStatus status) { if (log.isDebugEnabled()) log.debug("Getting Key : " + key + "; Status : " + status.getStatusCode().name() + (log.isTraceEnabled() ? " Node : " + getEVCacheNode(key) : "") + "; Message : " + status.getMessage() + "; Elapsed Time - " + (System.currentTimeMillis() - rv.getStartTime())); try { if (val != null) { if (log.isTraceEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.trace("Key : " + key + "; val : " + val.get()); rv.set(val.get(), status); } else { if (log.isTraceEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.trace("Key : " + key + "; val is null"); rv.set(null, status); } } catch (Exception e) { log.error(e.getMessage(), e); rv.set(null, status); } } @SuppressWarnings("unchecked") public void gotData(String k, int flags, byte[] data) { if (isWrongKeyReturned(key, k)) return; if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug("Read data : key " + key + "; flags : " + flags + "; data : " + data); if (data != null) { if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug("Key : " + key + "; val size : " + data.length); getDataSizeDistributionSummary(EVCacheMetricsFactory.GET_OPERATION, EVCacheMetricsFactory.READ, EVCacheMetricsFactory.IPC_SIZE_INBOUND).record(data.length); if (tc == null) { if (tcService == null) { log.error("tcService is null, will not be able to decode"); throw new RuntimeException("TranscoderSevice is null. Not able to decode"); } else { final Transcoder<T> t = (Transcoder<T>) getTranscoder(); val = tcService.decode(t, new CachedData(flags, data, t.getMaxSize())); } } else { if (tcService == null) { log.error("tcService is null, will not be able to decode"); throw new RuntimeException("TranscoderSevice is null. Not able to decode"); } else { val = tcService.decode(tc, new CachedData(flags, data, tc.getMaxSize())); } } } else { if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug("Key : " + key + "; val is null" ); } } public void complete() { latch.countDown(); final String host = ((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(EVCacheMetricsFactory.GET_OPERATION, EVCacheMetricsFactory.READ, rv.getStatus(), (val != null ? EVCacheMetricsFactory.YES : EVCacheMetricsFactory.NO), host, getReadMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); rv.signalComplete(); } }); rv.setOperation(op); if (listener != null) rv.addListener(listener); mconn.enqueueOperation(key, op); return rv; } public <T> EVCacheBulkGetFuture<T> asyncGetBulk(Collection<String> keys, final Transcoder<T> tc, EVCacheGetOperationListener<T> listener) { final Map<String, Future<T>> m = new ConcurrentHashMap<String, Future<T>>(); // Break the gets down into groups by key final Map<MemcachedNode, Collection<String>> chunks = new HashMap<MemcachedNode, Collection<String>>(); final NodeLocator locator = mconn.getLocator(); //Populate Node and key Map for (String key : keys) { StringUtils.validateKey(key, opFact instanceof BinaryOperationFactory); final MemcachedNode primaryNode = locator.getPrimary(key); if (primaryNode.isActive()) { Collection<String> ks = chunks.computeIfAbsent(primaryNode, k -> new ArrayList<>()); ks.add(key); } } final AtomicInteger pendingChunks = new AtomicInteger(chunks.size()); int initialLatchCount = chunks.isEmpty() ? 0 : 1; final CountDownLatch latch = new CountDownLatch(initialLatchCount); final Collection<Operation> ops = new ArrayList<Operation>(chunks.size()); final EVCacheBulkGetFuture<T> rv = new EVCacheBulkGetFuture<T>(m, ops, latch, executorService, client); GetOperation.Callback cb = new GetOperation.Callback() { @Override public void receivedStatus(OperationStatus status) { if (log.isDebugEnabled()) log.debug("GetBulk Keys : " + keys + "; Status : " + status.getStatusCode().name() + "; Message : " + status.getMessage() + "; Elapsed Time - " + (System.currentTimeMillis() - rv.getStartTime())); rv.setStatus(status); } @Override public void gotData(String k, int flags, byte[] data) { if (data != null) { getDataSizeDistributionSummary(EVCacheMetricsFactory.BULK_OPERATION, EVCacheMetricsFactory.READ, EVCacheMetricsFactory.IPC_SIZE_INBOUND).record(data.length); } m.put(k, tcService.decode(tc, new CachedData(flags, data, tc.getMaxSize()))); } @Override public void complete() { if (pendingChunks.decrementAndGet() <= 0) { latch.countDown(); getTimer(EVCacheMetricsFactory.BULK_OPERATION, EVCacheMetricsFactory.READ, rv.getStatus(), (m.size() == keys.size() ? EVCacheMetricsFactory.YES : EVCacheMetricsFactory.NO), null, getReadMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); rv.signalComplete(); } } }; // Now that we know how many servers it breaks down into, and the latch // is all set up, convert all of these strings collections to operations final Map<MemcachedNode, Operation> mops = new HashMap<MemcachedNode, Operation>(); for (Map.Entry<MemcachedNode, Collection<String>> me : chunks.entrySet()) { Operation op = opFact.get(me.getValue(), cb); mops.put(me.getKey(), op); ops.add(op); } assert mops.size() == chunks.size(); mconn.checkState(); mconn.addOperations(mops); return rv; } public <T> EVCacheOperationFuture<CASValue<T>> asyncGetAndTouch(final String key, final int exp, final Transcoder<T> tc) { final CountDownLatch latch = new CountDownLatch(1); final EVCacheOperationFuture<CASValue<T>> rv = new EVCacheOperationFuture<CASValue<T>>(key, latch, new AtomicReference<CASValue<T>>(null), operationTimeout, executorService, client); Operation op = opFact.getAndTouch(key, exp, new GetAndTouchOperation.Callback() { private CASValue<T> val = null; public void receivedStatus(OperationStatus status) { if (log.isDebugEnabled()) log.debug("GetAndTouch Key : " + key + "; Status : " + status.getStatusCode().name() + (log.isTraceEnabled() ? " Node : " + getEVCacheNode(key) : "") + "; Message : " + status.getMessage() + "; Elapsed Time - " + (System.currentTimeMillis() - rv.getStartTime())); rv.set(val, status); } public void complete() { latch.countDown(); final String host = ((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(EVCacheMetricsFactory.GET_AND_TOUCH_OPERATION, EVCacheMetricsFactory.READ, rv.getStatus(), (val != null ? EVCacheMetricsFactory.YES : EVCacheMetricsFactory.NO), host, getReadMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); rv.signalComplete(); } public void gotData(String k, int flags, long cas, byte[] data) { if (isWrongKeyReturned(key, k)) return; if (data != null) getDataSizeDistributionSummary(EVCacheMetricsFactory.GET_AND_TOUCH_OPERATION, EVCacheMetricsFactory.READ, EVCacheMetricsFactory.IPC_SIZE_INBOUND).record(data.length); val = new CASValue<T>(cas, tc.decode(new CachedData(flags, data, tc.getMaxSize()))); } }); rv.setOperation(op); mconn.enqueueOperation(key, op); return rv; } public <T> OperationFuture<Boolean> set(String key, int exp, T o, final Transcoder<T> tc) { return asyncStore(StoreType.set, key, exp, o, tc, null); } public OperationFuture<Boolean> set(String key, int exp, Object o) { return asyncStore(StoreType.set, key, exp, o, transcoder, null); } @SuppressWarnings("unchecked") public <T> OperationFuture<Boolean> set(String key, int exp, T o, final Transcoder<T> tc, EVCacheLatch latch) { Transcoder<T> t = (Transcoder<T>) ((tc == null) ? transcoder : tc); return asyncStore(StoreType.set, key, exp, o, t, latch); } @SuppressWarnings("unchecked") public <T> OperationFuture<Boolean> replace(String key, int exp, T o, final Transcoder<T> tc, EVCacheLatch latch) { Transcoder<T> t = (Transcoder<T>) ((tc == null) ? transcoder : tc); return asyncStore(StoreType.replace, key, exp, o, t, latch); } public <T> OperationFuture<Boolean> add(String key, int exp, T o, Transcoder<T> tc) { return asyncStore(StoreType.add, key, exp, o, tc, null); } public OperationFuture<Boolean> delete(String key, EVCacheLatch evcacheLatch) { final CountDownLatch latch = new CountDownLatch(1); final EVCacheOperationFuture<Boolean> rv = new EVCacheOperationFuture<Boolean>(key, latch, new AtomicReference<Boolean>(null), operationTimeout, executorService, client); final DeleteOperation op = opFact.delete(key, new DeleteOperation.Callback() { @Override public void receivedStatus(OperationStatus status) { rv.set(Boolean.TRUE, status); } @Override public void gotData(long cas) { rv.setCas(cas); } @Override public void complete() { latch.countDown(); final String host = ((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(EVCacheMetricsFactory.DELETE_OPERATION, EVCacheMetricsFactory.WRITE, rv.getStatus(), null, host, getWriteMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); rv.signalComplete(); } }); rv.setOperation(op); if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl && !client.isInWriteOnly()) ((EVCacheLatchImpl) evcacheLatch).addFuture(rv); mconn.enqueueOperation(key, op); return rv; } public <T> OperationFuture<Boolean> touch(final String key, final int exp, EVCacheLatch evcacheLatch) { final CountDownLatch latch = new CountDownLatch(1); final EVCacheOperationFuture<Boolean> rv = new EVCacheOperationFuture<Boolean>(key, latch, new AtomicReference<Boolean>(null), operationTimeout, executorService, client); final Operation op = opFact.touch(key, exp, new OperationCallback() { @Override public void receivedStatus(OperationStatus status) { rv.set(status.isSuccess(), status); } @Override public void complete() { latch.countDown(); final String host = ((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(EVCacheMetricsFactory.TOUCH_OPERATION, EVCacheMetricsFactory.WRITE, rv.getStatus(), null, host, getWriteMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); rv.signalComplete(); } }); rv.setOperation(op); if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl && !client.isInWriteOnly()) ((EVCacheLatchImpl) evcacheLatch).addFuture(rv); mconn.enqueueOperation(key, op); return rv; } public <T> OperationFuture<Boolean> asyncAppendOrAdd(final String key, int exp, CachedData co, EVCacheLatch evcacheLatch) { final CountDownLatch latch = new CountDownLatch(1); if(co != null && co.getData() != null) getDataSizeDistributionSummary(EVCacheMetricsFactory.AOA_OPERATION, EVCacheMetricsFactory.WRITE, EVCacheMetricsFactory.IPC_SIZE_OUTBOUND).record(co.getData().length); final EVCacheOperationFuture<Boolean> rv = new EVCacheOperationFuture<Boolean>(key, latch, new AtomicReference<Boolean>(null), operationTimeout, executorService, client); final Operation opAppend = opFact.cat(ConcatenationType.append, 0, key, co.getData(), new OperationCallback() { boolean appendSuccess = false; @Override public void receivedStatus(OperationStatus val) { if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug("AddOrAppend Key (Append Operation): " + key + "; Status : " + val.getStatusCode().name() + "; Message : " + val.getMessage() + "; Elapsed Time - " + (System.currentTimeMillis() - rv.getStartTime())); if (val.getStatusCode().equals(StatusCode.SUCCESS)) { rv.set(Boolean.TRUE, val); appendSuccess = true; } } @Override public void complete() { if(appendSuccess) { final String host = ((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(EVCacheMetricsFactory.AOA_OPERATION_APPEND, EVCacheMetricsFactory.WRITE, rv.getStatus(), EVCacheMetricsFactory.YES, host, getWriteMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS);; latch.countDown(); rv.signalComplete(); } else { Operation opAdd = opFact.store(StoreType.add, key, co.getFlags(), exp, co.getData(), new StoreOperation.Callback() { @Override public void receivedStatus(OperationStatus addStatus) { if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug("AddOrAppend Key (Add Operation): " + key + "; Status : " + addStatus.getStatusCode().name() + "; Message : " + addStatus.getMessage() + "; Elapsed Time - " + (System.currentTimeMillis() - rv.getStartTime())); if(addStatus.isSuccess()) { appendSuccess = true; rv.set(addStatus.isSuccess(), addStatus); } else { Operation opReappend = opFact.cat(ConcatenationType.append, 0, key, co.getData(), new OperationCallback() { public void receivedStatus(OperationStatus retryAppendStatus) { if (retryAppendStatus.getStatusCode().equals(StatusCode.SUCCESS)) { rv.set(Boolean.TRUE, retryAppendStatus); if (log.isDebugEnabled()) log.debug("AddOrAppend Retry append Key (Append Operation): " + key + "; Status : " + retryAppendStatus.getStatusCode().name() + "; Message : " + retryAppendStatus.getMessage() + "; Elapsed Time - " + (System.currentTimeMillis() - rv.getStartTime())); } else { rv.set(Boolean.FALSE, retryAppendStatus); } } public void complete() { final String host = ((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(EVCacheMetricsFactory.AOA_OPERATION_REAPPEND, EVCacheMetricsFactory.WRITE, rv.getStatus(), EVCacheMetricsFactory.YES, host, getWriteMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); latch.countDown(); rv.signalComplete(); } }); rv.setOperation(opReappend); mconn.enqueueOperation(key, opReappend); } } @Override public void gotData(String key, long cas) { rv.setCas(cas); } @Override public void complete() { if(appendSuccess) { final String host = ((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(EVCacheMetricsFactory.AOA_OPERATION_ADD, EVCacheMetricsFactory.WRITE, rv.getStatus(), EVCacheMetricsFactory.YES, host, getWriteMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); latch.countDown(); rv.signalComplete(); } } }); rv.setOperation(opAdd); mconn.enqueueOperation(key, opAdd); } } }); rv.setOperation(opAppend); mconn.enqueueOperation(key, opAppend); if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl && !client.isInWriteOnly()) ((EVCacheLatchImpl) evcacheLatch).addFuture(rv); return rv; } private Timer getTimer(String operation, String operationType, OperationStatus status, String hit, String host, long maxDuration) { String name = ((status != null) ? operation + status.getMessage() : operation ); if(hit != null) name = name + hit; Timer timer = timerMap.get(name); if(timer != null) return timer; final List<Tag> tagList = new ArrayList<Tag>(client.getTagList().size() + 4 + (host == null ? 0 : 1)); tagList.addAll(client.getTagList()); if(operation != null) tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, operation)); if(operationType != null) tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TYPE_TAG, operationType)); if(status != null) { if(status.getStatusCode() == StatusCode.SUCCESS || status.getStatusCode() == StatusCode.ERR_NOT_FOUND || status.getStatusCode() == StatusCode.ERR_EXISTS) { tagList.add(new BasicTag(EVCacheMetricsFactory.IPC_RESULT, EVCacheMetricsFactory.SUCCESS)); } else { tagList.add(new BasicTag(EVCacheMetricsFactory.IPC_RESULT, EVCacheMetricsFactory.FAIL)); } tagList.add(new BasicTag(EVCacheMetricsFactory.IPC_STATUS, getStatusCode(status.getStatusCode()))); } if(hit != null) tagList.add(new BasicTag(EVCacheMetricsFactory.CACHE_HIT, hit)); if(host != null) tagList.add(new BasicTag(EVCacheMetricsFactory.FAILED_HOST, host)); timer = EVCacheMetricsFactory.getInstance().getPercentileTimer(EVCacheMetricsFactory.IPC_CALL, tagList, Duration.ofMillis(maxDuration)); timerMap.put(name, timer); return timer; } private String getStatusCode(StatusCode sc) { return EVCacheMetricsFactory.getInstance().getStatusCode(sc); } private DistributionSummary getDataSizeDistributionSummary(String operation, String type, String metric) { DistributionSummary distributionSummary = distributionSummaryMap.get(operation); if(distributionSummary != null) return distributionSummary; final List<Tag> tagList = new ArrayList<Tag>(6); tagList.addAll(client.getTagList()); tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TAG, operation)); tagList.add(new BasicTag(EVCacheMetricsFactory.CALL_TYPE_TAG, type)); distributionSummary = EVCacheMetricsFactory.getInstance().getDistributionSummary(metric, tagList); distributionSummaryMap.put(operation, distributionSummary); return distributionSummary; } private <T> OperationFuture<Boolean> asyncStore(final StoreType storeType, final String key, int exp, T value, Transcoder<T> tc, EVCacheLatch evcacheLatch) { final CachedData co; if (value instanceof CachedData) { co = (CachedData) value; } else { co = tc.encode(value); } final CountDownLatch latch = new CountDownLatch(1); final String operationStr; if (storeType == StoreType.set) { operationStr = EVCacheMetricsFactory.SET_OPERATION; } else if (storeType == StoreType.add) { operationStr = EVCacheMetricsFactory.ADD_OPERATION; } else { operationStr = EVCacheMetricsFactory.REPLACE_OPERATION; } if(co != null && co.getData() != null) getDataSizeDistributionSummary(operationStr, EVCacheMetricsFactory.WRITE, EVCacheMetricsFactory.IPC_SIZE_OUTBOUND).record(co.getData().length); final EVCacheOperationFuture<Boolean> rv = new EVCacheOperationFuture<Boolean>(key, latch, new AtomicReference<Boolean>(null), operationTimeout, executorService, client); final Operation op = opFact.store(storeType, key, co.getFlags(), exp, co.getData(), new StoreOperation.Callback() { @Override public void receivedStatus(OperationStatus val) { if (log.isDebugEnabled()) log.debug("Storing Key : " + key + "; Status : " + val.getStatusCode().name() + (log.isTraceEnabled() ? " Node : " + getEVCacheNode(key) : "") + "; Message : " + val.getMessage() + "; Elapsed Time - " + (System.currentTimeMillis() - rv.getStartTime())); rv.set(val.isSuccess(), val); if (log.isTraceEnabled() && !val.getStatusCode().equals(StatusCode.SUCCESS)) log.trace(val.getStatusCode().name() + " storing Key : " + key , new Exception()); } @Override public void gotData(String key, long cas) { rv.setCas(cas); } @Override public void complete() { latch.countDown(); final String host = (((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) || rv.getStatus().getStatusCode().equals(StatusCode.ERR_NO_MEM)) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(operationStr, EVCacheMetricsFactory.WRITE, rv.getStatus(), null, host, getWriteMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); rv.signalComplete(); } }); rv.setOperation(op); if (evcacheLatch != null && evcacheLatch instanceof EVCacheLatchImpl && !client.isInWriteOnly()) ((EVCacheLatchImpl) evcacheLatch).addFuture(rv); mconn.enqueueOperation(key, op); return rv; } public String toString() { return appName + "-" + client.getZone() + "-" + client.getId(); } @SuppressWarnings("unchecked") public <T> OperationFuture<Boolean> add(String key, int exp, T o, final Transcoder<T> tc, EVCacheLatch latch) { Transcoder<T> t = (Transcoder<T>) ((tc == null) ? transcoder : tc); return asyncStore(StoreType.add, key, exp, o, t, latch); } public long incr(String key, long by, long def, int exp) { return mutate(Mutator.incr, key, by, def, exp); } public long decr(String key, long by, long def, int exp) { return mutate(Mutator.decr, key, by, def, exp); } public long mutate(final Mutator m, String key, long by, long def, int exp) { final String operationStr = m.name(); final long start = System.currentTimeMillis(); final AtomicLong rv = new AtomicLong(); final CountDownLatch latch = new CountDownLatch(1); final List<OperationStatus> statusList = new ArrayList<OperationStatus>(1); final Operation op = opFact.mutate(m, key, by, def, exp, new OperationCallback() { @Override public void receivedStatus(OperationStatus s) { statusList.add(s); rv.set(new Long(s.isSuccess() ? s.getMessage() : "-1")); } @Override public void complete() { latch.countDown(); } }); mconn.enqueueOperation(key, op); long retVal = def; try { if(mutateOperationTimeout == null) { mutateOperationTimeout = EVCacheConfig.getInstance().getPropertyRepository().get(appName + ".mutate.timeout", Long.class).orElse(connectionFactory.getOperationTimeout()); } if (!latch.await(mutateOperationTimeout.get(), TimeUnit.MILLISECONDS)) { if (log.isDebugEnabled()) log.debug("Mutation operation timeout. Will return -1"); retVal = -1; } else { retVal = rv.get(); } } catch (Exception e) { log.error("Exception on mutate operation : " + operationStr + " Key : " + key + "; by : " + by + "; default : " + def + "; exp : " + exp + "; val : " + retVal + "; Elapsed Time - " + (System.currentTimeMillis() - start), e); } final OperationStatus status = statusList.size() > 0 ? statusList.get(0) : null; final String host = ((status != null && status.getStatusCode().equals(StatusCode.TIMEDOUT) && op != null) ? getHostName(op.getHandlingNode().getSocketAddress()) : null); getTimer(operationStr, EVCacheMetricsFactory.WRITE, status, null, host, getWriteMetricMaxValue()).record((System.currentTimeMillis() - start), TimeUnit.MILLISECONDS); if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug(operationStr + " Key : " + key + "; by : " + by + "; default : " + def + "; exp : " + exp + "; val : " + retVal + "; Elapsed Time - " + (System.currentTimeMillis() - start)); return retVal; } public void reconnectNode(EVCacheNode evcNode ) { final long upTime = System.currentTimeMillis() - evcNode.getCreateTime(); if (log.isDebugEnabled()) log.debug("Reconnecting node : " + evcNode + "; UpTime : " + upTime); if(upTime > 30000) { //not more than once every 30 seconds : TODO make this configurable final List<Tag> tagList = new ArrayList<Tag>(client.getTagList().size() + 2); tagList.addAll(client.getTagList()); tagList.add(new BasicTag(EVCacheMetricsFactory.CONFIG_NAME, EVCacheMetricsFactory.RECONNECT)); tagList.add(new BasicTag(EVCacheMetricsFactory.FAILED_HOST, evcNode.getHostName())); EVCacheMetricsFactory.getInstance().increment(EVCacheMetricsFactory.CONFIG, tagList); evcNode.setConnectTime(System.currentTimeMillis()); mconn.queueReconnect(evcNode); } } public int getWriteMetricMaxValue() { return maxWriteDuration.get().intValue(); } public int getReadMetricMaxValue() { return maxReadDuration.get().intValue(); } private String getHostNameByKey(String key) { MemcachedNode evcNode = getEVCacheNode(key); return getHostName(evcNode.getSocketAddress()); } private String getHostName(SocketAddress sa) { if (sa == null) return null; if(sa instanceof InetSocketAddress) { return ((InetSocketAddress)sa).getHostName(); } else { return sa.toString(); } } public EVCacheItemMetaData metaDebug(String key) { final CountDownLatch latch = new CountDownLatch(1); final EVCacheItemMetaData rv = new EVCacheItemMetaData(); if(opFact instanceof EVCacheAsciiOperationFactory) { final Operation op = ((EVCacheAsciiOperationFactory)opFact).metaDebug(key, new MetaDebugOperation.Callback() { public void receivedStatus(OperationStatus status) { if (!status.isSuccess()) { if (log.isDebugEnabled()) log.debug("Unsuccessful stat fetch: %s", status); } if (log.isDebugEnabled()) log.debug("Getting Meta Debug: " + key + "; Status : " + status.getStatusCode().name() + (log.isTraceEnabled() ? " Node : " + getEVCacheNode(key) : "") + "; Message : " + status.getMessage()); } public void debugInfo(String k, String val) { if (log.isDebugEnabled()) log.debug("key " + k + "; val : " + val); if(k.equals("exp")) rv.setSecondsLeftToExpire(Long.parseLong(val) * -1); else if(k.equals("la")) rv.setSecondsSinceLastAccess(Long.parseLong(val)); else if(k.equals("cas")) rv.setCas(Long.parseLong(val)); else if(k.equals("fetch")) rv.setHasBeenFetchedAfterWrite(Boolean.parseBoolean(val)); else if(k.equals("cls")) rv.setSlabClass(Integer.parseInt(val)); else if(k.equals("size")) rv.setSizeInBytes(Integer.parseInt(val)); } public void complete() { latch.countDown(); }}); mconn.enqueueOperation(key, op); try { if (!latch.await(operationTimeout, TimeUnit.MILLISECONDS)) { if (log.isDebugEnabled()) log.debug("meta debug operation timeout. Will return empty opbject."); } } catch (Exception e) { log.error("Exception on meta debug operation : Key : " + key, e); } if (log.isDebugEnabled()) log.debug("Meta Debug Data : " + rv); } return rv; } public Map<SocketAddress, String> execCmd(final String cmd, String[] ips) { final Map<SocketAddress, String> rv = new HashMap<SocketAddress, String>(); Collection<MemcachedNode> nodes = null; if(ips == null || ips.length == 0) { nodes = mconn.getLocator().getAll(); } else { nodes = new ArrayList<MemcachedNode>(ips.length); for(String ip : ips) { for(MemcachedNode node : mconn.getLocator().getAll()) { if(((InetSocketAddress)node.getSocketAddress()).getAddress().getHostAddress().equals(ip)) { nodes.add(node); } } } } if(nodes != null && !nodes.isEmpty()) { CountDownLatch blatch = broadcastOp(new BroadcastOpFactory() { @Override public Operation newOp(final MemcachedNode n, final CountDownLatch latch) { final SocketAddress sa = n.getSocketAddress(); return ((EVCacheAsciiOperationFactory)opFact).execCmd(cmd, new ExecCmdOperation.Callback() { @Override public void receivedStatus(OperationStatus status) { if (log.isDebugEnabled()) log.debug("cmd : " + cmd + "; MemcachedNode : " + n + "; Status : " + status); rv.put(sa, status.getMessage()); } @Override public void complete() { latch.countDown(); } }); } }, nodes); try { blatch.await(operationTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException("Interrupted waiting for stats", e); } } return rv; } public <T> EVCacheOperationFuture<EVCacheItem<T>> asyncMetaGet(final String key, final Transcoder<T> tc, EVCacheGetOperationListener<T> listener) { final CountDownLatch latch = new CountDownLatch(1); final EVCacheOperationFuture<EVCacheItem<T>> rv = new EVCacheOperationFuture<EVCacheItem<T>>(key, latch, new AtomicReference<EVCacheItem<T>>(null), readTimeout.get().intValue(), executorService, client); if(opFact instanceof EVCacheAsciiOperationFactory) { final Operation op = ((EVCacheAsciiOperationFactory)opFact).metaGet(key, new MetaGetOperation.Callback() { private EVCacheItem<T> evItem = new EVCacheItem<T>(); public void receivedStatus(OperationStatus status) { if (log.isDebugEnabled()) log.debug("Getting Key : " + key + "; Status : " + status.getStatusCode().name() + (log.isTraceEnabled() ? " Node : " + getEVCacheNode(key) : "") + "; Message : " + status.getMessage() + "; Elapsed Time - " + (System.currentTimeMillis() - rv.getStartTime())); try { if (evItem.getData() != null) { if (log.isTraceEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.trace("Key : " + key + "; val : " + evItem); rv.set(evItem, status); } else { if (log.isTraceEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.trace("Key : " + key + "; val is null"); rv.set(null, status); } } catch (Exception e) { log.error(e.getMessage(), e); rv.set(null, status); } } @Override public void gotMetaData(String k, char flag, String fVal) { if (log.isDebugEnabled()) log.debug("key " + k + "; val : " + fVal + "; flag : " + flag); if (isWrongKeyReturned(key, k)) return; switch (flag) { case 's': evItem.getItemMetaData().setSizeInBytes(Integer.parseInt(fVal)); break; case 'c': evItem.getItemMetaData().setCas(Long.parseLong(fVal)); break; case 'f': evItem.setFlag(Integer.parseInt(fVal)); break; case 'h': evItem.getItemMetaData().setHasBeenFetchedAfterWrite(fVal.equals("1")); break; case 'l': evItem.getItemMetaData().setSecondsSinceLastAccess(Long.parseLong(fVal)); break; case 'O': //opaque = val; break; case 't': final int ttlLeft = Integer.parseInt(fVal); evItem.getItemMetaData().setSecondsLeftToExpire(ttlLeft); getDataSizeDistributionSummary(EVCacheMetricsFactory.META_GET_OPERATION, EVCacheMetricsFactory.READ, EVCacheMetricsFactory.INTERNAL_TTL).record(ttlLeft); break; default: break; } } @Override public void gotData(String k, int flag, byte[] data) { if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug("Read data : key " + k + "; flags : " + flag + "; data : " + data); if (isWrongKeyReturned(key, k)) return; if (data != null) { if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug("Key : " + k + "; val size : " + data.length); getDataSizeDistributionSummary(EVCacheMetricsFactory.META_GET_OPERATION, EVCacheMetricsFactory.READ, EVCacheMetricsFactory.IPC_SIZE_INBOUND).record(data.length); if (tc == null) { if (tcService == null) { log.error("tcService is null, will not be able to decode"); throw new RuntimeException("TranscoderSevice is null. Not able to decode"); } else { final Transcoder<T> t = (Transcoder<T>) getTranscoder(); final T item = t.decode(new CachedData(flag, data, t.getMaxSize())); evItem.setData(item); } } else { if (tcService == null) { log.error("tcService is null, will not be able to decode"); throw new RuntimeException("TranscoderSevice is null. Not able to decode"); } else { final T item = tc.decode(new CachedData(flag, data, tc.getMaxSize())); evItem.setData(item); } } } else { if (log.isDebugEnabled() && client.getPool().getEVCacheClientPoolManager().shouldLog(appName)) log.debug("Key : " + k + "; val is null" ); } } public void complete() { latch.countDown(); final String host = ((rv.getStatus().getStatusCode().equals(StatusCode.TIMEDOUT) && rv.getOperation() != null) ? getHostName(rv.getOperation().getHandlingNode().getSocketAddress()) : null); getTimer(EVCacheMetricsFactory.META_GET_OPERATION, EVCacheMetricsFactory.READ, rv.getStatus(), (evItem.getData() != null ? EVCacheMetricsFactory.YES : EVCacheMetricsFactory.NO), host, getReadMetricMaxValue()).record((System.currentTimeMillis() - rv.getStartTime()), TimeUnit.MILLISECONDS); rv.signalComplete(); } }); rv.setOperation(op); mconn.enqueueOperation(key, op); if (log.isDebugEnabled()) log.debug("Meta_Get Data : " + rv); } return rv; } }
46,371
54.668667
305
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/EVCacheConnection.java
package net.spy.memcached; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedSelectorException; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.spy.memcached.ops.Operation; public class EVCacheConnection extends MemcachedConnection { private static final Logger log = LoggerFactory.getLogger(EVCacheConnection.class); public EVCacheConnection(String name, int bufSize, ConnectionFactory f, List<InetSocketAddress> a, Collection<ConnectionObserver> obs, FailureMode fm, OperationFactory opfactory) throws IOException { super(bufSize, f, a, obs, fm, opfactory); setName(name); } @Override public void shutdown() throws IOException { try { super.shutdown(); for (MemcachedNode qa : getLocator().getAll()) { if (qa instanceof EVCacheNode) { ((EVCacheNode) qa).shutdown(); } } } finally { if(running) { running = false; if(log.isWarnEnabled()) log.warn("Forceful shutdown by interrupting the thread.", new Exception()); interrupt(); } } } public void run() { while (running) { try { handleIO(); } catch (IOException e) { if (log.isDebugEnabled()) log.debug(e.getMessage(), e); } catch (CancelledKeyException e) { if (log.isDebugEnabled()) log.debug(e.getMessage(), e); } catch (ClosedSelectorException e) { if (log.isDebugEnabled()) log.debug(e.getMessage(), e); } catch (IllegalStateException e) { if (log.isDebugEnabled()) log.debug(e.getMessage(), e); } catch (ConcurrentModificationException e) { if (log.isDebugEnabled()) log.debug(e.getMessage(), e); } catch (Throwable e) { log.error("SEVERE EVCACHE ISSUE.", e);// This ensures the thread // doesn't die } } if (log.isDebugEnabled()) log.debug(toString() + " : Shutdown"); } public String toString() { return super.toString(); } protected void addOperation(final MemcachedNode node, final Operation o) { super.addOperation(node, o); ((EVCacheNode) node).incrOps(); } @Override public void addOperations(Map<MemcachedNode, Operation> ops) { super.addOperations(ops); for (MemcachedNode node : ops.keySet()) { ((EVCacheNode) node).incrOps(); } } @Override public void enqueueOperation(final String key, final Operation o) { checkState(); addOperation(key, o); } @Override public CountDownLatch broadcastOperation(BroadcastOpFactory of, Collection<MemcachedNode> nodes) { for (MemcachedNode node : nodes) { ((EVCacheNode) node).incrOps(); } return super.broadcastOperation(of, nodes); } }
3,348
32.158416
115
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/EVCacheNode.java
package net.spy.memcached; import java.util.List; import com.netflix.evcache.EVCache; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.ServerGroup; import com.netflix.spectator.api.Tag; public interface EVCacheNode extends MemcachedNode { void registerMonitors(); boolean isAvailable(EVCache.Call call); int getWriteQueueSize(); int getReadQueueSize(); int getInputQueueSize(); long incrOps(); long getNumOfOps(); void flushInputQueue(); long getStartTime(); long getTimeoutStartTime(); void removeMonitoring(); void shutdown(); long getCreateTime(); void setConnectTime(long cTime); String getAppName(); String getHostName(); ServerGroup getServerGroup(); int getId(); List<Tag> getTags(); int getTotalReconnectCount(); String getSocketChannelLocalAddress(); String getSocketChannelRemoteAddress(); String getConnectTime(); int getContinuousTimeout(); int getReconnectCount(); boolean isActive(); EVCacheClient getEVCacheClient(); }
1,105
16.015385
52
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/binary/EVCacheNodeImpl.java
package net.spy.memcached.protocol.binary; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SocketChannel; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanServer; import javax.management.ObjectName; import org.joda.time.format.ISODateTimeFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.evcache.EVCache; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.ServerGroup; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Tag; import net.spy.memcached.ConnectionFactory; import net.spy.memcached.EVCacheNode; import net.spy.memcached.EVCacheNodeMBean; import net.spy.memcached.ops.Operation; //import sun.misc.Cleaner; //import sun.nio.ch.DirectBuffer; @SuppressWarnings("restriction") @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "FCBL_FIELD_COULD_BE_LOCAL", "EXS_EXCEPTION_SOFTENING_NO_CHECKED", "REC_CATCH_EXCEPTION", "SCII_SPOILED_CHILD_INTERFACE_IMPLEMENTATOR" }) public class EVCacheNodeImpl extends BinaryMemcachedNodeImpl implements EVCacheNodeMBean, EVCacheNode { private static final Logger log = LoggerFactory.getLogger(EVCacheNodeImpl.class); protected long stTime; protected final String hostName; protected final BlockingQueue<Operation> readQ; protected final BlockingQueue<Operation> inputQueue; protected final EVCacheClient client; //protected Counter reconnectCounter; private final AtomicInteger numOps = new AtomicInteger(0); private long timeoutStartTime; protected final Counter operationsCounter; public EVCacheNodeImpl(SocketAddress sa, SocketChannel c, int bufSize, BlockingQueue<Operation> rq, BlockingQueue<Operation> wq, BlockingQueue<Operation> iq, long opQueueMaxBlockTimeMillis, boolean waitForAuth, long dt, long at, ConnectionFactory fa, EVCacheClient client, long stTime) { super(sa, c, bufSize, rq, wq, iq, Long.valueOf(opQueueMaxBlockTimeMillis), waitForAuth, dt, at, fa); this.client = client; final String appName = client.getAppName(); this.readQ = rq; this.inputQueue = iq; this.hostName = ((InetSocketAddress) getSocketAddress()).getHostName(); // final List<Tag> tagsCounter = new ArrayList<Tag>(5); // tagsCounter.add(new BasicTag(EVCacheMetricsFactory.CACHE, client.getAppName())); // tagsCounter.add(new BasicTag(EVCacheMetricsFactory.SERVERGROUP, client.getServerGroupName())); // tagsCounter.add(new BasicTag(EVCacheMetricsFactory.ZONE, client.getZone())); //tagsCounter.add(new BasicTag(EVCacheMetricsFactory.HOST, hostName)); //TODO : enable this and see what is the impact this.operationsCounter = client.getOperationCounter(); setConnectTime(stTime); setupMonitoring(appName); } private String getMonitorName(String appName) { return "com.netflix.evcache:Group=" + appName + ",SubGroup=pool" + ",SubSubGroup=" + client.getServerGroupName() + ",SubSubSubGroup=" + client.getId() + ",SubSubSubSubGroup=" + hostName + "_" + stTime; } private void setupMonitoring(String appName) { try { final ObjectName mBeanName = ObjectName.getInstance(getMonitorName(appName)); final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); if (mbeanServer.isRegistered(mBeanName)) { if (log.isDebugEnabled()) log.debug("MBEAN with name " + mBeanName + " has been registered. Will unregister the previous instance and register a new one."); mbeanServer.unregisterMBean(mBeanName); } mbeanServer.registerMBean(this, mBeanName); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Exception while setting up the monitoring.", e); } } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#registerMonitors() */ @Override public void registerMonitors() { // try { // EVCacheMetricsFactory.getInstance().getRegistry().register(this); // } catch (Exception e) { // if (log.isWarnEnabled()) log.warn("Exception while registering.", e); // } } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#isAvailable(com.netflix.evcache.EVCache.Call) */ @Override public boolean isAvailable(EVCache.Call call) { return isActive(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getWriteQueueSize() */ @Override public int getWriteQueueSize() { return writeQ.size(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getReadQueueSize() */ @Override public int getReadQueueSize() { return readQ.size(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getInputQueueSize() */ @Override public int getInputQueueSize() { return inputQueue.size(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#incrOps() */ @Override public long incrOps() { operationsCounter.increment(); return numOps.incrementAndGet(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getNumOfOps() */ @Override public long getNumOfOps() { return numOps.get(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#flushInputQueue() */ @Override public void flushInputQueue() { inputQueue.clear(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getStartTime() */ @Override public long getStartTime() { return stTime; } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getTimeoutStartTime() */ @Override public long getTimeoutStartTime() { return timeoutStartTime; } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#removeMonitoring() */ @Override public void removeMonitoring() { try { final ObjectName mBeanName = ObjectName.getInstance(getMonitorName(client.getAppName())); final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); if (mbeanServer.isRegistered(mBeanName)) { if (log.isDebugEnabled()) log.debug("MBEAN with name " + mBeanName + " has been registered. Will unregister the previous instance and register a new one."); mbeanServer.unregisterMBean(mBeanName); } } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Exception while setting up the monitoring.", e); } } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#shutdown() */ @Override public void shutdown() { removeMonitoring(); writeQ.clear(); readQ.clear(); inputQueue.clear(); try { // Cleanup the ByteBuffers only if they are sun.nio.ch.DirectBuffer // If we don't cleanup then we will leak 16K of memory // if (getRbuf() instanceof DirectBuffer) { // Cleaner cleaner = ((DirectBuffer) getRbuf()).cleaner(); // if (cleaner != null) cleaner.clean(); // cleaner = ((DirectBuffer) getWbuf()).cleaner(); // if (cleaner != null) cleaner.clean(); // } } catch (Throwable t) { getLogger().error("Exception cleaning ByteBuffer.", t); } } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getCreateTime() */ @Override public long getCreateTime() { return stTime; } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#setConnectTime(long) */ @Override public void setConnectTime(long cTime) { this.stTime = cTime; // if(reconnectCounter == null) { // final List<Tag> tags = new ArrayList<Tag>(5); // tags.add(new BasicTag(EVCacheMetricsFactory.CACHE, client.getAppName())); // tags.add(new BasicTag(EVCacheMetricsFactory.SERVERGROUP, client.getServerGroupName())); // tags.add(new BasicTag(EVCacheMetricsFactory.ZONE, client.getZone())); // tags.add(new BasicTag(EVCacheMetricsFactory.HOST, hostName)); // tags.add(new BasicTag(EVCacheMetricsFactory.CONFIG_NAME, EVCacheMetricsFactory.RECONNECT)); // this.reconnectCounter = EVCacheMetricsFactory.getInstance().getCounter(EVCacheMetricsFactory.INTERNAL_RECONNECT, tags); // // } // reconnectCounter.increment(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getAppName() */ @Override public String getAppName() { return client.getAppName(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getHostName() */ @Override public String getHostName() { return hostName; } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getServerGroup() */ @Override public ServerGroup getServerGroup() { return client.getServerGroup(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getId() */ @Override public int getId() { return client.getId(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getTags() */ @Override public List<Tag> getTags() { return client.getTagList(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getTotalReconnectCount() */ @Override public int getTotalReconnectCount() { // if(reconnectCounter == null) return 0; // return (int)reconnectCounter.count(); return getReconnectCount(); } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getSocketChannelLocalAddress() */ @Override public String getSocketChannelLocalAddress() { try { if(getChannel() != null) { return getChannel().getLocalAddress().toString(); } } catch (IOException e) { log.error("Exception", e); } return "NULL"; } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getSocketChannelRemoteAddress() */ @Override public String getSocketChannelRemoteAddress() { try { if(getChannel() != null) { return getChannel().getRemoteAddress().toString(); } } catch (IOException e) { log.error("Exception", e); } return "NULL"; } /* (non-Javadoc) * @see net.spy.memcached.protocol.binary.EVCacheNode1#getConnectTime() */ @Override public String getConnectTime() { return ISODateTimeFormat.dateTime().print(stTime); } @Override public EVCacheClient getEVCacheClient() { return client; } }
11,480
33.374251
172
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/MetaDebugOperation.java
package net.spy.memcached.protocol.ascii; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; public interface MetaDebugOperation extends Operation { /** * Operation callback for the get request. */ public interface Callback extends OperationCallback { /** * Callback for each result from a get. * * @param key the key that was retrieved * @param flags the flags for this value * @param data the data stored under this key */ void debugInfo(String key, String val); } }
586
26.952381
57
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/ExecCmdOperation.java
package net.spy.memcached.protocol.ascii; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; public interface ExecCmdOperation extends Operation { /** * Callback for cmd operation. */ interface Callback extends OperationCallback { } }
299
20.428571
53
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/ExecCmdOperationImpl.java
package net.spy.memcached.protocol.ascii; import java.nio.ByteBuffer; import java.util.Arrays; import net.spy.memcached.ops.OperationState; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.ops.StatusCode; public class ExecCmdOperationImpl extends OperationImpl implements ExecCmdOperation { private static final OperationStatus OK = new OperationStatus(true, "OK", StatusCode.SUCCESS); private static final OperationStatus ERROR = new OperationStatus(true, "ERROR", StatusCode.ERR_INTERNAL); private final byte[] cmd; public ExecCmdOperationImpl(String arg, ExecCmdOperation.Callback c) { super(c); this.cmd = (arg + "\r\n").getBytes(); } @Override public void initialize() { setBuffer(ByteBuffer.wrap(cmd)); } @Override public void handleLine(String line) { if (line.equals("OK")) { callback.receivedStatus(OK); transitionState(OperationState.COMPLETE); } else if (line.equals("ERROR")) { callback.receivedStatus(ERROR); transitionState(OperationState.COMPLETE); } } @Override protected void wasCancelled() { callback.receivedStatus(CANCELLED); } @Override public String toString() { return "Cmd: " + Arrays.toString(cmd); } }
1,363
24.735849
85
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/MetaArithmeticOperationImpl.java
package net.spy.memcached.protocol.ascii; import net.spy.memcached.KeyUtil; import net.spy.memcached.ops.Mutator; import net.spy.memcached.ops.MutatorOperation; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.ops.OperationState; import net.spy.memcached.ops.StatusCode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Collections; /** * Operation for Meta Arithmetic commands of memcached. */ public class MetaArithmeticOperationImpl extends EVCacheOperationImpl implements MutatorOperation { private static final Logger log = LoggerFactory.getLogger(MetaArithmeticOperationImpl.class); private static final OperationStatus NOT_FOUND = new OperationStatus(false, "NOT_FOUND", StatusCode.ERR_NOT_FOUND); // TODO : Move to a Builder as we expand this to support better isolation guarantees // Request private static final String META_ARITHMETIC_OP = "ma"; private static final String AUTO_CREATE = "N%d"; private static final String MUTATOR_MODE ="M%c"; private static final char INCR = '+'; private static final char DECR = '-'; private static final String DEFAULT = "J%d"; private static final String DELTA = "D%d"; private static final char FLAG_VALUE = 'v'; // Response private static final String VALUE_RETURN = "VA"; private final Mutator mutator; private final String key; private final long amount; private final long def; private final int exp; private boolean readingValue; public static final int OVERHEAD = 32; public MetaArithmeticOperationImpl(Mutator m, String k, long amt, long defaultVal, int expiry, OperationCallback c) { super(c); mutator = m; key = k; amount = amt; def = defaultVal; exp = expiry; readingValue = false; } @Override public void handleLine(String line) { log.debug("Result: %s", line); OperationStatus found = null; if (line.startsWith(VALUE_RETURN)) { // TODO : We may need to tokenize this when more flags are supplied to the request. this.readingValue = true; // Ask state machine to read the next line which has the response this.setReadType(OperationReadType.LINE); return; } else if (readingValue) { // TODO : Tokenize if multiple values are in this line, as of now, it's just the result. found = new OperationStatus(true, line, StatusCode.SUCCESS); } else { // TODO: Other NF/NS/EX and also OK are treated as errors, this will change as we extend the meta API found = NOT_FOUND; } getCallback().receivedStatus(found); transitionState(OperationState.COMPLETE); } @Override public void initialize() { int size = KeyUtil.getKeyBytes(key).length + OVERHEAD; ByteBuffer b = ByteBuffer.allocate(size); setArguments(b, META_ARITHMETIC_OP, key, String.format(AUTO_CREATE, exp), String.format(MUTATOR_MODE, (mutator == Mutator.incr ? INCR : DECR)), String.format(DEFAULT,def), String.format(DELTA,amount), FLAG_VALUE); b.flip(); setBuffer(b); } public Collection<String> getKeys() { return Collections.singleton(key); } public long getBy() { return amount; } public long getDefault() { return def; } public int getExpiration() { return exp; } public Mutator getType() { return mutator; } @Override public String toString() { return "Cmd: " + mutator.name() + " Key: " + key + " Amount: " + amount + " Default: " + def + " Expiry: " + exp; } }
3,946
31.891667
113
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/MetaGetOperationImpl.java
package net.spy.memcached.protocol.ascii; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.spy.memcached.KeyUtil; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationState; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.ops.StatusCode; public class MetaGetOperationImpl extends EVCacheOperationImpl implements MetaGetOperation { private static final Logger log = LoggerFactory.getLogger(MetaGetOperationImpl.class); private static final OperationStatus END = new OperationStatus(true, "EN", StatusCode.SUCCESS); private static final int OVERHEAD = 32; private final MetaGetOperation.Callback cb; private final String key; private int currentFlag = -1; private byte[] data = null; private int readOffset = 0; private byte lookingFor = '\0'; public MetaGetOperationImpl(String k, MetaGetOperation.Callback cb) { super(cb); this.key = k; this.cb = cb; } @Override public void handleLine(String line) { if(log.isDebugEnabled()) log.debug("meta get of {} returned {}", key, line); if (line.length() == 0 || line.equals("EN")) { getCallback().receivedStatus(END); transitionState(OperationState.COMPLETE); } else if (line.startsWith("VA")) { String[] parts = line.split(" "); if(log.isDebugEnabled()) log.debug("Num of parts "+ parts.length); if(parts.length <= 2) return; int size = Integer.parseInt(parts[1]); if(log.isDebugEnabled()) log.debug("Size of value in bytes : "+ size); data = new byte[size]; for(int i = 2; i < parts.length; i++) { final char flag = parts[i].charAt(0); final String val = parts[i].substring(1); if(log.isDebugEnabled()) log.debug("flag="+ flag + "; Val=" + val); cb.gotMetaData(key, flag, val); if(flag == 'f') currentFlag = Integer.parseInt(val); } setReadType(OperationReadType.DATA); } } public void handleRead(ByteBuffer b) { if(log.isDebugEnabled()) log.debug("readOffset: {}, length: {}", readOffset, data.length); // If we're not looking for termination, we're still looking for data if (lookingFor == '\0') { int toRead = data.length - readOffset; int available = b.remaining(); toRead = Math.min(toRead, available); if(log.isDebugEnabled()) log.debug("Reading {} bytes", toRead); b.get(data, readOffset, toRead); readOffset += toRead; } // Transition us into a ``looking for \r\n'' kind of state if we've // read enough and are still in a data state. if (readOffset == data.length && lookingFor == '\0') { // The callback is most likely a get callback. If it's not, then // it's a gets callback. OperationCallback cb = getCallback(); if (cb instanceof MetaGetOperation.Callback) { MetaGetOperation.Callback mgcb = (MetaGetOperation.Callback) cb; mgcb.gotData(key, currentFlag, data); } lookingFor = '\r'; } // If we're looking for an ending byte, let's go find it. if (lookingFor != '\0' && b.hasRemaining()) { do { byte tmp = b.get(); assert tmp == lookingFor : "Expecting " + lookingFor + ", got " + (char) tmp; switch (lookingFor) { case '\r': lookingFor = '\n'; break; case '\n': lookingFor = '\0'; break; default: assert false : "Looking for unexpected char: " + (char) lookingFor; } } while (lookingFor != '\0' && b.hasRemaining()); // Completed the read, reset stuff. if (lookingFor == '\0') { data = null; readOffset = 0; currentFlag = -1; getCallback().receivedStatus(END); transitionState(OperationState.COMPLETE); getLogger().debug("Setting read type back to line."); setReadType(OperationReadType.LINE); } } } @Override public void initialize() { final String flags = "s f t h l c v"; final ByteBuffer b = ByteBuffer.allocate(KeyUtil.getKeyBytes(key).length + flags.length() + OVERHEAD); setArguments(b, "mg", key, flags); b.flip(); setBuffer(b); } @Override public String toString() { return "Cmd: me Key: " + key; } }
4,878
36.530769
107
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/MetaGetOperation.java
package net.spy.memcached.protocol.ascii; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationCallback; public interface MetaGetOperation extends Operation { /** * Operation callback for the get request. */ public interface Callback extends OperationCallback { /** * Callback for each result from each meta data. * * @param key the key that was retrieved * @param flag all the flag * @param data the data for the flag */ void gotMetaData(String key, char flag, String data); /** * Callback for result from a get. * * @param key the key that was retrieved * @param flag the flag for this value * @param data the data stored under this key */ void gotData(String key, int flag, byte[] data); } }
881
28.4
58
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/MetaDebugOperationImpl.java
package net.spy.memcached.protocol.ascii; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.spy.memcached.KeyUtil; import net.spy.memcached.ops.OperationState; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.ops.StatusCode; public class MetaDebugOperationImpl extends EVCacheOperationImpl implements MetaDebugOperation { private static final Logger log = LoggerFactory.getLogger(MetaDebugOperationImpl.class); private static final OperationStatus END = new OperationStatus(true, "EN", StatusCode.SUCCESS); private static final int OVERHEAD = 32; private final MetaDebugOperation.Callback cb; private final String key; public MetaDebugOperationImpl(String k, MetaDebugOperation.Callback cb) { super(cb); this.key = k; this.cb = cb; } @Override public void handleLine(String line) { if(log.isDebugEnabled()) log.debug("meta debug of {} returned {}", key, line); if (line.equals("EN")) { getCallback().receivedStatus(END); transitionState(OperationState.COMPLETE); } else { String[] parts = line.split(" ", 3); if(log.isDebugEnabled()) log.debug("Num of parts "+ parts.length); if(parts.length <= 2) return; String[] kvPairs = parts[2].split(" "); for(String kv : kvPairs) { if(log.isDebugEnabled()) log.debug("kv "+ kv); String[] tuple = kv.split("=",2); if(log.isDebugEnabled()) log.debug("{} = {}", tuple[0], tuple[1]); cb.debugInfo(tuple[0], tuple[1]); } } getCallback().receivedStatus(matchStatus(line, END)); transitionState(OperationState.COMPLETE); } @Override public void initialize() { ByteBuffer b = ByteBuffer.allocate(KeyUtil.getKeyBytes(key).length + OVERHEAD); setArguments(b, "me", key); b.flip(); setBuffer(b); } @Override public String toString() { return "Cmd: me Key: " + key; } }
2,185
32.630769
99
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/EVCacheAsciiNodeImpl.java
package net.spy.memcached.protocol.ascii; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SocketChannel; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanServer; import javax.management.ObjectName; import org.joda.time.format.ISODateTimeFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.evcache.EVCache; import com.netflix.evcache.pool.EVCacheClient; import com.netflix.evcache.pool.ServerGroup; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Tag; import net.spy.memcached.ConnectionFactory; import net.spy.memcached.EVCacheNode; import net.spy.memcached.EVCacheNodeMBean; import net.spy.memcached.ops.GetOperation; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OperationState; import net.spy.memcached.protocol.ProxyCallback; import net.spy.memcached.protocol.TCPMemcachedNodeImpl; public class EVCacheAsciiNodeImpl extends TCPMemcachedNodeImpl implements EVCacheNodeMBean, EVCacheNode { private static final Logger log = LoggerFactory.getLogger(EVCacheAsciiNodeImpl.class); protected long stTime; protected final String hostName; protected final BlockingQueue<Operation> readQ; protected final BlockingQueue<Operation> inputQueue; protected final EVCacheClient client; private final AtomicInteger numOps = new AtomicInteger(0); private long timeoutStartTime; protected final Counter operationsCounter; public EVCacheAsciiNodeImpl(SocketAddress sa, SocketChannel c, int bufSize, BlockingQueue<Operation> rq, BlockingQueue<Operation> wq, BlockingQueue<Operation> iq, long opQueueMaxBlockTimeMillis, boolean waitForAuth, long dt, long at, ConnectionFactory fa, EVCacheClient client, long stTime) { // ASCII never does auth super(sa, c, bufSize, rq, wq, iq, opQueueMaxBlockTimeMillis, false, dt, at, fa); this.client = client; final String appName = client.getAppName(); this.readQ = rq; this.inputQueue = iq; this.hostName = ((InetSocketAddress) getSocketAddress()).getHostName(); this.operationsCounter = client.getOperationCounter(); setConnectTime(stTime); setupMonitoring(appName); } @Override protected void optimize() { // make sure there are at least two get operations in a row before // attempting to optimize them. if (writeQ.peek() instanceof GetOperation) { optimizedOp = writeQ.remove(); if (writeQ.peek() instanceof GetOperation) { OptimizedGetImpl og = new OptimizedGetImpl((GetOperation) optimizedOp); optimizedOp = og; while (writeQ.peek() instanceof GetOperation) { GetOperationImpl o = (GetOperationImpl) writeQ.remove(); if (!o.isCancelled()) { og.addOperation(o); } } // Initialize the new mega get optimizedOp.initialize(); assert optimizedOp.getState() == OperationState.WRITE_QUEUED; ProxyCallback pcb = (ProxyCallback) og.getCallback(); getLogger().debug("Set up %s with %s keys and %s callbacks", this, pcb.numKeys(), pcb.numCallbacks()); } } } private String getMonitorName(String appName) { return "com.netflix.evcache:Group=" + appName + ",SubGroup=pool" + ",SubSubGroup=" + client.getServerGroupName() + ",SubSubSubGroup=" + client.getId() + ",SubSubSubSubGroup=" + hostName + "_" + stTime; } private void setupMonitoring(String appName) { try { final ObjectName mBeanName = ObjectName.getInstance(getMonitorName(appName)); final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); if (mbeanServer.isRegistered(mBeanName)) { if (log.isDebugEnabled()) log.debug("MBEAN with name " + mBeanName + " has been registered. Will unregister the previous instance and register a new one."); mbeanServer.unregisterMBean(mBeanName); } mbeanServer.registerMBean(this, mBeanName); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Exception while setting up the monitoring.", e); } } public void registerMonitors() { } public boolean isAvailable(EVCache.Call call) { return isActive(); } public int getWriteQueueSize() { return writeQ.size(); } public int getReadQueueSize() { return readQ.size(); } public int getInputQueueSize() { return inputQueue.size(); } public long incrOps() { operationsCounter.increment(); return numOps.incrementAndGet(); } public long getNumOfOps() { return numOps.get(); } public void flushInputQueue() { inputQueue.clear(); } public long getStartTime() { return stTime; } public long getTimeoutStartTime() { return timeoutStartTime; } public void removeMonitoring() { try { final ObjectName mBeanName = ObjectName.getInstance(getMonitorName(client.getAppName())); final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); if (mbeanServer.isRegistered(mBeanName)) { if (log.isDebugEnabled()) log.debug("MBEAN with name " + mBeanName + " has been registered. Will unregister the previous instance and register a new one."); mbeanServer.unregisterMBean(mBeanName); } } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Exception while setting up the monitoring.", e); } } public void shutdown() { removeMonitoring(); writeQ.clear(); readQ.clear(); inputQueue.clear(); } public long getCreateTime() { return stTime; } public void setConnectTime(long cTime) { this.stTime = cTime; } public String getAppName() { return client.getAppName(); } public String getHostName() { return hostName; } public ServerGroup getServerGroup() { return client.getServerGroup(); } public int getId() { return client.getId(); } public List<Tag> getTags() { return client.getTagList(); } public int getTotalReconnectCount() { return getReconnectCount(); } @Override public String getSocketChannelLocalAddress() { try { if(getChannel() != null) { return getChannel().getLocalAddress().toString(); } } catch (IOException e) { log.error("Exception", e); } return "NULL"; } @Override public String getSocketChannelRemoteAddress() { try { if(getChannel() != null) { return getChannel().getRemoteAddress().toString(); } } catch (IOException e) { log.error("Exception", e); } return "NULL"; } @Override public String getConnectTime() { return ISODateTimeFormat.dateTime().print(stTime); } @Override public EVCacheClient getEVCacheClient() { return client; } }
7,162
29.096639
170
java
EVCache
EVCache-master/evcache-core/src/main/java/net/spy/memcached/protocol/ascii/EVCacheOperationImpl.java
package net.spy.memcached.protocol.ascii; import net.spy.memcached.ops.OperationCallback; public class EVCacheOperationImpl extends OperationImpl { protected EVCacheOperationImpl(OperationCallback cb) { super(cb); } @Override public void handleLine(String line) { // TODO Auto-generated method stub } @Override public void initialize() { // TODO Auto-generated method stub } }
459
18.166667
58
java
json-io
json-io-master/src/test/groovy/com/cedarsoftware/util/io/ObjectHolder.java
package com.cedarsoftware.util.io; /** * @author Kai Hufenbach * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class ObjectHolder { public String name; public Object obj; public ObjectHolder() { } public ObjectHolder(String name, Object obj) { this.name = name; this.obj = obj; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((obj == null) ? 0 : obj.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ObjectHolder other = (ObjectHolder) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (this.obj == null) { if (other.obj != null) { return false; } } else if (!this.obj.equals(other.obj)) { return false; } return true; } }
2,109
24.119048
83
java
json-io
json-io-master/src/test/groovy/com/cedarsoftware/util/io/TestObjectHolder.java
package com.cedarsoftware.util.io; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertTrue; /** * @author Kai Hufenbach * * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestObjectHolder { @Test public void simpleTest() { ObjectHolder holder = new ObjectHolder("bool", true); String json = JsonWriter.objectToJson(holder); ObjectHolder deserialized = (ObjectHolder) JsonReader.jsonToJava(json); assertTrue(holder.equals(deserialized)); } @Test public void testWithoutMetaData() { ObjectHolder boolHolder = new ObjectHolder("bool", true); ObjectHolder stringHolder = new ObjectHolder("string", "true"); ObjectHolder intHolder = new ObjectHolder("int", 123l); //convenience for test //Arrays will be created as Object[] arrays, as Javascript allows non uniform arrays. In deserialization process this could be checked, too. testSerialization(boolHolder); testSerialization(stringHolder); testSerialization(intHolder); } private void testSerialization(ObjectHolder holder) { Map<String, Object> serialParams = new HashMap<String, Object>(); serialParams.put(JsonWriter.TYPE, false); Map<String, Object> deSerialParams = new HashMap<String, Object>(); deSerialParams.put(JsonReader.UNKNOWN_OBJECT, ObjectHolder.class.getName()); String json = JsonWriter.objectToJson(holder, serialParams); ObjectHolder deserialized = (ObjectHolder) JsonReader.jsonToJava(json, deSerialParams); assertTrue(holder.equals(deserialized)); } }
2,383
34.058824
148
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestNotLenientNanInfinity.java
package com.cedarsoftware.util.io; import org.junit.Test; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.BeforeClass; /** * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestNotLenientNanInfinity { @BeforeClass public static void init() { JsonReader.setAllowNanAndInfinity(false); JsonWriter.setAllowNanAndInfinity(false); } public class A { private final Double doubleField; private final Float floatField; public A(Double doubleField, Float floatField) { this.doubleField = doubleField; this.floatField = floatField; } /** * @return the doubleField */ public Double getDoubleField() { return doubleField; } /** * @return the floatField */ public Float getFloatField() { return floatField; } } @Test public void testFloatDoubleNaNInf() { // Test NaN, +/-Infinity testFloatDouble(Float.NaN, Double.NaN); testFloatDouble(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); testFloatDouble(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); // Mixed. testFloatDouble(Float.NaN, Double.POSITIVE_INFINITY); testFloatDouble(Float.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); testFloatDouble(Float.NEGATIVE_INFINITY, Double.NaN); } private final void testFloatDouble(float float1, double double1) { A a = new A(double1, float1); String json = TestUtil.getJsonString(a); TestUtil.printLine("a = " + a); TestUtil.printLine("json = " + json); A newA = (A) TestUtil.readJsonObject(json); TestUtil.printLine("newA = " + newA); Double newDoubleField = newA.getDoubleField(); Float newFloatField = newA.getFloatField(); assertNull(newDoubleField); assertNull(newFloatField); } }
2,822
29.354839
83
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestSimpleValues.java
/* * */ package com.cedarsoftware.util.io; import static org.junit.Assert.assertEquals; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestSimpleValues { public class A { private final Double doubleField; private final Float floatField; private final int intField; public A(Double doubleField, Float floatField, int intField) { this.doubleField = doubleField; this.floatField = floatField; this.intField = intField; } @Override public boolean equals(Object obj) { if (null == obj || !(obj instanceof A)) { return false; } final A a = (A) obj; if (a.doubleField.equals(doubleField)) { if (a.floatField.equals(floatField)) { if (a.intField == intField) { return true; } } } return false; } /** * @return the doubleField */ public Double getDoubleField() { return doubleField; } /** * @return the floatField */ public Float getFloatField() { return floatField; } /** * @return the intField */ public int getIntField() { return intField; } @Override public String toString() { return this.getClass().getSimpleName() + ": double=" + doubleField + " ; float=" + floatField + " ; int=" + intField; } } static boolean readAllowNan; static boolean writeAllowNan; @BeforeClass public static void init() { readAllowNan = JsonReader.isAllowNanAndInfinity(); writeAllowNan = JsonWriter.isAllowNanAndInfinity(); } @AfterClass public static void tearDown() { JsonReader.setAllowNanAndInfinity(readAllowNan); JsonWriter.setAllowNanAndInfinity(writeAllowNan); } public void simpleCases() { testWriteRead(1234); testWriteRead(1f); testWriteRead(2.0); testWriteRead(-1234); testWriteRead(-1f); testWriteRead(-2.0); } @Test public void testSimpleCases() { JsonReader.setAllowNanAndInfinity(false); JsonWriter.setAllowNanAndInfinity(false); simpleCases(); JsonReader.setAllowNanAndInfinity(true); JsonWriter.setAllowNanAndInfinity(true); simpleCases(); testWriteRead(Double.POSITIVE_INFINITY); testWriteRead(Double.NEGATIVE_INFINITY); testWriteRead(Double.NaN); } private final void testWriteRead(Object testObj) { final String json = TestUtil.getJsonString(testObj); TestUtil.printLine("testObj = " + testObj); TestUtil.printLine("json = " + json); final Object newObj = TestUtil.readJsonObject(json); TestUtil.printLine("newObj = " + newObj); assertEquals(testObj, newObj); } }
3,858
26.176056
117
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestLenientNanInfinity.java
package com.cedarsoftware.util.io; import org.junit.AfterClass; import org.junit.Test; import static org.junit.Assert.assertTrue; import org.junit.BeforeClass; /** * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestLenientNanInfinity { static boolean readAllowNan; static boolean writeAllowNan; @BeforeClass public static void init() { readAllowNan = JsonReader.isAllowNanAndInfinity(); JsonReader.setAllowNanAndInfinity(true); writeAllowNan = JsonWriter.isAllowNanAndInfinity(); JsonWriter.setAllowNanAndInfinity(true); } @AfterClass public static void tearDown() { JsonReader.setAllowNanAndInfinity(readAllowNan); JsonWriter.setAllowNanAndInfinity(writeAllowNan); } public class A { private final Double doubleField; private final Float floatField; public A(Double doubleField, Float floatField) { this.doubleField = doubleField; this.floatField = floatField; } /** * @return the doubleField */ public Double getDoubleField() { return doubleField; } /** * @return the floatField */ public Float getFloatField() { return floatField; } } @Test public void testFloatDoubleNormal() { float float1 = 1f; double double1 = 2.0; testFloatDouble(float1, double1); } @Test public void testFloatDoubleNaNInf() { // Test NaN, +/-Infinity testFloatDouble(Float.NaN, Double.NaN); testFloatDouble(Float.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY); testFloatDouble(Float.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); // Mixed. testFloatDouble(Float.NaN, Double.POSITIVE_INFINITY); testFloatDouble(Float.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); testFloatDouble(Float.NEGATIVE_INFINITY, Double.NaN); } private final void testFloatDouble(float float1, double double1) { A a = new A(double1, float1); String json = TestUtil.getJsonString(a); TestUtil.printLine("a = " + a); TestUtil.printLine("json = " + json); A newA = (A) TestUtil.readJsonObject(json); TestUtil.printLine("newA = " + newA); Double newDoubleField = newA.getDoubleField(); Float newFloatField = newA.getFloatField(); Double doubleField = a.getDoubleField(); Float floatField = a.getFloatField(); assertTrue(newDoubleField.equals(doubleField)); assertTrue(newFloatField.equals(floatField)); } }
3,477
28.726496
83
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestGsonNotHandleMapWithNonStringKeysButJsonIoCan.java
package com.cedarsoftware.util.io; import com.google.gson.Gson; import org.junit.Test; import java.awt.*; import java.util.LinkedHashMap; import java.util.Map; /** * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestGsonNotHandleMapWithNonStringKeysButJsonIoCan { @Test public void testMapWithNonStringKeys() { Map<Point, String> map = new LinkedHashMap<Point, String>(); // Parameterized types of <Point, String> supplied Point pt1 = new Point(1, 10); map.put(pt1, "one"); Point pt2 = new Point(2, 20); map.put(pt2, "two"); Point pt3 = new Point(3, 30); map.put(pt3, "three"); // ------------------------ gson ------------------------ Gson gson = new Gson(); String json = gson.toJson(map); Map newMap = gson.fromJson(json, Map.class); assert newMap.size() == 3; assert !newMap.containsKey(pt1); // fail, pt1 not found assert !(newMap.keySet().iterator().next() instanceof Point); // fail, keys should be Point instances. assert newMap.keySet().iterator().next() instanceof String; // fail, keys turned into Strings. // ------------------------ json-io ------------------------ json = JsonWriter.objectToJson(map); newMap = (Map) JsonReader.jsonToJava(json); assert newMap.size() == 3; assert newMap.containsKey(pt1); // success, pt1 not found assert newMap.keySet().iterator().next() instanceof Point; // success, keys are Points } }
2,358
37.672131
122
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestGsonNotHandleStaticInnerButJsonIoCan.java
package com.cedarsoftware.util.io; import com.google.gson.Gson; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestGsonNotHandleStaticInnerButJsonIoCan { public class A { public String a; class B { public String b; public B() { // No args constructor for B } } } @Test public void testInner() { A a = new A(); a.a = "Tesla"; String json = TestUtil.getJsonString(a); TestUtil.printLine("json = " + json); A o1 = (A) TestUtil.readJsonObject(json); assertTrue(o1.a.equals("Tesla")); A.B b = a.new B(); b.b = "Elon Musk"; json = TestUtil.getJsonString(b); TestUtil.printLine("json = " + json); A.B b1 = (A.B) TestUtil.readJsonObject(json); assertTrue(b1.b.equals("Elon Musk")); // gson fail Gson gson = new Gson(); String x = gson.toJson(a); assert !x.contains("b"); // inner B dropped } }
1,876
27.014925
83
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestEmptyEnumSetOnJDK17.java
package com.cedarsoftware.util.io; import com.google.gson.Gson; import org.junit.Test; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; /** * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestEmptyEnumSetOnJDK17 { static enum TestEnum { V1 } @Test public void testEmptyEnumSetOnJDK17() { Object o = EnumSet.noneOf(TestEnum.class); String json = JsonWriter.objectToJson(o); EnumSet es = (EnumSet) JsonReader.jsonToJava(json); assert es.isEmpty(); } @Test public void testEnumSetOnJDK17() { EnumSet source = EnumSet.of(TestEnum.V1); String json = JsonWriter.objectToJson(source); EnumSet target = (EnumSet) JsonReader.jsonToJava(json); assert source.equals(target); } }
1,597
27.035088
83
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestEmptyListForJdk17.java
package com.cedarsoftware.util.io; import java.util.Collections; import java.util.List; import org.junit.Assert; import org.junit.Test; /** * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestEmptyListForJdk17 { @Test public void testEmptyListJDK17() { final Object o = Collections.emptyList(); String json = JsonWriter.objectToJson(o); List es = (List) JsonReader.jsonToJava(json); Assert.assertTrue(es.isEmpty()); Assert.assertEquals(Collections.EMPTY_LIST.getClass(), es.getClass()); } }
1,304
31.625
83
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestGsonNotHandleCycleButJsonIoCan.java
package com.cedarsoftware.util.io; import com.google.gson.Gson; import org.junit.Test; import static org.junit.Assert.fail; /** * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestGsonNotHandleCycleButJsonIoCan { static class Node { String name; Node next; Node(String name) { this.name = name; } } @Test public void testCycle() { Node alpha = new Node("alpha"); Node beta = new Node("beta"); alpha.next = beta; beta.next = alpha; // Google blows the stack when there is a cycle in the data try { Gson gson = new Gson(); String json = gson.toJson(alpha); fail(); } catch(StackOverflowError e) { // Expected with gson } // json-io handles cycles just fine. String json = JsonWriter.objectToJson(alpha); Node a2 = (Node) JsonReader.jsonToJava(json); assert "alpha".equals(a2.name); Node b2 = a2.next; assert "beta".equals(b2.name); assert b2.next == a2; assert a2.next == b2; } }
1,919
27.235294
83
java
json-io
json-io-master/src/test/java/com/cedarsoftware/util/io/TestGsonNotHandleHeteroCollections.java
package com.cedarsoftware.util.io; import com.google.gson.Gson; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import static junit.framework.TestCase.fail; /** * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestGsonNotHandleHeteroCollections { static class Node { String name; TestGsonNotHandleCycleButJsonIoCan.Node next; Node(String name) { this.name = name; } } @Test public void testGsonFailOnHeteroCollection() { List list = new ArrayList(); list.add(1); list.add(42L); list.add(Math.PI); list.add(new Node("Bitcoin")); Gson gson = new Gson(); String json = gson.toJson(list); List newList = gson.fromJson(json, List.class); // ---------------------------- gson fails ---------------------------- assert !(newList.get(0) instanceof Integer); // Fail - Integer 1 becomes 1.0 (double) assert !(newList.get(1) instanceof Long); // FAIL - Long 42 becomes 42.0 (double)) assert newList.get(2) instanceof Double; assert !(newList.get(3) instanceof Node); // Fail, last element (Node) converted to Map Map map = (Map) newList.get(3); assert "Bitcoin".equals(map.get("name")); // ---------------------------- json-io maintains types ---------------------------- json = JsonWriter.objectToJson(list); newList = (List) JsonReader.jsonToJava(json); assert newList.get(0) instanceof Integer; assert newList.get(1) instanceof Long; assert newList.get(2) instanceof Double; assert newList.get(3) instanceof Node; Node testObj = (Node) newList.get(3); assert "Bitcoin".equals(testObj.name); } }
2,601
33.693333
97
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/ObjectResolver.java
package com.cedarsoftware.util.io; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Map; import static com.cedarsoftware.util.io.JsonObject.ITEMS; import static com.cedarsoftware.util.io.JsonObject.KEYS; /** * <p>The ObjectResolver converts the raw Maps created from the JsonParser to Java * objects (a graph of Java instances). The Maps have an optional type entry associated * to them to indicate what Java peer instance to create. The reason type is optional * is because it can be inferred in a couple instances. A non-primitive field that * points to an object that is of the same type of the field, does not require the * '@type' because it can be inferred from the field. This is not always the case. * For example, if a Person field points to an Employee object (where Employee is a * subclass of Person), then the resolver cannot create an instance of the field type * (Person) because this is not the proper type. (It had an Employee record with more * fields in this example). In this case, the writer recognizes that the instance type * and field type are not the same and therefore it writes the @type. * </p><p> * A similar case as above occurs with specific array types. If there is a Person[] * containing Person and Employee instances, then the Person instances will not have * the '@type' but the employee instances will (because they are more derived than Person). * </p><p> * The resolver 'wires' the original object graph. It does this by replacing * '@ref' values in the Maps with pointers (on the field of the associated instance of the * Map) to the object that has the same ID. If the object has not yet been read, then * an UnresolvedReference is created. These are back-patched at the end of the resolution * process. UnresolvedReference keeps track of what field or array element the actual value * should be stored within, and then locates the object (by id), and updates the appropriate * value. * </p> * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class ObjectResolver extends Resolver { private final ClassLoader classLoader; protected JsonReader.MissingFieldHandler missingFieldHandler; /** * Constructor * @param reader JsonReader instance being used * @param classLoader ClassLoader that was set in the passed in 'options' arguments to JsonReader. */ protected ObjectResolver(JsonReader reader, ClassLoader classLoader) { super(reader); this.classLoader = classLoader; missingFieldHandler = reader.getMissingFieldHandler(); } /** * Walk the Java object fields and copy them from the JSON object to the Java object, performing * any necessary conversions on primitives, or deep traversals for field assignments to other objects, * arrays, Collections, or Maps. * @param stack Stack (Deque) used for graph traversal. * @param jsonObj a Map-of-Map representation of the current object being examined (containing all fields). */ public void traverseFields(final Deque<JsonObject<String, Object>> stack, final JsonObject<String, Object> jsonObj) { final Object javaMate = jsonObj.target; final Iterator<Map.Entry<String, Object>> i = jsonObj.entrySet().iterator(); final Class cls = javaMate.getClass(); while (i.hasNext()) { Map.Entry<String, Object> e = i.next(); String key = e.getKey(); final Field field = MetaUtils.getField(cls, key); Object rhs = e.getValue(); if (field != null) { assignField(stack, jsonObj, field, rhs); } else if (missingFieldHandler != null) { handleMissingField(stack, jsonObj, rhs, key); }//else no handler so ignor. } } static boolean isBasicWrapperType(Class clazz) { return clazz == Boolean.class || clazz == Integer.class || clazz == Short.class || clazz == Character.class || clazz == Byte.class || clazz == Long.class || clazz == Double.class || clazz == Float.class; } /** * Map Json Map object field to Java object field. * * @param stack Stack (Deque) used for graph traversal. * @param jsonObj a Map-of-Map representation of the current object being examined (containing all fields). * @param field a Java Field object representing where the jsonObj should be converted and stored. * @param rhs the JSON value that will be converted and stored in the 'field' on the associated * Java target object. */ protected void assignField(final Deque<JsonObject<String, Object>> stack, final JsonObject jsonObj, final Field field, final Object rhs) { final Object target = jsonObj.target; final Class targetClass = target.getClass(); try { final Class fieldType = field.getType(); if (rhs == null) { // Logically clear field (allows null to be set against primitive fields, yielding their zero value. if (fieldType.isPrimitive()) { if(isBasicWrapperType(targetClass)) { jsonObj.target = MetaUtils.convert(fieldType, "0"); } else { field.set(target, MetaUtils.convert(fieldType, "0")); } } else { field.set(target, null); } return; } // If there is a "tree" of objects (e.g, Map<String, List<Person>>), the subobjects may not have an // @type on them, if the source of the JSON is from JSON.stringify(). Deep traverse the args and // mark @type on the items within the Maps and Collections, based on the parameterized type (if it // exists). if (rhs instanceof JsonObject) { if (field.getGenericType() instanceof ParameterizedType) { // Only JsonObject instances could contain unmarked objects. markUntypedObjects(field.getGenericType(), rhs, MetaUtils.getDeepDeclaredFields(fieldType)); } // Ensure .type field set on JsonObject final JsonObject job = (JsonObject) rhs; final String type = job.type; if (type == null || type.isEmpty()) { job.setType(fieldType.getName()); } } Object special; if (rhs == JsonParser.EMPTY_OBJECT) { final JsonObject jObj = new JsonObject(); jObj.type = fieldType.getName(); Object value = createJavaObjectInstance(fieldType, jObj); field.set(target, value); } else if ((special = readIfMatching(rhs, fieldType, stack)) != null) { //TODO enum class create a field also named : "name"? that's not good rule, so will not consider that if(Enum.class.isAssignableFrom(field.getDeclaringClass()) && "name".equals(field.getName())) { //no need to set for this case } else { field.set(target, special); } } else if (rhs.getClass().isArray()) { // LHS of assignment is an [] field or RHS is an array and LHS is Object final Object[] elements = (Object[]) rhs; JsonObject<String, Object> jsonArray = new JsonObject<String, Object>(); if (char[].class == fieldType) { // Specially handle char[] because we are writing these // out as UTF8 strings for compactness and speed. if (elements.length == 0) { field.set(target, new char[]{}); } else { field.set(target, ((String) elements[0]).toCharArray()); } } else { jsonArray.put(ITEMS, elements); createJavaObjectInstance(fieldType, jsonArray); field.set(target, jsonArray.target); stack.addFirst(jsonArray); } } else if (rhs instanceof JsonObject) { final JsonObject<String, Object> jObj = (JsonObject) rhs; final Long ref = jObj.getReferenceId(); if (ref != null) { // Correct field references final JsonObject refObject = getReferencedObj(ref); if (refObject.target != null) { field.set(target, refObject.target); } else { unresolvedRefs.add(new UnresolvedReference(jsonObj, field.getName(), ref)); } } else { // Assign ObjectMap's to Object (or derived) fields field.set(target, createJavaObjectInstance(fieldType, jObj)); if (!MetaUtils.isLogicalPrimitive(jObj.getTargetClass())) { stack.addFirst((JsonObject) rhs); } } } else { if (MetaUtils.isPrimitive(fieldType)) { if(isBasicWrapperType(targetClass)) { jsonObj.target = MetaUtils.convert(fieldType, rhs); } else { field.set(target, MetaUtils.convert(fieldType, rhs)); } } else if (rhs instanceof String && "".equals(((String) rhs).trim()) && fieldType != String.class) { // Allow "" to null out a non-String field field.set(target, null); } else { field.set(target, rhs); } } } catch (Exception e) { String message = e.getClass().getSimpleName() + " setting field '" + field.getName() + "' on target: " + safeToString(target) + " with value: " + rhs; if (MetaUtils.loadClassException != null) { message += " Caused by: " + MetaUtils.loadClassException + " (which created a LinkedHashMap instead of the desired class)"; } throw new JsonIoException(message, e); } } /** * Try to create an java object from the missing field. * Mosly primitive types and jsonObject that contains @type attribute will * be candidate for the missing field callback, others will be ignored. * All missing field are stored for later notification * * @param stack Stack (Deque) used for graph traversal. * @param jsonObj a Map-of-Map representation of the current object being examined (containing all fields). * @param rhs the JSON value that will be converted and stored in the 'field' on the associated Java target object. * @param missingField name of the missing field in the java object. */ protected void handleMissingField(final Deque<JsonObject<String, Object>> stack, final JsonObject jsonObj, final Object rhs, final String missingField) { final Object target = jsonObj.target; try { if (rhs == null) { // Logically clear field (allows null to be set against primitive fields, yielding their zero value. storeMissingField(target, missingField, null); return; } // we have a jsonobject with a type Object special; if (rhs == JsonParser.EMPTY_OBJECT) { storeMissingField(target, missingField, null); } else if ((special = readIfMatching(rhs, null, stack)) != null) { storeMissingField(target, missingField, special); } else if (rhs.getClass().isArray()) { // impossible to determine the array type. storeMissingField(target, missingField, null); } else if (rhs instanceof JsonObject) { final JsonObject<String, Object> jObj = (JsonObject) rhs; final Long ref = jObj.getReferenceId(); if (ref != null) { // Correct field references final JsonObject refObject = getReferencedObj(ref); storeMissingField(target, missingField, refObject.target); } else { // Assign ObjectMap's to Object (or derived) fields // check that jObj as a type if (jObj.getType() != null) { Object createJavaObjectInstance = createJavaObjectInstance(null, jObj); if (!MetaUtils.isLogicalPrimitive(jObj.getTargetClass())) { stack.addFirst((JsonObject) rhs); } storeMissingField(target, missingField, createJavaObjectInstance); } else //no type found, just notify. { storeMissingField(target, missingField, null); } } } else { storeMissingField(target, missingField, rhs); } } catch (Exception e) { String message = e.getClass().getSimpleName() + " missing field '" + missingField + "' on target: " + safeToString(target) + " with value: " + rhs; if (MetaUtils.loadClassException != null) { message += " Caused by: " + MetaUtils.loadClassException + " (which created a LinkedHashMap instead of the desired class)"; } throw new JsonIoException(message, e); } } /** * stores the missing field and their values to call back the handler at the end of the resolution, cause some * reference may need to be resolved later. */ private void storeMissingField(Object target, String missingField, Object value) { missingFields.add(new Missingfields(target, missingField, value)); } /** * @param o Object to turn into a String * @return .toString() version of o or "null" if o is null. */ private static String safeToString(Object o) { if (o == null) { return "null"; } try { return o.toString(); } catch (Exception e) { return o.getClass().toString(); } } /** * Process java.util.Collection and it's derivatives. Collections are written specially * so that the serialization does not expose the Collection's internal structure, for * example, a TreeSet. All entries are processed, except unresolved references, which * are filled in later. For an indexable collection, the unresolved references are set * back into the proper element location. For non-indexable collections (Sets), the * unresolved references are added via .add(). * @param jsonObj a Map-of-Map representation of the JSON input stream. */ protected void traverseCollection(final Deque<JsonObject<String, Object>> stack, final JsonObject<String, Object> jsonObj) { final Object[] items = jsonObj.getArray(); if (items == null || items.length == 0) { return; } final Collection col = (Collection) jsonObj.target; final boolean isList = col instanceof List; int idx = 0; for (final Object element : items) { Object special; if (element == null) { col.add(null); } else if (element == JsonParser.EMPTY_OBJECT) { // Handles {} col.add(new JsonObject()); } else if ((special = readIfMatching(element, null, stack)) != null) { col.add(special); } else if (element instanceof String || element instanceof Boolean || element instanceof Double || element instanceof Long) { // Allow Strings, Booleans, Longs, and Doubles to be "inline" without Java object decoration (@id, @type, etc.) col.add(element); } else if (element.getClass().isArray()) { final JsonObject jObj = new JsonObject(); jObj.put(ITEMS, element); createJavaObjectInstance(Object.class, jObj); col.add(jObj.target); convertMapsToObjects(jObj); } else // if (element instanceof JsonObject) { final JsonObject jObj = (JsonObject) element; final Long ref = jObj.getReferenceId(); if (ref != null) { JsonObject refObject = getReferencedObj(ref); if (refObject.target != null) { col.add(refObject.target); } else { unresolvedRefs.add(new UnresolvedReference(jsonObj, idx, ref)); if (isList) { // Indexable collection, so set 'null' as element for now - will be patched in later. col.add(null); } } } else { createJavaObjectInstance(Object.class, jObj); if (!MetaUtils.isLogicalPrimitive(jObj.getTargetClass())) { convertMapsToObjects(jObj); } col.add(jObj.target); } } idx++; } jsonObj.remove(ITEMS); // Reduce memory required during processing } /** * Traverse the JsonObject associated to an array (of any type). Convert and * assign the list of items in the JsonObject (stored in the @items field) * to each array element. All array elements are processed excluding elements * that reference an unresolved object. These are filled in later. * * @param stack a Stack (Deque) used to support graph traversal. * @param jsonObj a Map-of-Map representation of the JSON input stream. */ protected void traverseArray(final Deque<JsonObject<String, Object>> stack, final JsonObject<String, Object> jsonObj) { final int len = jsonObj.getLength(); if (len == 0) { return; } final Class compType = jsonObj.getComponentType(); if (char.class == compType) { return; } if (byte.class == compType) { // Handle byte[] special for performance boost. jsonObj.moveBytesToMate(); jsonObj.clearArray(); return; } final boolean isPrimitive = MetaUtils.isPrimitive(compType); final Object array = jsonObj.target; final Object[] items = jsonObj.getArray(); for (int i=0; i < len; i++) { final Object element = items[i]; Object special; if (element == null) { Array.set(array, i, null); } else if (element == JsonParser.EMPTY_OBJECT) { // Use either explicitly defined type in ObjectMap associated to JSON, or array component type. Object arrayElement = createJavaObjectInstance(compType, new JsonObject()); Array.set(array, i, arrayElement); } else if ((special = readIfMatching(element, compType, stack)) != null) { Array.set(array, i, special); } else if (isPrimitive) { // Primitive component type array Array.set(array, i, MetaUtils.convert(compType, element)); } else if (element.getClass().isArray()) { // Array of arrays if (char[].class == compType) { // Specially handle char[] because we are writing these // out as UTF-8 strings for compactness and speed. Object[] jsonArray = (Object[]) element; if (jsonArray.length == 0) { Array.set(array, i, new char[]{}); } else { final String value = (String) jsonArray[0]; final int numChars = value.length(); final char[] chars = new char[numChars]; for (int j = 0; j < numChars; j++) { chars[j] = value.charAt(j); } Array.set(array, i, chars); } } else { JsonObject<String, Object> jsonObject = new JsonObject<String, Object>(); jsonObject.put(ITEMS, element); Array.set(array, i, createJavaObjectInstance(compType, jsonObject)); stack.addFirst(jsonObject); } } else if (element instanceof JsonObject) { JsonObject<String, Object> jsonObject = (JsonObject<String, Object>) element; Long ref = jsonObject.getReferenceId(); if (ref != null) { // Connect reference JsonObject refObject = getReferencedObj(ref); if (refObject.target != null) { // Array element with reference to existing object Array.set(array, i, refObject.target); } else { // Array with a forward reference as an element unresolvedRefs.add(new UnresolvedReference(jsonObj, i, ref)); } } else { // Convert JSON HashMap to Java Object instance and assign values Object arrayElement = createJavaObjectInstance(compType, jsonObject); Array.set(array, i, arrayElement); if (!MetaUtils.isLogicalPrimitive(arrayElement.getClass())) { // Skip walking primitives, primitive wrapper classes, Strings, and Classes stack.addFirst(jsonObject); } } } else { if (element instanceof String && "".equals(((String) element).trim()) && compType != String.class && compType != Object.class) { // Allow an entry of "" in the array to set the array element to null, *if* the array type is NOT String[] and NOT Object[] Array.set(array, i, null); } else { Array.set(array, i, element); } } } jsonObj.clearArray(); } /** * Convert the passed in object (o) to a proper Java object. If the passed in object (o) has a custom reader * associated to it, then have it convert the object. If there is no custom reader, then return null. * @param o Object to read (convert). Will be either a JsonObject or a JSON primitive String, long, boolean, * double, or null. * @param compType Class destination type to which the passed in object should be converted to. * @param stack a Stack (Deque) used to support graph traversal. * @return Java object converted from the passed in object o, or if there is no custom reader. */ protected Object readIfMatching(final Object o, final Class compType, final Deque<JsonObject<String, Object>> stack) { if (o == null) { throw new JsonIoException("Bug in json-io, null must be checked before calling this method."); } if (compType != null && notCustom(compType)) { return null; } final boolean isJsonObject = o instanceof JsonObject; if (!isJsonObject && compType == null) { // If not a JsonObject (like a Long that represents a date, then compType must be set) return null; } Class c; boolean needsType = false; // Set up class type to check against reader classes (specified as @type, or jObj.target, or compType) if (isJsonObject) { JsonObject jObj = (JsonObject) o; if (jObj.isReference()) { return null; } if (jObj.target == null) { // '@type' parameter used (not target instance) String typeStr = null; try { Object type = jObj.type; if (type != null) { typeStr = (String) type; c = MetaUtils.classForName((String) type, classLoader); } else { if (compType != null) { c = compType; needsType = true; } else { return null; } } createJavaObjectInstance(c, jObj); } catch(Exception e) { throw new JsonIoException("Class listed in @type [" + typeStr + "] is not found", e); } } else { // Type inferred from target object c = jObj.target.getClass(); } } else { c = compType; } if (notCustom(c)) { return null; } JsonReader.JsonClassReaderBase closestReader = getCustomReader(c); if (closestReader == null) { return null; } if (needsType) { ((JsonObject)o).setType(c.getName()); } Object read; if (closestReader instanceof JsonReader.JsonClassReaderEx) { read = ((JsonReader.JsonClassReaderEx)closestReader).read(o, stack, getReader().getArgs()); } else { read = ((JsonReader.JsonClassReader)closestReader).read(o, stack); } return read; } private void markUntypedObjects(final Type type, final Object rhs, final Map<String, Field> classFields) { final Deque<Object[]> stack = new ArrayDeque<Object[]>(); stack.addFirst(new Object[] {type, rhs}); while (!stack.isEmpty()) { Object[] item = stack.removeFirst(); final Type t = (Type) item[0]; final Object instance = item[1]; if (t instanceof ParameterizedType) { final Class clazz = getRawType(t); final ParameterizedType pType = (ParameterizedType)t; final Type[] typeArgs = pType.getActualTypeArguments(); if (typeArgs == null || typeArgs.length < 1 || clazz == null) { continue; } stampTypeOnJsonObject(instance, t); if (Map.class.isAssignableFrom(clazz)) { Map map = (Map) instance; if (!map.containsKey(KEYS) && !map.containsKey(ITEMS) && map instanceof JsonObject) { // Maps created in Javascript will come over without @keys / @items. convertMapToKeysItems((JsonObject) map); } Object[] keys = (Object[])map.get(KEYS); getTemplateTraverseWorkItem(stack, keys, typeArgs[0]); Object[] items = (Object[])map.get(ITEMS); getTemplateTraverseWorkItem(stack, items, typeArgs[1]); } else if (Collection.class.isAssignableFrom(clazz)) { if (instance instanceof Object[]) { Object[] array = (Object[]) instance; for (int i=0; i < array.length; i++) { Object vals = array[i]; stack.addFirst(new Object[]{t, vals}); if (vals instanceof JsonObject) { stack.addFirst(new Object[]{t, vals}); } else if (vals instanceof Object[]) { JsonObject coll = new JsonObject(); coll.type = clazz.getName(); List items = Arrays.asList((Object[]) vals); coll.put(ITEMS, items.toArray()); stack.addFirst(new Object[]{t, items}); array[i] = coll; } else { stack.addFirst(new Object[]{t, vals}); } } } else if (instance instanceof Collection) { final Collection col = (Collection)instance; for (Object o : col) { stack.addFirst(new Object[]{typeArgs[0], o}); } } else if (instance instanceof JsonObject) { final JsonObject jObj = (JsonObject) instance; final Object[] array = jObj.getArray(); if (array != null) { for (Object o : array) { stack.addFirst(new Object[]{typeArgs[0], o}); } } } } else { if (instance instanceof JsonObject) { final JsonObject<String, Object> jObj = (JsonObject) instance; for (Map.Entry<String, Object> entry : jObj.entrySet()) { final String fieldName = entry.getKey(); if (!fieldName.startsWith("this$")) { // TODO: If more than one type, need to associate correct typeArgs entry to value Field field = classFields.get(fieldName); if (field != null && (field.getType().getTypeParameters().length > 0 || field.getGenericType() instanceof TypeVariable)) { stack.addFirst(new Object[]{typeArgs[0], entry.getValue()}); } } } } } } else { stampTypeOnJsonObject(instance, t); } } } private static void getTemplateTraverseWorkItem(final Deque<Object[]> stack, final Object[] items, final Type type) { if (items == null || items.length < 1) { return; } Class rawType = getRawType(type); if (rawType != null && Collection.class.isAssignableFrom(rawType)) { stack.add(new Object[]{type, items}); } else { for (Object o : items) { stack.add(new Object[]{type, o}); } } } // Mark 'type' on JsonObject when the type is missing and it is a 'leaf' // node (no further subtypes in it's parameterized type definition) private static void stampTypeOnJsonObject(final Object o, final Type t) { Class clazz = t instanceof Class ? (Class)t : getRawType(t); if (o instanceof JsonObject && clazz != null) { JsonObject jObj = (JsonObject) o; if ((jObj.type == null || jObj.type.isEmpty()) && jObj.target == null) { jObj.type = clazz.getName(); } } } /** * Given the passed in Type t, return the raw type of it, if the passed in value is a ParameterizedType. * @param t Type to attempt to get raw type from. * @return Raw type obtained from the passed in parameterized type or null if T is not a ParameterizedType */ public static Class getRawType(final Type t) { if (t instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) t; if (pType.getRawType() instanceof Class) { return (Class) pType.getRawType(); } } return null; } }
35,413
39.380844
162
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/JsonReader.java
package com.cedarsoftware.util.io; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static com.cedarsoftware.util.io.JsonObject.ITEMS; /** * Read an object graph in JSON format and make it available in Java objects, or * in a "Map of Maps." (untyped representation). This code handles cyclic references * and can deserialize any Object graph without requiring a class to be 'Serializeable' * or have any specific methods on it. It will handle classes with non public constructors. * <br><br> * Usages: * <ul><li> * Call the static method: {@code JsonReader.jsonToJava(String json)}. This will * return a typed Java object graph.</li> * <li> * Call the static method: {@code JsonReader.jsonToMaps(String json)}. This will * return an untyped object representation of the JSON String as a Map of Maps, where * the fields are the Map keys, and the field values are the associated Map's values. You can * call the JsonWriter.objectToJson() method with the returned Map, and it will serialize * the Graph into the equivalent JSON stream from which it was read. * <li> * Instantiate the JsonReader with an InputStream: {@code JsonReader(InputStream in)} and then call * {@code readObject()}. Cast the return value of readObject() to the Java class that was the root of * the graph. * </li> * <li> * Instantiate the JsonReader with an InputStream: {@code JsonReader(InputStream in, true)} and then call * {@code readObject()}. The return value will be a Map of Maps. * </li></ul><br> * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class JsonReader implements Closeable { /** If set, this maps class ==> CustomReader */ public static final String CUSTOM_READER_MAP = "CUSTOM_READERS"; /** If set, this indicates that no custom reader should be used for the specified class ==> CustomReader */ public static final String NOT_CUSTOM_READER_MAP = "NOT_CUSTOM_READERS"; /** If set, the read-in JSON will be turned into a Map of Maps (JsonObject) representation */ public static final String USE_MAPS = "USE_MAPS"; /** What to do when an object is found and 'type' cannot be determined. */ public static final String UNKNOWN_OBJECT = "UNKNOWN_OBJECT"; /** Will fail JSON parsing if 'type' class defined but is not on classpath. */ public static final String FAIL_ON_UNKNOWN_TYPE = "FAIL_ON_UNKNOWN_TYPE"; /** Pointer to 'this' (automatically placed in the Map) */ public static final String JSON_READER = "JSON_READER"; /** Pointer to the current ObjectResolver (automatically placed in the Map) */ public static final String OBJECT_RESOLVER = "OBJECT_RESOLVER"; /** If set, this map will be used when writing @type values - allows short-hand abbreviations type names */ public static final String TYPE_NAME_MAP = "TYPE_NAME_MAP"; /** If set, this object will be called when a field is present in the JSON but missing from the corresponding class */ public static final String MISSING_FIELD_HANDLER = "MISSING_FIELD_HANDLER"; /** If set, use the specified ClassLoader */ public static final String CLASSLOADER = "CLASSLOADER"; /** This map is the reverse of the TYPE_NAME_MAP (value ==> key) */ static final String TYPE_NAME_MAP_REVERSE = "TYPE_NAME_MAP_REVERSE"; private static Map<Class, JsonClassReaderBase> BASE_READERS; protected final Map<Class, JsonClassReaderBase> readers = new HashMap<>(BASE_READERS); protected MissingFieldHandler missingFieldHandler; protected final Set<Class> notCustom = new HashSet<>(); private static final Map<String, Factory> factory = new ConcurrentHashMap<>(); private final Map<Long, JsonObject> objsRead = new HashMap<>(); private final FastPushbackReader input; /** _args is using ThreadLocal so that static inner classes can have access to them */ private final Map<String, Object> args = new HashMap<>(); private static volatile boolean allowNanAndInfinity = false; /** * @return boolean the allowNanAndInfinity setting */ public static boolean isAllowNanAndInfinity() { return allowNanAndInfinity; } /** * Set the reader to be out of RFC 4627: it will accept "NaN", "-Infinity" and "Infinity" values. * @param lenient the lenient to set */ public static void setAllowNanAndInfinity(boolean lenient) { JsonReader.allowNanAndInfinity = lenient; } static { Factory colFactory = new CollectionFactory(); assignInstantiator(Collection.class, colFactory); assignInstantiator(List.class, colFactory); assignInstantiator(Set.class, colFactory); assignInstantiator(SortedSet.class, colFactory); Factory mapFactory = new MapFactory(); assignInstantiator(Map.class, mapFactory); assignInstantiator(SortedMap.class, mapFactory); Map<Class, JsonClassReaderBase> temp = new HashMap<>(); temp.put(String.class, new Readers.StringReader()); temp.put(Date.class, new Readers.DateReader()); temp.put(AtomicBoolean.class, new Readers.AtomicBooleanReader()); temp.put(AtomicInteger.class, new Readers.AtomicIntegerReader()); temp.put(AtomicLong.class, new Readers.AtomicLongReader()); temp.put(BigInteger.class, new Readers.BigIntegerReader()); temp.put(BigDecimal.class, new Readers.BigDecimalReader()); temp.put(java.sql.Date.class, new Readers.SqlDateReader()); temp.put(Timestamp.class, new Readers.TimestampReader()); temp.put(Calendar.class, new Readers.CalendarReader()); temp.put(TimeZone.class, new Readers.TimeZoneReader()); temp.put(Locale.class, new Readers.LocaleReader()); temp.put(Class.class, new Readers.ClassReader()); temp.put(StringBuilder.class, new Readers.StringBuilderReader()); temp.put(StringBuffer.class, new Readers.StringBufferReader()); temp.put(UUID.class, new Readers.UUIDReader()); BASE_READERS = temp; } /** * Common ancestor for ClassFactory and ClassFactoryEx. */ public interface Factory { } /** * Subclass this interface and create a class that will return a new instance of the * passed in Class (c). Your subclass will be called when json-io encounters an * the new to instantiate an instance of (c). * * Make json-io aware that it needs to call your class by calling the public * JsonReader.assignInstantiator() API. */ public interface ClassFactory extends Factory { Object newInstance(Class c); } /** * Subclass this interface and create a class that will return a new instance of the * passed in Class (c). Your subclass will be called when json-io encounters an * the new to instantiate an instance of (c). The 'args' Map passed in will * contain a 'jsonObj' key that holds the JsonObject (Map) representing the * object being converted. If you need values from the fields of this object * in order to instantiate your class, you can grab them from the JsonObject (Map). * * Make json-io aware that it needs to call your class by calling the public * JsonReader.assignInstantiator() API. */ public interface ClassFactoryEx extends Factory { Object newInstance(Class c, Map args); } /** * Used to react to fields missing when reading an object. This method will be called after all deserialization has * occured to allow all ref to be resolved. * <p> * Used in conjunction with {@link JsonReader#MISSING_FIELD_HANDLER}. */ public interface MissingFieldHandler { /** * Notify that a field is missing. <br> * Warning : not every type can be deserialized upon missing fields. Arrays and Object type that do not have * serialized @type definition will be ignored. * * @param object the object that contains the missing field * @param fieldName name of the field to be replaced * @param value current value of the field */ void fieldMissing(Object object, String fieldName, Object value); } /** * Common ancestor for JsonClassReader and JsonClassReaderEx. */ public interface JsonClassReaderBase { } /** * Implement this interface to add a custom JSON reader. */ public interface JsonClassReader extends JsonClassReaderBase { /** * @param jOb Object being read. Could be a fundamental JSON type (String, long, boolean, double, null, or JsonObject) * @param stack Deque of objects that have been read (Map of Maps view). * @return Object you wish to convert the jOb value into. */ Object read(Object jOb, Deque<JsonObject<String, Object>> stack); } /** * Implement this interface to add a custom JSON reader. */ public interface JsonClassReaderEx extends JsonClassReaderBase { /** * @param jOb Object being read. Could be a fundamental JSON type (String, long, boolean, double, null, or JsonObject) * @param stack Deque of objects that have been read (Map of Maps view). * @param args Map of argument settings that were passed to JsonReader when instantiated. * @return Java Object you wish to convert the the passed in jOb into. */ Object read(Object jOb, Deque<JsonObject<String, Object>> stack, Map<String, Object> args); /** * Allow custom readers to have access to the JsonReader */ class Support { /** * Call this method to get an instance of the JsonReader (if needed) inside your custom reader. * @param args Map that was passed to your read(jOb, stack, args) method. * @return JsonReader instance */ public static JsonReader getReader(Map<String, Object> args) { return (JsonReader) args.get(JSON_READER); } } } /** * Use to create new instances of collection interfaces (needed for empty collections) */ public static class CollectionFactory implements ClassFactory { public Object newInstance(Class c) { if (List.class.isAssignableFrom(c)) { return new ArrayList(); } else if (SortedSet.class.isAssignableFrom(c)) { return new TreeSet(); } else if (Set.class.isAssignableFrom(c)) { return new LinkedHashSet(); } else if (Collection.class.isAssignableFrom(c)) { return new ArrayList(); } throw new JsonIoException("CollectionFactory handed Class for which it was not expecting: " + c.getName()); } } /** * Use to create new instances of Map interfaces (needed for empty Maps). Used * internally to handle Map, SortedMap when they are within parameterized types. */ public static class MapFactory implements ClassFactory { /** * @param c Map interface that was requested for instantiation. * @return a concrete Map type. */ public Object newInstance(Class c) { if (SortedMap.class.isAssignableFrom(c)) { return new TreeMap(); } else if (Map.class.isAssignableFrom(c)) { return new LinkedHashMap(); } throw new JsonIoException("MapFactory handed Class for which it was not expecting: " + c.getName()); } } /** * For difficult to instantiate classes, you can add your own ClassFactory * or ClassFactoryEx which will be called when the passed in class 'c' is * encountered. Your ClassFactory will be called with newInstance(c) and * your factory is expected to return a new instance of 'c'. * * This API is an 'escape hatch' to allow ANY object to be instantiated by JsonReader * and is useful when you encounter a class that JsonReader cannot instantiate using its * internal exhausting attempts (trying all constructors, varying arguments to them, etc.) * @param n Class name to assign an ClassFactory to * @param f ClassFactory that will create 'c' instances */ public static void assignInstantiator(String n, Factory f) { factory.put(n, f); } /** * Assign instantiated by Class. Falls back to JsonReader.assignInstantiator(String, Factory) * @param c Class to assign an ClassFactory to * @param f ClassFactory that will create 'c' instances */ public static void assignInstantiator(Class c, Factory f) { assignInstantiator(c.getName(), f); } /** * Call this method to add a custom JSON reader to json-io. It will * associate the Class 'c' to the reader you pass in. The readers are * found with isAssignableFrom(). If this is too broad, causing too * many classes to be associated to the custom reader, you can indicate * that json-io should not use a custom reader for a particular class, * by calling the addNotCustomReader() method. * @param c Class to assign a custom JSON reader to * @param reader The JsonClassReader which will read the custom JSON format of 'c' */ public void addReader(Class c, JsonClassReaderBase reader) { readers.put(c, reader); } /** * Call this method to add a custom JSON reader to json-io. It will * associate the Class 'c' to the reader you pass in. The readers are * found with isAssignableFrom(). If this is too broad, causing too * many classes to be associated to the custom reader, you can indicate * that json-io should not use a custom reader for a particular class, * by calling the addNotCustomReader() method. This method will add * the customer reader such that it will be there permanently, for the * life of the JVM (static). * @param c Class to assign a custom JSON reader to * @param reader The JsonClassReader which will read the custom JSON format of 'c' */ public static void addReaderPermanent(Class c, JsonClassReaderBase reader) { BASE_READERS.put(c, reader); } /** * Force json-io to use it's internal generic approach to writing the * passed in class, even if a Custom JSON reader is specified for its * parent class. * @param c Class to which to force no custom JSON reading to occur. * Normally, this is not needed, however, if a reader is assigned to a * parent class of 'c', then calling this method on 'c' will prevent * any custom reader from processing class 'c' */ public void addNotCustomReader(Class c) { notCustom.add(c); } MissingFieldHandler getMissingFieldHandler() { return missingFieldHandler; } public void setMissingFieldHandler(MissingFieldHandler handler) { missingFieldHandler = handler; } /** * @return The arguments used to configure the JsonReader. These are thread local. */ public Map<String, Object> getArgs() { return args; } /** * Convert the passed in JSON string into a Java object graph. * * @param json String JSON input * @return Java object graph matching JSON input */ public static Object jsonToJava(String json) { return jsonToJava(json, null); } /** * Convert the passed in JSON string into a Java object graph. * * @param json String JSON input * @param optionalArgs Map of optional parameters to control parsing. See readme file for details. * @return Java object graph matching JSON input */ public static Object jsonToJava(String json, Map<String, Object> optionalArgs) { if (json == null || "".equals(json.trim())) { return null; } if (optionalArgs == null) { optionalArgs = new HashMap<String, Object>(); optionalArgs.put(USE_MAPS, false); } if (!optionalArgs.containsKey(USE_MAPS)) { optionalArgs.put(USE_MAPS, false); } JsonReader jr = new JsonReader(json, optionalArgs); Object obj = jr.readObject(); jr.close(); return obj; } /** * Convert the passed in JSON string into a Java object graph. * * @param inputStream InputStream containing JSON input * @param optionalArgs Map of optional parameters to control parsing. See readme file for details. * @return Java object graph matching JSON input */ public static Object jsonToJava(InputStream inputStream, Map<String, Object> optionalArgs) { if (optionalArgs == null) { optionalArgs = new HashMap<String, Object>(); optionalArgs.put(USE_MAPS, false); } if (!optionalArgs.containsKey(USE_MAPS)) { optionalArgs.put(USE_MAPS, false); } JsonReader jr = new JsonReader(inputStream, optionalArgs); Object obj = jr.readObject(); jr.close(); return obj; } /** * Map args = ["USE_MAPS": true] * Use JsonReader.jsonToJava(String json, args) * Note that the return type will match the JSON type (array, object, string, long, boolean, or null). * No longer recommended: Use jsonToJava with USE_MAPS:true * @param json String of JSON content * @return Map representing JSON content. Each object is represented by a Map. */ public static Map jsonToMaps(String json) { return jsonToMaps(json, null); } /** * Map args = ["USE_MAPS": true] * Use JsonReader.jsonToJava(String json, args) * Note that the return type will match the JSON type (array, object, string, long, boolean, or null). * No longer recommended: Use jsonToJava with USE_MAPS:true * @param json String of JSON content * @param optionalArgs Map of optional arguments to control customization. See readme file for * details on these options. * @return Map where each Map representa an object in the JSON input. */ public static Map jsonToMaps(String json, Map<String, Object> optionalArgs) { if (optionalArgs == null) { optionalArgs = new HashMap<String, Object>(); } optionalArgs.put(USE_MAPS, true); ByteArrayInputStream ba = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); JsonReader jr = new JsonReader(ba, optionalArgs); Object ret = jr.readObject(); jr.close(); return adjustOutputMap(ret); } /** * Map args = ["USE_MAPS": true] * Use JsonReader.jsonToJava(inputStream, args) * Note that the return type will match the JSON type (array, object, string, long, boolean, or null). * No longer recommended: Use jsonToJava with USE_MAPS:true * @param inputStream containing JSON content * @param optionalArgs Map of optional arguments to control customization. See readme file for * details on these options. * @return Map containing the content from the JSON input. Each Map represents an object from the input. */ public static Map jsonToMaps(InputStream inputStream, Map<String, Object> optionalArgs) { if (optionalArgs == null) { optionalArgs = new HashMap<String, Object>(); } optionalArgs.put(USE_MAPS, true); JsonReader jr = new JsonReader(inputStream, optionalArgs); Object ret = jr.readObject(); jr.close(); return adjustOutputMap(ret); } private static Map adjustOutputMap(Object ret) { if (ret instanceof Map) { return (Map) ret; } if (ret != null && ret.getClass().isArray()) { JsonObject<String, Object> retMap = new JsonObject<String, Object>(); retMap.put(ITEMS, ret); return retMap; } JsonObject<String, Object> retMap = new JsonObject<String, Object>(); retMap.put(ITEMS, new Object[]{ret}); return retMap; } public JsonReader() { input = null; getArgs().put(USE_MAPS, false); getArgs().put(CLASSLOADER, JsonReader.class.getClassLoader()); } public JsonReader(InputStream inp) { this(inp, false); } /** * Use this constructor if you already have a JsonObject graph and want to parse it into * Java objects by calling jsonReader.jsonObjectsToJava(rootJsonObject) after constructing * the JsonReader. * @param optionalArgs Map of optional arguments for the JsonReader. */ public JsonReader(Map<String, Object> optionalArgs) { this(new ByteArrayInputStream(new byte[]{}), optionalArgs); } // This method is needed to get around the fact that 'this()' has to be the first method of a constructor. static Map makeArgMap(Map<String, Object> args, boolean useMaps) { args.put(USE_MAPS, useMaps); return args; } public JsonReader(InputStream inp, boolean useMaps) { this(inp, makeArgMap(new HashMap<String, Object>(), useMaps)); } public JsonReader(InputStream inp, Map<String, Object> optionalArgs) { initializeFromArgs(optionalArgs); input = new FastPushbackBufferedReader(new InputStreamReader(inp, StandardCharsets.UTF_8)); } public JsonReader(String inp, Map<String, Object> optionalArgs) { initializeFromArgs(optionalArgs); byte[] bytes = inp.getBytes(StandardCharsets.UTF_8); input = new FastPushbackBufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes), StandardCharsets.UTF_8)); } public JsonReader(byte[] inp, Map<String, Object> optionalArgs) { initializeFromArgs(optionalArgs); input = new FastPushbackBufferedReader(new InputStreamReader(new ByteArrayInputStream(inp), StandardCharsets.UTF_8)); } private void initializeFromArgs(Map<String, Object> optionalArgs) { if (optionalArgs == null) { optionalArgs = new HashMap(); } Map<String, Object> args = getArgs(); args.putAll(optionalArgs); args.put(JSON_READER, this); if (!args.containsKey(CLASSLOADER)) { args.put(CLASSLOADER, JsonReader.class.getClassLoader()); } Map<String, String> typeNames = (Map<String, String>) args.get(TYPE_NAME_MAP); if (typeNames != null) { // Reverse the Map (this allows the users to only have a Map from type to short-hand name, // and not keep a 2nd map from short-hand name to type. Map<String, String> typeNameMap = new HashMap<String, String>(); for (Map.Entry<String, String> entry : typeNames.entrySet()) { typeNameMap.put(entry.getValue(), entry.getKey()); } args.put(TYPE_NAME_MAP_REVERSE, typeNameMap); // replace with our reversed Map. } setMissingFieldHandler((MissingFieldHandler) args.get(MISSING_FIELD_HANDLER)); Map<Class, JsonClassReaderBase> customReaders = (Map<Class, JsonClassReaderBase>) args.get(CUSTOM_READER_MAP); if (customReaders != null) { for (Map.Entry<Class, JsonClassReaderBase> entry : customReaders.entrySet()) { addReader(entry.getKey(), entry.getValue()); } } Iterable<Class> notCustomReaders = (Iterable<Class>) args.get(NOT_CUSTOM_READER_MAP); if (notCustomReaders != null) { for (Class c : notCustomReaders) { addNotCustomReader(c); } } } public Map<Long, JsonObject> getObjectsRead() { return objsRead; } public Object getRefTarget(JsonObject jObj) { if (!jObj.isReference()) { return jObj; } Long id = jObj.getReferenceId(); JsonObject target = objsRead.get(id); if (target == null) { throw new IllegalStateException("The JSON input had an @ref to an object that does not exist."); } return getRefTarget(target); } /** * Read JSON input from the stream that was set up in the constructor, turning it into * Java Maps (JsonObject's). Then, if requested, the JsonObjects can be converted * into Java instances. * * @return Java Object graph constructed from InputStream supplying * JSON serialized content. */ public Object readObject() { JsonParser parser = new JsonParser(input, objsRead, getArgs()); JsonObject<String, Object> root = new JsonObject(); Object o; try { o = parser.readValue(root); if (o == JsonParser.EMPTY_OBJECT) { return new JsonObject(); } } catch (JsonIoException e) { throw e; } catch (Exception e) { throw new JsonIoException("error parsing JSON value", e); } Object graph; if (o instanceof Object[]) { root.setType(Object[].class.getName()); root.setTarget(o); root.put(ITEMS, o); graph = convertParsedMapsToJava(root); } else { graph = o instanceof JsonObject ? convertParsedMapsToJava((JsonObject) o) : o; } // Allow a complete 'Map' return (Javascript style) if (useMaps()) { return o; } return graph; } /** * Convert a root JsonObject that represents parsed JSON, into * an actual Java object. * @param root JsonObject instance that was the root object from the * JSON input that was parsed in an earlier call to JsonReader. * @return a typed Java instance that was serialized into JSON. */ public Object jsonObjectsToJava(JsonObject root) { getArgs().put(USE_MAPS, false); return convertParsedMapsToJava(root); } protected boolean useMaps() { return Boolean.TRUE.equals(getArgs().get(USE_MAPS)); } /** * @return ClassLoader to be used by Custom Writers */ ClassLoader getClassLoader() { return (ClassLoader) args.get(CLASSLOADER); } /** * This method converts a root Map, (which contains nested Maps * and so forth representing a Java Object graph), to a Java * object instance. The root map came from using the JsonReader * to parse a JSON graph (using the API that puts the graph * into Maps, not the typed representation). * @param root JsonObject instance that was the root object from the * JSON input that was parsed in an earlier call to JsonReader. * @return a typed Java instance that was serialized into JSON. */ protected Object convertParsedMapsToJava(JsonObject root) { try { Resolver resolver = useMaps() ? new MapResolver(this) : new ObjectResolver(this, (ClassLoader)args.get(CLASSLOADER)); resolver.createJavaObjectInstance(Object.class, root); Object graph = resolver.convertMapsToObjects((JsonObject<String, Object>) root); resolver.cleanup(); readers.clear(); return graph; } catch (Exception e) { try { close(); } catch (Exception ignored) { // Exception handled in close() } if (e instanceof JsonIoException) { throw (JsonIoException)e; } throw new JsonIoException(getErrorMessage(e.getMessage()), e); } } public static Object newInstance(Class c) { if (factory.containsKey(c.getName())) { ClassFactory cf = (ClassFactory) factory.get(c.getName()); return cf.newInstance(c); } return MetaUtils.newInstance(c); } public static Object newInstance(Class c, JsonObject jsonObject) { if (factory.containsKey(c.getName())) { Factory cf = factory.get(c.getName()); if (cf instanceof ClassFactoryEx) { Map args = new HashMap(); args.put("jsonObj", jsonObject); return ((ClassFactoryEx)cf).newInstance(c, args); } if (cf instanceof ClassFactory) { return ((ClassFactory)cf).newInstance(c); } throw new JsonIoException("Unknown instantiator (Factory) class. Must subclass ClassFactoryEx or ClassFactory, found: " + cf.getClass().getName()); } return MetaUtils.newInstance(c); } public void close() { try { if (input != null) { input.close(); } } catch (Exception e) { throw new JsonIoException("Unable to close input", e); } } private String getErrorMessage(String msg) { if (input != null) { return msg + "\nLast read: " + input.getLastSnippet() + "\nline: " + input.getLine() + ", col: " + input.getCol(); } return msg; } }
30,820
36.26844
160
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/JsonIoException.java
package com.cedarsoftware.util.io; /** * Custom RuntimeException subclass that is used as the main exception thrown by * json-io. * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class JsonIoException extends RuntimeException { /** * Constructs a new runtime exception with {@code null} as its * detail message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ public JsonIoException() { super(); } /** * Constructs a new runtime exception with the specified detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public JsonIoException(String message) { super(message); } /** * Constructs a new runtime exception with the specified detail message and * cause. <p>Note that the detail message associated with * {@code cause} is <i>not</i> automatically incorporated in * this runtime exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public JsonIoException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new runtime exception with the specified cause and a * detail message of <tt>(cause==null ? null : cause.toString())</tt> * (which typically contains the class and detail message of * <tt>cause</tt>). This constructor is useful for runtime exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) */ public JsonIoException(Throwable cause) { super(cause); } }
3,151
36.975904
83
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/Writers.java
package com.cedarsoftware.util.io; import java.io.IOException; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Timestamp; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * All custom writers for json-io subclass this class. Special writers are not needed for handling * user-defined classes. However, special writers are built/supplied by json-io for many of the * primitive types and other JDK classes simply to allow for a more concise form. * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.* */ public class Writers { private Writers () {} public static class TimeZoneWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { TimeZone cal = (TimeZone) obj; output.write("\"zone\":\""); output.write(cal.getID()); output.write('"'); } public boolean hasPrimitiveForm() { return false; } public void writePrimitiveForm(Object o, Writer output) throws IOException {} } public static class CalendarWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { Calendar cal = (Calendar) obj; MetaUtils.dateFormat.get().setTimeZone(cal.getTimeZone()); output.write("\"time\":\""); output.write(MetaUtils.dateFormat.get().format(cal.getTime())); output.write("\",\"zone\":\""); output.write(cal.getTimeZone().getID()); output.write('"'); } public boolean hasPrimitiveForm() { return false; } public void writePrimitiveForm(Object o, Writer output) throws IOException {} } public static class DateWriter implements JsonWriter.JsonClassWriter, JsonWriter.JsonClassWriterEx { public void write(Object obj, boolean showType, Writer output) throws IOException { throw new JsonIoException("Should never be called."); } public void write(Object obj, boolean showType, Writer output, Map args) throws IOException { Date date = (Date)obj; Object dateFormat = args.get(DATE_FORMAT); if (dateFormat instanceof String) { // Passed in as String, turn into a SimpleDateFormat instance to be used throughout this stream write. dateFormat = new SimpleDateFormat((String) dateFormat, Locale.ENGLISH); args.put(DATE_FORMAT, dateFormat); } if (showType) { output.write("\"value\":"); } if (dateFormat instanceof Format) { output.write("\""); output.write(((Format) dateFormat).format(date)); output.write("\""); } else { output.write(Long.toString(((Date) obj).getTime())); } } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { throw new JsonIoException("Should never be called."); } public void writePrimitiveForm(Object o, Writer output, Map args) throws IOException { if (args.containsKey(DATE_FORMAT)) { write(o, false, output, args); } else { output.write(Long.toString(((Date) o).getTime())); } } } public static class TimestampWriter implements JsonWriter.JsonClassWriter { public void write(Object o, boolean showType, Writer output) throws IOException { Timestamp tstamp = (Timestamp) o; output.write("\"time\":\""); output.write(Long.toString((tstamp.getTime() / 1000) * 1000)); output.write("\",\"nanos\":\""); output.write(Integer.toString(tstamp.getNanos())); output.write('"'); } public boolean hasPrimitiveForm() { return false; } public void writePrimitiveForm(Object o, Writer output) throws IOException { } } public static class ClassWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { String value = ((Class) obj).getName(); output.write("\"value\":"); writeJsonUtf8String(value, output); } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { writeJsonUtf8String(((Class)o).getName(), output); } } public static class JsonStringWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { output.write("\"value\":"); writeJsonUtf8String((String) obj, output); } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { writeJsonUtf8String((String) o, output); } } public static class LocaleWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { Locale locale = (Locale) obj; output.write("\"language\":\""); output.write(locale.getLanguage()); output.write("\",\"country\":\""); output.write(locale.getCountry()); output.write("\",\"variant\":\""); output.write(locale.getVariant()); output.write('"'); } public boolean hasPrimitiveForm() { return false; } public void writePrimitiveForm(Object o, Writer output) throws IOException { } } public static class BigIntegerWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { if (showType) { BigInteger big = (BigInteger) obj; output.write("\"value\":\""); output.write(big.toString(10)); output.write('"'); } else { writePrimitiveForm(obj, output); } } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { BigInteger big = (BigInteger) o; output.write('"'); output.write(big.toString(10)); output.write('"'); } } public static class AtomicBooleanWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { if (showType) { AtomicBoolean value = (AtomicBoolean) obj; output.write("\"value\":"); output.write(value.toString()); } else { writePrimitiveForm(obj, output); } } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { AtomicBoolean value = (AtomicBoolean) o; output.write(value.toString()); } } public static class AtomicIntegerWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { if (showType) { AtomicInteger value = (AtomicInteger) obj; output.write("\"value\":"); output.write(value.toString()); } else { writePrimitiveForm(obj, output); } } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { AtomicInteger value = (AtomicInteger) o; output.write(value.toString()); } } public static class AtomicLongWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { if (showType) { AtomicLong value = (AtomicLong) obj; output.write("\"value\":"); output.write(value.toString()); } else { writePrimitiveForm(obj, output); } } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { AtomicLong value = (AtomicLong) o; output.write(value.toString()); } } public static class BigDecimalWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { if (showType) { BigDecimal big = (BigDecimal) obj; output.write("\"value\":\""); output.write(big.toPlainString()); output.write('"'); } else { writePrimitiveForm(obj, output); } } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { BigDecimal big = (BigDecimal) o; output.write('"'); output.write(big.toPlainString()); output.write('"'); } } public static class StringBuilderWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { StringBuilder builder = (StringBuilder) obj; output.write("\"value\":\""); output.write(builder.toString()); output.write('"'); } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { StringBuilder builder = (StringBuilder) o; output.write('"'); output.write(builder.toString()); output.write('"'); } } public static class StringBufferWriter implements JsonWriter.JsonClassWriter { public void write(Object obj, boolean showType, Writer output) throws IOException { StringBuffer buffer = (StringBuffer) obj; output.write("\"value\":\""); output.write(buffer.toString()); output.write('"'); } public boolean hasPrimitiveForm() { return true; } public void writePrimitiveForm(Object o, Writer output) throws IOException { StringBuffer buffer = (StringBuffer) o; output.write('"'); output.write(buffer.toString()); output.write('"'); } } public static class UUIDWriter implements JsonWriter.JsonClassWriter { /** * To preserve backward compatibility with previous serialized format the internal fields must be stored as longs */ public void write(Object obj, boolean showType, Writer output) throws IOException { UUID uuid = (UUID) obj; output.write("\"mostSigBits\": "); output.write(Long.toString(uuid.getMostSignificantBits())); output.write(",\"leastSigBits\":"); output.write(Long.toString(uuid.getLeastSignificantBits())); } public boolean hasPrimitiveForm() { return true; } /** * We can use the String representation for easier handling, but this may break backwards compatibility * if an earlier library version is used */ public void writePrimitiveForm(Object o, Writer output) throws IOException { UUID buffer = (UUID) o; output.write('"'); output.write(buffer.toString()); output.write('"'); } } // ========== Maintain knowledge about relationships below this line ========== static final String DATE_FORMAT = JsonWriter.DATE_FORMAT; protected static void writeJsonUtf8String(String s, final Writer output) throws IOException { JsonWriter.writeJsonUtf8String(s, output); } }
13,917
33.19656
121
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/FastPushbackBufferedReader.java
package com.cedarsoftware.util.io; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; /** * This class adds significant performance increase over using the JDK * PushbackReader. This is due to this class not using synchronization * as it is not needed. */ public class FastPushbackBufferedReader extends BufferedReader implements FastPushbackReader { private final int[] buf = new int[256]; private int idx = 0; private int unread = Integer.MAX_VALUE; protected int line = 1; protected int col = 0; public FastPushbackBufferedReader(Reader reader) { super(reader); } public String getLastSnippet() { StringBuilder s = new StringBuilder(); for (int i=idx; i < buf.length; i++) { if (appendChar(s, i)) { break; } } for (int i=0; i < idx; i++) { if (appendChar(s, i)) { break; } } return s.toString(); } private boolean appendChar(StringBuilder s, int i) { try { final int snip = buf[i]; if (snip == 0) { return true; } s.appendCodePoint(snip); } catch (Exception e) { return true; } return false; } public int read() throws IOException { int ch; if (unread == 0x7fffffff) { ch = super.read(); } else { ch = unread; unread = 0x7fffffff; } if ((buf[idx++] = ch) == 0x0a) { line++; col = 0; } else { col++; } if (idx >= buf.length) { idx = 0; } return ch; } public void unread(int c) throws IOException { if ((unread = c) == 0x0a) { line--; } else { col--; } if (idx < 1) { idx = buf.length - 1; } else { idx--; } } public int getCol() { return col; } public int getLine() { return line; } }
2,339
17.870968
92
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/Readers.java
package com.cedarsoftware.util.io; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * All custom readers for json-io subclass this class. Special readers are not needed for handling * user-defined classes. However, special readers are built/supplied by json-io for many of the * primitive types and other JDK classes simply to allow for a more concise form. * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.* */ public class Readers { private Readers () {} private static final String DAYS = "(monday|mon|tuesday|tues|tue|wednesday|wed|thursday|thur|thu|friday|fri|saturday|sat|sunday|sun)"; // longer before shorter matters private static final String MOS = "(January|Jan|February|Feb|March|Mar|April|Apr|May|June|Jun|July|Jul|August|Aug|September|Sept|Sep|October|Oct|November|Nov|December|Dec)"; private static final Pattern datePattern1 = Pattern.compile("(\\d{4})[./-](\\d{1,2})[./-](\\d{1,2})"); private static final Pattern datePattern2 = Pattern.compile("(\\d{1,2})[./-](\\d{1,2})[./-](\\d{4})"); private static final Pattern datePattern3 = Pattern.compile(MOS + "[ ]*[,]?[ ]*(\\d{1,2})(st|nd|rd|th|)[ ]*[,]?[ ]*(\\d{4})", Pattern.CASE_INSENSITIVE); private static final Pattern datePattern4 = Pattern.compile("(\\d{1,2})(st|nd|rd|th|)[ ]*[,]?[ ]*" + MOS + "[ ]*[,]?[ ]*(\\d{4})", Pattern.CASE_INSENSITIVE); private static final Pattern datePattern5 = Pattern.compile("(\\d{4})[ ]*[,]?[ ]*" + MOS + "[ ]*[,]?[ ]*(\\d{1,2})(st|nd|rd|th|)", Pattern.CASE_INSENSITIVE); private static final Pattern datePattern6 = Pattern.compile(DAYS + "[ ]+" + MOS + "[ ]+(\\d{1,2})[ ]+(\\d{2}:\\d{2}:\\d{2})[ ]+[A-Z]{1,4}\\s+(\\d{4})", Pattern.CASE_INSENSITIVE); private static final Pattern timePattern1 = Pattern.compile("(\\d{2})[.:](\\d{2})[.:](\\d{2})[.](\\d{1,10})([+-]\\d{2}[:]?\\d{2}|Z)?"); private static final Pattern timePattern2 = Pattern.compile("(\\d{2})[.:](\\d{2})[.:](\\d{2})([+-]\\d{2}[:]?\\d{2}|Z)?"); private static final Pattern timePattern3 = Pattern.compile("(\\d{2})[.:](\\d{2})([+-]\\d{2}[:]?\\d{2}|Z)?"); private static final Pattern dayPattern = Pattern.compile(DAYS, Pattern.CASE_INSENSITIVE); private static final Map<String, String> months = new LinkedHashMap<>(); static { // Month name to number map months.put("jan", "1"); months.put("january", "1"); months.put("feb", "2"); months.put("february", "2"); months.put("mar", "3"); months.put("march", "3"); months.put("apr", "4"); months.put("april", "4"); months.put("may", "5"); months.put("jun", "6"); months.put("june", "6"); months.put("jul", "7"); months.put("july", "7"); months.put("aug", "8"); months.put("august", "8"); months.put("sep", "9"); months.put("sept", "9"); months.put("september", "9"); months.put("oct", "10"); months.put("october", "10"); months.put("nov", "11"); months.put("november", "11"); months.put("dec", "12"); months.put("december", "12"); } public static class TimeZoneReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { JsonObject jObj = (JsonObject)o; Object zone = jObj.get("zone"); if (zone == null) { throw new JsonIoException("java.util.TimeZone must specify 'zone' field"); } jObj.target = TimeZone.getTimeZone((String) zone); return jObj.target; } } public static class LocaleReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { JsonObject jObj = (JsonObject) o; Object language = jObj.get("language"); if (language == null) { throw new JsonIoException("java.util.Locale must specify 'language' field"); } Object country = jObj.get("country"); Object variant = jObj.get("variant"); if (country == null) { jObj.target = new Locale((String) language); return jObj.target; } if (variant == null) { jObj.target = new Locale((String) language, (String) country); return jObj.target; } jObj.target = new Locale((String) language, (String) country, (String) variant); return jObj.target; } } public static class CalendarReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { String time = null; try { JsonObject jObj = (JsonObject) o; time = (String) jObj.get("time"); if (time == null) { throw new JsonIoException("Calendar missing 'time' field"); } Date date = MetaUtils.dateFormat.get().parse(time); Class c; if (jObj.getTarget() != null) { c = jObj.getTarget().getClass(); } else { Object type = jObj.type; c = classForName((String) type, (ClassLoader)args.get(JsonReader.CLASSLOADER)); } Calendar calendar = (Calendar) newInstance(c, jObj); calendar.setTime(date); jObj.setTarget(calendar); String zone = (String) jObj.get("zone"); if (zone != null) { calendar.setTimeZone(TimeZone.getTimeZone(zone)); } return calendar; } catch(Exception e) { throw new JsonIoException("Failed to parse calendar, time: " + time); } } } public static class DateReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { if (o instanceof Long) { return new Date((Long) o); } else if (o instanceof String) { return parseDate((String) o); } else if (o instanceof JsonObject) { JsonObject jObj = (JsonObject) o; Object val = jObj.get("value"); if (val instanceof Long) { return new Date((Long) val); } else if (val instanceof String) { return parseDate((String) val); } throw new JsonIoException("Unable to parse date: " + o); } else { throw new JsonIoException("Unable to parse date, encountered unknown object: " + o); } } static Date parseDate(String dateStr) { dateStr = dateStr.trim(); if (dateStr.isEmpty()) { return null; } // Determine which date pattern (Matcher) to use Matcher matcher = datePattern1.matcher(dateStr); String year, month = null, day, mon = null, remains; if (matcher.find()) { year = matcher.group(1); month = matcher.group(2); day = matcher.group(3); remains = matcher.replaceFirst(""); } else { matcher = datePattern2.matcher(dateStr); if (matcher.find()) { month = matcher.group(1); day = matcher.group(2); year = matcher.group(3); remains = matcher.replaceFirst(""); } else { matcher = datePattern3.matcher(dateStr); if (matcher.find()) { mon = matcher.group(1); day = matcher.group(2); year = matcher.group(4); remains = matcher.replaceFirst(""); } else { matcher = datePattern4.matcher(dateStr); if (matcher.find()) { day = matcher.group(1); mon = matcher.group(3); year = matcher.group(4); remains = matcher.replaceFirst(""); } else { matcher = datePattern5.matcher(dateStr); if (matcher.find()) { year = matcher.group(1); mon = matcher.group(2); day = matcher.group(3); remains = matcher.replaceFirst(""); } else { matcher = datePattern6.matcher(dateStr); if (!matcher.find()) { throw new JsonIoException("Unable to parse: " + dateStr); } year = matcher.group(5); mon = matcher.group(2); day = matcher.group(3); remains = matcher.group(4); } } } } } if (mon != null) { // Month will always be in Map, because regex forces this. month = months.get(mon.trim().toLowerCase()); } // Determine which date pattern (Matcher) to use String hour = null, min = null, sec = "00", milli = "0", tz = null; remains = remains.trim(); matcher = timePattern1.matcher(remains); if (matcher.find()) { hour = matcher.group(1); min = matcher.group(2); sec = matcher.group(3); milli = matcher.group(4); if (matcher.groupCount() > 4) { tz = matcher.group(5); } } else { matcher = timePattern2.matcher(remains); if (matcher.find()) { hour = matcher.group(1); min = matcher.group(2); sec = matcher.group(3); if (matcher.groupCount() > 3) { tz = matcher.group(4); } } else { matcher = timePattern3.matcher(remains); if (matcher.find()) { hour = matcher.group(1); min = matcher.group(2); if (matcher.groupCount() > 2) { tz = matcher.group(3); } } else { matcher = null; } } } if (matcher != null) { remains = matcher.replaceFirst(""); } // Clear out day of week (mon, tue, wed, ...) if (remains != null && remains.length() > 0) { Matcher dayMatcher = dayPattern.matcher(remains); if (dayMatcher.find()) { remains = dayMatcher.replaceFirst("").trim(); } } if (remains != null && remains.length() > 0) { remains = remains.trim(); if (!remains.equals(",") && (!remains.equals("T"))) { throw new JsonIoException("Issue parsing data/time, other characters present: " + remains); } } Calendar c = Calendar.getInstance(); c.clear(); if (tz != null) { if ("z".equalsIgnoreCase(tz)) { c.setTimeZone(TimeZone.getTimeZone("GMT")); } else { c.setTimeZone(TimeZone.getTimeZone("GMT" + tz)); } } // Regex prevents these from ever failing to parse int y = Integer.parseInt(year); int m = Integer.parseInt(month) - 1; // months are 0-based int d = Integer.parseInt(day); if (m < 0 || m > 11) { throw new JsonIoException("Month must be between 1 and 12 inclusive, date: " + dateStr); } if (d < 1 || d > 31) { throw new JsonIoException("Day must be between 1 and 31 inclusive, date: " + dateStr); } if (matcher == null) { // no [valid] time portion c.set(y, m, d); } else { // Regex prevents these from ever failing to parse. int h = Integer.parseInt(hour); int mn = Integer.parseInt(min); int s = Integer.parseInt(sec); int ms = Integer.parseInt(milli); if (h > 23) { throw new JsonIoException("Hour must be between 0 and 23 inclusive, time: " + dateStr); } if (mn > 59) { throw new JsonIoException("Minute must be between 0 and 59 inclusive, time: " + dateStr); } if (s > 59) { throw new JsonIoException("Second must be between 0 and 59 inclusive, time: " + dateStr); } // regex enforces millis to number c.set(y, m, d, h, mn, s); c.set(Calendar.MILLISECOND, ms); } return c.getTime(); } } public static class SqlDateReader extends DateReader { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { return new java.sql.Date(((Date) super.read(o, stack, args)).getTime()); } } public static class StringReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { if (o instanceof String) { return o; } if (MetaUtils.isPrimitive(o.getClass())) { return o.toString(); } JsonObject jObj = (JsonObject) o; if (jObj.containsKey("value")) { jObj.target = jObj.get("value"); return jObj.target; } throw new JsonIoException("String missing 'value' field"); } } public static class ClassReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { if (o instanceof String) { return classForName((String) o, (ClassLoader)args.get(JsonReader.CLASSLOADER)); } JsonObject jObj = (JsonObject) o; if (jObj.containsKey("value")) { jObj.target = classForName((String) jObj.get("value"), (ClassLoader)args.get(JsonReader.CLASSLOADER)); return jObj.target; } throw new JsonIoException("Class missing 'value' field"); } } public static class AtomicBooleanReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { Object value = o; value = getValueFromJsonObject(o, value, "AtomicBoolean"); if (value instanceof String) { String state = (String) value; if ("".equals(state.trim())) { // special case return null; } return new AtomicBoolean("true".equalsIgnoreCase(state)); } else if (value instanceof Boolean) { return new AtomicBoolean((Boolean) value); } else if (value instanceof Number && !(value instanceof Double) && !(value instanceof Float)) { return new AtomicBoolean(((Number)value).longValue() != 0); } throw new JsonIoException("Unknown value in JSON assigned to AtomicBoolean, value type = " + value.getClass().getName()); } } public static class AtomicIntegerReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { Object value = o; value = getValueFromJsonObject(o, value, "AtomicInteger"); if (value instanceof String) { String num = (String) value; if ("".equals(num.trim())) { // special case return null; } return new AtomicInteger(Integer.parseInt(MetaUtils.removeLeadingAndTrailingQuotes(num))); } else if (value instanceof Number && !(value instanceof Double) && !(value instanceof Float)) { return new AtomicInteger(((Number)value).intValue()); } throw new JsonIoException("Unknown value in JSON assigned to AtomicInteger, value type = " + value.getClass().getName()); } } public static class AtomicLongReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { Object value = o; value = getValueFromJsonObject(o, value, "AtomicLong"); if (value instanceof String) { String num = (String) value; if ("".equals(num.trim())) { // special case return null; } return new AtomicLong(Long.parseLong(MetaUtils.removeLeadingAndTrailingQuotes(num))); } else if (value instanceof Number && !(value instanceof Double) && !(value instanceof Float)) { return new AtomicLong(((Number)value).longValue()); } throw new JsonIoException("Unknown value in JSON assigned to AtomicLong, value type = " + value.getClass().getName()); } } private static Object getValueFromJsonObject(Object o, Object value, String typeName) { if (o instanceof JsonObject) { JsonObject jObj = (JsonObject) o; if (jObj.containsKey("value")) { value = jObj.get("value"); } else { throw new JsonIoException(typeName + " defined as JSON {} object, missing 'value' field"); } } return value; } public static class BigIntegerReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { JsonObject jObj = null; Object value = o; if (o instanceof JsonObject) { jObj = (JsonObject) o; if (jObj.containsKey("value")) { value = jObj.get("value"); } else { throw new JsonIoException("BigInteger missing 'value' field"); } } if (value instanceof JsonObject) { JsonObject valueObj = (JsonObject)value; if ("java.math.BigDecimal".equals(valueObj.type)) { BigDecimalReader reader = new BigDecimalReader(); value = reader.read(value, stack, args); } else if ("java.math.BigInteger".equals(valueObj.type)) { value = read(value, stack, args); } else { return bigIntegerFrom(valueObj.get("value")); } } BigInteger x = bigIntegerFrom(value); if (jObj != null) { jObj.target = x; } return x; } } /** * @param value to be converted to BigInteger. Can be a null which will return null. Can be * BigInteger in which case it will be returned as-is. Can also be String, BigDecimal, * Boolean (which will be returned as BigInteger.ZERO or .ONE), byte, short, int, long, float, * or double. If an unknown type is passed in, an exception will be thrown. * @return a BigInteger from the given input. A best attempt will be made to support * as many input types as possible. For example, if the input is a Boolean, a BigInteger of * 1 or 0 will be returned. If the input is a String "", a null will be returned. If the * input is a Double, Float, or BigDecimal, a BigInteger will be returned that retains the * integer portion (fractional part is dropped). The input can be a Byte, Short, Integer, * or Long. */ public static BigInteger bigIntegerFrom(Object value) { if (value == null) { return null; } else if (value instanceof BigInteger) { return (BigInteger) value; } else if (value instanceof String) { String s = (String) value; if ("".equals(s.trim())) { // Allows "" to be used to assign null to BigInteger field. return null; } try { return new BigInteger(MetaUtils.removeLeadingAndTrailingQuotes(s)); } catch (Exception e) { throw new JsonIoException("Could not parse '" + value + "' as BigInteger.", e); } } else if (value instanceof BigDecimal) { BigDecimal bd = (BigDecimal) value; return bd.toBigInteger(); } else if (value instanceof Boolean) { return (Boolean) value ? BigInteger.ONE : BigInteger.ZERO; } else if (value instanceof Double || value instanceof Float) { return new BigDecimal(((Number)value).doubleValue()).toBigInteger(); } else if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) { return new BigInteger(value.toString()); } throw new JsonIoException("Could not convert value: " + value.toString() + " to BigInteger."); } public static class BigDecimalReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { JsonObject jObj = null; Object value = o; if (o instanceof JsonObject) { jObj = (JsonObject) o; if (jObj.containsKey("value")) { value = jObj.get("value"); } else { throw new JsonIoException("BigDecimal missing 'value' field"); } } if (value instanceof JsonObject) { JsonObject valueObj = (JsonObject)value; if ("java.math.BigInteger".equals(valueObj.type)) { BigIntegerReader reader = new BigIntegerReader(); value = reader.read(value, stack, args); } else if ("java.math.BigDecimal".equals(valueObj.type)) { value = read(value, stack, args); } else { return bigDecimalFrom(valueObj.get("value")); } } BigDecimal x = bigDecimalFrom(value); if (jObj != null) { jObj.target = x; } return x; } } /** * @param value to be converted to BigDecimal. Can be a null which will return null. Can be * BigDecimal in which case it will be returned as-is. Can also be String, BigInteger, * Boolean (which will be returned as BigDecimal.ZERO or .ONE), byte, short, int, long, float, * or double. If an unknown type is passed in, an exception will be thrown. * * @return a BigDecimal from the given input. A best attempt will be made to support * as many input types as possible. For example, if the input is a Boolean, a BigDecimal of * 1 or 0 will be returned. If the input is a String "", a null will be returned. The input * can be a Byte, Short, Integer, Long, or BigInteger. */ public static BigDecimal bigDecimalFrom(Object value) { if (value == null) { return null; } else if (value instanceof BigDecimal) { return (BigDecimal) value; } else if (value instanceof String) { String s = (String) value; if ("".equals(s.trim())) { return null; } try { return new BigDecimal(MetaUtils.removeLeadingAndTrailingQuotes(s)); } catch (Exception e) { throw new JsonIoException("Could not parse '" + s + "' as BigDecimal.", e); } } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger) value); } else if (value instanceof Boolean) { return (Boolean) value ? BigDecimal.ONE : BigDecimal.ZERO; } else if (value instanceof Long || value instanceof Integer || value instanceof Double || value instanceof Short || value instanceof Byte || value instanceof Float) { return new BigDecimal(value.toString()); } throw new JsonIoException("Could not convert value: " + value.toString() + " to BigInteger."); } public static class StringBuilderReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { if (o instanceof String) { return new StringBuilder((String) o); } JsonObject jObj = (JsonObject) o; if (jObj.containsKey("value")) { jObj.target = new StringBuilder((String) jObj.get("value")); return jObj.target; } throw new JsonIoException("StringBuilder missing 'value' field"); } } public static class StringBufferReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { if (o instanceof String) { return new StringBuffer((String) o); } JsonObject jObj = (JsonObject) o; if (jObj.containsKey("value")) { jObj.target = new StringBuffer((String) jObj.get("value")); return jObj.target; } throw new JsonIoException("StringBuffer missing 'value' field"); } } public static class TimestampReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { JsonObject jObj = (JsonObject) o; Object time = jObj.get("time"); if (time == null) { throw new JsonIoException("java.sql.Timestamp must specify 'time' field"); } Object nanos = jObj.get("nanos"); if (nanos == null) { jObj.target = new Timestamp(Long.valueOf((String) time)); return jObj.target; } Timestamp tstamp = new Timestamp(Long.valueOf((String) time)); tstamp.setNanos(Integer.valueOf((String) nanos)); jObj.target = tstamp; return jObj.target; } } public static class UUIDReader implements JsonReader.JsonClassReaderEx { public Object read(Object o, Deque<JsonObject<String, Object>> stack, Map<String, Object> args) { // to use the String representation if (o instanceof String) { return UUID.fromString((String) o); } JsonObject jObj = (JsonObject) o; Long mostSigBits = (Long) jObj.get("mostSigBits"); if (mostSigBits == null) { throw new JsonIoException("java.util.UUID must specify 'mostSigBits' field"); } Long leastSigBits = (Long) jObj.get("leastSigBits"); if (leastSigBits == null) { throw new JsonIoException("java.util.UUID must specify 'leastSigBits' field"); } UUID uuid = new UUID(mostSigBits, leastSigBits); jObj.setTarget(uuid); return jObj.getTarget(); } } // ========== Maintain dependency knowledge in once place, down here ========= static Class classForName(String name, ClassLoader classLoader) { return MetaUtils.classForName(name, classLoader); } static Object newInstance(Class c, JsonObject jsonObject) { return JsonReader.newInstance(c, jsonObject); } }
32,398
36.283084
182
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/JsonParser.java
package com.cedarsoftware.util.io; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.cedarsoftware.util.io.JsonObject.*; /** * Parse the JSON input stream supplied by the FastPushbackReader to the constructor. * The entire JSON input stream will be read until it is emptied: an EOF (-1) is read. * * While reading the content, Java Maps (JsonObjects) are used to hold the contents of * JSON objects { }. Lists are used to hold the contents of JSON arrays. Each object * that has an @id field will be copied into the supplied 'objectsMap' constructor * argument. This allows the user of this class to locate any referenced object * directly. * * When this parser completes, the @ref (references to objects identified with @id) * are stored as a JsonObject with an @ref as the key and the ID value of the object. * No substitution has yet occurred (substituting the @ref pointers with a Java * reference to the actual Map (Map containing the @id)). * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class JsonParser { public static final String EMPTY_OBJECT = "~!o~"; // compared with == private static final String EMPTY_ARRAY = "~!a~"; // compared with == private static final int STATE_READ_START_OBJECT = 0; private static final int STATE_READ_FIELD = 1; private static final int STATE_READ_VALUE = 2; private static final int STATE_READ_POST_VALUE = 3; private static final Map<String, String> stringCache = new HashMap<String, String>(); private final FastPushbackReader input; private final Map<Long, JsonObject> objsRead; private final StringBuilder strBuf = new StringBuilder(256); private final StringBuilder hexBuf = new StringBuilder(); private final StringBuilder numBuf = new StringBuilder(); private final boolean useMaps; private final Map<String, String> typeNameMap; static { // Save heap memory by re-using common strings (String's immutable) stringCache.put("", ""); stringCache.put("true", "true"); stringCache.put("True", "True"); stringCache.put("TRUE", "TRUE"); stringCache.put("false", "false"); stringCache.put("False", "False"); stringCache.put("FALSE", "FALSE"); stringCache.put("null", "null"); stringCache.put("yes", "yes"); stringCache.put("Yes", "Yes"); stringCache.put("YES", "YES"); stringCache.put("no", "no"); stringCache.put("No", "No"); stringCache.put("NO", "NO"); stringCache.put("on", "on"); stringCache.put("On", "On"); stringCache.put("ON", "ON"); stringCache.put("off", "off"); stringCache.put("Off", "Off"); stringCache.put("OFF", "OFF"); stringCache.put(ID, ID); stringCache.put(REF, REF); stringCache.put(JsonObject.ITEMS, JsonObject.ITEMS); stringCache.put(TYPE, TYPE); stringCache.put(KEYS, KEYS); stringCache.put("0", "0"); stringCache.put("1", "1"); stringCache.put("2", "2"); stringCache.put("3", "3"); stringCache.put("4", "4"); stringCache.put("5", "5"); stringCache.put("6", "6"); stringCache.put("7", "7"); stringCache.put("8", "8"); stringCache.put("9", "9"); } JsonParser(FastPushbackReader reader, Map<Long, JsonObject> objectsMap, Map<String, Object> args) { input = reader; useMaps = Boolean.TRUE.equals(args.get(JsonReader.USE_MAPS)); objsRead = objectsMap; typeNameMap = (Map<String, String>) args.get(JsonReader.TYPE_NAME_MAP_REVERSE); } private Object readJsonObject() throws IOException { boolean done = false; String field = null; JsonObject<String, Object> object = new JsonObject<String, Object>(); int state = STATE_READ_START_OBJECT; final FastPushbackReader in = input; while (!done) { int c; switch (state) { case STATE_READ_START_OBJECT: c = skipWhitespaceRead(); if (c == '{') { object.line = in.getLine(); object.col = in.getCol(); c = skipWhitespaceRead(); if (c == '}') { // empty object return EMPTY_OBJECT; } in.unread(c); state = STATE_READ_FIELD; } else { error("Input is invalid JSON; object does not start with '{', c=" + c); } break; case STATE_READ_FIELD: c = skipWhitespaceRead(); if (c == '"') { field = readString(); c = skipWhitespaceRead(); if (c != ':') { error("Expected ':' between string field and value"); } if (field.startsWith("@")) { // Expand short-hand meta keys if (field.equals("@t")) { field = stringCache.get(TYPE); } else if (field.equals("@i")) { field = stringCache.get(ID); } else if (field.equals("@r")) { field = stringCache.get(REF); } else if (field.equals("@k")) { field = stringCache.get(KEYS); } else if (field.equals("@e")) { field = stringCache.get(ITEMS); } } state = STATE_READ_VALUE; } else { error("Expected quote"); } break; case STATE_READ_VALUE: if (field == null) { // field is null when you have an untyped Object[], so we place // the JsonArray on the @items field. field = ITEMS; } Object value = readValue(object); if (TYPE.equals(field) && typeNameMap != null) { final String substitute = typeNameMap.get(value); if (substitute != null) { value = substitute; } } object.put(field, value); // If object is referenced (has @id), then put it in the _objsRead table. if (ID.equals(field)) { objsRead.put((Long) value, object); } state = STATE_READ_POST_VALUE; break; case STATE_READ_POST_VALUE: c = skipWhitespaceRead(); if (c == -1) { error("EOF reached before closing '}'"); } if (c == '}') { done = true; } else if (c == ',') { state = STATE_READ_FIELD; } else { error("Object not ended with '}'"); } break; } } if (useMaps && object.isLogicalPrimitive()) { return object.getPrimitiveValue(); } return object; } Object readValue(JsonObject object) throws IOException { int c = skipWhitespaceRead(); if (c == '"') { return readString(); } else if (c >= '0' && c <= '9' || c == '-' || c == 'N' || c == 'I') { return readNumber(c); } switch(c) { case '{': input.unread('{'); return readJsonObject(); case '[': return readArray(object); case ']': // empty array input.unread(']'); return EMPTY_ARRAY; case 'f': case 'F': readToken("false"); return Boolean.FALSE; case 'n': case 'N': readToken("null"); return null; case 't': case 'T': readToken("true"); return Boolean.TRUE; case -1: error("EOF reached prematurely"); } return error("Unknown JSON value type"); } /** * Read a JSON array */ private Object readArray(JsonObject object) throws IOException { final List<Object> array = new ArrayList(); while (true) { final Object o = readValue(object); if (o != EMPTY_ARRAY) { array.add(o); } final int c = skipWhitespaceRead(); if (c == ']') { break; } else if (c != ',') { error("Expected ',' or ']' inside array"); } } return array.toArray(); } /** * Return the specified token from the reader. If it is not found, * throw an IOException indicating that. Converting to c to * (char) c is acceptable because the 'tokens' allowed in a * JSON input stream (true, false, null) are all ASCII. */ private void readToken(String token) throws IOException { final int len = token.length(); for (int i = 1; i < len; i++) { int c = input.read(); if (c == -1) { error("EOF reached while reading token: " + token); } c = Character.toLowerCase((char) c); int loTokenChar = token.charAt(i); if (loTokenChar != c) { error("Expected token: " + token); } } } /** * Read a JSON number * * @param c int a character representing the first digit of the number that * was already read. * @return a Number (a Long or a Double) depending on whether the number is * a decimal number or integer. This choice allows all smaller types (Float, int, short, byte) * to be represented as well. * @throws IOException for stream errors or parsing errors. */ private Number readNumber(int c) throws IOException { final FastPushbackReader in = input; boolean isFloat = false; if (JsonReader.isAllowNanAndInfinity() && (c == '-' || c == 'N' || c == 'I') ) { /* * In this branch, we must have either one of these scenarios: (a) -NaN or NaN (b) Inf or -Inf (c) -123 but * NOT 123 (replace 123 by any number) * * In case of (c), we do nothing and revert input and c for normal processing. */ // Handle negativity. final boolean isNeg = (c == '-'); if (isNeg) { // Advance to next character. c = input.read(); } // Case "-Infinity", "Infinity" or "NaN". if (c == 'I') { readToken("infinity"); // [Out of RFC 4627] accept NaN/Infinity values return (isNeg) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } else if ('N' == c) { // [Out of RFC 4627] accept NaN/Infinity values readToken("nan"); return Double.NaN; } else { // This is (c) case, meaning there was c = '-' at the beginning. // This is a number like "-2", but not "-Infinity". We let the normal code process. input.unread(c); c = '-'; } } // We are sure we have a positive or negative number, so we read char by char. final StringBuilder number = numBuf; number.setLength(0); number.appendCodePoint(c); while (true) { c = in.read(); if ((c >= '0' && c <= '9') || c == '-' || c == '+') { number.appendCodePoint(c); } else if (c == '.' || c == 'e' || c == 'E') { number.appendCodePoint(c); isFloat = true; } else if (c == -1) { break; } else { in.unread(c); break; } } try { if (isFloat) { // Floating point number needed return Double.parseDouble(number.toString()); } else { return Long.parseLong(number.toString()); } } catch (Exception e) { return (Number) error("Invalid number: " + number, e); } } private static final int STRING_START = 0; private static final int STRING_SLASH = 1; private static final int HEX_DIGITS = 2; /** * Read a JSON string * This method assumes the initial quote has already been read. * * @return String read from JSON input stream. * @throws IOException for stream errors or parsing errors. */ private String readString() throws IOException { final StringBuilder str = strBuf; final StringBuilder hex = hexBuf; str.setLength(0); int state = STRING_START; final FastPushbackReader in = input; while (true) { final int c = in.read(); if (c == -1) { error("EOF reached while reading JSON string"); } if (state == STRING_START) { if (c == '"') { break; } else if (c == '\\') { state = STRING_SLASH; } else { str.appendCodePoint(c); } } else if (state == STRING_SLASH) { switch(c) { case '\\': str.appendCodePoint('\\'); break; case '/': str.appendCodePoint('/'); break; case '"': str.appendCodePoint('"'); break; case '\'': str.appendCodePoint('\''); break; case 'b': str.appendCodePoint('\b'); break; case 'f': str.appendCodePoint('\f'); break; case 'n': str.appendCodePoint('\n'); break; case 'r': str.appendCodePoint('\r'); break; case 't': str.appendCodePoint('\t'); break; case 'u': hex.setLength(0); state = HEX_DIGITS; break; default: error("Invalid character escape sequence specified: " + c); } if (c != 'u') { state = STRING_START; } } else { if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) { hex.appendCodePoint((char) c); if (hex.length() == 4) { int value = Integer.parseInt(hex.toString(), 16); str.appendCodePoint(value); state = STRING_START; } } else { error("Expected hexadecimal digits"); } } } final String s = str.toString(); final String translate = stringCache.get(s); return translate == null ? s : translate; } /** * Read until non-whitespace character and then return it. * This saves extra read/pushback. * * @return int representing the next non-whitespace character in the stream. * @throws IOException for stream errors or parsing errors. */ private int skipWhitespaceRead() throws IOException { FastPushbackReader in = input; int c; do { c = in.read(); } while (c == ' ' || c == '\n' || c == '\r' || c == '\t'); return c; } Object error(String msg) { throw new JsonIoException(getMessage(msg)); } Object error(String msg, Exception e) { throw new JsonIoException(getMessage(msg), e); } String getMessage(String msg) { return msg + "\nline: " + input.getLine()+ ", col: " + input.getCol()+ "\n" + input.getLastSnippet(); } }
19,054
32.488576
119
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/JsonWriter.java
package com.cedarsoftware.util.io; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Timestamp; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static com.cedarsoftware.util.io.JsonObject.ITEMS; /** * Output a Java object graph in JSON format. This code handles cyclic * references and can serialize any Object graph without requiring a class * to be 'Serializeable' or have any specific methods on it. * <br><ul><li> * Call the static method: {@code JsonWriter.objectToJson(employee)}. This will * convert the passed in 'employee' instance into a JSON String.</li> * <li>Using streams: * <pre> JsonWriter writer = new JsonWriter(stream); * writer.write(employee); * writer.close();</pre> * This will write the 'employee' object to the passed in OutputStream. * </li></ul> * <p>That's it. This can be used as a debugging tool. Output an object * graph using the above code. Use the JsonWriter PRETTY_PRINT option to * format the the JSON to be human readable. * <br> * <p>This will output any object graph deeply (or null). Object references are * properly handled. For example, if you had A-&gt;B, B-&gt;C, and C-&gt;A, then * A will be serialized with a B object in it, B will be serialized with a C * object in it, and then C will be serialized with a reference to A (ref), not a * redefinition of A.</p> * <br> * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class JsonWriter implements Closeable, Flushable { /** If set, this maps class ==> CustomWriter */ public static final String CUSTOM_WRITER_MAP = "CUSTOM_WRITERS"; /** If set, this maps class ==> CustomWriter */ public static final String NOT_CUSTOM_WRITER_MAP = "NOT_CUSTOM_WRITERS"; /** Set the date format to use within the JSON output */ public static final String DATE_FORMAT = "DATE_FORMAT"; /** Constant for use as DATE_FORMAT value */ public static final String ISO_DATE_FORMAT = "yyyy-MM-dd"; /** Constant for use as DATE_FORMAT value */ public static final String ISO_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; /** Force @type always */ public static final String TYPE = "TYPE"; /** Force nicely formatted JSON output */ public static final String PRETTY_PRINT = "PRETTY_PRINT"; /** Set value to a Map<Class, List<String>> which will be used to control which fields on a class are output */ public static final String FIELD_SPECIFIERS = "FIELD_SPECIFIERS"; /** Set value to a Map<Class, List<String>> which will be used to control which fields on a class are not output. Black list has always priority to FIELD_SPECIFIERS */ public static final String FIELD_NAME_BLACK_LIST = "FIELD_NAME_BLACK_LIST"; /** same as above only internal for storing Field instances instead of strings. This avoid the initial argument content to be modified. */ private static final String FIELD_BLACK_LIST = "FIELD_BLACK_LIST"; /** If set, indicates that private variables of ENUMs are not to be serialized */ public static final String ENUM_PUBLIC_ONLY = "ENUM_PUBLIC_ONLY"; /** If set, longs are written in quotes (Javascript safe) */ public static final String WRITE_LONGS_AS_STRINGS = "WLAS"; /** If set, this map will be used when writing @type values - allows short-hand abbreviations type names */ public static final String TYPE_NAME_MAP = "TYPE_NAME_MAP"; /** If set, then @type -> @t, @keys -> @k, @items -> @i */ public static final String SHORT_META_KEYS = "SHORT_META_KEYS"; /** If set, null fields are not written */ public static final String SKIP_NULL_FIELDS = "SKIP_NULL"; /** If set, use the specified ClassLoader */ public static final String CLASSLOADER = "CLASSLOADER"; /** If set to true all maps are transferred to the format @keys[],@items[] regardless of the key_type */ public static final String FORCE_MAP_FORMAT_ARRAY_KEYS_ITEMS = "FORCE_MAP_FORMAT_ARRAY_KEYS_ITEMS"; private static Map<Class, JsonClassWriterBase> BASE_WRITERS; private final Map<Class, JsonClassWriterBase> writers = new HashMap<>(BASE_WRITERS); // Add customer writers (these make common classes more succinct) private final Map<Class, JsonClassWriterBase> writerCache = new HashMap<>(); private final Set<Class> notCustom = new HashSet<>(); private static final Object[] byteStrings = new Object[256]; private static final String NEW_LINE = System.getProperty("line.separator"); private static final Long ZERO = 0L; private static final NullClass nullWriter = new NullClass(); private final Map<Object, Long> objVisited = new IdentityHashMap<>(); private final Map<Object, Long> objsReferenced = new IdentityHashMap<>(); private final Writer out; private Map<String, String> typeNameMap = null; private boolean shortMetaKeys = false; private boolean neverShowType = false; private boolean alwaysShowType = false; private boolean isPrettyPrint = false; private boolean isEnumPublicOnly = false; private boolean writeLongsAsStrings = false; private boolean skipNullFields = false; private boolean forceMapFormatWithKeyArrays = false; private long identity = 1; private int depth = 0; /** _args is using ThreadLocal so that static inner classes can have access to them */ final Map<String, Object> args = new HashMap<>(); static { for (short i = -128; i <= 127; i++) { char[] chars = Integer.toString(i).toCharArray(); byteStrings[i + 128] = chars; } Map<Class, JsonClassWriterBase> temp = new HashMap<>(); temp.put(String.class, new Writers.JsonStringWriter()); temp.put(Date.class, new Writers.DateWriter()); temp.put(AtomicBoolean.class, new Writers.AtomicBooleanWriter()); temp.put(AtomicInteger.class, new Writers.AtomicIntegerWriter()); temp.put(AtomicLong.class, new Writers.AtomicLongWriter()); temp.put(BigInteger.class, new Writers.BigIntegerWriter()); temp.put(BigDecimal.class, new Writers.BigDecimalWriter()); temp.put(java.sql.Date.class, new Writers.DateWriter()); temp.put(Timestamp.class, new Writers.TimestampWriter()); temp.put(Calendar.class, new Writers.CalendarWriter()); temp.put(TimeZone.class, new Writers.TimeZoneWriter()); temp.put(Locale.class, new Writers.LocaleWriter()); temp.put(Class.class, new Writers.ClassWriter()); temp.put(StringBuilder.class, new Writers.StringBuilderWriter()); temp.put(StringBuffer.class, new Writers.StringBufferWriter()); temp.put(UUID.class, new Writers.UUIDWriter()); BASE_WRITERS = temp; } private static volatile boolean allowNanAndInfinity = false; /** * @return boolean the allowsNanAndInifnity flag */ public static boolean isAllowNanAndInfinity() { return allowNanAndInfinity; } /** * Set the writer to be out of RFC 4627: it will accept "NaN", "-Infinity" and "Infinity" values. * @param lenient boolean true allows Nan and Inifinity, -Infinity to be used within JSON. */ public static void setAllowNanAndInfinity(boolean lenient) { JsonWriter.allowNanAndInfinity = lenient; } /** * Common ancestor for JsonClassWriter and JsonClassWriterEx. */ public interface JsonClassWriterBase { } /** * Implement this interface to customize the JSON output for a given class. */ public interface JsonClassWriter extends JsonClassWriterBase { /** * When write() is called, it is expected that subclasses will write the appropriate JSON * to the passed in Writer. * @param o Object to be written in JSON format. * @param showType boolean indicating whether to show @type. * @param output Writer destination to where the actual JSON is written. * @throws IOException if thrown by the writer. Will be caught at a higher level and wrapped in JsonIoException. */ void write(Object o, boolean showType, Writer output) throws IOException; /** * @return boolean true if the class being written has a primitive (non-object) form. */ boolean hasPrimitiveForm(); /** * This method will be called to write the item in primitive form (if the response to hasPrimitiveForm() * was true). * @param o Object to be written * @param output Writer destination to where the actual JSON is written. * @throws IOException if thrown by the writer. Will be caught at a higher level and wrapped in JsonIoException. */ void writePrimitiveForm(Object o, Writer output) throws IOException; } /** * Implement this interface to customize the JSON output for a given class. */ public interface JsonClassWriterEx extends JsonClassWriterBase { String JSON_WRITER = "JSON_WRITER"; /** * When write() is called, it is expected that subclasses will write the appropriate JSON * to the passed in Writer. * @param o Object to be written in JSON format. * @param showType boolean indicating whether to show @type. * @param output Writer destination to where the actual JSON is written. * @param args Map of 'settings' arguments initially passed into the JsonWriter. * @throws IOException if thrown by the writer. Will be caught at a higher level and wrapped in JsonIoException. */ void write(Object o, boolean showType, Writer output, Map<String, Object> args) throws IOException; /** * If access to the JsonWriter is needed, JsonClassWriter's can access it by accessing Support.getWriter(args). * The args are the same arguments passed into the write(o, showType, args) method of JsonClassWriterEx. */ class Support { /** * This method will return the JsonWriter instance performing the overall work. * @param args Map of settings initially passed to JsonWriter. * @return JsonWriter instance performing the work. */ public static JsonWriter getWriter(Map<String, Object> args) { return (JsonWriter) args.get(JSON_WRITER); } } } /** * Provide access to subclasses. * @return Map containing all objects that were referenced within input object graph. */ public Map getObjectsReferenced() { return objsReferenced; } /** * Provide access to subclasses. * @return Map containing all objects that were visited within input object graph */ public Map getObjectsVisited() { return objVisited; } /** * Used internally to substitute type names. For example, 'java.util.ArrayList, could have a substitute * type name of 'alist'. Set substitute type names using the TYPE_NAME_MAP option. * @param typeName String name of type to substitute. * @return String substituted name, or null if there is no substitute. */ protected String getSubstituteTypeNameIfExists(String typeName) { if (typeNameMap == null) { return null; } return typeNameMap.get(typeName); } /** * Used internally to substitute type names. For example, 'java.util.ArrayList, could have a substitute * type name of 'alist'. Set substitute type names using the TYPE_NAME_MAP option. * @param typeName String name of type to substitute. * @return String substituted type name. */ protected String getSubstituteTypeName(String typeName) { if (typeNameMap == null) { return typeName; } String shortName = typeNameMap.get(typeName); return shortName == null ? typeName : shortName; } /** * @see JsonWriter#objectToJson(Object, java.util.Map) * @param item Object (root) to serialized to JSON String. * @return String of JSON format representing complete object graph rooted by item. */ public static String objectToJson(Object item) { return objectToJson(item, null); } /** * Convert a Java Object to a JSON String. * * @param item Object to convert to a JSON String. * @param optionalArgs (optional) Map of extra arguments indicating how dates are formatted, * what fields are written out (optional). For Date parameters, use the public static * DATE_TIME key, and then use the ISO_DATE or ISO_DATE_TIME indicators. Or you can specify * your own custom SimpleDateFormat String, or you can associate a SimpleDateFormat object, * in which case it will be used. This setting is for both java.util.Date and java.sql.Date. * If the DATE_FORMAT key is not used, then dates will be formatted as longs. This long can * be turned back into a date by using 'new Date(longValue)'. * @return String containing JSON representation of passed in object root. */ public static String objectToJson(Object item, Map<String, Object> optionalArgs) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); JsonWriter writer = new JsonWriter(stream, optionalArgs); writer.write(item); writer.close(); return new String(stream.toByteArray(), "UTF-8"); } catch (Exception e) { throw new JsonIoException("Unable to convert object to JSON", e); } } /** * Format the passed in JSON string in a nice, human readable format. * @param json String input JSON * @return String containing equivalent JSON, formatted nicely for human readability. */ public static String formatJson(String json) { return formatJson(json, null, null); } /** * Format the passed in JSON string in a nice, human readable format. * @param json String input JSON * @param readingArgs (optional) Map of extra arguments for parsing json. Can be null. * @param writingArgs (optional) Map of extra arguments for writing out json. Can be null. * @return String containing equivalent JSON, formatted nicely for human readability. */ public static String formatJson(String json, Map readingArgs, Map writingArgs) { Map args = new HashMap(); if (readingArgs != null) { args.putAll(readingArgs); } args.put(JsonReader.USE_MAPS, true); Object obj = JsonReader.jsonToJava(json, args); args.clear(); if (writingArgs != null) { args.putAll(writingArgs); } args.put(PRETTY_PRINT, true); return objectToJson(obj, args); } /** * @see JsonWriter#JsonWriter(OutputStream, Map) * @param out OutputStream to which the JSON will be written. */ public JsonWriter(OutputStream out) { this(out, null); } /** * @param out OutputStream to which the JSON output will be written. * @param optionalArgs (optional) Map of extra arguments indicating how dates are formatted, * what fields are written out (optional). For Date parameters, use the public static * DATE_TIME key, and then use the ISO_DATE or ISO_DATE_TIME indicators. Or you can specify * your own custom SimpleDateFormat String, or you can associate a SimpleDateFormat object, * in which case it will be used. This setting is for both java.util.Date and java.sql.Date. * If the DATE_FORMAT key is not used, then dates will be formatted as longs. This long can * be turned back into a date by using 'new Date(longValue)'. */ public JsonWriter(OutputStream out, Map<String, Object> optionalArgs) { if (optionalArgs == null) { optionalArgs = new HashMap<String, Object>(); } args.putAll(optionalArgs); args.put(JsonClassWriterEx.JSON_WRITER, this); typeNameMap = (Map<String, String>) args.get(TYPE_NAME_MAP); shortMetaKeys = isTrue(args.get(SHORT_META_KEYS)); alwaysShowType = isTrue(args.get(TYPE)); neverShowType = Boolean.FALSE.equals(args.get(TYPE)) || "false".equals(args.get(TYPE)); isPrettyPrint = isTrue(args.get(PRETTY_PRINT)); isEnumPublicOnly = isTrue(args.get(ENUM_PUBLIC_ONLY)); writeLongsAsStrings = isTrue(args.get(WRITE_LONGS_AS_STRINGS)); writeLongsAsStrings = isTrue(args.get(WRITE_LONGS_AS_STRINGS)); skipNullFields = isTrue(args.get(SKIP_NULL_FIELDS)); forceMapFormatWithKeyArrays = isTrue(args.get(FORCE_MAP_FORMAT_ARRAY_KEYS_ITEMS)); if (!args.containsKey(CLASSLOADER)) { args.put(CLASSLOADER, JsonWriter.class.getClassLoader()); } Map<Class, JsonClassWriterBase> customWriters = (Map<Class, JsonClassWriterBase>) args.get(CUSTOM_WRITER_MAP); if (customWriters != null) { for (Map.Entry<Class, JsonClassWriterBase> entry : customWriters.entrySet()) { addWriter(entry.getKey(), entry.getValue()); } } Collection<Class> notCustomClasses = (Collection<Class>) args.get(NOT_CUSTOM_WRITER_MAP); if (notCustomClasses != null) { for (Class c : notCustomClasses) { addNotCustomWriter(c); } } if (optionalArgs.containsKey(FIELD_SPECIFIERS)) { // Convert String field names to Java Field instances (makes it easier for user to set this up) Map<Class, List<String>> specifiers = (Map<Class, List<String>>) args.get(FIELD_SPECIFIERS); Map<Class, List<Field>> copy = new HashMap<Class, List<Field>>(); for (Entry<Class, List<String>> entry : specifiers.entrySet()) { Class c = entry.getKey(); List<String> fields = entry.getValue(); List<Field> newList = new ArrayList(fields.size()); Map<String, Field> classFields = MetaUtils.getDeepDeclaredFields(c); for (String field : fields) { Field f = classFields.get(field); if (f == null) { throw new JsonIoException("Unable to locate field: " + field + " on class: " + c.getName() + ". Make sure the fields in the FIELD_SPECIFIERS map existing on the associated class."); } newList.add(f); } copy.put(c, newList); } args.put(FIELD_SPECIFIERS, copy); } else { // Ensure that at least an empty Map is in the FIELD_SPECIFIERS entry args.put(FIELD_SPECIFIERS, new HashMap()); } if (optionalArgs.containsKey(FIELD_NAME_BLACK_LIST)) { // Convert String field names to Java Field instances (makes it easier for user to set this up) Map<Class, List<String>> blackList = (Map<Class, List<String>>) args.get(FIELD_NAME_BLACK_LIST); Map<Class, List<Field>> copy = new HashMap<Class, List<Field>>(); for (Entry<Class, List<String>> entry : blackList.entrySet()) { Class c = entry.getKey(); List<String> fields = entry.getValue(); List<Field> newList = new ArrayList<Field>(fields.size()); Map<String, Field> classFields = MetaUtils.getDeepDeclaredFields(c); for (String field : fields) { Field f = classFields.get(field); if (f == null) { throw new JsonIoException("Unable to locate field: " + field + " on class: " + c.getName() + ". Make sure the fields in the FIELD_NAME_BLACK_LIST map existing on the associated class."); } newList.add(f); } copy.put(c, newList); } args.put(FIELD_BLACK_LIST, copy); } else { // Ensure that at least an empty Map is in the FIELD_SPECIFIERS entry args.put(FIELD_BLACK_LIST, new HashMap()); } try { this.out = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new JsonIoException("UTF-8 not supported on your JVM. Unable to convert object to JSON.", e); } } /** * @return ClassLoader to be used by Custom Writers */ ClassLoader getClassLoader() { return (ClassLoader) args.get(CLASSLOADER); } /** * @param setting Object setting value from JsonWriter args map. * @return boolean true if the value is (boolean) true, Boolean.TRUE, "true" (any case), or non-zero if a Number. */ static boolean isTrue(Object setting) { if (setting instanceof Boolean) { return Boolean.TRUE.equals(setting); } else if (setting instanceof String) { return "true".equalsIgnoreCase((String) setting); } else if (setting instanceof Number) { return ((Number)setting).intValue() != 0; } return false; } /** * Tab the output left (less indented) * @throws IOException */ public void tabIn() throws IOException { tab(out, 1); } /** * Add newline (\n) to output * @throws IOException */ public void newLine() throws IOException { tab(out, 0); } /** * Tab the output right (more indented) * @throws IOException */ public void tabOut() throws IOException { tab(out, -1); } /** * tab the JSON output by the given number of characters specified by delta. * @param output Writer being used for JSON outpt. * @param delta int number of characters to tab. * @throws IOException */ private void tab(Writer output, int delta) throws IOException { if (!isPrettyPrint) { return; } output.write(NEW_LINE); depth += delta; for (int i=0; i < depth; i++) { output.write(" "); } } /** * Write the passed in object (o) to the JSON output stream, if and only if, there is a custom * writer associated to the Class of object (o). * @param o Object to be (potentially written) * @param showType boolean indicating whether or not to show @type. * @param output Writer where the actual JSON is being written to. * @return boolean true if written, false is there is no custom writer for the passed in object. */ public boolean writeIfMatching(Object o, boolean showType, Writer output) { if (neverShowType) { showType = false; } Class c = o.getClass(); if (notCustom.contains(c)) { return false; } try { return writeCustom(c, o, showType, output); } catch (IOException e) { throw new JsonIoException("Unable to write custom formatted object:", e); } } /** * Write the passed in array element to the JSON output, if any only if, there is a customer writer * for the class of the instance 'o'. * @param arrayComponentClass Class type of the array * @param o Object instance to write * @param showType boolean indicating whether or not @type should be output. * @param output Writer to write the JSON to (if there is a custom writer for o's Class). * @return true if the array element was written, false otherwise. */ public boolean writeArrayElementIfMatching(Class arrayComponentClass, Object o, boolean showType, Writer output) { if (!o.getClass().isAssignableFrom(arrayComponentClass) || notCustom.contains(o.getClass())) { return false; } try { return writeCustom(arrayComponentClass, o, showType, output); } catch (IOException e) { throw new JsonIoException("Unable to write custom formatted object as array element:", e); } } /** * Perform the actual custom writing for an array element that has a custom writer. * @param arrayComponentClass Class type of the array * @param o Object instance to write * @param showType boolean indicating whether or not @type should be output. * @param output Writer to write the JSON to (if there is a custom writer for o's Class). * @return true if the array element was written, false otherwise. */ protected boolean writeCustom(Class arrayComponentClass, Object o, boolean showType, Writer output) throws IOException { if (neverShowType) { showType = false; } JsonClassWriterBase closestWriter = getCustomWriter(arrayComponentClass); if (closestWriter == null) { return false; } if (writeOptionalReference(o)) { return true; } boolean referenced = objsReferenced.containsKey(o); if (closestWriter instanceof JsonClassWriter) { JsonClassWriter writer = (JsonClassWriter) closestWriter; if (writer.hasPrimitiveForm()) { if ((!referenced && !showType) || closestWriter instanceof Writers.JsonStringWriter) { if (writer instanceof Writers.DateWriter) { ((Writers.DateWriter)writer).writePrimitiveForm(o, output, args); } else { writer.writePrimitiveForm(o, output); } return true; } } } output.write('{'); tabIn(); if (referenced) { writeId(getId(o)); if (showType) { output.write(','); newLine(); } } if (showType) { writeType(o, output); } if (referenced || showType) { output.write(','); newLine(); } if (closestWriter instanceof JsonClassWriterEx) { ((JsonClassWriterEx)closestWriter).write(o, showType || referenced, output, args); } else { ((JsonClassWriter)closestWriter).write(o, showType || referenced, output); } tabOut(); output.write('}'); return true; } /** * Dummy place-holder class exists only because ConcurrentHashMap cannot contain a * null value. Instead, singleton instance of this class is placed where null values * are needed. */ static final class NullClass implements JsonClassWriterBase { } /** * Fetch the customer writer for the passed in Class. If it is cached (already associated to the * passed in Class), return the same instance, otherwise, make a call to get the custom writer * and store that result. * @param c Class of object for which fetch a custom writer * @return JsonClassWriter/JsonClassWriterEx for the custom class (if one exists), null otherwise. */ private JsonClassWriterBase getCustomWriter(Class c) { JsonClassWriterBase writer = writerCache.get(c); if (writer == null) { writer = forceGetCustomWriter(c); writerCache.put(c, writer); } return writer == nullWriter ? null : writer; } /** * Fetch the customer writer for the passed in Class. This method always fetches the custom writer, doing * the complicated inheritance distance checking. This method is only called when a cache miss has happened. * A sentinal 'nullWriter' is returned when no custom writer is found. This prevents future cache misses * from re-attempting to find custom writers for classes that do not have a custom writer. * @param c Class of object for which fetch a custom writer * @return JsonClassWriter/JsonClassWriterEx for the custom class (if one exists), nullWriter otherwise. */ private JsonClassWriterBase forceGetCustomWriter(Class c) { JsonClassWriterBase closestWriter = nullWriter; int minDistance = Integer.MAX_VALUE; for (Map.Entry<Class, JsonClassWriterBase> entry : writers.entrySet()) { Class clz = entry.getKey(); if (clz == c) { return entry.getValue(); } int distance = MetaUtils.getDistance(clz, c); if (distance < minDistance) { minDistance = distance; closestWriter = entry.getValue(); } } return closestWriter; } /** * Add a custom writer which will manage writing objects of the * passed in Class in JSON format. The custom writer will be * called for objects of the passed in class, including subclasses. * If this is not desired, call addNotCustomWriter(c) which will * force objects of the passed in Class to be written by the standard * JSON writer. * @param c Class to associate a custom JSON writer too * @param writer JsonClassWriterBase which implements the appropriate * subclass of JsonClassWriterBase (JsonClassWriter or JsonClassWriterEx). */ public void addWriter(Class c, JsonClassWriterBase writer) { writers.put(c, writer); } /** * Add a permanent Customer Writer (Lifetime of JVM) * @param c Class to associate a custom JSON writer too * @param writer JsonClassWriterBase which implements the appropriate * subclass of JsonClassWriterBase (JsonClassWriter or JsonClassWriterEx). */ public static void addWriterPermanent(Class c, JsonClassWriterBase writer) { BASE_WRITERS.put(c, writer); } /** * For no custom writing to occur for the passed in Class. * @param c Class which should NOT have any custom writer associated to it. Use this * to prevent a custom writer from being used due to inheritance. */ public void addNotCustomWriter(Class c) { notCustom.add(c); } /** * Write the passed in Java object in JSON format. * @param obj Object any Java Object or JsonObject. */ public void write(Object obj) { traceReferences(obj); objVisited.clear(); try { writeImpl(obj, true); } catch (Exception e) { throw new JsonIoException("Error writing object to JSON:", e); } flush(); objVisited.clear(); objsReferenced.clear(); } /** * Walk object graph and visit each instance, following each field, each Collection, Map and so on. * Tracks visited to handle cycles and to determine if an item is referenced elsewhere. If an * object is never referenced more than once, no @id field needs to be emitted for it. * @param root Object to be deeply traced. The objVisited and objsReferenced Maps will be written to * during the trace. */ protected void traceReferences(Object root) { if (root == null) { return; } Map<Class, List<Field>> fieldSpecifiers = (Map) args.get(FIELD_SPECIFIERS); final Deque<Object> stack = new ArrayDeque<Object>(); stack.addFirst(root); final Map<Object, Long> visited = objVisited; final Map<Object, Long> referenced = objsReferenced; while (!stack.isEmpty()) { final Object obj = stack.removeFirst(); if (!MetaUtils.isLogicalPrimitive(obj.getClass())) { Long id = visited.get(obj); if (id != null) { // Only write an object once. if (id == ZERO) { // 2nd time this object has been seen, so give it a unique ID and mark it referenced id = identity++; visited.put(obj, id); referenced.put(obj, id); } continue; } else { // Initially, mark an object with 0 as the ID, in case it is never referenced, // we don't waste the memory to store a Long instance that is never used. visited.put(obj, ZERO); } } final Class clazz = obj.getClass(); if (clazz.isArray()) { if (!MetaUtils.isLogicalPrimitive(clazz.getComponentType())) { // Speed up: do not traceReferences of primitives, they cannot reference anything final int len = Array.getLength(obj); for (int i = 0; i < len; i++) { final Object o = Array.get(obj, i); if (o != null) { // Slight perf gain (null is legal) stack.addFirst(o); } } } } else if (Map.class.isAssignableFrom(clazz)) { // Speed up - logically walk maps, as opposed to following their internal structure. try { Map map = (Map) obj; for (final Object item : map.entrySet()) { final Entry entry = (Entry) item; if (entry.getValue() != null) { stack.addFirst(entry.getValue()); } if (entry.getKey() != null) { stack.addFirst(entry.getKey()); } } } catch (UnsupportedOperationException e) { // Some kind of Map that does not support .entrySet() - some Maps throw UnsupportedOperation for // this API. Do not attempt any further tracing of references. Likely a ClassLoader field or // something unusual like that. } } else if (Collection.class.isAssignableFrom(clazz)) { for (final Object item : (Collection)obj) { if (item != null) { stack.addFirst(item); } } } else { // Speed up: do not traceReferences of primitives, they cannot reference anything if (!MetaUtils.isLogicalPrimitive(obj.getClass())) { traceFields(stack, obj, fieldSpecifiers); } } } } /** * Reach-ability trace to visit all objects within the graph to be written. * This API will handle any object, using either reflection APIs or by * consulting a specified FIELD_SPECIFIERS map if provided. * @param stack Deque used to manage descent into graph (rather than using Java stack.) This allows for * much larger graph processing. * @param obj Object root of graph * @param fieldSpecifiers Map of optional field specifiers, which are used to override the field list returned by * the JDK reflection operations. This allows a subset of the actual fields on an object to be serialized. */ protected void traceFields(final Deque<Object> stack, final Object obj, final Map<Class, List<Field>> fieldSpecifiers) { // If caller has special Field specifier for a given class // then use it, otherwise use reflection. Collection<Field> fields = getFieldsUsingSpecifier(obj.getClass(), fieldSpecifiers); Collection<Field> fieldsBySpec = fields; if (fields == null) { // Trace fields using reflection fields = MetaUtils.getDeepDeclaredFields(obj.getClass()).values(); } for (final Field field : fields) { if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { if (fieldsBySpec == null || !fieldsBySpec.contains(field)) { // Skip tracing transient fields EXCEPT when the field is listed explicitly by using the fieldSpecifiers Map. // In that case, the field must be traced, even though it is transient. continue; } } try { final Object o = field.get(obj); if (o != null && !MetaUtils.isLogicalPrimitive(o.getClass())) { // Trace through objects that can reference other objects stack.addFirst(o); } } catch (Exception ignored) { } } } private static List<Field> getFieldsUsingSpecifier(final Class classBeingWritten, final Map<Class, List<Field>> fieldSpecifiers) { final Iterator<Map.Entry<Class, List<Field>>> i = fieldSpecifiers.entrySet().iterator(); int minDistance = Integer.MAX_VALUE; List<Field> fields = null; while (i.hasNext()) { final Map.Entry<Class, List<Field>> entry = i.next(); final Class c = entry.getKey(); if (c == classBeingWritten) { return entry.getValue(); } int distance = MetaUtils.getDistance(c, classBeingWritten); if (distance < minDistance) { minDistance = distance; fields = entry.getValue(); } } return fields; } private boolean writeOptionalReference(Object obj) throws IOException { if (obj == null) { return false; } if (MetaUtils.isLogicalPrimitive(obj.getClass())) { return false; } final Writer output = this.out; if (objVisited.containsKey(obj)) { // Only write (define) an object once in the JSON stream, otherwise emit a @ref String id = getId(obj); if (id == null) { // Test for null because of Weak/Soft references being gc'd during serialization. return false; } output.write(shortMetaKeys ? "{\"@r\":" : "{\"@ref\":"); output.write(id); output.write('}'); return true; } // Mark the object as visited by putting it in the Map (this map is re-used / clear()'d after walk()). objVisited.put(obj, null); return false; } /** * Main entry point (mostly used internally, but may be called from a Custom JSON writer). * This method will write out whatever object type it is given, including JsonObject's. * It will handle null, detecting if a custom writer should be called, array, array of * JsonObject, Map, Map of JsonObjects, Collection, Collection of JsonObject, any regular * object, or a JsonObject representing a regular object. * @param obj Object to be written * @param showType if set to true, the @type tag will be output. If false, it will be * dropped. * @throws IOException if one occurs on the underlying output stream. */ public void writeImpl(Object obj, boolean showType) throws IOException { writeImpl(obj, showType, true, true); } /** * Main entry point (mostly used internally, but may be called from a Custom JSON writer). * This method will write out whatever object type it is given, including JsonObject's. * It will handle null, detecting if a custom writer should be called, array, array of * JsonObject, Map, Map of JsonObjects, Collection, Collection of JsonObject, any regular * object, or a JsonObject representing a regular object. * @param obj Object to be written * @param showType if set to true, the @type tag will be output. If false, it will be * @param allowRef if set to true, @ref will be used, otherwise 2+ occurrence will be * output as full object. * @param allowCustom if set to true, the object being called will allowed to be checked for a matching * custom writer to be used. This does not affect subobjects, just the top-level 'obj' * being passed in. * @throws IOException if one occurs on the underlying output stream. */ public void writeImpl(Object obj, boolean showType, boolean allowRef, boolean allowCustom) throws IOException { if (neverShowType) { showType = false; } if (obj == null) { out.write("null"); return; } if (allowCustom && writeIfMatching(obj, showType, out)) { return; } if (allowRef && writeOptionalReference(obj)) { return; } if (obj.getClass().isArray()) { writeArray(obj, showType); } else if (obj instanceof Collection) { writeCollection((Collection) obj, showType); } else if (obj instanceof JsonObject) { // symmetric support for writing Map of Maps representation back as equivalent JSON format. JsonObject jObj = (JsonObject) obj; if (jObj.isArray()) { writeJsonObjectArray(jObj, showType); } else if (jObj.isCollection()) { writeJsonObjectCollection(jObj, showType); } else if (jObj.isMap()) { if (!writeJsonObjectMapWithStringKeys(jObj, showType)) { writeJsonObjectMap(jObj, showType); } } else { writeJsonObjectObject(jObj, showType); } } else if (obj instanceof Map) { if (!writeMapWithStringKeys((Map) obj, showType)) { writeMap((Map) obj, showType); } } else { writeObject(obj, showType, false); } } private void writeId(final String id) throws IOException { out.write(shortMetaKeys ? "\"@i\":" : "\"@id\":"); out.write(id == null ? "0" : id); } private void writeType(Object obj, Writer output) throws IOException { if (neverShowType) { return; } output.write(shortMetaKeys ? "\"@t\":\"" : "\"@type\":\""); final Class c = obj.getClass(); String typeName = c.getName(); String shortName = getSubstituteTypeNameIfExists(typeName); if (shortName != null) { output.write(shortName); output.write('"'); return; } String s = c.getName(); if (s.equals("java.lang.Boolean")) { output.write("boolean"); } else if (s.equals("java.lang.Byte")) { output.write("byte"); } else if (s.equals("java.lang.Character")) { output.write("char"); } else if (s.equals("java.lang.Class")) { output.write("class"); } else if (s.equals("java.lang.Double")) { output.write("double"); } else if (s.equals("java.lang.Float")) { output.write("float"); } else if (s.equals("java.lang.Integer")) { output.write("int"); } else if (s.equals("java.lang.Long")) { output.write("long"); } else if (s.equals("java.lang.Short")) { output.write("short"); } else if (s.equals("java.lang.String")) { output.write("string"); } else if (s.equals("java.util.Date")) { output.write("date"); } else { output.write(c.getName()); } output.write('"'); } private void writePrimitive(final Object obj, boolean showType) throws IOException { if (neverShowType) { showType = false; } if (obj instanceof Character) { writeJsonUtf8String(String.valueOf(obj), out); } else { if (obj instanceof Long && writeLongsAsStrings) { if (showType) { out.write(shortMetaKeys ? "{\"@t\":\"" : "{\"@type\":\""); out.write(getSubstituteTypeName("long")); out.write("\",\"value\":\""); out.write(obj.toString()); out.write("\"}"); } else { out.write('"'); out.write(obj.toString()); out.write('"'); } } else if ( (!isAllowNanAndInfinity()) && obj instanceof Double && (Double.isNaN((Double) obj) || Double.isInfinite((Double) obj))) { out.write("null"); } else if ( (!isAllowNanAndInfinity()) && obj instanceof Float && (Float.isNaN((Float) obj) || Float.isInfinite((Float) obj))) { out.write("null"); } else { out.write(obj.toString()); } } } private void writeArray(final Object array, boolean showType) throws IOException { if (neverShowType) { showType = false; } Class arrayType = array.getClass(); int len = Array.getLength(array); boolean referenced = objsReferenced.containsKey(array); // boolean typeWritten = showType && !(Object[].class == arrayType); // causes IDE warning in NetBeans 7/4 Java 1.7 boolean typeWritten = showType && !(arrayType.equals(Object[].class)); final Writer output = this.out; // performance opt: place in final local for quicker access if (typeWritten || referenced) { output.write('{'); tabIn(); } if (referenced) { writeId(getId(array)); output.write(','); newLine(); } if (typeWritten) { writeType(array, output); output.write(','); newLine(); } if (len == 0) { if (typeWritten || referenced) { output.write(shortMetaKeys ? "\"@e\":[]" : "\"@items\":[]"); tabOut(); output.write('}'); } else { output.write("[]"); } return; } if (typeWritten || referenced) { output.write(shortMetaKeys ? "\"@e\":[" : "\"@items\":["); } else { output.write('['); } tabIn(); final int lenMinus1 = len - 1; // Intentionally processing each primitive array type in separate // custom loop for speed. All of them could be handled using // reflective Array.get() but it is slower. I chose speed over code length. if (byte[].class == arrayType) { writeByteArray((byte[]) array, lenMinus1); } else if (char[].class == arrayType) { writeJsonUtf8String(new String((char[]) array), output); } else if (short[].class == arrayType) { writeShortArray((short[]) array, lenMinus1); } else if (int[].class == arrayType) { writeIntArray((int[]) array, lenMinus1); } else if (long[].class == arrayType) { writeLongArray((long[]) array, lenMinus1); } else if (float[].class == arrayType) { writeFloatArray((float[]) array, lenMinus1); } else if (double[].class == arrayType) { writeDoubleArray((double[]) array, lenMinus1); } else if (boolean[].class == arrayType) { writeBooleanArray((boolean[]) array, lenMinus1); } else { final Class componentClass = array.getClass().getComponentType(); final boolean isPrimitiveArray = MetaUtils.isPrimitive(componentClass); for (int i = 0; i < len; i++) { final Object value = Array.get(array, i); if (value == null) { output.write("null"); } else if (writeArrayElementIfMatching(componentClass, value, false, output)) { } else if (isPrimitiveArray || value instanceof Boolean || value instanceof Long || value instanceof Double) { writePrimitive(value, value.getClass() != componentClass); } else if (neverShowType && MetaUtils.isPrimitive(value.getClass())) { // When neverShowType specified, do not allow primitives to show up as {"value":6} for example. writePrimitive(value, false); } else { // Specific Class-type arrays - only force type when // the instance is derived from array base class. boolean forceType = !(value.getClass() == componentClass); writeImpl(value, forceType || alwaysShowType); } if (i != lenMinus1) { output.write(','); newLine(); } } } tabOut(); output.write(']'); if (typeWritten || referenced) { tabOut(); output.write('}'); } } private void writeBooleanArray(boolean[] booleans, int lenMinus1) throws IOException { final Writer output = this.out; for (int i = 0; i < lenMinus1; i++) { output.write(booleans[i] ? "true," : "false,"); } output.write(Boolean.toString(booleans[lenMinus1])); } private void writeDoubleArray(double[] doubles, int lenMinus1) throws IOException { final Writer output = this.out; for (int i = 0; i < lenMinus1; i++) { output.write(doubleToString(doubles[i])); output.write(','); } output.write(doubleToString(doubles[lenMinus1])); } private void writeFloatArray(float[] floats, int lenMinus1) throws IOException { final Writer output = this.out; for (int i = 0; i < lenMinus1; i++) { output.write(floatToString(floats[i])); output.write(','); } output.write(floatToString(floats[lenMinus1])); } private String doubleToString(double d) { if (isAllowNanAndInfinity()) { return Double.toString(d); } return (Double.isNaN(d) || Double.isInfinite(d)) ? "null" : Double.toString(d); } private String floatToString(float d) { if (isAllowNanAndInfinity()) { return Float.toString(d); } return (Float.isNaN(d) || Float.isInfinite(d)) ? "null" : Float.toString(d); } private void writeLongArray(long[] longs, int lenMinus1) throws IOException { final Writer output = this.out; if (writeLongsAsStrings) { for (int i = 0; i < lenMinus1; i++) { output.write('"'); output.write(Long.toString(longs[i])); output.write('"'); output.write(','); } output.write('"'); output.write(Long.toString(longs[lenMinus1])); output.write('"'); } else { for (int i = 0; i < lenMinus1; i++) { output.write(Long.toString(longs[i])); output.write(','); } output.write(Long.toString(longs[lenMinus1])); } } private void writeIntArray(int[] ints, int lenMinus1) throws IOException { final Writer output = this.out; for (int i = 0; i < lenMinus1; i++) { output.write(Integer.toString(ints[i])); output.write(','); } output.write(Integer.toString(ints[lenMinus1])); } private void writeShortArray(short[] shorts, int lenMinus1) throws IOException { final Writer output = this.out; for (int i = 0; i < lenMinus1; i++) { output.write(Integer.toString(shorts[i])); output.write(','); } output.write(Integer.toString(shorts[lenMinus1])); } private void writeByteArray(byte[] bytes, int lenMinus1) throws IOException { final Writer output = this.out; final Object[] byteStrs = byteStrings; for (int i = 0; i < lenMinus1; i++) { output.write((char[]) byteStrs[bytes[i] + 128]); output.write(','); } output.write((char[]) byteStrs[bytes[lenMinus1] + 128]); } private void writeCollection(Collection col, boolean showType) throws IOException { if (neverShowType) { showType = false; } final Writer output = this.out; boolean referenced = objsReferenced.containsKey(col); boolean isEmpty = col.isEmpty(); if (referenced || showType) { output.write('{'); tabIn(); } else if (isEmpty) { output.write('['); } writeIdAndTypeIfNeeded(col, showType, referenced); if (isEmpty) { if (referenced || showType) { tabOut(); output.write('}'); } else { output.write(']'); } return; } beginCollection(showType, referenced); Iterator i = col.iterator(); writeElements(output, i); tabOut(); output.write(']'); if (showType || referenced) { // Finished object, as it was output as an object if @id or @type was output tabOut(); output.write("}"); } } private void writeElements(Writer output, Iterator i) throws IOException { while (i.hasNext()) { writeCollectionElement(i.next()); if (i.hasNext()) { output.write(','); newLine(); } } } private void writeIdAndTypeIfNeeded(Object col, boolean showType, boolean referenced) throws IOException { if (neverShowType) { showType = false; } if (referenced) { writeId(getId(col)); } if (showType) { if (referenced) { out.write(','); newLine(); } writeType(col, out); } } private void beginCollection(boolean showType, boolean referenced) throws IOException { if (showType || referenced) { out.write(','); newLine(); out.write(shortMetaKeys ? "\"@e\":[" : "\"@items\":["); } else { out.write('['); } tabIn(); } private void writeJsonObjectArray(JsonObject jObj, boolean showType) throws IOException { if (neverShowType) { showType = false; } int len = jObj.getLength(); String type = jObj.type; Class arrayClass; if (type == null || Object[].class.getName().equals(type)) { arrayClass = Object[].class; } else { arrayClass = MetaUtils.classForName(type, getClassLoader()); } final Writer output = this.out; final boolean isObjectArray = Object[].class == arrayClass; final Class componentClass = arrayClass.getComponentType(); boolean referenced = objsReferenced.containsKey(jObj) && jObj.hasId(); boolean typeWritten = showType && !isObjectArray; if (typeWritten || referenced) { output.write('{'); tabIn(); } if (referenced) { writeId(Long.toString(jObj.id)); output.write(','); newLine(); } if (typeWritten) { output.write(shortMetaKeys ? "\"@t\":\"" : "\"@type\":\""); output.write(getSubstituteTypeName(arrayClass.getName())); output.write("\","); newLine(); } if (len == 0) { if (typeWritten || referenced) { output.write(shortMetaKeys ? "\"@e\":[]" : "\"@items\":[]"); tabOut(); output.write("}"); } else { output.write("[]"); } return; } if (typeWritten || referenced) { output.write(shortMetaKeys ? "\"@e\":[" : "\"@items\":["); } else { output.write('['); } tabIn(); Object[] items = (Object[]) jObj.get(ITEMS); final int lenMinus1 = len - 1; for (int i = 0; i < len; i++) { final Object value = items[i]; if (value == null) { output.write("null"); } else if (Character.class == componentClass || char.class == componentClass) { writeJsonUtf8String((String) value, output); } else if (value instanceof Boolean || value instanceof Long || value instanceof Double) { writePrimitive(value, value.getClass() != componentClass); } else if (neverShowType && MetaUtils.isPrimitive(value.getClass())) { writePrimitive(value, false); } else if (value instanceof String) { // Have to specially treat String because it could be referenced, but we still want inline (no @type, value:) writeJsonUtf8String((String) value, output); } else if (writeArrayElementIfMatching(componentClass, value, false, output)) { } else { // Specific Class-type arrays - only force type when // the instance is derived from array base class. boolean forceType = !(value.getClass() == componentClass); writeImpl(value, forceType || alwaysShowType); } if (i != lenMinus1) { output.write(','); newLine(); } } tabOut(); output.write(']'); if (typeWritten || referenced) { tabOut(); output.write('}'); } } private void writeJsonObjectCollection(JsonObject jObj, boolean showType) throws IOException { if (neverShowType) { showType = false; } String type = jObj.type; Class colClass = MetaUtils.classForName(type, getClassLoader()); boolean referenced = objsReferenced.containsKey(jObj) && jObj.hasId(); final Writer output = this.out; int len = jObj.getLength(); if (referenced || showType || len == 0) { output.write('{'); tabIn(); } if (referenced) { writeId(String.valueOf(jObj.id)); } if (showType) { if (referenced) { output.write(','); newLine(); } output.write(shortMetaKeys ? "\"@t\":\"" : "\"@type\":\""); output.write(getSubstituteTypeName(colClass.getName())); output.write('"'); } if (len == 0) { tabOut(); output.write('}'); return; } beginCollection(showType, referenced); Object[] items = (Object[]) jObj.get(ITEMS); final int itemsLen = items.length; final int itemsLenMinus1 = itemsLen - 1; for (int i=0; i < itemsLen; i++) { writeCollectionElement(items[i]); if (i != itemsLenMinus1) { output.write(','); newLine(); } } tabOut(); output.write("]"); if (showType || referenced) { tabOut(); output.write('}'); } } private void writeJsonObjectMap(JsonObject jObj, boolean showType) throws IOException { if (neverShowType) { showType = false; } boolean referenced = objsReferenced.containsKey(jObj) && jObj.hasId(); final Writer output = this.out; output.write('{'); tabIn(); if (referenced) { writeId(String.valueOf(jObj.getId())); } if (showType) { if (referenced) { output.write(','); newLine(); } String type = jObj.getType(); if (type != null) { Class mapClass = MetaUtils.classForName(type, getClassLoader()); output.write(shortMetaKeys ? "\"@t\":\"" : "\"@type\":\""); output.write(getSubstituteTypeName(mapClass.getName())); output.write('"'); } else { // type not displayed showType = false; } } if (jObj.isEmpty()) { // Empty tabOut(); output.write('}'); return; } if (showType) { output.write(','); newLine(); } output.write(shortMetaKeys ? "\"@k\":[" : "\"@keys\":["); tabIn(); Iterator i = jObj.keySet().iterator(); writeElements(output, i); tabOut(); output.write("],"); newLine(); output.write(shortMetaKeys ? "\"@e\":[" : "\"@items\":["); tabIn(); i =jObj.values().iterator(); writeElements(output, i); tabOut(); output.write(']'); tabOut(); output.write('}'); } private boolean writeJsonObjectMapWithStringKeys(JsonObject jObj, boolean showType) throws IOException { if (neverShowType) { showType = false; } if ((forceMapFormatWithKeyArrays) || (!ensureJsonPrimitiveKeys(jObj)) ) { return false; } boolean referenced = objsReferenced.containsKey(jObj) && jObj.hasId(); final Writer output = this.out; output.write('{'); tabIn(); if (referenced) { writeId(String.valueOf(jObj.getId())); } if (showType) { if(referenced) { output.write(','); newLine(); } String type = jObj.getType(); if (type != null) { Class mapClass = MetaUtils.classForName(type, getClassLoader()); output.write(shortMetaKeys ? "\"@t\":\"" : "\"@type\":\""); output.write(getSubstituteTypeName(mapClass.getName())); output.write('"'); } else { // type not displayed showType = false; } } if (jObj.isEmpty()) { // Empty tabOut(); output.write('}'); return true; } if (showType) { output.write(','); newLine(); } return writeMapBody(jObj.entrySet().iterator()); } /** * Write fields of an Object (JsonObject) */ private void writeJsonObjectObject(JsonObject jObj, boolean showType) throws IOException { if (neverShowType) { showType = false; } final Writer output = this.out; boolean referenced = objsReferenced.containsKey(jObj) && jObj.hasId(); showType = showType && jObj.type != null; Class type = null; output.write('{'); tabIn(); if (referenced) { writeId(String.valueOf(jObj.id)); } if (showType) { if (referenced) { output.write(','); newLine(); } output.write(shortMetaKeys ? "\"@t\":\"" : "\"@type\":\""); output.write(getSubstituteTypeName(jObj.type)); output.write('"'); try { type = MetaUtils.classForName(jObj.type, getClassLoader()); } catch(Exception ignored) { type = null; } } if (jObj.isEmpty()) { tabOut(); output.write('}'); return; } if (showType || referenced) { output.write(','); newLine(); } Iterator<Map.Entry<String,Object>> i = jObj.entrySet().iterator(); boolean first = true; while (i.hasNext()) { Map.Entry<String, Object>entry = i.next(); if (skipNullFields && entry.getValue() == null) { continue; } if (!first) { output.write(','); newLine(); } first = false; final String fieldName = entry.getKey(); output.write('"'); output.write(fieldName); output.write("\":"); Object value = entry.getValue(); if (value == null) { output.write("null"); } else if (neverShowType && MetaUtils.isPrimitive(value.getClass())) { writePrimitive(value, false); } else if (value instanceof BigDecimal || value instanceof BigInteger) { writeImpl(value, !doesValueTypeMatchFieldType(type, fieldName, value)); } else if (value instanceof Number || value instanceof Boolean) { output.write(value.toString()); } else if (value instanceof String) { writeJsonUtf8String((String) value, output); } else if (value instanceof Character) { writeJsonUtf8String(String.valueOf(value), output); } else { writeImpl(value, !doesValueTypeMatchFieldType(type, fieldName, value)); } } tabOut(); output.write('}'); } private static boolean doesValueTypeMatchFieldType(Class type, String fieldName, Object value) { if (type != null) { Map<String, Field> classFields = MetaUtils.getDeepDeclaredFields(type); Field field = classFields.get(fieldName); return field != null && (value.getClass() == field.getType()); } return false; } private void writeMap(Map map, boolean showType) throws IOException { if (neverShowType) { showType = false; } final Writer output = this.out; boolean referenced = objsReferenced.containsKey(map); output.write('{'); tabIn(); if (referenced) { writeId(getId(map)); } if (showType) { if (referenced) { output.write(','); newLine(); } writeType(map, output); } if (map.isEmpty()) { tabOut(); output.write('}'); return; } if (showType || referenced) { output.write(','); newLine(); } output.write(shortMetaKeys ? "\"@k\":[" : "\"@keys\":["); tabIn(); Iterator i = map.keySet().iterator(); writeElements(output, i); tabOut(); output.write("],"); newLine(); output.write(shortMetaKeys ? "\"@e\":[" : "\"@items\":["); tabIn(); i = map.values().iterator(); writeElements(output, i); tabOut(); output.write(']'); tabOut(); output.write('}'); } private boolean writeMapWithStringKeys(Map map, boolean showType) throws IOException { if (neverShowType) { showType = false; } if ((forceMapFormatWithKeyArrays) || (!ensureJsonPrimitiveKeys(map))) { return false; } boolean referenced = objsReferenced.containsKey(map); out.write('{'); tabIn(); writeIdAndTypeIfNeeded(map, showType, referenced); if (map.isEmpty()) { tabOut(); out.write('}'); return true; } if (showType || referenced) { out.write(','); newLine(); } return writeMapBody(map.entrySet().iterator()); } private boolean writeMapBody(final Iterator i) throws IOException { final Writer output = out; while (i.hasNext()) { Entry att2value = (Entry) i.next(); writeJsonUtf8String((String)att2value.getKey(), output); output.write(":"); writeCollectionElement(att2value.getValue()); if (i.hasNext()) { output.write(','); newLine(); } } tabOut(); output.write('}'); return true; } /** * Ensure that all keys within the Map are String instances * @param map Map to inspect that all keys are primitive. This allows the output JSON * to be optimized into {"key1":value1, "key2": value2} format if all the * keys of the Map are Strings. If not, then a Map is written as two * arrays, an @keys array and an @items array. This allows support for Maps * with non-String keys. */ public static boolean ensureJsonPrimitiveKeys(Map map) { for (Object o : map.keySet()) { if (!(o instanceof String)) { return false; } } return true; } /** * Write an element that is contained in some type of Collection or Map. * @param o Collection element to output in JSON format. * @throws IOException if an error occurs writing to the output stream. */ private void writeCollectionElement(Object o) throws IOException { if (o == null) { out.write("null"); } else if (o instanceof Boolean || o instanceof Double) { writePrimitive(o, false); } else if (o instanceof Long) { writePrimitive(o, writeLongsAsStrings); } else if (o instanceof String) { // Never do an @ref to a String (they are treated as logical primitives and intern'ed on read) writeJsonUtf8String((String) o, out); } else if (neverShowType && MetaUtils.isPrimitive(o.getClass())) { // If neverShowType, then force primitives (and primitive wrappers) // to be output with toString() - prevents {"value":6} for example writePrimitive(o, false); } else { writeImpl(o, true); } } /** * @param obj Object to be written in JSON format * @param showType boolean true means show the "@type" field, false * eliminates it. Many times the type can be dropped because it can be * inferred from the field or array type. * @param bodyOnly write only the body of the object * @throws IOException if an error occurs writing to the output stream. */ public void writeObject(final Object obj, boolean showType, boolean bodyOnly) throws IOException { if (neverShowType) { showType = false; } final boolean referenced = objsReferenced.containsKey(obj); if (!bodyOnly) { out.write('{'); tabIn(); if (referenced) { writeId(getId(obj)); } if (referenced && showType) { out.write(','); newLine(); } if (showType) { writeType(obj, out); } } boolean first = !showType; if (referenced && !showType) { first = false; } final Map<Class, List<Field>> fieldSpecifiers = (Map) args.get(FIELD_SPECIFIERS); final List<Field> fieldBlackListForClass = getFieldsUsingSpecifier(obj.getClass(), (Map) args.get(FIELD_BLACK_LIST)); final List<Field> externallySpecifiedFields = getFieldsUsingSpecifier(obj.getClass(), fieldSpecifiers); if (externallySpecifiedFields != null) { for (Field field : externallySpecifiedFields) { //output field if not on the blacklist if (fieldBlackListForClass == null || !fieldBlackListForClass.contains(field)){ // Not currently supporting overwritten field names in hierarchy when using external field specifier first = writeField(obj, first, field.getName(), field, true); }//else field is black listed. } } else { // Reflectively use fields, skipping transient and static fields final Map<String, Field> classFields = MetaUtils.getDeepDeclaredFields(obj.getClass()); for (Map.Entry<String, Field> entry : classFields.entrySet()) { final String fieldName = entry.getKey(); final Field field = entry.getValue(); //output field if not on the blacklist if (fieldBlackListForClass == null || !fieldBlackListForClass.contains(field)){ first = writeField(obj, first, fieldName, field, false); }//else field is black listed. } } if (!bodyOnly) { tabOut(); out.write('}'); } } private Object getValueByReflect(Object obj, Field field) { try { return field.get(obj); } catch (Exception ignored) { return null; } } private boolean writeField(Object obj, boolean first, String fieldName, Field field, boolean allowTransient) throws IOException { if (!allowTransient && (field.getModifiers() & Modifier.TRANSIENT) != 0) { // Do not write transient fields return first; } final int modifiers = field.getModifiers(); final Class fieldDeclaringClass = field.getDeclaringClass(); Object o = null; if (Enum.class.isAssignableFrom(fieldDeclaringClass)) { if (!"name".equals(field.getName())) { if (!Modifier.isPublic(modifiers) && isEnumPublicOnly) { return first; } if ("ordinal".equals(field.getName()) || "internal".equals(field.getName())) { return first; } o = getValueByReflect(obj, field); } else { //not advice to use reflect to get name field value from enum since jdk17 //TODO enum class create a field also named : "name"? that's not good rule, so will not consider that o = ((Enum)obj).name(); } } else if(ObjectResolver.isBasicWrapperType(fieldDeclaringClass)) { o = obj; } else { o = getValueByReflect(obj, field); } if (skipNullFields && o == null) { // If skip null, skip field and return the same status on first field written indicator return first; } if (!first) { out.write(','); newLine(); } writeJsonUtf8String(fieldName, out); out.write(':'); if (o == null) { // don't quote null out.write("null"); return false; } Class type = field.getType(); boolean forceType = o.getClass() != type; // If types are not exactly the same, write "@type" field //When no type is written we can check the Object itself not the declaration if (MetaUtils.isPrimitive(type) || (neverShowType && MetaUtils.isPrimitive(o.getClass()))) { writePrimitive(o, false); } else { writeImpl(o, forceType || alwaysShowType, true, true); } return false; } /** * Write out special characters "\b, \f, \t, \n, \r", as such, backslash as \\ * quote as \" and values less than an ASCII space (20hex) as "\\u00xx" format, * characters in the range of ASCII space to a '~' as ASCII, and anything higher in UTF-8. * * @param s String to be written in UTF-8 format on the output stream. * @param output Writer to which the UTF-8 string will be written to * @throws IOException if an error occurs writing to the output stream. */ public static void writeJsonUtf8String(String s, final Writer output) throws IOException { output.write('\"'); final int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c < ' ') { // Anything less than ASCII space, write either in \\u00xx form, or the special \t, \n, etc. form switch (c) { case '\b': output.write("\\b"); break; case '\f': output.write("\\f"); break; case '\n': output.write("\\n"); break; case '\r': output.write("\\r"); break; case '\t': output.write("\\t"); break; default: output.write(String.format("\\u%04X", (int)c)); break; } } else if (c == '\\' || c == '"') { output.write('\\'); output.write(c); } else { // Anything else - write in UTF-8 form (multi-byte encoded) (OutputStreamWriter is UTF-8) output.write(c); } } output.write('\"'); } public void flush() { try { if (out != null) { out.flush(); } } catch (Exception ignored) { } } public void close() { try { out.close(); } catch (Exception ignore) { } writerCache.clear(); writers.clear(); } private String getId(Object o) { if (o instanceof JsonObject) { long id = ((JsonObject) o).id; if (id != -1) { return String.valueOf(id); } } Long id = objsReferenced.get(o); return id == null ? null : Long.toString(id); } }
82,131
32.550654
210
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/JsonObject.java
package com.cedarsoftware.util.io; import java.lang.reflect.Array; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /** * This class holds a JSON object in a LinkedHashMap. * LinkedHashMap used to keep fields in same order as they are * when reflecting them in Java. Instances of this class hold a * Map-of-Map representation of a Java object, read from the JSON * input stream. * * @param <K> field name in Map-of-Map * @param <V> Value * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.* */ public class JsonObject<K, V> extends LinkedHashMap<K, V> { public static final String KEYS = "@keys"; public static final String ITEMS = "@items"; public static final String ID = "@id"; public static final String REF = "@ref"; public static final String TYPE = "@type"; static Set<String> primitives = new HashSet<>(); static Set<String> primitiveWrappers = new HashSet<>(); Object target; boolean isMap = false; String type; long id = -1; int line; int col; static { primitives.add("boolean"); primitives.add("byte"); primitives.add("char"); primitives.add("double"); primitives.add("float"); primitives.add("int"); primitives.add("long"); primitives.add("short"); primitiveWrappers.add("java.lang.Boolean"); primitiveWrappers.add("java.lang.Byte"); primitiveWrappers.add("java.lang.Character"); primitiveWrappers.add("java.lang.Double"); primitiveWrappers.add("java.lang.Float"); primitiveWrappers.add("java.lang.Integer"); primitiveWrappers.add("java.lang.Long"); primitiveWrappers.add("java.lang.Short"); } public long getId() { return id; } public boolean hasId() { return id != -1; } public void setType(String type) { this.type = type; } public String getType() { return type; } public Object getTarget() { return target; } public void setTarget(Object target) { this.target = target; } public Class getTargetClass() { return target.getClass(); } public boolean isLogicalPrimitive() { return primitiveWrappers.contains(type) || primitives.contains(type) || "date".equals(type) || "java.math.BigInteger".equals(type) || "java.math.BigDecimal".equals(type); } public Object getPrimitiveValue() { if ("boolean".equals(type) || "double".equals(type) || "long".equals(type)) { return get("value"); } else if ("byte".equals(type)) { Number b = (Number) get("value"); return b.byteValue(); } else if ("char".equals(type)) { String c = (String) get("value"); return c.charAt(0); } else if ("float".equals(type)) { Number f = (Number) get("value"); return f.floatValue(); } else if ("int".equals(type)) { Number integer = (Number) get("value"); return integer.intValue(); } else if ("short".equals(type)) { Number s = (Number) get("value"); return s.shortValue(); } else if ("date".equals(type)) { Object date = get("value"); if (date instanceof Long) { return new Date((Long)(date)); } else if (date instanceof String) { return Readers.DateReader.parseDate((String) date); } else { throw new JsonIoException("Unknown date type: " + type); } } else if ("java.math.BigInteger".equals(type)) { Object value = get("value"); return Readers.bigIntegerFrom(value); } else if ("java.math.BigDecimal".equals(type)) { Object value = get("value"); return Readers.bigDecimalFrom(value); } else { throw new JsonIoException("Invalid primitive type, line " + line + ", col " + col); } } /** * @return boolean true if this object references another object, false otherwise. */ public boolean isReference() { return containsKey(REF); } public Long getReferenceId() { return (Long) get(REF); } // Map APIs public boolean isMap() { return isMap || target instanceof Map; } // Collection APIs public boolean isCollection() { if (target instanceof Collection) { return true; } if (containsKey(ITEMS) && !containsKey(KEYS)) { return type != null && !type.contains("["); } return false; } // Array APIs public boolean isArray() { if (target == null) { if (type != null) { return type.contains("["); } return containsKey(ITEMS) && !containsKey(KEYS); } return target.getClass().isArray(); } // Return the array that this JSON object wraps. This is used when there is a Collection class (like ArrayList) // represented in the JSON. This also occurs if a specified array type is used (not Object[], but Integer[], for // example). public Object[] getArray() { return (Object[]) get(ITEMS); } public int getLength() { if (isArray()) { if (target == null) { Object[] items = (Object[]) get(ITEMS); return items == null ? 0 : items.length; } return Array.getLength(target); } if (isCollection() || isMap()) { Object[] items = (Object[]) get(ITEMS); return items == null ? 0 : items.length; } throw new JsonIoException("getLength() called on a non-collection, line " + line + ", col " + col); } public Class getComponentType() { return target.getClass().getComponentType(); } void moveBytesToMate() { final byte[] bytes = (byte[]) target; final Object[] items = getArray(); final int len = items.length; for (int i = 0; i < len; i++) { bytes[i] = ((Number) items[i]).byteValue(); } } void moveCharsToMate() { Object[] items = getArray(); if (items == null) { target = null; } else if (items.length == 0) { target = new char[0]; } else if (items.length == 1) { String s = (String) items[0]; target = s.toCharArray(); } else { throw new JsonIoException("char[] should only have one String in the [], found " + items.length + ", line " + line + ", col " + col); } } public V put(K key, V value) { if (key == null) { return super.put(null, value); } if (key.equals(TYPE)) { String oldType = type; type = (String) value; return (V) oldType; } else if (key.equals(ID)) { Long oldId = id; id = (Long) value; return (V) oldId; } else if ((ITEMS.equals(key) && containsKey(KEYS)) || (KEYS.equals(key) && containsKey(ITEMS))) { isMap = true; } return super.put(key, value); } public void clear() { super.clear(); type = null; } void clearArray() { remove(ITEMS); } /** * @return int line where this object '{' started in the JSON stream */ public int getLine() { return line; } /** * @return int column where this object '{' started in the JSON stream */ public int getCol() { return col; } public int size() { if (containsKey(ITEMS)) { Object value = get(ITEMS); if (value instanceof Object[]) { return ((Object[])value).length; } else if (value == null) { return 0; } else { throw new JsonIoException("JsonObject with @items, but no array [] associated to it, line " + line + ", col " + col); } } else if (containsKey(REF)) { return 0; } return super.size(); } }
9,622
24.86828
145
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/MapResolver.java
package com.cedarsoftware.util.io; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.Deque; import java.util.List; import java.util.Map; /** * <p>The MapResolver converts the raw Maps created from the JsonParser to higher * quality Maps representing the implied object graph. It does this by replacing * <code>@ref</code> values with the Map indicated by the @id key with the same value. * </p><p> * This approach 'wires' the original object graph. During the resolution process, * if 'peer' classes can be found for given Maps (for example, an @type entry is * available which indicates the class that would have been associated to the Map, * then the associated class is consulted to help 'improve' the quality of the primitive * values within the map fields. For example, if the peer class indicated that a field * was of type 'short', and the Map had a long value (JSON only returns long's for integer * types), then the long would be converted to a short. * </p><p> * The final Map representation is a very high-quality graph that represents the original * JSON graph. It can be passed as input to JsonWriter, and the JsonWriter will write * out the equivalent JSON to what was originally read. This technique allows json-io to * be used on a machine that does not have any of the Java classes from the original graph, * read it in a JSON graph (any JSON graph), return the equivalent maps, allow mutations of * those maps, and finally this graph can be written out. * </p> * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class MapResolver extends Resolver { protected MapResolver(JsonReader reader) { super(reader); } protected Object readIfMatching(Object o, Class compType, Deque<JsonObject<String, Object>> stack) { // No custom reader support for maps return null; } /** * Walk the JsonObject fields and perform necessary substitutions so that all references matched up. * This code patches @ref and @id pairings up, in the 'Map of Map' mode. Where the JSON may contain * an @id of an object which can have more than one @ref to it, this code will make sure that each * @ref (value side of the Map associated to a given field name) will be pointer to the appropriate Map * instance. * @param stack Stack (Deque) used for graph traversal. * @param jsonObj a Map-of-Map representation of the current object being examined (containing all fields). */ public void traverseFields(final Deque<JsonObject<String, Object>> stack, final JsonObject<String, Object> jsonObj) { final Object target = jsonObj.target; for (Map.Entry<String, Object> e : jsonObj.entrySet()) { final String fieldName = e.getKey(); final Field field = (target != null) ? MetaUtils.getField(target.getClass(), fieldName) : null; final Object rhs = e.getValue(); if (rhs == null) { jsonObj.put(fieldName, null); } else if (rhs == JsonParser.EMPTY_OBJECT) { jsonObj.put(fieldName, new JsonObject()); } else if (rhs.getClass().isArray()) { // RHS is an array // Trace the contents of the array (so references inside the array and into the array work) JsonObject<String, Object> jsonArray = new JsonObject<String, Object>(); jsonArray.put(JsonObject.ITEMS, rhs); stack.addFirst(jsonArray); // Assign the array directly to the Map key (field name) jsonObj.put(fieldName, rhs); } else if (rhs instanceof JsonObject) { JsonObject<String, Object> jObj = (JsonObject) rhs; if (field != null && MetaUtils.isLogicalPrimitive(field.getType())) { jObj.put("value", MetaUtils.convert(field.getType(), jObj.get("value"))); continue; } Long refId = jObj.getReferenceId(); if (refId != null) { // Correct field references JsonObject refObject = getReferencedObj(refId); jsonObj.put(fieldName, refObject); // Update Map-of-Maps reference } else { stack.addFirst(jObj); } } else if (field != null) { // The code below is 'upgrading' the RHS values in the passed in JsonObject Map // by using the @type class name (when specified and exists), to coerce the vanilla // JSON values into the proper types defined by the class listed in @type. This is // a cool feature of json-io, that even when reading a map-of-maps JSON file, it will // improve the final types of values in the maps RHS, to be of the field type that // was optionally specified in @type. final Class fieldType = field.getType(); if (MetaUtils.isPrimitive(fieldType) || BigDecimal.class.equals(fieldType) || BigInteger.class.equals(fieldType) || Date.class.equals(fieldType)) { jsonObj.put(fieldName, MetaUtils.convert(fieldType, rhs)); } else if (rhs instanceof String) { if (fieldType != String.class && fieldType != StringBuilder.class && fieldType != StringBuffer.class) { if ("".equals(((String)rhs).trim())) { // Allow "" to null out a non-String field on the inbound JSON jsonObj.put(fieldName, null); } } } } } jsonObj.target = null; // don't waste space (used for typed return, not for Map return) } /** * Process java.util.Collection and it's derivatives. Collections are written specially * so that the serialization does not expose the Collection's internal structure, for * example a TreeSet. All entries are processed, except unresolved references, which * are filled in later. For an indexable collection, the unresolved references are set * back into the proper element location. For non-indexable collections (Sets), the * unresolved references are added via .add(). * @param stack a Stack (Deque) used to support graph traversal. * @param jsonObj a Map-of-Map representation of the JSON input stream. */ protected void traverseCollection(final Deque<JsonObject<String, Object>> stack, final JsonObject<String, Object> jsonObj) { final Object[] items = jsonObj.getArray(); if (items == null || items.length == 0) { return; } int idx = 0; final List copy = new ArrayList(items.length); for (Object element : items) { if (element == JsonParser.EMPTY_OBJECT) { copy.add(new JsonObject()); continue; } copy.add(element); if (element instanceof Object[]) { // array element inside Collection JsonObject<String, Object> jsonObject = new JsonObject<String, Object>(); jsonObject.put(JsonObject.ITEMS, element); stack.addFirst(jsonObject); } else if (element instanceof JsonObject) { JsonObject<String, Object> jsonObject = (JsonObject<String, Object>) element; Long refId = jsonObject.getReferenceId(); if (refId != null) { // connect reference JsonObject refObject = getReferencedObj(refId); copy.set(idx, refObject); } else { stack.addFirst(jsonObject); } } idx++; } jsonObj.target = null; // don't waste space (used for typed return, not generic Map return) for (int i=0; i < items.length; i++) { items[i] = copy.get(i); } } protected void traverseArray(Deque<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) { traverseCollection(stack, jsonObj); } }
9,379
43.037559
161
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/FastPushbackReader.java
package com.cedarsoftware.util.io; import java.io.Closeable; import java.io.IOException; public interface FastPushbackReader extends Closeable { int getCol(); int getLine(); void unread(int c) throws IOException; int read() throws IOException; String getLastSnippet(); }
298
15.611111
55
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/MetaUtils.java
package com.cedarsoftware.util.io; import java.lang.reflect.*; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.reflect.Modifier.*; /** * This utility class has the methods mostly related to reflection related code. * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.* */ public class MetaUtils { private MetaUtils () {} private static final Map<Class, Map<String, Field>> classMetaCache = new ConcurrentHashMap<>(); private static final Set<Class> prims = new HashSet<>(); private static final Map<String, Class> nameToClass = new HashMap<>(); private static final Byte[] byteCache = new Byte[256]; private static final Character[] charCache = new Character[128]; private static final Pattern extraQuotes = Pattern.compile("([\"]*)([^\"]*)([\"]*)"); private static final Class[] emptyClassArray = new Class[]{}; private static final ConcurrentMap<Class, Object[]> constructors = new ConcurrentHashMap<>(); private static final Collection unmodifiableCollection = Collections.unmodifiableCollection(new ArrayList()); private static final Collection unmodifiableSet = Collections.unmodifiableSet(new HashSet()); private static final Collection unmodifiableSortedSet = Collections.unmodifiableSortedSet(new TreeSet()); private static final Map unmodifiableMap = Collections.unmodifiableMap(new HashMap()); private static final Map unmodifiableSortedMap = Collections.unmodifiableSortedMap(new TreeMap()); static final ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() { public SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); } }; private static boolean useUnsafe = false; private static Unsafe unsafe; static Exception loadClassException; /** * Globally turn on (or off) the 'unsafe' option of Class construction. The unsafe option * is used when all constructors have been tried and the Java class could not be instantiated. * @param state boolean true = on, false = off. */ public static void setUseUnsafe(boolean state) { useUnsafe = state; if (state) { try { unsafe = new Unsafe(); } catch (InvocationTargetException e) { useUnsafe = false; } } } static { prims.add(Byte.class); prims.add(Integer.class); prims.add(Long.class); prims.add(Double.class); prims.add(Character.class); prims.add(Float.class); prims.add(Boolean.class); prims.add(Short.class); nameToClass.put("string", String.class); nameToClass.put("boolean", boolean.class); nameToClass.put("char", char.class); nameToClass.put("byte", byte.class); nameToClass.put("short", short.class); nameToClass.put("int", int.class); nameToClass.put("long", long.class); nameToClass.put("float", float.class); nameToClass.put("double", double.class); nameToClass.put("date", Date.class); nameToClass.put("class", Class.class); // Save memory by re-using all byte instances (Bytes are immutable) for (int i = 0; i < byteCache.length; i++) { byteCache[i] = (byte) (i - 128); } // Save memory by re-using common Characters (Characters are immutable) for (int i = 0; i < charCache.length; i++) { charCache[i] = (char) i; } } /** * Return an instance of of the Java Field class corresponding to the passed in field name. * @param c class containing the field / field name * @param field String name of a field on the class. * @return Field instance if the field with the corresponding name is found, null otherwise. */ public static Field getField(Class c, String field) { return getDeepDeclaredFields(c).get(field); } /** * @param c Class instance * @return ClassMeta which contains fields of class. The results are cached internally for performance * when called again with same Class. */ public static Map<String, Field> getDeepDeclaredFields(Class c) { Map<String, Field> classFields = classMetaCache.get(c); if (classFields != null) { return classFields; } classFields = new LinkedHashMap<String, Field>(); Class curr = c; while (curr != null) { try { final Field[] local = curr.getDeclaredFields(); for (Field field : local) { if ((field.getModifiers() & Modifier.STATIC) == 0) { // speed up: do not process static fields. if ("metaClass".equals(field.getName()) && "groovy.lang.MetaClass".equals(field.getType().getName())) { // Skip Groovy metaClass field if present continue; } try { field.setAccessible(true); } catch (Exception ignored) { } if (classFields.containsKey(field.getName())) { classFields.put(curr.getName() + '.' + field.getName(), field); } else { classFields.put(field.getName(), field); } } } } catch (ThreadDeath t) { throw t; } catch (Throwable ignored) { } curr = curr.getSuperclass(); } classMetaCache.put(c, classFields); return classFields; } /** * @param a Class source class * @param b Class target class * @return inheritance distance between two classes, or Integer.MAX_VALUE if they are not related. Each * step upward in the inheritance from one class to the next (calling class.getSuperclass()) is counted * as 1. This can be a lot of computational effort, therefore the results of this determination should be cached. */ public static int getDistance(Class a, Class b) { if (a.isInterface()) { return getDistanceToInterface(a, b); } Class curr = b; int distance = 0; while (curr != a) { distance++; curr = curr.getSuperclass(); if (curr == null) { return Integer.MAX_VALUE; } } return distance; } /** * @return int distance between two passed in classes. This method performs an exhaustive * walk up the inheritance chain to compute the distance. This can be a lot of * computational effort, therefore the results of this determination should be cached internally. */ static int getDistanceToInterface(Class<?> to, Class<?> from) { Set<Class<?>> possibleCandidates = new LinkedHashSet<Class<?>>(); Class<?>[] interfaces = from.getInterfaces(); // is the interface direct inherited or via interfaces extends interface? for (Class<?> interfase : interfaces) { if (to.equals(interfase)) { return 1; } // because of multi-inheritance from interfaces if (to.isAssignableFrom(interfase)) { possibleCandidates.add(interfase); } } // it is also possible, that the interface is included in superclasses if (from.getSuperclass() != null && to.isAssignableFrom(from.getSuperclass())) { possibleCandidates.add(from.getSuperclass()); } int minimum = Integer.MAX_VALUE; for (Class<?> candidate : possibleCandidates) { // Could do that in a non recursive way later int distance = getDistanceToInterface(to, candidate); if (distance < minimum) { minimum = ++distance; } } return minimum; } /** * @param c Class to test * @return boolean true if the passed in class is a Java primitive, false otherwise. The Wrapper classes * Integer, Long, Boolean, etc. are considered primitives by this method. */ public static boolean isPrimitive(Class c) { return c.isPrimitive() || prims.contains(c); } /** * @param c Class to test * @return boolean true if the passed in class is a 'logical' primitive. A logical primitive is defined * as all Java primitives, the primitive wrapper classes, String, Number, and Class. The reason these are * considered 'logical' primitives is that they are immutable and therefore can be written without references * in JSON content (making the JSON more readable - less @id / @ref), without breaking the semantics (shape) * of the object graph being written. */ public static boolean isLogicalPrimitive(Class c) { return c.isPrimitive() || prims.contains(c) || String.class.isAssignableFrom(c) || Number.class.isAssignableFrom(c) || Date.class.isAssignableFrom(c) || c.isEnum() || c.equals(Class.class); } /** * Given the passed in String class name, return the named JVM class. * @param name String name of a JVM class. * @param classLoader ClassLoader to use when searching for JVM classes. * @param failOnClassLoadingError If named class is not loadable off classpath: true will raise JsonIoException, * false will return default LinkedHashMap. * @return Class the named JVM class. * @throws JsonIoException if named Class is invalid or not loadable via the classLoader and failOnClassLoadingError is * true */ static Class classForName(String name, ClassLoader classLoader, boolean failOnClassLoadingError) { if (name == null || name.isEmpty()) { throw new JsonIoException("Class name cannot be null or empty."); } Class c = nameToClass.get(name); try { loadClassException = null; return c == null ? loadClass(name, classLoader) : c; } catch (Exception e) { // Remember why in case later we have a problem loadClassException = e; if(failOnClassLoadingError) { throw new JsonIoException("Unable to create class: " + name, e); } return LinkedHashMap.class; } } /** * Given the passed in String class name, return the named JVM class. * @param name String name of a JVM class. * @param classLoader ClassLoader to use when searching for JVM classes. * @return Class the named JVM class. * @throws JsonIoException if named Class is invalid. */ static Class classForName(String name, ClassLoader classLoader) { return classForName(name, classLoader, false); } /** * loadClass() provided by: Thomas Margreiter */ private static Class loadClass(String name, ClassLoader classLoader) throws ClassNotFoundException { String className = name; boolean arrayType = false; Class primitiveArray = null; while (className.startsWith("[")) { arrayType = true; if (className.endsWith(";")) { className = className.substring(0, className.length() - 1); } if (className.equals("[B")) { primitiveArray = byte[].class; } else if (className.equals("[S")) { primitiveArray = short[].class; } else if (className.equals("[I")) { primitiveArray = int[].class; } else if (className.equals("[J")) { primitiveArray = long[].class; } else if (className.equals("[F")) { primitiveArray = float[].class; } else if (className.equals("[D")) { primitiveArray = double[].class; } else if (className.equals("[Z")) { primitiveArray = boolean[].class; } else if (className.equals("[C")) { primitiveArray = char[].class; } int startpos = className.startsWith("[L") ? 2 : 1; className = className.substring(startpos); } Class currentClass = null; if (null == primitiveArray) { try { currentClass = classLoader.loadClass(className); } catch (ClassNotFoundException e) { currentClass = Thread.currentThread().getContextClassLoader().loadClass(className); } } if (arrayType) { currentClass = (null != primitiveArray) ? primitiveArray : Array.newInstance(currentClass, 0).getClass(); while (name.startsWith("[[")) { currentClass = Array.newInstance(currentClass, 0).getClass(); name = name.substring(1); } } return currentClass; } /** * This is a performance optimization. The lowest 128 characters are re-used. * * @param c char to match to a Character. * @return a Character that matches the passed in char. If the value is * less than 127, then the same Character instances are re-used. */ static Character valueOf(char c) { return c <= 127 ? charCache[(int) c] : c; } /** * Strip leading and trailing double quotes from the passed in String. */ static String removeLeadingAndTrailingQuotes(String s) { Matcher m = extraQuotes.matcher(s); if (m.find()) { s = m.group(2); } return s; } /** * <p>C language malloc() for Java * </p><p> * Create a new instance of the passed in Class. This method will make a valiant effort to instantiate * the passed in Class, including calling all of its constructors until successful. The order they * are tried are public with the fewest arguments first to private with the most arguments. If, after * exhausting all constructors, then it will attempt using the 'unsafe allocate' from Sun. This step is * optional - by default it will use this if on a Sun (Oracle) JVM unless MetaUtil.setUseUnsafe(false) is called. * </p><p> * This method will handle common interfaces, such as Collection, Map, etc. which commonly show up in * parameterized types. Any other interface passed to this method will cause a JsonIoException to be thrown. * </p><p> * To improve performance, when called a 2nd time for the same Class, the constructor that was successfully * used to construct the instance will be retrieved from an internal cache. * </p> * @param c Class to instantiate * @return an instance of the instantiated class. This instance is intended to have its fields 'stuffed' by * direct assignment, not called via setter methods. * @throws JsonIoException if it cannot instantiate the passed in class. */ public static Object newInstance(Class c) { if (c.isAssignableFrom(ProcessBuilder.class) && c != Object.class) { throw new IllegalArgumentException("For security reasons, json-io does not allow instantiation of the ProcessBuilder class."); } if (unmodifiableSortedMap.getClass().isAssignableFrom(c)) { return new TreeMap(); } if (unmodifiableMap.getClass().isAssignableFrom(c)) { return new LinkedHashMap(); } if (unmodifiableSortedSet.getClass().isAssignableFrom(c)) { return new TreeSet(); } if (unmodifiableSet.getClass().isAssignableFrom(c)) { return new LinkedHashSet(); } if (unmodifiableCollection.getClass().isAssignableFrom(c)) { return new ArrayList(); } if (Collections.EMPTY_LIST.getClass().equals(c)) { return Collections.emptyList(); } if (c.isInterface()) { throw new JsonIoException("Cannot instantiate unknown interface: " + c.getName()); } // Constructor not cached, go find a constructor Object[] constructorInfo = constructors.get(c); if (constructorInfo != null) { // Constructor was cached Constructor constructor = (Constructor) constructorInfo[0]; if (constructor == null && useUnsafe) { // null constructor --> set to null when object instantiated with unsafe.allocateInstance() try { return unsafe.allocateInstance(c); } catch (Exception e) { // Should never happen, as the code that fetched the constructor was able to instantiate it once already throw new JsonIoException("Could not instantiate " + c.getName(), e); } } if (constructor == null) { throw new JsonIoException("No constructor found to instantiate " + c.getName()); } Boolean useNull = (Boolean) constructorInfo[1]; Class[] paramTypes = constructor.getParameterTypes(); if (paramTypes == null || paramTypes.length == 0) { try { return constructor.newInstance(); } catch (Exception e) { // Should never happen, as the code that fetched the constructor was able to instantiate it once already throw new JsonIoException("Could not instantiate " + c.getName(), e); } } Object[] values = fillArgs(paramTypes, useNull); try { return constructor.newInstance(values); } catch (Exception e) { // Should never happen, as the code that fetched the constructor was able to instantiate it once already throw new JsonIoException("Could not instantiate " + c.getName(), e); } } Object[] ret = newInstanceEx(c); constructors.put(c, new Object[]{ret[1], ret[2]}); return ret[0]; } /** * Returns an array with the following: * <ol> * <li>object instance</li> * <li>constructor</li> * <li>a Boolean, true if all constructor arguments are to be "null"</li> * </ol> */ static Object[] newInstanceEx(Class c) { try { Constructor constructor = c.getConstructor(emptyClassArray); if (constructor != null) { return new Object[] {constructor.newInstance(), constructor, true}; } // No empty arg constructor return tryOtherConstruction(c); } catch (Exception e) { // OK, this class does not have a public no-arg constructor. Instantiate with // first constructor found, filling in constructor values with null or // defaults for primitives. return tryOtherConstruction(c); } } /** * Brute force attempt to locate a constructor to construct the passed in Class. This involves trying all * constructors, public, protected, package-private, and private. It will try with null arguments as well * as it will make a 2nd attempt with populated values for some known types (Collection classes, Dates, Strings, * primitive wrappers, TimeZone, Calendar). * @param c Class to instantiate * @return an Object[] containing three (3) elements. Position 0 is the instance of the class, position 1 * is the constructor used, and position 2 indicates whether fillArgs was called with useNull or !useNull. */ static Object[] tryOtherConstruction(Class c) { Constructor[] constructors = c.getDeclaredConstructors(); if (constructors.length == 0) { throw new JsonIoException("Cannot instantiate '" + c.getName() + "' - Primitive, interface, array[] or void"); } // Sort constructors - public, protected, private, package-private List<Constructor> constructorList = Arrays.asList(constructors); Collections.sort(constructorList, new Comparator<Constructor>() { public int compare(Constructor c1, Constructor c2) { int c1Vis = c1.getModifiers(); int c2Vis = c2.getModifiers(); if (c1Vis == c2Vis) { // both are public, protected, private, etc. Compare by arguments. return compareConstructors(c1, c2); } if (isPublic(c1Vis) != isPublic(c2Vis)) { // favor 'public' as first return isPublic(c1Vis) ? -1 : 1; } if (isProtected(c1Vis) != isProtected(c2Vis)) { // favor protected 2nd return isProtected(c1Vis) ? -1 : 1; } if (isPrivate(c1Vis) != isPrivate(c2Vis)) { // favor private last return isPrivate(c1Vis) ? 1 : -1; } return 0; } }); // Try each constructor (public, protected, private, package-private) with null values for non-primitives. for (Constructor constructor : constructorList) { constructor.setAccessible(true); Class[] argTypes = constructor.getParameterTypes(); Object[] values = fillArgs(argTypes, true); try { return new Object[] {constructor.newInstance(values), constructor, true}; } catch (Exception ignored) { } } // Try each constructor (public, protected, private, package-private) with non-null values for non-primitives. for (Constructor constructor : constructorList) { constructor.setAccessible(true); Class[] argTypes = constructor.getParameterTypes(); Object[] values = fillArgs(argTypes, false); try { return new Object[] {constructor.newInstance(values), constructor, false}; } catch (Exception ignored) { } } // Try instantiation via unsafe // This may result in heapdumps for e.g. ConcurrentHashMap or can cause problems when the class is not initialized // Thats why we try ordinary constructors first if (useUnsafe) { try { return new Object[]{unsafe.allocateInstance(c), null, null}; } catch (Exception ignored) { } } throw new JsonIoException("Could not instantiate " + c.getName() + " using any constructor"); } /** * When two constructors have the same access type (both public, both private, etc.) * then compare constructors by parameter length (fewer params comes before more params). * If parameter count is the same, then compare by parameter Class names. If those are equal, * which should never happen, then the constructors are equal. */ private static int compareConstructors(Constructor c1, Constructor c2) { Class[] c1ParamTypes = c1.getParameterTypes(); Class[] c2ParamTypes = c2.getParameterTypes(); if (c1ParamTypes.length != c2ParamTypes.length) { // negative value if c1 has less (less parameters will be chosen ahead of more), positive value otherwise. return c1ParamTypes.length - c2ParamTypes.length; } // Has same number of parameters.s int len = c1ParamTypes.length; for (int i=0; i < len; i++) { Class class1 = c1ParamTypes[i]; Class class2 = c2ParamTypes[i]; int compare = class1.getName().compareTo(class2.getName()); if (compare != 0) { return compare; } } return 0; } /** * Return an Object[] of instance values that can be passed into a given Constructor. This method * will return an array of nulls if useNull is true, otherwise it will return sensible values for * primitive classes, and null for non-known primitive / primitive wrappers. This class is used * when attempting to call constructors on Java objects to get them instantiated, since there is no * 'malloc' in Java. */ static Object[] fillArgs(Class[] argTypes, boolean useNull) { final Object[] values = new Object[argTypes.length]; for (int i = 0; i < argTypes.length; i++) { final Class argType = argTypes[i]; if (isPrimitive(argType)) { values[i] = convert(argType, null); } else if (useNull) { values[i] = null; } else { if (argType == String.class) { values[i] = ""; } else if (argType == Date.class) { values[i] = new Date(); } else if (List.class.isAssignableFrom(argType)) { values[i] = new ArrayList(); } else if (SortedSet.class.isAssignableFrom(argType)) { values[i] = new TreeSet(); } else if (Set.class.isAssignableFrom(argType)) { values[i] = new LinkedHashSet(); } else if (SortedMap.class.isAssignableFrom(argType)) { values[i] = new TreeMap(); } else if (Map.class.isAssignableFrom(argType)) { values[i] = new LinkedHashMap(); } else if (Collection.class.isAssignableFrom(argType)) { values[i] = new ArrayList(); } else if (Calendar.class.isAssignableFrom(argType)) { values[i] = Calendar.getInstance(); } else if (TimeZone.class.isAssignableFrom(argType)) { values[i] = TimeZone.getDefault(); } else if (argType == BigInteger.class) { values[i] = BigInteger.TEN; } else if (argType == BigDecimal.class) { values[i] = BigDecimal.TEN; } else if (argType == StringBuilder.class) { values[i] = new StringBuilder(); } else if (argType == StringBuffer.class) { values[i] = new StringBuffer(); } else if (argType == Locale.class) { values[i] = Locale.FRANCE; // overwritten } else if (argType == Class.class) { values[i] = String.class; } else if (argType == Timestamp.class) { values[i] = new Timestamp(System.currentTimeMillis()); } else if (argType == java.sql.Date.class) { values[i] = new java.sql.Date(System.currentTimeMillis()); } else if (argType == URL.class) { try { values[i] = new URL("http://localhost"); // overwritten } catch (MalformedURLException e) { values[i] = null; } } else if (argType == Object.class) { values[i] = new Object(); } else { values[i] = null; } } } return values; } /** * @return a new primitive wrapper instance for the given class, using the * rhs parameter as a hint. For example, convert(long.class, "45") * will return 45L. However, if null is passed for the rhs, then the value 0L * would be returned in this case. For boolean, it would return false if null * was passed in. This method is similar to the GitHub project java-util's * Converter.convert() API. */ static Object convert(Class c, Object rhs) { try { if (c == boolean.class || c == Boolean.class) { if (rhs instanceof String) { rhs = removeLeadingAndTrailingQuotes((String) rhs); if ("".equals(rhs)) { rhs = "false"; } return Boolean.parseBoolean((String) rhs); } return rhs != null ? rhs : Boolean.FALSE; } else if (c == byte.class || c == Byte.class) { if (rhs instanceof String) { rhs = removeLeadingAndTrailingQuotes((String) rhs); if ("".equals(rhs)) { rhs = "0"; } return Byte.parseByte((String) rhs); } return rhs != null ? byteCache[((Number) rhs).byteValue() + 128] : (byte) 0; } else if (c == char.class || c == Character.class) { if (rhs == null) { return '\u0000'; } if (rhs instanceof String) { if (rhs.equals("\"")) { return '\"'; } rhs = removeLeadingAndTrailingQuotes((String) rhs); if ("".equals(rhs)) { rhs = "\u0000"; } return ((CharSequence) rhs).charAt(0); } if (rhs instanceof Character) { return rhs; } // Let it throw exception } else if (c == double.class || c == Double.class) { if (rhs instanceof String) { rhs = removeLeadingAndTrailingQuotes((String) rhs); if ("".equals(rhs)) { rhs = "0.0"; } return Double.parseDouble((String) rhs); } return rhs != null ? ((Number) rhs).doubleValue() : 0.0d; } else if (c == float.class || c == Float.class) { if (rhs instanceof String) { rhs = removeLeadingAndTrailingQuotes((String) rhs); if ("".equals(rhs)) { rhs = "0.0f"; } return Float.parseFloat((String) rhs); } return rhs != null ? ((Number) rhs).floatValue() : 0.0f; } else if (c == int.class || c == Integer.class) { if (rhs instanceof String) { rhs = removeLeadingAndTrailingQuotes((String) rhs); if ("".equals(rhs)) { rhs = "0"; } return Integer.parseInt((String) rhs); } return rhs != null ? ((Number) rhs).intValue() : 0; } else if (c == long.class || c == Long.class) { if (rhs instanceof String) { rhs = removeLeadingAndTrailingQuotes((String) rhs); if ("".equals(rhs)) { rhs = "0"; } return Long.parseLong((String) rhs); } return rhs != null ? ((Number) rhs).longValue() : 0L; } else if (c == short.class || c == Short.class) { if (rhs instanceof String) { rhs = removeLeadingAndTrailingQuotes((String) rhs); if ("".equals(rhs)) { rhs = "0"; } return Short.parseShort((String) rhs); } return rhs != null ? ((Number) rhs).shortValue() : (short) 0; } else if (c == Date.class) { if (rhs instanceof String) { return Readers.DateReader.parseDate((String) rhs); } else if (rhs instanceof Long) { return new Date((Long)(rhs)); } } else if (c == BigInteger.class) { return Readers.bigIntegerFrom(rhs); } else if (c == BigDecimal.class) { return Readers.bigDecimalFrom(rhs); } } catch (Exception e) { String className = c == null ? "null" : c.getName(); throw new JsonIoException("Error creating primitive wrapper instance for Class: " + className, e); } throw new JsonIoException("Class '" + c.getName() + "' does not have primitive wrapper."); } /** * Format a nice looking method signature for logging output */ public static String getLogMessage(String methodName, Object[] args) { return getLogMessage(methodName, args, 64); } public static String getLogMessage(String methodName, Object[] args, int argCharLen) { StringBuilder sb = new StringBuilder(); sb.append(methodName); sb.append('('); for (Object arg : args) { sb.append(getJsonStringToMaxLength(arg, argCharLen)); sb.append(" "); } String result = sb.toString().trim(); return result + ')'; } private static String getJsonStringToMaxLength(Object obj, int argCharLen) { Map<String, Object> args = new HashMap<String, Object>(); args.put(JsonWriter.TYPE, false); args.put(JsonWriter.SHORT_META_KEYS, true); String arg = JsonWriter.objectToJson(obj, args); if (arg.length() > argCharLen) { arg = arg.substring(0, argCharLen) + "..."; } return arg; } /** * Wrapper for unsafe, decouples direct usage of sun.misc.* package. * @author Kai Hufenback */ static final class Unsafe { private final Object sunUnsafe; private final Method allocateInstance; /** * Constructs unsafe object, acting as a wrapper. * @throws InvocationTargetException */ public Unsafe() throws InvocationTargetException { try { Constructor<Unsafe> unsafeConstructor = classForName("sun.misc.Unsafe", MetaUtils.class.getClassLoader()).getDeclaredConstructor(); unsafeConstructor.setAccessible(true); sunUnsafe = unsafeConstructor.newInstance(); allocateInstance = sunUnsafe.getClass().getMethod("allocateInstance", Class.class); allocateInstance.setAccessible(true); } catch(Exception e) { throw new InvocationTargetException(e); } } /** * Creates an object without invoking constructor or initializing variables. * <b>Be careful using this with JDK objects, like URL or ConcurrentHashMap this may bring your VM into troubles.</b> * @param clazz to instantiate * @return allocated Object */ public Object allocateInstance(Class clazz) { try { return allocateInstance.invoke(sunUnsafe, clazz); } catch (IllegalAccessException e ) { String name = clazz == null ? "null" : clazz.getName(); throw new JsonIoException("Unable to create instance of class: " + name, e); } catch (IllegalArgumentException e) { String name = clazz == null ? "null" : clazz.getName(); throw new JsonIoException("Unable to create instance of class: " + name, e); } catch (InvocationTargetException e) { String name = clazz == null ? "null" : clazz.getName(); throw new JsonIoException("Unable to create instance of class: " + name, e.getCause() != null ? e.getCause() : e); } } } }
39,442
35.759553
147
java
json-io
json-io-master/src/main/java/com/cedarsoftware/util/io/Resolver.java
package com.cedarsoftware.util.io; import com.cedarsoftware.util.io.JsonReader.MissingFieldHandler; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.*; import static com.cedarsoftware.util.io.JsonObject.ITEMS; import static com.cedarsoftware.util.io.JsonObject.KEYS; /** * This class is used to convert a source of Java Maps that were created from * the JsonParser. These are in 'raw' form with no 'pointers'. This code will * reconstruct the 'shape' of the graph by connecting @ref's to @ids. * * The subclasses that override this class can build an object graph using Java * classes or a Map-of-Map representation. In both cases, the @ref value will * be replaced with the Object (or Map) that had the corresponding @id. * * @author John DeRegnaucourt (jdereg@gmail.com) * <br> * Copyright (c) Cedar Software LLC * <br><br> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br><br> * http://www.apache.org/licenses/LICENSE-2.0 * <br><br> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.* */ abstract class Resolver { final Collection<UnresolvedReference> unresolvedRefs = new ArrayList<>(); protected final JsonReader reader; private static final NullClass nullReader = new NullClass(); final Map<Class, JsonReader.JsonClassReaderBase> readerCache = new HashMap<>(); private final Collection<Object[]> prettyMaps = new ArrayList<>(); private final boolean useMaps; private final Object unknownClass; private final boolean failOnUnknownType; private final static Map<String, Class> coercedTypes = new LinkedHashMap<>(); // store the missing field found during deserialization to notify any client after the complete resolution is done protected final Collection<Missingfields> missingFields = new ArrayList<>(); Class singletonMap = Collections.singletonMap("foo", "bar").getClass(); static { coercedTypes.put("java.util.Arrays$ArrayList", ArrayList.class); coercedTypes.put("java.util.LinkedHashMap$LinkedKeySet", LinkedHashSet.class); coercedTypes.put("java.util.LinkedHashMap$LinkedValues", ArrayList.class); coercedTypes.put("java.util.HashMap$KeySet", HashSet.class); coercedTypes.put("java.util.HashMap$Values", ArrayList.class); coercedTypes.put("java.util.TreeMap$KeySet", TreeSet.class); coercedTypes.put("java.util.TreeMap$Values", ArrayList.class); coercedTypes.put("java.util.concurrent.ConcurrentHashMap$KeySet", LinkedHashSet.class); coercedTypes.put("java.util.concurrent.ConcurrentHashMap$KeySetView", LinkedHashSet.class); coercedTypes.put("java.util.concurrent.ConcurrentHashMap$Values", ArrayList.class); coercedTypes.put("java.util.concurrent.ConcurrentHashMap$ValuesView", ArrayList.class); coercedTypes.put("java.util.concurrent.ConcurrentSkipListMap$KeySet", LinkedHashSet.class); coercedTypes.put("java.util.concurrent.ConcurrentSkipListMap$Values", ArrayList.class); coercedTypes.put("java.util.IdentityHashMap$KeySet", LinkedHashSet.class); coercedTypes.put("java.util.IdentityHashMap$Values", ArrayList.class); coercedTypes.put("java.util.Collections$EmptyList", Collections.EMPTY_LIST.getClass()); } /** * UnresolvedReference is created to hold a logical pointer to a reference that * could not yet be loaded, as the @ref appears ahead of the referenced object's * definition. This can point to a field reference or an array/Collection element reference. */ static final class UnresolvedReference { private final JsonObject referencingObj; private String field; private final long refId; private int index = -1; UnresolvedReference(JsonObject referrer, String fld, long id) { referencingObj = referrer; field = fld; refId = id; } UnresolvedReference(JsonObject referrer, int idx, long id) { referencingObj = referrer; index = idx; refId = id; } } /** * stores missing fields information to notify client after the complete deserialization resolution */ protected static class Missingfields { private Object target; private String fieldName; private Object value; public Missingfields(Object target, String fieldName, Object value) { this.target = target; this.fieldName = fieldName; this.value = value; } } /** * Dummy place-holder class exists only because ConcurrentHashMap cannot contain a * null value. Instead, singleton instance of this class is placed where null values * are needed. */ private static final class NullClass implements JsonReader.JsonClassReaderBase { } protected Resolver(JsonReader reader) { this.reader = reader; Map<String, Object> optionalArgs = reader.getArgs(); optionalArgs.put(JsonReader.OBJECT_RESOLVER, this); useMaps = Boolean.TRUE.equals(optionalArgs.get(JsonReader.USE_MAPS)); unknownClass = optionalArgs.containsKey(JsonReader.UNKNOWN_OBJECT) ? optionalArgs.get(JsonReader.UNKNOWN_OBJECT) : null; failOnUnknownType = Boolean.TRUE.equals(optionalArgs.get(JsonReader.FAIL_ON_UNKNOWN_TYPE)); } protected JsonReader getReader() { return reader; } /** * Walk a JsonObject (Map of String keys to values) and return the * Java object equivalent filled in as best as possible (everything * except unresolved reference fields or unresolved array/collection elements). * * @param root JsonObject reference to a Map-of-Maps representation of the JSON * input after it has been completely read. * @return Properly constructed, typed, Java object graph built from a Map * of Maps representation (JsonObject root). */ protected Object convertMapsToObjects(final JsonObject<String, Object> root) { final Deque<JsonObject<String, Object>> stack = new ArrayDeque<JsonObject<String, Object>>(); stack.addFirst(root); while (!stack.isEmpty()) { final JsonObject<String, Object> jsonObj = stack.removeFirst(); if (jsonObj.isArray()) { traverseArray(stack, jsonObj); } else if (jsonObj.isCollection()) { traverseCollection(stack, jsonObj); } else if (jsonObj.isMap()) { traverseMap(stack, jsonObj); } else { Object special; if ((special = readIfMatching(jsonObj, null, stack)) != null) { jsonObj.target = special; } else { traverseFields(stack, jsonObj); } } } return root.target; } protected abstract Object readIfMatching(final Object o, final Class compType, final Deque<JsonObject<String, Object>> stack); public abstract void traverseFields(Deque<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj); protected abstract void traverseCollection(Deque<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj); protected abstract void traverseArray(Deque<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj); protected void cleanup() { patchUnresolvedReferences(); rehashMaps(); reader.getObjectsRead().clear(); unresolvedRefs.clear(); prettyMaps.clear(); readerCache.clear(); handleMissingFields(); } // calls the missing field handler if any for each recorded missing field. private void handleMissingFields() { MissingFieldHandler missingFieldHandler = reader.getMissingFieldHandler(); if (missingFieldHandler != null) { for (Missingfields mf : missingFields) { missingFieldHandler.fieldMissing(mf.target, mf.fieldName, mf.value); } }//else no handler so ignore. } /** * Process java.util.Map and it's derivatives. These can be written specially * so that the serialization would not expose the derivative class internals * (internal fields of TreeMap for example). * * @param stack a Stack (Deque) used to support graph traversal. * @param jsonObj a Map-of-Map representation of the JSON input stream. */ protected void traverseMap(Deque<JsonObject<String, Object>> stack, JsonObject<String, Object> jsonObj) { // Convert @keys to a Collection of Java objects. convertMapToKeysItems(jsonObj); final Object[] keys = (Object[]) jsonObj.get(KEYS); final Object[] items = jsonObj.getArray(); if (keys == null || items == null) { if (keys != items) { throw new JsonIoException("Map written where one of " + KEYS + " or @items is empty"); } return; } final int size = keys.length; if (size != items.length) { throw new JsonIoException("Map written with " + KEYS + " and @items entries of different sizes"); } Object[] mapKeys = buildCollection(stack, keys, size); Object[] mapValues = buildCollection(stack, items, size); // Save these for later so that unresolved references inside keys or values // get patched first, and then build the Maps. prettyMaps.add(new Object[]{jsonObj, mapKeys, mapValues}); } private static Object[] buildCollection(Deque<JsonObject<String, Object>> stack, Object[] items, int size) { final JsonObject<String, Object> jsonCollection = new JsonObject<String, Object>(); jsonCollection.put(ITEMS, items); final Object[] javaKeys = new Object[size]; jsonCollection.target = javaKeys; stack.addFirst(jsonCollection); return javaKeys; } /** * Convert an input JsonObject map (known to represent a Map.class or derivative) that has regular keys and values * to have its keys placed into @keys, and its values placed into @items. * * @param map Map to convert */ protected static void convertMapToKeysItems(final JsonObject<String, Object> map) { if (!map.containsKey(KEYS) && !map.isReference()) { final Object[] keys = new Object[map.size()]; final Object[] values = new Object[map.size()]; int i = 0; for (Object e : map.entrySet()) { final Map.Entry entry = (Map.Entry) e; keys[i] = entry.getKey(); values[i] = entry.getValue(); i++; } String saveType = map.getType(); map.clear(); map.setType(saveType); map.put(KEYS, keys); map.put(ITEMS, values); } } /** * This method creates a Java Object instance based on the passed in parameters. * If the JsonObject contains a key '@type' then that is used, as the type was explicitly * set in the JSON stream. If the key '@type' does not exist, then the passed in Class * is used to create the instance, handling creating an Array or regular Object * instance. * <br> * The '@type' is not often specified in the JSON input stream, as in many * cases it can be inferred from a field reference or array component type. * * @param clazz Instance will be create of this class. * @param jsonObj Map-of-Map representation of object to create. * @return a new Java object of the appropriate type (clazz) using the jsonObj to provide * enough hints to get the right class instantiated. It is not populated when returned. */ protected Object createJavaObjectInstance(Class clazz, JsonObject jsonObj) { final boolean useMapsLocal = useMaps; String type = jsonObj.type; // We can't set values to an Object, so well try to use the contained type instead if ("java.lang.Object".equals(type)) { Object value = jsonObj.get("value"); if (jsonObj.keySet().size() == 1 && value != null) { type = value.getClass().getName(); } } Object mate; // @type always takes precedence over inferred Java (clazz) type. if (type != null) { // @type is explicitly set, use that as it always takes precedence Class c; try { c = MetaUtils.classForName(type, reader.getClassLoader(), failOnUnknownType); } catch (Exception e) { if (useMapsLocal) { jsonObj.type = null; jsonObj.target = null; return jsonObj; } else { String name = clazz == null ? "null" : clazz.getName(); throw new JsonIoException("Unable to create class: " + name, e); } } if (c.isArray()) { // Handle [] Object[] items = jsonObj.getArray(); int size = (items == null) ? 0 : items.length; if (c == char[].class) { jsonObj.moveCharsToMate(); mate = jsonObj.target; } else { mate = Array.newInstance(c.getComponentType(), size); } } else { // Handle regular field.object reference if (MetaUtils.isPrimitive(c)) { mate = MetaUtils.convert(c, jsonObj.get("value")); } else if (c == Class.class) { mate = MetaUtils.classForName((String) jsonObj.get("value"), reader.getClassLoader()); } else if (c.isEnum()) { mate = getEnum(c, jsonObj); } else if (Enum.class.isAssignableFrom(c)) // anonymous subclass of an enum { mate = getEnum(c.getSuperclass(), jsonObj); } else if (EnumSet.class.isAssignableFrom(c)) { mate = getEnumSet(c, jsonObj); } else if ((mate = coerceCertainTypes(c.getName())) != null) { // if coerceCertainTypes() returns non-null, it did the work } else if (singletonMap.isAssignableFrom(c)) { Object key = jsonObj.keySet().iterator().next(); Object value = jsonObj.values().iterator().next(); mate = Collections.singletonMap(key, value); } else { mate = newInstance(c, jsonObj); } } } else { // @type, not specified, figure out appropriate type Object[] items = jsonObj.getArray(); // if @items is specified, it must be an [] type. // if clazz.isArray(), then it must be an [] type. if (clazz.isArray() || (items != null && clazz == Object.class && !jsonObj.containsKey(KEYS))) { int size = (items == null) ? 0 : items.length; mate = Array.newInstance(clazz.isArray() ? clazz.getComponentType() : Object.class, size); } else if (clazz.isEnum()) { mate = getEnum(clazz, jsonObj); } else if (Enum.class.isAssignableFrom(clazz)) // anonymous subclass of an enum { mate = getEnum(clazz.getSuperclass(), jsonObj); } else if (EnumSet.class.isAssignableFrom(clazz)) // anonymous subclass of an enum { mate = getEnumSet(clazz, jsonObj); } else if ((mate = coerceCertainTypes(clazz.getName())) != null) { // if coerceCertainTypes() returns non-null, it did the work } else if (clazz == Object.class && !useMapsLocal) { if (unknownClass == null) { mate = new JsonObject(); ((JsonObject)mate).type = Map.class.getName(); } else if (unknownClass instanceof String) { mate = newInstance(MetaUtils.classForName(((String)unknownClass).trim(), reader.getClassLoader()), jsonObj); } else { throw new JsonIoException("Unable to determine object type at column: " + jsonObj.col + ", line: " + jsonObj.line + ", content: " + jsonObj); } } else { mate = newInstance(clazz, jsonObj); } } jsonObj.target = mate; return jsonObj.target; } protected Object coerceCertainTypes(String type) { Class clazz = coercedTypes.get(type); if (clazz == null) { return null; } return MetaUtils.newInstance(clazz); } protected JsonObject getReferencedObj(Long ref) { JsonObject refObject = reader.getObjectsRead().get(ref); if (refObject == null) { throw new JsonIoException("Forward reference @ref: " + ref + ", but no object defined (@id) with that value"); } return refObject; } protected JsonReader.JsonClassReaderBase getCustomReader(Class c) { JsonReader.JsonClassReaderBase reader = readerCache.get(c); if (reader == null) { reader = forceGetCustomReader(c); readerCache.put(c, reader); } return reader == nullReader ? null : reader; } private JsonReader.JsonClassReaderBase forceGetCustomReader(Class c) { JsonReader.JsonClassReaderBase closestReader = nullReader; int minDistance = Integer.MAX_VALUE; for (Map.Entry<Class, JsonReader.JsonClassReaderBase> entry : getReaders().entrySet()) { Class clz = entry.getKey(); if (clz == c) { return entry.getValue(); } int distance = MetaUtils.getDistance(clz, c); if (distance < minDistance) { minDistance = distance; closestReader = entry.getValue(); } } return closestReader; } /** * Fetch enum value (may need to try twice, due to potential 'name' field shadowing by enum subclasses */ private Object getEnum(Class c, JsonObject jsonObj) { try { return Enum.valueOf(c, (String) jsonObj.get("name")); } catch (Exception e) { // In case the enum class has it's own 'name' member variable (shadowing the 'name' variable on Enum) return Enum.valueOf(c, (String) jsonObj.get("java.lang.Enum.name")); } } private static enum OneEnum { L1, L2, L3 } /* /* java 17 don't allow to call reflect on internal java api like EnumSet's implement, so need to create like this */ private Object getEmptyEnumSet() { return EnumSet.noneOf(OneEnum.class); } /** * Create the EnumSet with its values (it must be created this way) */ private Object getEnumSet(Class c, JsonObject<String, Object> jsonObj) { Object[] items = jsonObj.getArray(); if (items == null || items.length == 0) { return getEmptyEnumSet(); //return newInstance(c, jsonObj); } JsonObject item = (JsonObject) items[0]; String type = item.getType(); Class enumClass = MetaUtils.classForName(type, reader.getClassLoader()); EnumSet enumSet = null; for (Object objectItem : items) { item = (JsonObject) objectItem; Enum enumItem = (Enum) getEnum(enumClass, item); if (enumSet == null) { // Lazy init the EnumSet enumSet = EnumSet.of(enumItem); } else { enumSet.add(enumItem); } } return enumSet; } /** * For all fields where the value was "@ref":"n" where 'n' was the id of an object * that had not yet been encountered in the stream, make the final substitution. */ protected void patchUnresolvedReferences() { Iterator i = unresolvedRefs.iterator(); while (i.hasNext()) { UnresolvedReference ref = (UnresolvedReference) i.next(); Object objToFix = ref.referencingObj.target; JsonObject objReferenced = reader.getObjectsRead().get(ref.refId); if (ref.index >= 0) { // Fix []'s and Collections containing a forward reference. if (objToFix instanceof List) { // Patch up Indexable Collections List list = (List) objToFix; list.set(ref.index, objReferenced.target); } else if (objToFix instanceof Collection) { // Add element (since it was not indexable, add it to collection) Collection col = (Collection) objToFix; col.add(objReferenced.target); } else { Array.set(objToFix, ref.index, objReferenced.target); // patch array element here } } else { // Fix field forward reference Field field = MetaUtils.getField(objToFix.getClass(), ref.field); if (field != null) { try { field.set(objToFix, objReferenced.target); // patch field here } catch (Exception e) { throw new JsonIoException("Error setting field while resolving references '" + field.getName() + "', @ref = " + ref.refId, e); } } } } unresolvedRefs.clear(); } /** * Process Maps/Sets (fix up their internal indexing structure) * This is required because Maps hash items using hashCode(), which will * change between VMs. Rehashing the map fixes this. * <br> * If useMaps==true, then move @keys to keys and @items to values * and then drop these two entries from the map. * <br> * This hashes both Sets and Maps because the JDK sets are implemented * as Maps. If you have a custom built Set, this would not 'treat' it * and you would need to provider a custom reader for that set. */ protected void rehashMaps() { final boolean useMapsLocal = useMaps; for (Object[] mapPieces : prettyMaps) { JsonObject jObj = (JsonObject) mapPieces[0]; Object[] javaKeys, javaValues; Map map; if (useMapsLocal) { // Make the @keys be the actual keys of the map. map = jObj; javaKeys = (Object[]) jObj.remove(KEYS); javaValues = (Object[]) jObj.remove(ITEMS); } else { map = (Map) jObj.target; javaKeys = (Object[]) mapPieces[1]; javaValues = (Object[]) mapPieces[2]; jObj.clear(); } if (singletonMap.isAssignableFrom(map.getClass())) { // Handle SingletonMaps - Do nothing here. They are single entry maps. The code before here // has already instantiated the SingletonMap, and has filled in its values. } else { int j = 0; while (javaKeys != null && j < javaKeys.length) { map.put(javaKeys[j], javaValues[j]); j++; } } } } // ========== Keep relationship knowledge below the line ========== public static Object newInstance(Class c, JsonObject jsonObject) { return JsonReader.newInstance(c, jsonObject); } protected Map<Class, JsonReader.JsonClassReaderBase> getReaders() { return reader.readers; } protected boolean notCustom(Class cls) { return reader.notCustom.contains(cls); } }
25,669
36.861357
161
java
nominatim-java-api
nominatim-java-api-master/src/test/java/fr/dudie/nominatim/client/JsonNominatimClientTest.java
package fr.dudie.nominatim.client; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import com.vividsolutions.jts.geom.Geometry; import fr.dudie.nominatim.client.request.NominatimLookupRequest; import fr.dudie.nominatim.client.request.NominatimSearchRequest; import fr.dudie.nominatim.client.request.paramhelper.PolygonFormat; import fr.dudie.nominatim.model.Address; import fr.dudie.nominatim.model.BoundingBox; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import static org.junit.Assert.*; /** * Test class for {@link JsonNominatimClient}. * * @author Jérémie Huchet * @author Sunil D S */ public final class JsonNominatimClientTest { /** The event logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(JsonNominatimClientTest.class); /** The tested Nominatim client. */ private static JsonNominatimClient nominatimClient; /** A bounded Nominatim client for defaults options tests. */ private static JsonNominatimClient boundedNominatimClient; /** Path to the properties file. */ private static final String PROPS_PATH = "/nominatim-client-test.properties"; /** Loaded properties. */ private static final Properties PROPS = new Properties(); /** * Instantiates the test. * * @throws IOException * an error occurred during initialization */ public JsonNominatimClientTest() throws IOException { LOGGER.info("Loading configuration file {}", PROPS_PATH); final InputStream in = JsonNominatimClientTest.class.getResourceAsStream(PROPS_PATH); PROPS.load(in); LOGGER.info("Preparing http client"); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final ClientConnectionManager connexionManager = new SingleClientConnManager(null, registry); final HttpClient httpClient = new DefaultHttpClient(connexionManager, null); final String baseUrl = PROPS.getProperty("nominatim.server.url"); final String email = PROPS.getProperty("nominatim.headerEmail"); nominatimClient = new JsonNominatimClient(baseUrl, httpClient, email); final BoundingBox viewBox = new BoundingBox(); viewBox.setNorth(48.2731); viewBox.setSouth(48.2163); viewBox.setEast(-4.5758); viewBox.setWest(-4.4127); final NominatimOptions options = new NominatimOptions(); options.setViewBox(viewBox); options.setBounded(true); boundedNominatimClient = new JsonNominatimClient(baseUrl, httpClient, email, options); } @Test public void testGetAddress() throws IOException { LOGGER.info("testGetAddress.start"); final Address address = nominatimClient.getAddress(1.64891269513038, 48.1166561643464); LOGGER.debug(ToStringBuilder.reflectionToString(address, ToStringStyle.MULTI_LINE_STYLE)); assertNotNull("a result should be found", address); assertTrue("address expose the OSM place_id", address.getPlaceId() > 0); assertNull("no polygonpoint", address.getPolygonPoints()); assertNull("no geojson", address.getGeojson()); LOGGER.info("testGetAddress.end"); } @Test public void testSearchWithResults() throws IOException { LOGGER.info("testSearchWithResults.start"); final List<Address> addresses = nominatimClient.search("vitré, rennes"); assertNotNull("result list is never null", addresses); for (final Address address : addresses) { LOGGER.debug(ToStringBuilder .reflectionToString(address, ToStringStyle.MULTI_LINE_STYLE)); } assertTrue("list is not empty", !addresses.isEmpty()); LOGGER.info("testSearchWithResults.end"); } @Test public void testSearchWithGeoJsonResults() throws IOException { LOGGER.info("testSearchWithGeoJsonResults.start"); NominatimSearchRequest request = new NominatimSearchRequest(); request.setPolygonFormat(PolygonFormat.GEO_JSON); request.setQuery("vitré, rennes"); final List<Address> addresses = nominatimClient.search(request); assertNotNull("result list is never null", addresses); assertTrue("list is not empty", !addresses.isEmpty()); for (final Address address : addresses) { final Geometry geom = address.getGeojson(); assertNotNull("geometry/geojson of address is available in result", geom); assertTrue("geometry/geojson of address has at least one vertex", geom.getNumPoints() > 0); } LOGGER.info("testSearchWithGeoJsonResults.end"); } @Test public void testSearchWithoutResults() throws IOException { LOGGER.info("testSearchWithoutResults.start"); final List<Address> addresses = nominatimClient .search("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbb"); assertNotNull("result list is never null", addresses); assertTrue("list is empty", addresses.isEmpty()); LOGGER.info("testSearchWithoutResults.end"); } @Test public void testSearchWithForLongPlaceId() throws IOException { LOGGER.info("testSearchWithResults.start"); final List<Address> addresses = nominatimClient.search("ул. Евдокимова,37, Ростов-на-дону"); assertNotNull("result list is not null", addresses); for (final Address address : addresses) { LOGGER.debug(ToStringBuilder .reflectionToString(address, ToStringStyle.MULTI_LINE_STYLE)); } assertTrue("list is not empty", !addresses.isEmpty()); LOGGER.info("testSearchWithResults.end"); } @Test @Ignore public void testReverseLookUpZoomLevelCanBeControlled() throws Exception { LOGGER.info("testReverseLookUpZoomLevelCanBeControlled.start"); final Address highLevelAddress = nominatimClient.getAddress(-0.32, 51.44, 1); assertEquals("European Union", highLevelAddress.getDisplayName()); final Address lowerLevelAddress = nominatimClient.getAddress(-0.32, 51.44, 10); assertTrue(lowerLevelAddress.getPlaceId() != highLevelAddress.getPlaceId()); LOGGER.info("testReverseLookUpZoomLevelCanBeControlled.end"); } @Test @Ignore public void testReverseLookUpTypeOsmId() throws Exception { LOGGER.info("testReverseLookUpTypeOsmId"); final Address address = nominatimClient.getAddress("W", 26932726); assertEquals( "Eel Pie Island, Thames Path, Ham, London Borough of Richmond upon Thames, London, Greater London, England, TW1 3DT, United Kingdom, European Union", address.getDisplayName()); assertEquals("way", address.getOsmType()); assertEquals("26932726", address.getOsmId()); LOGGER.info("testReverseLookUpTypeOsmId"); } @Test public void testAddressWithDetails() throws IOException { LOGGER.info("testAddressWithDetails"); final NominatimSearchRequest r = new NominatimSearchRequest(); r.setQuery("rennes, france"); r.setAddress(true); final List<Address> addresses = nominatimClient.search(r); assertNotNull("result list is not null", addresses); assertTrue("there is more than one result", addresses.size() > 0); for (final Address address : addresses) { assertNotNull("address details are available in result", address.getAddressElements()); assertTrue("at least one address detail is available", address.getAddressElements().length > 0); } LOGGER.info("testAddressWithDetails"); } @Test public void testAddressWithNameDetails() throws IOException { LOGGER.info("testAddressWithDetails"); final NominatimSearchRequest r = new NominatimSearchRequest(); r.setQuery("pkin"); r.setName(true); final List<Address> addresses = nominatimClient.search(r); assertNotNull("result list is not null", addresses); assertTrue("there is more than one result", addresses.size() > 0); for (final Address address : addresses) { assertNotNull("address details are available in result", address.getNameDetails()); assertTrue("at least one address detail is available", address.getNameDetails().length > 0); } LOGGER.info("testAddressWithDetails"); } @Test public void testAddressWithoutDetails() throws IOException { LOGGER.info("testAddressWithoutDetails"); final NominatimSearchRequest r = new NominatimSearchRequest(); r.setQuery("rennes, france"); r.setAddress(false); final List<Address> addresses = nominatimClient.search(r); assertNotNull("result list is not null", addresses); assertTrue("there is more than one result", addresses.size() > 0); for (final Address address : addresses) { assertNull("address details are not available in result", address.getAddressElements()); } LOGGER.info("testAddressWithoutDetails"); } @Test public void testAddressLookupWithDetails() throws IOException { LOGGER.info("testAddressLookupWithDetails"); final NominatimLookupRequest r = new NominatimLookupRequest(); List<String> typeIds = new ArrayList<String>(); typeIds.add("R146656"); typeIds.add("W104393803"); typeIds.add("N240109189"); r.setQuery(typeIds); r.setAddressDetails(true); final List<Address> addresses = nominatimClient.lookupAddress(r); assertNotNull("result list is not null", addresses); assertTrue("there is more than one result", addresses.size() > 0); for (final Address address : addresses) { assertNotNull("address details are available in result", address.getAddressElements()); assertTrue("at least one address detail is available", address.getAddressElements().length > 0); } LOGGER.info("testAddressLookupWithDetails"); } @Test public void testAddressLookupWithoutDetails() throws IOException { LOGGER.info("testAddressLookupWithDetails"); final NominatimLookupRequest r = new NominatimLookupRequest(); List<String> typeIds = new ArrayList<String>(); typeIds.add("R146656"); typeIds.add("W104393803"); typeIds.add("N240109189"); r.setQuery(typeIds); r.setAddressDetails(false); final List<Address> addresses = nominatimClient.lookupAddress(r); assertNotNull("result list is not null", addresses); assertTrue("there is more than one result", addresses.size() > 0); for (final Address address : addresses) { assertNull("address details are not available in result", address.getAddressElements()); } LOGGER.info("testAddressLookupWithoutDetails"); } @Test public void testBuildingLevelPlaceRank() throws IOException { final NominatimSearchRequest r = new NominatimSearchRequest(); r.setQuery("2 rue de chateaudun, rennes, france"); final List<Address> addresses = nominatimClient.search(r); assertEquals("there is one result", 1, addresses.size()); final Address result = addresses.get(0); assertEquals("building level place rank", 30, result.getPlaceRank()); } @Test public void testStreetLevelPlaceRank() throws IOException { final NominatimSearchRequest r = new NominatimSearchRequest(); r.setQuery("rue de chateaudun, rennes, france"); final List<Address> addresses = nominatimClient.search(r); assertEquals("there is one result", 1, addresses.size()); final Address result = addresses.get(0); assertEquals("streen level place rank", 26, result.getPlaceRank()); } @Test public void testDefaultOptionsForSearch() throws IOException { final List<Address> addresses = boundedNominatimClient.search("rue de chateaudun, rennes, france"); assertEquals("empty result list", 0, addresses.size()); } @Test public void testDefaultOptionsForQuery() throws IOException { final NominatimSearchRequest r = new NominatimSearchRequest(); r.setQuery("rue de chateaudun, rennes, france"); final List<Address> addresses = boundedNominatimClient.search(r); assertEquals("empty result list", 0, addresses.size()); } }
14,024
36.300532
165
java
nominatim-java-api
nominatim-java-api-master/src/test/java/fr/dudie/nominatim/client/request/NominatimSearchRequestTest.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.model.BoundingBox; import org.junit.Before; import org.junit.Test; import java.io.UnsupportedEncodingException; import static org.junit.Assert.assertEquals; public class NominatimSearchRequestTest { private NominatimSearchRequest req; @Before public void reset() { req = new NominatimSearchRequest(); } @Test public void simpleQuery() throws UnsupportedEncodingException { req.setQuery("vitré, france"); assertEquals("q=vitré,%20france", req.getQueryString()); } @Test public void simpleQueryWithAcceptLanguage() throws UnsupportedEncodingException { req.setQuery("france"); req.setAcceptLanguage("fr_FR"); assertEquals("q=france&accept-language=fr_FR", req.getQueryString()); } @Test public void simpleQueryWithAddress() throws UnsupportedEncodingException { req.setQuery("france"); req.setAddress(true); assertEquals("q=france&addressdetails=1", req.getQueryString()); } @Test public void simpleQueryWithName() throws UnsupportedEncodingException { req.setQuery("france"); req.setName(true); assertEquals("q=france&namedetails=1", req.getQueryString()); } @Test public void simpleQueryWithoutAddress() throws UnsupportedEncodingException { req.setQuery("france"); req.setAddress(false); assertEquals("q=france&addressdetails=0", req.getQueryString()); } @Test public void simpleQueryWithCountryCodes() throws UnsupportedEncodingException { req.setQuery("france"); req.addCountryCode("FR"); assertEquals("q=france&countrycodes=FR", req.getQueryString()); req.addCountryCode("BE"); assertEquals("q=france&countrycodes=FR,BE", req.getQueryString()); } @Test public void simpleQueryWithViewBox() throws UnsupportedEncodingException { final double w = -1.14465546607971; final double n = 48.1462173461914; final double e = -1.24950230121613; final double s = 48.0747871398926; final String expectedQueryString = "q=france&viewbox=-1.14465546607971,48.14621734619140,-1.24950230121613,48.07478713989260"; final String expectedQueryStringE6 = "q=france&viewbox=-1.14465500000000,48.14621700000000,-1.24950200000000,48.07478700000000"; req.setQuery("france"); final BoundingBox bbox = new BoundingBox(); bbox.setWest(w); bbox.setNorth(n); bbox.setEast(e); bbox.setSouth(s); req.setViewBox(bbox); assertEquals(expectedQueryString, req.getQueryString()); req.setViewBox(w, n, e, s); assertEquals(expectedQueryString, req.getQueryString()); req.setViewBox((int) (w * 1E6), (int) (n * 1E6), (int) (e * 1E6), (int) (s * 1E6)); assertEquals(expectedQueryStringE6, req.getQueryString()); } }
3,770
32.669643
136
java
nominatim-java-api
nominatim-java-api-master/src/test/java/fr/dudie/nominatim/client/request/NominatimLookupRequestTest.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import static org.junit.Assert.*; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import fr.dudie.nominatim.model.BoundingBox; public class NominatimLookupRequestTest { private NominatimLookupRequest req; @Before public void reset() { req = new NominatimLookupRequest(); } @Test public void simpleQuery() throws UnsupportedEncodingException { List<String> typeIds = new ArrayList<String>(); typeIds.add("R146656"); typeIds.add("W104393803"); req.setQuery(typeIds); assertEquals("osm_ids=R146656,W104393803", req.getQueryString()); } @Test public void simpleQueryWithAcceptLanguage() throws UnsupportedEncodingException { List<String> typeIds = new ArrayList<String>(); typeIds.add("R146656"); typeIds.add("W104393803"); req.setQuery(typeIds); req.setAcceptLanguage("fr_FR"); assertEquals("accept-language=fr_FR&osm_ids=R146656,W104393803", req.getQueryString()); } @Test public void simpleQueryWithAddress() throws UnsupportedEncodingException { List<String> typeIds = new ArrayList<String>(); typeIds.add("R146656"); typeIds.add("W104393803"); req.setQuery(typeIds); req.setAddressDetails(true); assertEquals("osm_ids=R146656,W104393803&addressdetails=1", req.getQueryString()); } @Test public void simpleQueryWithoutAddress() throws UnsupportedEncodingException { List<String> typeIds = new ArrayList<String>(); typeIds.add("R146656"); typeIds.add("W104393803"); req.setQuery(typeIds); req.setAddressDetails(false); assertEquals("osm_ids=R146656,W104393803&addressdetails=0", req.getQueryString()); } }
2,649
28.775281
95
java
nominatim-java-api
nominatim-java-api-master/src/test/java/fr/dudie/nominatim/client/request/NominatimReverseRequestTest.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import static org.junit.Assert.*; import java.io.UnsupportedEncodingException; import org.junit.Before; import org.junit.Test; import fr.dudie.nominatim.client.request.paramhelper.OsmType; public class NominatimReverseRequestTest { private NominatimReverseRequest req; @Before public void reset() { req = new NominatimReverseRequest(); } @Test public void simpleCoordQuery() throws UnsupportedEncodingException { req.setQuery(-1.14465546607971, 48.1462173461914); assertEquals("lat=48.14621734619140&lon=-1.14465546607971", req.getQueryString()); } @Test public void simpleOsmTypeAndIdQuery() throws UnsupportedEncodingException { req.setQuery(OsmType.NODE, 12345); assertEquals("osm_type=N&osm_id=12345", req.getQueryString()); } @Test public void simpleCoordQueryWithAcceptLanguage() throws UnsupportedEncodingException { req.setQuery(-1.14465546607971, 48.1462173461914); req.setAcceptLanguage("fr_FR"); assertEquals("accept-language=fr_FR&lat=48.14621734619140&lon=-1.14465546607971", req.getQueryString()); } @Test public void simpleCoordQueryWithAddressDetails() throws UnsupportedEncodingException { req.setQuery(-1.14465546607971, 48.1462173461914); req.setAddressDetails(true); assertEquals("lat=48.14621734619140&lon=-1.14465546607971&addressdetails=1", req.getQueryString()); } @Test public void simpleCoordQueryWithoutAddressDetails() throws UnsupportedEncodingException { req.setQuery(-1.14465546607971, 48.1462173461914); req.setAddressDetails(false); assertEquals("lat=48.14621734619140&lon=-1.14465546607971&addressdetails=0", req.getQueryString()); } @Test public void simpleCoordQueryWithZoom() throws UnsupportedEncodingException { req.setQuery(-1.14465546607971, 48.1462173461914); req.setZoom(15); assertEquals("lat=48.14621734619140&lon=-1.14465546607971&zoom=15", req.getQueryString()); } }
2,894
33.879518
112
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/NominatimResponseHandler.java
package fr.dudie.nominatim.client; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ResponseHandler; import com.google.gson.Gson; /** * Parses a json response from the Nominatim API for a reverse geocoding request. * * @author Jérémie Huchet */ public final class NominatimResponseHandler<T> implements ResponseHandler<T> { /** Gson instance for Nominatim API calls. */ private final Gson gsonInstance; /** The expected type of objects. */ private final Type responseType; /** * Constructor. * * @param gsonInstance * the Gson instance * @param responseType * the expected type of objects */ public NominatimResponseHandler(final Gson gsonInstance, final Type responseType) { this.gsonInstance = gsonInstance; this.responseType = responseType; } /** * {@inheritDoc} * * @see org.apache.http.client.ResponseHandler#handleResponse(org.apache.http.HttpResponse) */ @Override public T handleResponse(final HttpResponse response) throws IOException { InputStream content = null; final T addresses; try { final StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) { throw new IOException(String.format("HTTP error: %s %s", status.getStatusCode(), status.getReasonPhrase())); } content = response.getEntity().getContent(); addresses = gsonInstance .fromJson(new InputStreamReader(content, "utf-8"), responseType); } finally { if (null != content) { content.close(); } response.getEntity().consumeContent(); } return addresses; } }
2,835
29.494624
124
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/JsonNominatimClient.java
package fr.dudie.nominatim.client; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.filosganga.geogson.gson.GeometryAdapterFactory; import com.github.filosganga.geogson.jts.JtsAdapterFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import fr.dudie.nominatim.client.request.NominatimLookupRequest; import fr.dudie.nominatim.client.request.NominatimReverseRequest; import fr.dudie.nominatim.client.request.NominatimSearchRequest; import fr.dudie.nominatim.client.request.paramhelper.OsmType; import fr.dudie.nominatim.gson.ArrayOfAddressElementsDeserializer; import fr.dudie.nominatim.gson.ArrayOfPolygonPointsDeserializer; import fr.dudie.nominatim.gson.BoundingBoxDeserializer; import fr.dudie.nominatim.gson.PolygonPointDeserializer; import fr.dudie.nominatim.model.Address; import fr.dudie.nominatim.model.Element; import fr.dudie.nominatim.model.BoundingBox; import fr.dudie.nominatim.model.PolygonPoint; /** * An implementation of the Nominatim Api Service. * * @author Jérémie Huchet * @author Sunil D S */ public final class JsonNominatimClient implements NominatimClient { /** The event logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(JsonNominatimClient.class); /** The default nominatim base URL. */ private static final String DEFAULT_BASE_URL = "https://nominatim.openstreetmap.org/"; /** UTF-8 encoding.*/ public static final String ENCODING_UTF_8 = "UTF-8"; /** Gson instance for Nominatim API calls. */ private final Gson gsonInstance; /** The url to make search queries. */ private final String searchUrl; /** The url for reverse geocoding. */ private final String reverseUrl; /** The url for address lookup. */ private final String lookupUrl; /** The default search options. */ private final NominatimOptions defaults; /** The HTTP client. */ private HttpClient httpClient; /** The default response handler for search requests. */ private NominatimResponseHandler<List<Address>> defaultSearchResponseHandler; /** The default response handler for reverse geocoding requests. */ private NominatimResponseHandler<Address> defaultReverseGeocodingHandler; /** The default response handler for lookup requests. */ private NominatimResponseHandler<List<Address>> defaultLookupHandler; /** * Creates the json nominatim client with the default base URL ({@value #DEFAULT_BASE_URL}. * * @param httpClient * an HTTP client * @param email * an email to add in the HTTP requests parameters to "sign" them */ public JsonNominatimClient(final HttpClient httpClient, final String email) { this(DEFAULT_BASE_URL, httpClient, email, new NominatimOptions()); } /** * Creates the json nominatim client with the default base URL ({@value #DEFAULT_BASE_URL}. * * @param httpClient * an HTTP client * @param email * an email to add in the HTTP requests parameters to "sign" them * @param defaults * defaults options, they override null valued requests options */ public JsonNominatimClient(final HttpClient httpClient, final String email, final NominatimOptions defaults) { this(DEFAULT_BASE_URL, httpClient, email, defaults); } /** * Creates the json nominatim client. * * @param baseUrl * the nominatim server url * @param httpClient * an HTTP client * @param email * an email to add in the HTTP requests parameters to "sign" them (see * https://wiki.openstreetmap.org/wiki/Nominatim_usage_policy) */ public JsonNominatimClient(final String baseUrl, final HttpClient httpClient, final String email) { this(baseUrl, httpClient, email, new NominatimOptions()); } /** * Creates the json nominatim client. * * @param baseUrl * the nominatim server url * @param httpClient * an HTTP client * @param email * an email to add in the HTTP requests parameters to "sign" them (see * https://wiki.openstreetmap.org/wiki/Nominatim_usage_policy) * @param defaults * defaults options, they override null valued requests options */ public JsonNominatimClient(final String baseUrl, final HttpClient httpClient, final String email, final NominatimOptions defaults) { String emailEncoded; try { emailEncoded = URLEncoder.encode(email, ENCODING_UTF_8); } catch (UnsupportedEncodingException e) { emailEncoded = email; } this.searchUrl = String.format("%s/search?format=jsonv2&email=%s", baseUrl.replaceAll("/$", ""), emailEncoded); this.reverseUrl = String.format("%s/reverse?format=jsonv2&email=%s", baseUrl.replaceAll("/$", ""), emailEncoded); this.lookupUrl = String.format("%s/lookup?format=json&email=%s", baseUrl.replaceAll("/$", ""), emailEncoded); if (LOGGER.isDebugEnabled()) { LOGGER.debug("API search URL: {}", searchUrl); LOGGER.debug("API reverse URL: {}", reverseUrl); } this.defaults = defaults; // prepare gson instance final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Element[].class, new ArrayOfAddressElementsDeserializer()); gsonBuilder.registerTypeAdapter(PolygonPoint.class, new PolygonPointDeserializer()); gsonBuilder.registerTypeAdapter(PolygonPoint[].class, new ArrayOfPolygonPointsDeserializer()); gsonBuilder.registerTypeAdapter(BoundingBox.class, new BoundingBoxDeserializer()); gsonBuilder.registerTypeAdapterFactory(new JtsAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new GeometryAdapterFactory()); gsonInstance = gsonBuilder.create(); // prepare httpclient this.httpClient = httpClient; defaultSearchResponseHandler = new NominatimResponseHandler<List<Address>>(gsonInstance, new TypeToken<List<Address>>() { }.getType()); defaultReverseGeocodingHandler = new NominatimResponseHandler<Address>(gsonInstance, Address.class); defaultLookupHandler = new NominatimResponseHandler<List<Address>>(gsonInstance, new TypeToken<List<Address>>() { }.getType()); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#search(fr.dudie.nominatim.client.request.NominatimSearchRequest) */ @Override public List<Address> search(final NominatimSearchRequest search) throws IOException { defaults.mergeTo(search); final String apiCall = String.format("%s&%s", searchUrl, search.getQueryString()); LOGGER.debug("search url: {}", apiCall); final HttpGet req = new HttpGet(apiCall); return httpClient.execute(req, defaultSearchResponseHandler); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#getAddress(fr.dudie.nominatim.client.request.NominatimReverseRequest) */ @Override public Address getAddress(final NominatimReverseRequest reverse) throws IOException { final String apiCall = String.format("%s&%s", reverseUrl, reverse.getQueryString()); LOGGER.debug("reverse geocoding url: {}", apiCall); final HttpGet req = new HttpGet(apiCall); return httpClient.execute(req, defaultReverseGeocodingHandler); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#lookupAddress(fr.dudie.nominatim.client.request.NominatimLookupRequest) */ @Override public List<Address> lookupAddress(final NominatimLookupRequest lookup) throws IOException { final String apiCall = String.format("%s&%s", lookupUrl, lookup.getQueryString()); LOGGER.debug("lookup url: {}", apiCall); final HttpGet req = new HttpGet(apiCall); return httpClient.execute(req, defaultLookupHandler); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#search(java.lang.String) */ @Override public List<Address> search(final String query) throws IOException { final NominatimSearchRequest q = new NominatimSearchRequest(); q.setQuery(query); return this.search(q); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#getAddress(double, double) */ @Override public Address getAddress(final double longitude, final double latitude) throws IOException { final NominatimReverseRequest q = new NominatimReverseRequest(); q.setQuery(longitude, latitude); return this.getAddress(q); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#getAddress(double, double, int) */ @Override public Address getAddress(final double longitude, final double latitude, final int zoom) throws IOException { final NominatimReverseRequest q = new NominatimReverseRequest(); q.setQuery(longitude, latitude); q.setZoom(zoom); return this.getAddress(q); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#getAddress(int, int) */ @Override public Address getAddress(final int longitudeE6, final int latitudeE6) throws IOException { return this.getAddress((double) (longitudeE6 / 1E6), (double) (latitudeE6 / 1E6)); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#getAddress(String, long) */ @Override public Address getAddress(final String type, final long id) throws IOException { final NominatimReverseRequest q = new NominatimReverseRequest(); q.setQuery(OsmType.from(type), id); return this.getAddress(q); } /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.NominatimClient#lookupAddress(java.util.List) */ @Override public List<Address> lookupAddress(final List<String> typeId) throws IOException { final NominatimLookupRequest q = new NominatimLookupRequest(); q.setQuery(typeId); return this.lookupAddress(q); } }
11,525
35.359621
136
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/NominatimOptions.java
package fr.dudie.nominatim.client; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.util.Locale; import fr.dudie.nominatim.client.request.NominatimSearchRequest; import fr.dudie.nominatim.client.request.paramhelper.PolygonFormat; import fr.dudie.nominatim.model.BoundingBox; /** * Nominatim client options. * * @author Jeremie Huchet */ public class NominatimOptions { /** The preferred search bounds. */ private BoundingBox viewBox; /** True to use strict bounds. */ private Boolean bounded; /** Default polygon points format. */ private PolygonFormat polygonFormat; /** Preferred localization for results. */ private Locale acceptLanguage; /** * Gets the preferred search bounds. * * @return the preferred search bounds */ public BoundingBox getViewBox() { return viewBox; } /** * Sets the preferred search bounds. * * @param searchBounds * the preferred search bounds to set */ public void setViewBox(final BoundingBox searchBounds) { this.viewBox = searchBounds; } /** * Gets whether or not the search is strictly bounded. * * @return whether or not the search is strictly bounded */ public boolean isBounded() { return bounded; } /** * Sets whether or not the search is strictly bounded. * * @param bounded * whether or not the search is strictly bounded */ public void setBounded(boolean bounded) { this.bounded = bounded; } /** * Gets the default polygon points format. * * @return the default polygon points format */ public PolygonFormat getPolygonFormat() { return polygonFormat; } /** * Sets the default polygon points format. * * @param format * the default polygon points format to set */ public void setPolygonFormat(final PolygonFormat format) { this.polygonFormat = format; } /** * Gets the preferred locale for results. * * @return the preferred locale for results */ public Locale getAcceptLanguage() { return acceptLanguage; } /** * Sets the preferred locale for results. * * @param acceptLanguage * the preferred locale for results */ public void setAcceptLanguage(final Locale acceptLanguage) { this.acceptLanguage = acceptLanguage; } /** * Merge this default options to the given request. * * @param request * the request where the result is merged */ void mergeTo(final NominatimSearchRequest request) { if (null == request.getBounded() && null != bounded) { request.setBounded(bounded); } if (null == request.getViewBox()) { request.setViewBox(viewBox); } if (null == request.getPolygonFormat()) { request.setPolygonFormat(polygonFormat); } if (null == request.getAcceptLanguage() && null != acceptLanguage) { request.setAcceptLanguage(acceptLanguage.toString()); } } }
3,963
25.965986
76
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/NominatimClient.java
package fr.dudie.nominatim.client; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.io.IOException; import java.util.List; import fr.dudie.nominatim.client.request.NominatimLookupRequest; import fr.dudie.nominatim.client.request.NominatimReverseRequest; import fr.dudie.nominatim.client.request.NominatimSearchRequest; import fr.dudie.nominatim.model.Address; /** * Interface to use the Nominatim Service. * * @author Jérémie Huchet * @author Sunil D S * @since 1.0 */ public interface NominatimClient { /** * Search for results with the given query. * <p> * See also {@link #search(NominatimSearchRequest)} to obtain more result details. * * @param query * the query * @return a list of results * @throws IOException * a communication error occurred * @since 1.0 */ List<Address> search(String query) throws IOException; /** * Reverse geocode the given coordinates. * * @param longitude * a longitude * @param latitude * a latitude * @return an address corresponding to the given longitude and latitude or <code>null</code> if no result found * @throws IOException * a communication error occurred * @since 1.0 */ Address getAddress(double longitude, double latitude) throws IOException; /** * Reverse geocode the given coordinates using a specific zoom level * * @param longitude * a longitude * @param latitude * a latitude * @param zoom * a osm zoom level * @return an address corresponding to the given longitude and latitude or <code>null</code> if no result found * @throws IOException * a communication error occurred * @since 2.0.1 */ Address getAddress(double longitude, double latitude, int zoom) throws IOException; /** * A convenience method to do the same as {@link #getAddress(double, double)} but with int E6 latitude and * longitude. * * @param longitudeE6 * a longitude E6 * @param latitudeE6 * a latitude E6 * @return an address corresponding to the given longitude and latitude or <code>null</code> if no result found * @throws IOException * a communication error occurred * @since 1.0 */ Address getAddress(int longitudeE6, int latitudeE6) throws IOException; /** * Reverse geocode the given OSM id. * * @param type * An OSM type [N|W|R] * @param id * An OSM id * @return an address corresponding to the given osm type and id pair or <code>null</code> if no result found * @throws IOException * a communication error occurred * @since 2.0.1 * @deprecated * @see fr.dudie.nominatim.client.NominatimClient#getAddress(fr.dudie.nominatim.client.request.NominatimReverseRequest) */ @Deprecated Address getAddress(String type, long id) throws IOException; /** * This method can be used to lookup addresses with an OSM type and ID * * @param typeId * [N|W|R]ID * @return a list of addresses corresponding to the given OSM type and ID or <code>null</code> if no result found * @throws IOException * a communication error occurred * @since 3.2 */ List<Address> lookupAddress(List<String> typeId) throws IOException; /** * Search for addresses. * * @param search * the search request parameters * @return a list of results * @throws IOException * a communication error occurred * @since 3.0 */ List<Address> search(NominatimSearchRequest search) throws IOException; /** * Reverse geocoding request. * * @param reverse * a reverse geocoding request * @return an address corresponding to the given longitude and latitude or <code>null</code> if no result found * @throws IOException * a communication error occurred * @since 3.0 */ Address getAddress(NominatimReverseRequest reverse) throws IOException; /** * Address lookup request. * * @param lookup * a lookup request * @return a list of addresses corresponding to the given OSM type and ID or <code>null</code> if no result found * @throws IOException * a communication error occurred * @since 3.2 */ List<Address> lookupAddress(NominatimLookupRequest lookup) throws IOException; }
5,463
31.718563
123
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/ReverseQuery.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ /** * Holds parameters for a reverse geocoding query. * * @author Jeremie Huchet */ abstract class ReverseQuery extends NominatimRequest { }
991
29.060606
71
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/SearchQuery.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ /** * Holds keywords for a search request. * <p> * There is two ways to enter the search query: * <ul> * <li>using the <i>query<i> <b>q</b> parameter, see {@link SimpleSearchQuery} ;</li> * <li>using one or more parameters from the following list : <i>street</i>, * <i>city</i>,<i>county</i>,<i>state</i>,<i>country</i>,<i>postal_code</i>, note that this option is currently labeled * as <b>experimental</b>, see {@link ExtendedSearchQuery}.</li> * </ul> * * @author Jeremie Huchet * @since 3.0 */ abstract class SearchQuery extends NominatimRequest { }
1,413
32.666667
119
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/LookupQuery.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ /** * Holds parameters for a lookup query. * * @author Sunil D S */ abstract class LookupQuery extends NominatimRequest { }
975
27.705882
71
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/CoordinatesReverseQuery.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.client.request.paramhelper.DoubleSerializer; import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; /** * Holds coordinates of the reverse geocoding request. * <p> * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a> * page on October 26th, 2013. * * @author Jeremie Huchet */ public class CoordinatesReverseQuery extends ReverseQuery { /** The latitude. */ @QueryParameter(value = "lat=%s", serializer = DoubleSerializer.class) private Double latitude; /** The longitude. */ @QueryParameter(value = "lon=%s", serializer = DoubleSerializer.class) private Double longitude; /** * @param longitude * the longitude * @param latitude * the latitude */ public CoordinatesReverseQuery(double longitude, double latitude) { this.longitude = longitude; this.latitude = latitude; } /** * @param longitudeE6 * the longitude * @param latitudeE6 * the latitude */ public CoordinatesReverseQuery(int longitudeE6, int latitudeE6) { this(longitudeE6 / 1E6, latitudeE6 / 1E6); } /** * @return the latitude */ public Double getLatitude() { return latitude; } /** * @param latitude * the latitude to set */ public void setLatitude(Double latitude) { this.latitude = latitude; } /** * @return the longitude */ public Double getLongitude() { return longitude; } /** * @param longitude * the longitude to set */ public void setLongitude(Double longitude) { this.longitude = longitude; } }
2,654
26.371134
121
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/OsmTypeAndIdLookupQuery.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.util.List; import fr.dudie.nominatim.client.request.paramhelper.ListSerializer; import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; /** * Holds OSM TYPE and ID of the lookup request. * <p> * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a> * page on September 1st, 2015. * * @author Sunil D S */ public class OsmTypeAndIdLookupQuery extends LookupQuery { /** * List of type and id of the elements to lookup. */ @QueryParameter(value = "osm_ids=%s", serializer = ListSerializer.class) private List<String> typeId; /** * @param typeId * list of type and id of the elements to lookup */ public OsmTypeAndIdLookupQuery(final List<String> typeId) { this.typeId = typeId; } /** * @return the typeId */ public List<String> getTypeId() { return typeId; } /** * @param typeId * list of type and id of the elements to lookup set */ public void setTypeId(List<String> typeId) { this.typeId = typeId; } }
1,994
27.913043
121
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/NominatimLookupRequest.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.util.List; import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer; import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; /** * Holds request parameters for a lookup request. * <p> * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a> * page on September 1st, 2015. * * @author Sunil D S */ public class NominatimLookupRequest extends NominatimRequest { /** * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616 * accept-language string or a simple comma separated list of language codes. */ @QueryParameter("accept-language=%s") private String acceptLanguage; /** Holds the OSM lookup request. */ @QueryParameter private LookupQuery query; /** Include a breakdown of the address into elements. */ @QueryParameter(value = "addressdetails=%s", serializer = BooleanSerializer.class) private Boolean addressDetails; /** * Gets the preferred language order for showing search results which overrides the browser value. * * @return the accept-language value */ public String getAcceptLanguage() { return acceptLanguage; } /** * Sets the preferred language order for showing search results, overrides the browser value. * * @param acceptLanguage * a standard rfc2616 accept-language string or a simple comma separated list of language codes */ public void setAcceptLanguage(final String acceptLanguage) { this.acceptLanguage = acceptLanguage; } /** * @return the lookup query parameters */ public LookupQuery getQuery() { return query; } /** * @param query * the lookup query parameters to set */ public void setQuery(final LookupQuery query) { this.query = query; } public void setQuery(final List<String> typeId) { this.query = new OsmTypeAndIdLookupQuery(typeId); } /** * Include a breakdown of the address into elements. * * @return the addressDetails */ public Boolean getAddressDetails() { return addressDetails; } /** * Include a breakdown of the address into elements. * * @param addressDetails * the addressDetails to set */ public void setAddressDetails(final boolean addressDetails) { this.addressDetails = addressDetails; } }
3,408
29.168142
121
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/OsmTypeAndIdReverseQuery.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.client.request.paramhelper.OsmType; import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; /** * Holds OSM TYPE and ID of the reverse geocoding request. * <p> * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a> * page on October 26th, 2013. * * @author Jeremie Huchet */ public class OsmTypeAndIdReverseQuery extends ReverseQuery { /** * The type of the searched element. */ @QueryParameter("osm_type=%s") private OsmType type; /** * The id of the searched element. */ @QueryParameter("osm_id=%s") private long id; /** * @param type * the type of the searched element * @param id * the id of the searched element */ public OsmTypeAndIdReverseQuery(final OsmType type, final long id) { this.type = type; this.id = id; } /** * @return the osm type */ public OsmType getType() { return type; } /** * @param type * the osm type to set */ public void setType(OsmType type) { this.type = type; } /** * @return the osm id */ public long getId() { return id; } /** * @param id * the osm id to set */ public void setId(long id) { this.id = id; } }
2,279
24.054945
121
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/ExtendedSearchQuery.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; /** * Holds parameters for an extended search query. * <p> * <b>This is labeled as experimental on Nominatim Wiki page</b> * <p> * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a> * page on October 26th, 2013. * @author Jeremie Huchet */ public class ExtendedSearchQuery extends SearchQuery { /** A street name. */ @QueryParameter("street=%s") private String street; /** A city name. */ @QueryParameter("city=%s") private String city; /** A county name. */ @QueryParameter("county=%s") private String county; /** A state name. */ @QueryParameter("state=%s") private String state; /** A country name. */ @QueryParameter("country=%s") private String country; /** A postal code. */ @QueryParameter("postalcode=%s") private String postalCode; /** * @return the street */ public String getStreet() { return street; } /** * @param street * the street to set */ public void setStreet(String street) { this.street = street; } /** * @return the city */ public String getCity() { return city; } /** * @param city * the city to set */ public void setCity(String city) { this.city = city; } /** * @return the county */ public String getCounty() { return county; } /** * @param county * the county to set */ public void setCounty(String county) { this.county = county; } /** * @return the state */ public String getState() { return state; } /** * @param state * the state to set */ public void setState(String state) { this.state = state; } /** * @return the country */ public String getCountry() { return country; } /** * @param country * the country to set */ public void setCountry(String country) { this.country = country; } /** * @return the postalCode */ public String getPostalCode() { return postalCode; } /** * @param postalCode * the postalCode to set */ public void setPostalCode(String postalCode) { this.postalCode = postalCode; } }
3,372
21.045752
121
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/QueryParameterAnnotationHandler.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.net.URI; import java.net.URISyntaxException; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; import fr.dudie.nominatim.client.request.paramhelper.ToStringSerializer; /** * Parse a bean definition wit {@link QueryParameter} annotations and generates a query string. * * <pre> * public class Query { * &#064;QueryParameter(&quot;paramName=%s&quot;) * private String param = &quot;value with space&quot;; * * &#064;QueryParameter(&quot;secondParamName=%d&quot;) * private Integer param2 = 10; * } * </pre> * * will generate the following query string : * * <pre> * paramName=value+with+space&param2=10 * </pre> * * @author Jeremie Huchet */ class QueryParameterAnnotationHandler { /** The event logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(QueryParameterAnnotationHandler.class); /** * Process an object to generate a query string. * <ul> * <li>only {@link QueryParameter} annotated fields are used</li> * <li>null or empty values are ignored</li> * </ul> * * @param o * the object to scan for {@link QueryParameter} annotations * @return the generated query string * @throws UnsupportedEncodingException */ static String process(final Object o) { final StringBuilder s = new StringBuilder(); for (final Field f : o.getClass().getDeclaredFields()) { final QueryParameter paramMetadata = f.getAnnotation(QueryParameter.class); final Object fieldValue = getValue(o, f); // each field having the QueryParameter annotation is processed if (null != fieldValue && null != paramMetadata) { final String paramFormat = paramMetadata.value(); String paramValue = serialize(paramMetadata, fieldValue, f.getName()); if (null != paramValue && !"".equals(paramValue.trim())) { if (s.length() > 0) { s.append('&'); } if (paramMetadata.encode()) { paramValue = uriEncode(paramValue); } s.append(String.format(Locale.US, paramFormat, paramValue)); } } } return s.toString(); } private static String uriEncode(String paramValue) { try { return new URI(null, null, null, paramValue, null).getRawQuery(); } catch (final URISyntaxException e) { LOGGER.error("Failure encoding query parameter value {}", new Object[] { paramValue, e }); return paramValue; } } /** * Serializes the field value regardless of reflection errors. Fallback to the {@link ToStringSerializer}. * * @param paramMetadata * the query parameter annotation * @param fieldValue * the field value * @param fieldName * the field name (for logging purposes only) * @return the serialized value * @throws UnsupportedEncodingException * UTF-8 encoding issue */ private static String serialize(final QueryParameter paramMetadata, final Object fieldValue, final String fieldName) { String paramValue; try { paramValue = paramMetadata.serializer().newInstance().handle(fieldValue); } catch (final InstantiationException e) { LOGGER.error("Failure while serializing field {}", new Object[] { fieldName, e }); paramValue = new ToStringSerializer().handle(fieldValue); } catch (final IllegalAccessException e) { LOGGER.error("Failure while serializing field {}", new Object[] { fieldName, e }); paramValue = new ToStringSerializer().handle(fieldValue); } return paramValue; } /** * Gets a field value regardless of reflection errors. * * @param o * the object instance * @param f * the field * @return the field value or null if a reflection error occurred */ private static Object getValue(final Object o, final Field f) { try { f.setAccessible(true); return f.get(o); } catch (final IllegalArgumentException e) { LOGGER.error("failure accessing field value {}", new Object[] { f.getName(), e }); } catch (final IllegalAccessException e) { LOGGER.error("failure accessing field value {}", new Object[] { f.getName(), e }); } return null; } }
5,644
33.845679
122
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/NominatimSearchRequest.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.util.ArrayList; import java.util.List; import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer; import fr.dudie.nominatim.client.request.paramhelper.BoundingBoxSerializer; import fr.dudie.nominatim.client.request.paramhelper.ListSerializer; import fr.dudie.nominatim.client.request.paramhelper.PolygonFormat; import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; import fr.dudie.nominatim.model.BoundingBox; /** * Holds request parameters for a search request. * <p> * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a> * page on October 26th, 2013. * * @author Jeremie Huchet */ public class NominatimSearchRequest extends NominatimRequest { /** Holds the query parameters. */ @QueryParameter(encode = false) private SearchQuery query; /** * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616 * accept-language string or a simple comma separated list of language codes. */ @QueryParameter("accept-language=%s") private String acceptLanguage; /** * Limit search results to a specific country (or a list of countries). &lt;countrycode&gt; should be the ISO * 3166-1alpha2 code, e.g. gb for the United Kingdom, de for Germany, etc. */ @QueryParameter(value = "countrycodes=%s", serializer = ListSerializer.class) private List<String> countryCodes; /** The preferred area to find search results. */ @QueryParameter(value = "viewbox=%s", serializer = BoundingBoxSerializer.class) private BoundingBox viewBox; /** * Restrict the results to only items contained with the bounding box. <br> * Restricting the results to the bounding box also enables searching by amenity only.<br> * For example a search query of just "[pub]" would normally be rejected but with bounded=1 will result in a list of * items matching within the bounding box. */ @QueryParameter(value = "bounded=%s", serializer = BooleanSerializer.class) private Boolean bounded; /** Include a breakdown of the address into elements. */ @QueryParameter(value = "addressdetails=%s", serializer = BooleanSerializer.class) private Boolean address; /** * Include a list of alternative names in the results. * These may include language variants, references, operator and brand. */ @QueryParameter(value = "namedetails=%s", serializer = BooleanSerializer.class) private Boolean name; /** * If you do not want certain openstreetmap objects to appear in the search result, give a comma separated list of * the place_id's you want to skip. */ @QueryParameter(value = "exclude_place_ids=%s", serializer = ListSerializer.class) private List<String> excludePlaceIds; /** Limit the number of returned results. */ @QueryParameter("limit=%s") private Integer limit; /** Choose output geometry format. */ @QueryParameter(encode = false) private PolygonFormat polygonFormat; /** * Gets the query parameters. * * @return the query parameters */ public SearchQuery getQuery() { return query; } /** * Sets query parameters. * * @param query * the query parameters object holder */ public void setQuery(final SearchQuery query) { this.query = query; } /** * Sets a simple query. * * @param simpleQuery * the query string, such as <i>Rennes, France</i> */ public void setQuery(final String simpleQuery) { this.query = new SimpleSearchQuery(simpleQuery); } /** * Gets the preferred language order for showing search results which overrides the browser value. * * @return the accept-language value */ public String getAcceptLanguage() { return acceptLanguage; } /** * Sets the preferred language order for showing search results, overrides the browser value. * * @param acceptLanguage * a standard rfc2616 accept-language string or a simple comma separated list of language codes */ public void setAcceptLanguage(final String acceptLanguage) { this.acceptLanguage = acceptLanguage; } /** * Gets the country codes. * * @return the country codes */ public List<String> getCountryCodes() { return countryCodes; } /** * Limit search results to a specific country (or a list of countries). &lt;countrycode&gt; should be the ISO * 3166-1alpha2 code, e.g. gb for the United Kingdom, de for Germany, etc. * * @param countryCodes * the country codes to set */ public void setCountryCodes(final List<String> countryCodes) { this.countryCodes = countryCodes; } /** * Limit search results to a specific country (or a list of countries). &lt;countrycode&gt; should be the ISO * 3166-1alpha2 code, e.g. gb for the United Kingdom, de for Germany, etc. * * @param countryCode * the country code to add */ public void addCountryCode(final String countryCode) { if (null == countryCodes) { countryCodes = new ArrayList<String>(); } countryCodes.add(countryCode); } /** * Gets the preferred area to find search results. * * @return the viewBox the preferred area to find search results */ public BoundingBox getViewBox() { return viewBox; } /** * Sets the preferred area to find search results; * * @param viewBox * the vthe preferred area to find search results to set */ public void setViewBox(final BoundingBox viewBox) { this.viewBox = viewBox; } /** * Sets the preferred area to find search results; * * @param west * the west bound * @param north * the north bound * @param east * the east bound * @param south * the south bound */ public void setViewBox(final double west, final double north, final double east, final double south) { this.viewBox = new BoundingBox(); this.viewBox.setWest(west); this.viewBox.setNorth(north); this.viewBox.setEast(east); this.viewBox.setSouth(south); } /** * Sets the preferred area to find search results; * * @param westE6 * the west bound * @param northE6 * the north bound * @param eastE6 * the east bound * @param southE6 * the south bound */ public void setViewBox(final int westE6, final int northE6, final int eastE6, final int southE6) { this.viewBox = new BoundingBox(); this.viewBox.setWestE6(westE6); this.viewBox.setNorthE6(northE6); this.viewBox.setEastE6(eastE6); this.viewBox.setSouthE6(southE6); } /** * Gets whether or not the results will be bounded to the given {@link #viewBox}. * * @return the bounded */ public Boolean getBounded() { return bounded; } /** * Setting <code>true</code> will restrict the results to only items contained with the bounding box. <br> * Restricting the results to the bounding box also enables searching by amenity only.<br> * For example a search query of just "[pub]" would normally be rejected but with bounded=1 will result in a list of * items matching within the bounding box. * * @param bounded * the bounded to set */ public void setBounded(final boolean bounded) { this.bounded = bounded; } /** * When true, include a breakdown of the address into elements. * * @return the address */ public boolean getAddress() { return address; } /** * Include a breakdown of the address into elements. * * @param address * the address to set */ public void setAddress(final boolean address) { this.address = address; } /** * When true, include a list of alternative names in the results. * * @return whether or not the alternative names should be included in the results */ public Boolean getName() { return name; } /** * When true, include a list of alternative names in the results. * * @param name true to include a list of alternative names in the results */ public void setName(Boolean name) { this.name = name; } /** * A list of OSM elements ids to be excluded from search results. * * @return the excluded place ids */ public List<String> getExcludePlaceIds() { return excludePlaceIds; } /** * If you do not want certain openstreetmap objects to appear in the search result, give a list of the place_id's * you want to skip. * * @param excludePlaceIds * the excluded place ids to set */ public void setExcludePlaceIds(final List<String> excludePlaceIds) { this.excludePlaceIds = excludePlaceIds; } /** * If you do not want certain openstreetmap objects to appear in the search result, give a list of the place_id's * you want to skip. * * @param placeId * the place id to exclude */ public void addExcludedlaceId(final String placeId) { if (null == this.countryCodes) { this.excludePlaceIds = new ArrayList<String>(); } this.excludePlaceIds.add(placeId); } /** * Gets the maximum number of results to be returned. * * @return the limit */ public Integer getLimit() { return limit; } /** * Limit the number of returned results. * * @param limit * the limit to set */ public void setLimit(Integer limit) { this.limit = limit; } /** * Gets the output geometry format. * * @return the polygon format */ public PolygonFormat getPolygonFormat() { return polygonFormat; } /** * Choose output geometry format. * * @param polygonFormat * the polygon format to set */ public void setPolygonFormat(PolygonFormat polygonFormat) { this.polygonFormat = polygonFormat; } }
11,457
29.636364
121
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/NominatimRequest.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; /** * Classes extending this should be able to build URL query string parts to append to nominatim server URL to make * requests. * * Uses {@link QueryParameter} annotations to describe the query parameters. * * @author Jeremie Huchet */ public abstract class NominatimRequest { /** * Generates the query string to be sent to nominatim to execute a request. * <p> * The query string <b>must</b> have URL encoded parameters. * <p> * example: <code>q=some%20city&amp;polygon_geojson=1</code> * * @return a query string */ public final String getQueryString() { return QueryParameterAnnotationHandler.process(this); } }
1,602
31.06
114
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/NominatimReverseRequest.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.client.request.paramhelper.BooleanSerializer; import fr.dudie.nominatim.client.request.paramhelper.OsmType; import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; /** * Holds request parameters for a reverse geocoding request. * <p> * Attributes documentation was extracted from <a href="https://wiki.openstreetmap.org/wiki/Nominatim">Nominatim Wiki</a> * page on October 26th, 2013. * * @author Jeremie Huchet */ public class NominatimReverseRequest extends NominatimRequest { /** * Preferred language order for showing search results, overrides the browser value. Either uses standard rfc2616 * accept-language string or a simple comma separated list of language codes. */ @QueryParameter("accept-language=%s") private String acceptLanguage; /** Holds the OSM reverse geocoding request. */ @QueryParameter private ReverseQuery query; /** Level of detail required where 0 is country and 18 is house/building. */ @QueryParameter("zoom=%s") private Integer zoom; /** Include a breakdown of the address into elements. */ @QueryParameter(value = "addressdetails=%s", serializer = BooleanSerializer.class) private Boolean addressDetails; /** * Gets the preferred language order for showing search results which overrides the browser value. * * @return the accept-language value */ public String getAcceptLanguage() { return acceptLanguage; } /** * Sets the preferred language order for showing search results, overrides the browser value. * * @param acceptLanguage * a standard rfc2616 accept-language string or a simple comma separated list of language codes */ public void setAcceptLanguage(final String acceptLanguage) { this.acceptLanguage = acceptLanguage; } /** * @return the reverse geocoding query parameters */ public ReverseQuery getQuery() { return query; } /** * @param query * the reverse geocoding query parameters to set */ public void setQuery(final ReverseQuery query) { this.query = query; } public void setQuery(final OsmType type, final long id) { this.query = new OsmTypeAndIdReverseQuery(type, id); } public void setQuery(final double longitude, final double latitude) { this.query = new CoordinatesReverseQuery(longitude, latitude); } /** * Gets the level of detail requested. * * 0 is country and 18 is house/building. * * @return the level of detail requested */ public Integer getZoom() { return zoom; } /** * Sets the level of detail required. * * @param zoom * the level of detail, where 0 is country and 18 is house/building */ public void setZoom(final int zoom) { this.zoom = zoom; } /** * Include a breakdown of the address into elements. * * @return the addressDetails */ public Boolean getAddressDetails() { return addressDetails; } /** * Include a breakdown of the address into elements. * * @param addressDetails * the addressDetails to set */ public void setAddressDetails(final boolean addressDetails) { this.addressDetails = addressDetails; } }
4,263
29.457143
121
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/SimpleSearchQuery.java
package fr.dudie.nominatim.client.request; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.client.request.paramhelper.QueryParameter; /** * Holds parameters for a simple search query. * * @author Jeremie Huchet */ public class SimpleSearchQuery extends SearchQuery { /** Query string to search for. */ @QueryParameter("q=%s") private String query; /** * @param simpleQuery * the query string to search for */ public SimpleSearchQuery(final String simpleQuery) { this.query = simpleQuery; } /** * @return the query string to search for */ public String getQuery() { return query; } /** * @param query * the querystring to set */ public void setQuery(final String query) { this.query = query; } }
1,619
25.129032
71
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/QueryParameter.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Formatter; /** * Declare a field as an URL query parameter. * * @author Jeremie Huchet * @since 3.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface QueryParameter { /** * A format string (see {@link Formatter}) in whish the output of the serialization of the field value will be * merged. * <p> * Default is "<code>%s</code>" * * @return the format string where to merge the field value */ String value() default "%s"; /** * Defines whether or not the output of the field value serialization should be URL encoded. * <p> * Default is true. * * @return whether or not the output of the field value serialization should be URL encoded */ boolean encode() default true; /** * Defines the serializer to use to convert the field value into a string value. * <p> * Default is {@link ToStringSerializer}. * * @return the serializer class to use */ Class<? extends QueryParameterSerializer> serializer() default ToStringSerializer.class; }
2,134
29.942029
114
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/QueryParameterSerializer.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ /** * Serializes a value to a String representation. * * @author Jeremie Huchet */ public interface QueryParameterSerializer { /** * Converts the input value into a string. * * @param value * the value to serialize * @return a string representation of the input value */ String handle(Object value); }
1,214
28.634146
71
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/DoubleSerializer.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.util.Locale; public class DoubleSerializer implements QueryParameterSerializer { /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object) */ @Override public String handle(final Object value) { if (value instanceof Double) { return String.format(Locale.US, "%.14f", (Double) value); } else { throw new IllegalArgumentException("Can't serialize anything but Double"); } } }
1,396
31.488372
107
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/BooleanSerializer.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ /** * Serializes a boolean parameter to nominatim expected format. * * @author Jeremie Huchet */ public class BooleanSerializer implements QueryParameterSerializer { /** * Converts the input value into a nominatim boolean parameter. * * @return either <code>1</code> or <code>0</code> * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object) */ @Override public String handle(final Object value) { if (Boolean.parseBoolean(value.toString())) { return "1"; } else { return "0"; } } }
1,482
29.895833
107
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/BoundingBoxSerializer.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.model.BoundingBox; /** * Serializes a bounding box parameter. * * @author Jeremie Huchet */ public class BoundingBoxSerializer implements QueryParameterSerializer { /** Serializer to transform double values to string. */ private final DoubleSerializer doubleSerializer = new DoubleSerializer(); /** * Converts the input value to a <code>left,top,right,bottom</code> string representation. * * @return a ltrb value * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object) */ @Override public String handle(Object value) { final StringBuilder s = new StringBuilder(); if (value instanceof BoundingBox) { final BoundingBox bbox = (BoundingBox) value; s.append(doubleSerializer.handle(bbox.getWest())).append(','); s.append(doubleSerializer.handle(bbox.getNorth())).append(','); s.append(doubleSerializer.handle(bbox.getEast())).append(','); s.append(doubleSerializer.handle(bbox.getSouth())); } else { s.append(value); } return s.toString(); } }
2,041
34.206897
107
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/ListSerializer.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.util.List; /** * Serializes list values. * * @author Jeremie Huchet */ public class ListSerializer implements QueryParameterSerializer { /** * Converts the list to a comma separated representation. * * @return a comma separated list of values * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object) */ @Override public String handle(final Object value) { final StringBuilder s = new StringBuilder(); if (value instanceof List) { final List<?> l = (List<?>) value; for (final Object o : l) { if (s.length() > 0) { s.append(','); } s.append(o.toString()); } } else { s.append(value); } return s.toString(); } }
1,729
29.350877
107
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/ToStringSerializer.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import fr.dudie.nominatim.client.request.NominatimRequest; /** * Serializes input value using {@link Object#toString()} unless the input object is an instance of * {@link NominatimRequest}, then it uses {@link NominatimRequest#getQueryString()}. * * @author Jeremie Huchet */ public class ToStringSerializer implements QueryParameterSerializer { /** * {@inheritDoc} * * @see fr.dudie.nominatim.client.request.paramhelper.QueryParameterSerializer#handle(java.lang.Object) */ @Override public String handle(final Object value) { if (value instanceof NominatimRequest) { return ((NominatimRequest) value).getQueryString(); } else { return value.toString(); } } }
1,609
31.857143
107
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/PolygonFormat.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ /** * Enumerates OSM POLYGON FORMAT possible parameters values. * * @author Jeremie Huchet */ public enum PolygonFormat { /** No polygons. */ NONE, /** Output geometry of results in geojson format. */ GEO_JSON("polygon_geojson=1"), /** Output geometry of results in kml format. */ KML("polygon_kml=1"), /** Output geometry of results in svg format. */ SVG("polygon_svg=1"), /** Output geometry of results as a WKT. */ TEXT("polygon_text=1"); /** The parameter name AND its value. */ private final String param; private PolygonFormat() { param = null; } private PolygonFormat(final String param) { this.param = param; } @Override public String toString() { return param; } }
1,644
25.111111
71
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/client/request/paramhelper/OsmType.java
package fr.dudie.nominatim.client.request.paramhelper; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Enumerates OSM TYPE possible parameters values. * * @author Jeremie Huchet */ public enum OsmType { /** A node. */ NODE("N"), /** A way. */ WAY("W"), /** A relation. */ RELATION("R"); private static final Logger LOGGER = LoggerFactory.getLogger(OsmType.class); /** The parameter value. */ private final String value; private OsmType(final String param) { this.value = param; } @Override public String toString() { return value; } public static OsmType from(final String type) { OsmType result = null; final OsmType[] v = values(); for (int i = 0; null == result && i < v.length; i++) { if (v[i].value.equalsIgnoreCase(type)) { result = v[i]; } } if (null == result) { LOGGER.warn("Unexpected OsmType value: {}. {}", type, Arrays.toString(v)); } return result; } }
1,911
24.837838
86
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/gson/ArrayOfPolygonPointsDeserializer.java
package fr.dudie.nominatim.gson; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.lang.reflect.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import fr.dudie.nominatim.model.PolygonPoint; /** * Deserializes the attribute named "polygonpoints" of a response from the Nominatim API. It will * become an array of {@link PolygonPoint}s. * <p> * Sample "polygonpoints" attribute: * * <pre> * "polygonpoints": [ * "48.1190567016602", * "48.1191635131836", * "-1.6499342918396", * "-1.64988231658936" * ], * </pre> * * @author Jérémie Huchet */ public final class ArrayOfPolygonPointsDeserializer implements JsonDeserializer<PolygonPoint[]> { /** The event logger. */ private static final Logger LOGGER = LoggerFactory .getLogger(ArrayOfPolygonPointsDeserializer.class); /** * {@inheritDoc} * * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) */ @Override public PolygonPoint[] deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) { final PolygonPoint[] points; if (json.isJsonArray()) { final JsonArray pointsJsonArray = json.getAsJsonArray(); points = new PolygonPoint[pointsJsonArray.size()]; for (int i = 0; i < pointsJsonArray.size(); i++) { points[i] = context.deserialize(pointsJsonArray.get(i), PolygonPoint.class); } } else { throw new JsonParseException("Unexpected data: " + json.toString()); } return points; } }
2,713
29.840909
97
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/gson/PolygonPointDeserializer.java
package fr.dudie.nominatim.gson; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.lang.reflect.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import fr.dudie.nominatim.model.PolygonPoint; /** * Deserializes a polygonpoint as a {@link PolygonPoint} object. * <p> * Sample "polygonpoint": * * <pre> * [ * "34.50669", * "28.0885916" * ], * </pre> * * @author Jérémie Huchet */ public final class PolygonPointDeserializer implements JsonDeserializer<PolygonPoint> { /** The event logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(PolygonPointDeserializer.class); /** * {@inheritDoc} * * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) */ @Override public PolygonPoint deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) { final PolygonPoint point; if (json.isJsonArray()) { final JsonArray pointsJsonArray = json.getAsJsonArray(); point = new PolygonPoint(); point.setLongitude(pointsJsonArray.get(0).getAsDouble()); point.setLatitude(pointsJsonArray.get(1).getAsDouble()); } else { throw new JsonParseException("Unexpected data: " + json.toString()); } return point; } }
2,453
29.296296
97
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/gson/BoundingBoxDeserializer.java
package fr.dudie.nominatim.gson; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.lang.reflect.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import fr.dudie.nominatim.model.BoundingBox; /** * Deserializes the attribute named "boundingbox" of a response from the Nominatim API. It will * become an {@link BoundingBox}. * <p> * Sample "boundingbox" attribute: * * <pre> * "boundingbox": [ * "48.1190567016602", S * "48.1191635131836", N * "-1.6499342918396", W * "-1.64988231658936" E * ], * </pre> * * @author Jérémie Huchet */ public final class BoundingBoxDeserializer implements JsonDeserializer<BoundingBox> { /** The event logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(BoundingBoxDeserializer.class); /** * {@inheritDoc} * * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) */ @Override public BoundingBox deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) { final BoundingBox bbox; if (json.isJsonArray()) { final JsonArray bboxJsonArray = json.getAsJsonArray(); bbox = new BoundingBox(); bbox.setSouth(bboxJsonArray.get(0).getAsDouble()); bbox.setNorth(bboxJsonArray.get(1).getAsDouble()); bbox.setWest(bboxJsonArray.get(2).getAsDouble()); bbox.setEast(bboxJsonArray.get(3).getAsDouble()); } else { throw new JsonParseException("Unexpected data: " + json.toString()); } return bbox; } }
2,710
30.523256
96
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/gson/ArrayOfAddressElementsDeserializer.java
package fr.dudie.nominatim.gson; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.lang.reflect.Type; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import fr.dudie.nominatim.model.Element; /** * Deserializes the attribute named "address" of a response from the Nominatim API. It will become * an Array of {@link Element}s. * <p> * Sample "address" attribute: * * <pre> * "address": { * "road": "Boulevard de Vitré", * "suburb": "Jeanne d'Arc", * "city": "Rennes", * "administrative": "Rennes", * "state": "Britanny", * "postcode": "35042", * "country": "France", * "country_code": "fr" * } * </pre> * * @author Jérémie Huchet */ public final class ArrayOfAddressElementsDeserializer implements JsonDeserializer<Element[]> { /** The event logger. */ private static final Logger LOGGER = LoggerFactory .getLogger(ArrayOfAddressElementsDeserializer.class); /** * {@inheritDoc} * * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) */ @Override public Element[] deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) { final Element[] elements; if (json.isJsonObject()) { elements = new Element[json.getAsJsonObject().entrySet().size()]; int i = 0; for (final Entry<String, JsonElement> elem : json.getAsJsonObject().entrySet()) { elements[i] = new Element(); elements[i].setKey(elem.getKey()); elements[i].setValue(elem.getValue().getAsString()); i++; } } else { throw new JsonParseException("Unexpected data: " + json.toString()); } return elements; } }
2,933
30.891304
98
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/model/BoundingBox.java
package fr.dudie.nominatim.model; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.io.Serializable; /** * Represents a viewport. * * <pre> * "boundingbox": [ * "48.1190567016602", * "48.1191635131836", * "-1.6499342918396", * "-1.64988231658936" * ], * </pre> * * @author Jérémie Huchet */ public class BoundingBox implements Serializable { /** The north bound of the boundingbox. */ private double north; /** The west bound of the boundingbox. */ private double west; /** The east bound of the boundingbox. */ private double east; /** The south bound of the boundingbox. */ private double south; /** * Gets the north. * * @return the north */ public final double getNorth() { return north; } /** * Gets the north. * * @return the north */ public final int getNorthE6() { return (int) (north * 1E6); } /** * Sets the north. * * @param north * the north to set */ public final void setNorth(final double north) { this.north = north; } /** * Sets the north. * * @param north * the north to set */ public final void setNorthE6(final int north) { this.north = north / 1E6; } /** * Gets the west. * * @return the west */ public final double getWest() { return west; } /** * Gets the west. * * @return the west */ public final int getWestE6() { return (int) (west * 1E6); } /** * Sets the west. * * @param west * the west to set */ public final void setWest(final double west) { this.west = west; } /** * Sets the west. * * @param west * the west to set */ public final void setWestE6(final int west) { this.west = west / 1E6; } /** * Gets the east. * * @return the east */ public final double getEast() { return east; } /** * Gets the east. * * @return the east */ public final int getEastE6() { return (int) (east * 1E6); } /** * Sets the east. * * @param east * the east to set */ public final void setEast(final double east) { this.east = east; } /** * Sets the east. * * @param east * the east to set */ public final void setEastE6(final int east) { this.east = east / 1E6; } /** * Gets the south. * * @return the south */ public final double getSouth() { return south; } /** * Gets the south. * * @return the south */ public final int getSouthE6() { return (int) (south * 1E6); } /** * Sets the south. * * @param south * the south to set */ public final void setSouth(final double south) { this.south = south; } /** * Sets the south. * * @param south * the south to set */ public final void setSouthE6(final int south) { this.south = south / 1E6; } }
4,124
17.415179
71
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/model/Element.java
package fr.dudie.nominatim.model; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.io.Serializable; /** * Represents an address element or nameDetails element. * <p> * Address element returned from the OpenStreetMap Nominatim API looks like the following: * * <pre> * { * "road": "Boulevard de Vitré", * "suburb": "Jeanne d'Arc", * "city": "Rennes", * "administrative": "Rennes", * "state": "Britanny", * "postcode": "35042", * "country": "France", * "country_code": "fr" * } * </pre> * * <p> * NameDetails element returned from the OpenStreetMap Nominatim API looks like the following: * <pre> * { * "name":"Pałac Kultury i Nauki","name:de":"Kultur- und Wissenschaftspalast", * "name:en":"Palace of Culture and Science", * (...) * "name:hu":"Kultúra és Tudomány Palotája","name:ru":"Дворец культуры и науки", * "alt_name":"Pałac Młodzieży", * "short_name":"PKiN"} * </pre> * * Keys can't be enumerated entirely, so the java representation is a list of multiple * {@link Element}s. * * @author Jérémie Huchet */ public class Element implements Serializable { /** The element key. */ private String key; /** The element value. */ private String value; /** * Gets the key. * * @return the key */ public final String getKey() { return key; } /** * Sets the key. * * @param key * the key to set */ public final void setKey(final String key) { this.key = key; } /** * Gets the value. * * @return the value */ public final String getValue() { return value; } /** * Sets the value. * * @param value * the value to set */ public final void setValue(final String value) { this.value = value; } }
2,673
22.875
94
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/model/PolygonPoint.java
package fr.dudie.nominatim.model; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import java.io.Serializable; /** * Represents a geographical location. * * @author Jérémie Huchet */ public class PolygonPoint implements Serializable { /** The point's longitude. */ private double longitude; /** The point's latitude. */ private double latitude; /** * Gets the longitude. * * @return the longitude */ public final double getLongitude() { return longitude; } /** * Gets the longitude. * * @return the longitude */ public final int getLongitudeE6() { return (int) (longitude * 1E6); } /** * Sets the longitude. * * @param longitude * the longitude to set */ public final void setLongitude(final double longitude) { this.longitude = longitude; } /** * Sets the longitude. * * @param longitude * the longitude to set */ public final void setLongitudeE6(final int longitude) { this.longitude = longitude / 1E6; } /** * Gets the latitude. * * @return the latitude */ public final double getLatitude() { return latitude; } /** * Gets the latitude. * * @return the latitude */ public final int getLatitudeE6() { return (int) (latitude * 1E6); } /** * Sets the latitude. * * @param latitude * the latitude to set */ public final void setLatitude(final double latitude) { this.latitude = latitude; } /** * Sets the latitude. * * @param latitude * the latitude to set */ public final void setLatitudeE6(final int latitude) { this.latitude = latitude / 1E6; } }
2,634
20.25
71
java
nominatim-java-api
nominatim-java-api-master/src/main/java/fr/dudie/nominatim/model/Address.java
package fr.dudie.nominatim.model; /* * [license] * Nominatim Java API client * ~~~~ * Copyright (C) 2010 - 2014 Dudie * ~~~~ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * [/license] */ import com.google.gson.annotations.SerializedName; import com.vividsolutions.jts.geom.Geometry; import java.io.Serializable; /** * Represents a search result. * * <pre> * { * * "place_id": "49135222", * "licence": "Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0.", * "osm_type": "way", * "osm_id": "42928962", * "boundingbox": [ * "48.1190567016602", * "48.1191635131836", * "-1.6499342918396", * "-1.64988231658936" * ], * "polygonpoints": [ * [ * "34.50669", * "28.0885916" * ], * [ * "34.5183936", * "28.1684821" * ] * ], * "lat": "48.11911095", * "lon": "-1.6499083", * "display_name": "Boulevard de Vitré, Jeanne d'Arc, Rennes, Britanny, 35042, France", * "category": "highway", * "type": "primary", * "address": { * "road": "Boulevard de Vitré", * "suburb": "Jeanne d'Arc", * "city": "Rennes", * "administrative": "Rennes", * "state": "Britanny", * "postcode": "35042", * "country": "France", * "country_code": "fr" * } * * }, * </pre> * * @author Jérémie Huchet */ public final class Address implements Serializable { /** The OpenStreetMap place id. */ @SerializedName("place_id") private long placeId; /** The data licence. */ private String licence; /** The OpenStreetMap type (way, node...). */ @SerializedName("osm_type") private String osmType; /** The OpenStreetMap identifier. */ @SerializedName("osm_id") private String osmId; /** The bounding box enclosing the element. */ @SerializedName("boundingbox") private BoundingBox boundingBox; /** The polygon points representing the element. */ @Deprecated @SerializedName("polygonpoints") private PolygonPoint[] polygonPoints; /** The geojson representing the element. */ @SerializedName("geojson") private Geometry geojson; /** The address longitude. */ @SerializedName("lon") private double longitude; /** The address latitude. */ @SerializedName("lat") private double latitude; /** The address display name. */ @SerializedName("display_name") private String displayName; /** The OpenStreetMap element category (ex: highway). */ @SerializedName("category") private String elementClass; /** The OpenStreetMap element type (ex: residential). */ @SerializedName("type") private String elementType; /** The elements describing the address (ex: road, city, coutry...). */ @SerializedName("address") private Element[] addressElements; /** * The elements describing the namedetails (ex: name, operator, short name...). */ @SerializedName("namedetails") private Element[] namedetails; /** * The elements rank (ex: 30 = building). */ @SerializedName("place_rank") private int placeRank; @SerializedName("importance") private double importance; /** The polygon as a WKT string */ @SerializedName("geotext") private String wkt; /** * Gets the OpenStreetMap place id. * * @return the OpenStreetMap place id */ public long getPlaceId() { return placeId; } /** * Sets the OpenStreetMap place id. * * @param placeId * the OpenStreetMap place id to set */ public void setPlaceId(final long placeId) { this.placeId = placeId; } /** * Gets the data licence. * * @return the data licence */ public String getLicence() { return licence; } /** * Sets the data licence. * * @param licence * the data licence to set */ public void setLicence(final String licence) { this.licence = licence; } /** * Gets the OpenStreetMap type. * * @return the OpenStreetMap type */ public String getOsmType() { return osmType; } /** * Sets the OpenStreetMap type. * * @param osmType * the OpenStreetMap type to set */ public void setOsmType(final String osmType) { this.osmType = osmType; } /** * Gets the OpenStreetMap identifier. * * @return the OpenStreetMap identifier */ public String getOsmId() { return osmId; } /** * Sets the OpenStreetMap identifier. * * @param osmId * the OpenStreetMap identifier to set */ public void setOsmId(final String osmId) { this.osmId = osmId; } /** * Gets the bounding box enclosing the element. * * @return the bounding box enclosing the element */ public BoundingBox getBoundingBox() { return boundingBox; } /** * Sets the bounding box enclosing the element. * * @param boundingBox * the bounding box enclosing the element to set */ public void setBoundingBox(final BoundingBox boundingBox) { this.boundingBox = boundingBox; } /** * Gets the polygon points representing the element. * * @return the polygon points representing the element */ public PolygonPoint[] getPolygonPoints() { return polygonPoints; } /** * Sets the polygon points representing the element. * * @param polygonPoints * the polygon points representing the element to set */ public void setPolygonPoints(final PolygonPoint[] polygonPoints) { this.polygonPoints = polygonPoints; } /** * @return the geojson */ public Geometry getGeojson() { return geojson; } /** * @param geojson the geojson to set */ public void setGeojson(Geometry geojson) { this.geojson = geojson; } /** * Gets the address longitude. * * @return the address longitude */ public double getLongitude() { return longitude; } /** * Gets the address longitude. * * @return the address longitude */ public int getLongitudeE6() { return (int) (longitude * 1E6); } /** * Sets the address longitude. * * @param longitude * the address longitude to set */ public void setLongitude(final double longitude) { this.longitude = longitude; } /** * Sets the address longitude. * * @param longitude * the address longitude to set */ public void setLongitudeE6(final int longitude) { this.longitude = longitude / 1E6; } /** * Gets the address latitude. * * @return the address latitude */ public double getLatitude() { return latitude; } /** * Gets the address latitude. * * @return the address latitude */ public int getLatitudeE6() { return (int) (latitude * 1E6); } /** * Sets the address latitude. * * @param latitude * the address latitude to set */ public void setLatitude(final double latitude) { this.latitude = latitude; } /** * Sets the address latitude. * * @param latitude * the address latitude to set */ public void setLatitudeE6(final int latitude) { this.latitude = latitude / 1E6; } /** * Gets the address display name. * * @return the address display name */ public String getDisplayName() { return displayName; } /** * Sets the address display name. * * @param displayName * the address display name to set */ public void setDisplayName(final String displayName) { this.displayName = displayName; } /** * Gets the OpenStreetMap element class (ex: highway). * * @return the OpenStreetMap element class (ex: highway) */ public String getElementClass() { return elementClass; } /** * Sets the OpenStreetMap element class (ex: highway). * * @param elementClass * the OpenStreetMap element class (ex: highway) to set */ public void setElementClass(final String elementClass) { this.elementClass = elementClass; } /** * Gets the penStreetMap element type (ex: residential). * * @return the penStreetMap element type (ex: residential) */ public String getElementType() { return elementType; } /** * Sets the penStreetMap element type (ex: residential). * * @param elementType * the penStreetMap element type (ex: residential) to set */ public void setElementType(final String elementType) { this.elementType = elementType; } /** * Gets the elements describing the address (ex: road, city, coutry...). * * @return the elements describing the address (ex: road, city, coutry...) */ public Element[] getAddressElements() { return addressElements; } /** * Sets the elements describing the address (ex: road, city, coutry...). * * @param addressElements * the elements describing the address (ex: road, city, coutry...) to set */ public void setAddressElements(final Element[] addressElements) { this.addressElements = addressElements; } /** * Sets the elements describing the namedetails (ex: name, operator, short name...). * * @return name */ public Element[] getNameDetails() { return namedetails; } /** * Sets the elements describing the namedetails (ex: name, operator, short name...). * * @param namedetails * the elements describing the namedetails (ex: name, operator, short name...) */ public void setNameDetails(Element[] namedetails) { this.namedetails = namedetails; } /** * Gets the elements rank (ex: 30 = building). * * @return the elements elements rank (ex: 30 = building). */ public int getPlaceRank() { return placeRank; } /** * Sets the elements rank (ex: 30 = building). * * @param placeRank * the elements elements rank (ex: 30 = building) to set */ public void setPlaceRank(final int placeRank) { this.placeRank = placeRank; } /** * Gets the address importance. * * @return the address importance */ public double getImportance() { return importance; } /** * Sets the address importance. * * @param importance * the address importance */ public void setImportance(final double importance) { this.importance = importance; } /** * Gets polygon's WKT string. * * @return the polygon's WKT string; NULL if not available or applicable. */ public String getWkt() { return wkt; } /** * Sets a polygon's WKT string. * * @param wkt * the WKT string to set. */ public void setWkt(String wkt) { this.wkt = wkt; } }
12,257
21.784387
99
java