优化seaweed

This commit is contained in:
2022-07-11 16:01:22 +08:00
parent 851d3d72f0
commit ecd0addb82
70 changed files with 6712 additions and 7367 deletions
+3 -3
View File
@@ -33,7 +33,7 @@
<addClasspath>true</addClasspath> <addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix> <classpathPrefix>lib/</classpathPrefix>
<mainClass>com.fangjia.datastore.DataStoreServer</mainClass> <mainClass>com.fangjia.datastore.DataStoreServer</mainClass>
</manifest> </manifest>
</archive> </archive>
</configuration> </configuration>
</plugin> </plugin>
@@ -94,8 +94,8 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mongodb</groupId> <groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId> <artifactId>mongodb-driver-legacy</artifactId>
<version>2.6.5</version> <version>3.9.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
@@ -1,22 +1,21 @@
package com.fangjia.datastore; package com.fangjia.datastore;
public class ConfigurationException extends Exception { public class ConfigurationException extends Exception
{
private static final long serialVersionUID = 6570405263317311822L; private static final long serialVersionUID = 6570405263317311822L;
public ConfigurationException() { public ConfigurationException() {
} }
public ConfigurationException(String message) { public ConfigurationException(final String message) {
super(message); super(message);
} }
public ConfigurationException(Throwable cause) { public ConfigurationException(final Throwable cause) {
super(cause); super(cause);
} }
public ConfigurationException(String message, Throwable cause) { public ConfigurationException(final String message, final Throwable cause) {
super(message, cause); super(message, cause);
} }
} }
@@ -1,80 +1,83 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import com.fangjia.datastore.mongo.protocol.QueryMessage;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import com.fangjia.datastore.mongo.protocol.QueryMessage; public class Cursor
{
public class Cursor { private static final AtomicLong ID_GENERATOR;
private static final AtomicLong ID_GENERATOR = new AtomicLong(1); private long id;
private long id; private int limit;
private int limit; private int skip;
private int skip; private long totalCount;
private long totalCount; private QueryMessage queryMessage;
private QueryMessage queryMessage;
public Cursor(final int skip, final int limit, final QueryMessage queryMessage, final long totalCount) {
public Cursor(int skip, int limit, QueryMessage queryMessage, long totalCount) { this.id = Cursor.ID_GENERATOR.getAndIncrement();
id = ID_GENERATOR.getAndIncrement(); this.skip = skip;
this.skip = skip; this.limit = limit;
this.limit = limit; this.totalCount = totalCount;
this.totalCount = totalCount; this.queryMessage = queryMessage;
this.queryMessage = queryMessage; }
}
public long getId() {
public long getId() { return this.id;
return id; }
}
public int getLimit() {
public int getLimit() { return this.limit;
return limit; }
}
public void setLimit(final int limit) {
public void setLimit(int limit) { this.limit = limit;
this.limit = limit; }
}
public int nextSkip() {
public int nextSkip() { return this.skip += this.limit;
skip += limit; }
return skip;
} public void setSkip(final int skip) {
this.skip = skip;
public void setSkip(int skip) { }
this.skip = skip;
} public boolean hasMore() {
return this.totalCount > this.skip;
public boolean hasMore() { }
return this.totalCount > this.skip;
} public long getTotalCount() {
return this.totalCount;
public long getTotalCount() { }
return totalCount;
} public void setTotalCount(final long totalCount) {
this.totalCount = totalCount;
public void setTotalCount(long totalCount) { }
this.totalCount = totalCount;
} public QueryMessage getQueryMessage() {
return this.queryMessage;
public QueryMessage getQueryMessage() { }
return queryMessage;
} public void setQueryMessage(final QueryMessage queryMessage) {
this.queryMessage = queryMessage;
public void setQueryMessage(QueryMessage queryMessage) { }
this.queryMessage = queryMessage;
} public int getSkip() {
return this.skip;
public int getSkip() { }
return skip;
} @Override
public String toString() {
public String toString() { final StringBuilder builder = new StringBuilder();
StringBuilder builder = new StringBuilder(); builder.append("{");
builder.append("{"); builder.append("id:").append(this.id);
builder.append("id:").append(id); builder.append(", limit:").append(this.limit);
builder.append(", limit:").append(limit); builder.append(", skip:").append(this.skip);
builder.append(", skip:").append(skip); builder.append(", totalCount:").append(this.totalCount);
builder.append(", totalCount:").append(totalCount); builder.append(", queryMessage:").append(this.queryMessage);
builder.append(", queryMessage:").append(queryMessage); builder.append("}");
builder.append("}"); return builder.toString();
return builder.toString(); }
}
static {
ID_GENERATOR = new AtomicLong(1L);
}
} }
@@ -1,44 +1,35 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import java.util.Collection;
import java.util.List; import java.util.List;
import org.bson.BSONObject; import org.bson.BSONObject;
import com.fangjia.datastore.config.Reloadable;
import com.fangjia.datastore.config.StoreConfig;
import com.fangjia.datastore.solr.Index; import com.fangjia.datastore.solr.Index;
import java.util.Collection;
import com.fangjia.datastore.config.StoreConfig;
import com.fangjia.datastore.config.Reloadable;
public interface DataStore extends Reloadable { public interface DataStore extends Reloadable
{
StoreConfig getStoreConfig(); StoreConfig getStoreConfig();
Mongo getMongo(); Mongo getMongo();
Object getAttribute(String key); Object getAttribute(final String p0);
Object setAttribute(String key, Object attr); Object setAttribute(final String p0, final Object p1);
Collection<Index> getIndexes() throws DataStoreException; Collection<Index> getIndexes() throws DataStoreException;
/** BSONObject reIndex(final BSONObject p0) throws DataStoreException;
* °´²éѯÌõ¼þÖØ½¨Ë÷Òý
* void ensureIndex(final Collection<Index> p0) throws DataStoreException;
* @param query
* @throws DataStoreException QueryResponse find(final BSONObject p0, final BSONObject p1, final BSONObject p2, final BSONObject p3, final int p4, final int p5, final boolean p6, final boolean p7) throws DataStoreException;
*/
BSONObject reIndex(BSONObject query) throws DataStoreException; int count(final BSONObject p0, final boolean p1) throws DataStoreException;
void ensureIndex(Collection<Index> indexes) throws DataStoreException; void remove(final BSONObject p0) throws DataStoreException;
QueryResponse find(BSONObject query, BSONObject fields, BSONObject sort, BSONObject facet, int skip, int limit, boolean bulk, int update(final BSONObject p0, final BSONObject p1) throws DataStoreException;
boolean fromMaster) throws DataStoreException;
void save(final List<? extends BSONObject> p0) throws DataStoreException;
int count(BSONObject query, boolean fromMaster) throws DataStoreException;
void remove(BSONObject query) throws DataStoreException;
void update(BSONObject query, BSONObject data,String ip) throws DataStoreException;
void save(List<? extends BSONObject> docList) throws DataStoreException;
} }
@@ -3,15 +3,15 @@ package com.fangjia.datastore;
import com.fangjia.datastore.config.DataStoreConfig; import com.fangjia.datastore.config.DataStoreConfig;
import com.fangjia.datastore.config.Reloadable; import com.fangjia.datastore.config.Reloadable;
public interface DataStoreContext extends Reloadable { public interface DataStoreContext extends Reloadable
{
DataStoreConfig getDataStoreConfig(); DataStoreConfig getDataStoreConfig();
DataStore getDataStore(String storeName) throws DataStoreException; DataStore getDataStore(final String p0) throws DataStoreException;
Cursor getCursor(long cursorId); Cursor getCursor(final long p0);
void addCursor(Cursor cursor); void addCursor(final Cursor p0);
Cursor removeCursor(long cursorId); Cursor removeCursor(final long p0);
} }
@@ -1,56 +1,61 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.fangjia.datastore.config.DataStoreConfig;
import com.fangjia.datastore.config.StoreConfig; import com.fangjia.datastore.config.StoreConfig;
import java.util.Iterator;
import java.util.Set;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.MapMaker; import com.google.common.collect.MapMaker;
import java.util.Map;
import com.fangjia.datastore.config.DataStoreConfig;
public class DataStoreContextImpl implements DataStoreContext { public class DataStoreContextImpl implements DataStoreContext
{
private final DataStoreConfig config; private final DataStoreConfig config;
private final Map<Long, Cursor> cursorMap; private final Map<Long, Cursor> cursorMap;
private final Map<String, DataStore> stores; private final Map<String, DataStore> stores;
public DataStoreContextImpl(DataStoreConfig config) throws ConfigurationException { public DataStoreContextImpl(final DataStoreConfig config) throws ConfigurationException {
this.config = config; this.config = config;
cursorMap = new MapMaker().concurrencyLevel(50).expiration(config.getServerConfig().getCursorExpirationMinutes(), this.cursorMap = new MapMaker().concurrencyLevel(50).expiration((long)config.getServerConfig().getCursorExpirationMinutes(), TimeUnit.MINUTES).makeMap();
TimeUnit.MINUTES).makeMap(); final Set<String> storeNames = config.getStoreNames();
Set<String> storeNames = config.getStoreNames(); this.stores = new HashMap<String, DataStore>(storeNames.size());
stores = new HashMap<String, DataStore>(storeNames.size()); for (final String storeName : storeNames) {
for (String storeName : storeNames) { final StoreConfig storeConfig = this.config.getStoreConfig(storeName);
StoreConfig storeConfig = this.config.getStoreConfig(storeName); this.stores.put(storeName, new DataStoreImpl(storeConfig, new Mongo(storeConfig.getMongoConfig())));
stores.put(storeName, new DataStoreImpl(storeConfig, new Mongo(storeConfig.getMongoConfig()))); }
} }
}
@Override
public DataStoreConfig getDataStoreConfig() { public DataStoreConfig getDataStoreConfig() {
return config; return this.config;
} }
public DataStore getDataStore(String storeName) throws DataStoreException { @Override
if (!stores.containsKey(storeName)) { public DataStore getDataStore(final String storeName) throws DataStoreException {
throw new DataStoreException("unknown store name: \"" + storeName + "\""); if (!this.stores.containsKey(storeName)) {
} throw new DataStoreException("unknown store name: \"" + storeName + "\"");
return stores.get(storeName); }
} return this.stores.get(storeName);
}
public void reload() throws ConfigurationException {
config.reload(); @Override
} public void reload() throws ConfigurationException {
this.config.reload();
public Cursor getCursor(long cursorId) { }
return this.cursorMap.get(cursorId);
} @Override
public Cursor getCursor(final long cursorId) {
public void addCursor(Cursor cursor) { return this.cursorMap.get(cursorId);
this.cursorMap.put(cursor.getId(), cursor); }
}
@Override
public Cursor removeCursor(long cursorId) { public void addCursor(final Cursor cursor) {
return this.cursorMap.remove(cursorId); this.cursorMap.put(cursor.getId(), cursor);
} }
@Override
public Cursor removeCursor(final long cursorId) {
return this.cursorMap.remove(cursorId);
}
} }
@@ -1,23 +1,21 @@
package com.fangjia.datastore; package com.fangjia.datastore;
public class DataStoreException extends Exception { public class DataStoreException extends Exception
{
private static final long serialVersionUID = -5492973985910379215L; private static final long serialVersionUID = -5492973985910379215L;
public DataStoreException() { public DataStoreException() {
super(); }
}
public DataStoreException(final String message, final Throwable cause) {
public DataStoreException(String message, Throwable cause) { super(message, cause);
super(message, cause); }
}
public DataStoreException(final String message) {
public DataStoreException(String message) { super(message);
super(message); }
}
public DataStoreException(final Throwable cause) {
public DataStoreException(Throwable cause) { super(cause);
super(cause); }
}
} }
File diff suppressed because it is too large Load Diff
@@ -1,193 +1,178 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import java.io.IOException; import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.service.IoService; import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener; import java.util.Arrays;
import org.apache.mina.core.service.SimpleIoProcessorPool;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecException;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LogLevel;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioProcessor;
import org.apache.mina.transport.socket.nio.NioSession;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.bson.BSONObject; import org.bson.BSONObject;
import org.bson.BasicBSONObject; import org.bson.BasicBSONObject;
import org.slf4j.Logger; import com.fangjia.datastore.mongo.protocol.ReplyMessage;
import org.slf4j.LoggerFactory; import org.apache.mina.filter.codec.ProtocolCodecException;
import java.io.IOException;
import com.fangjia.datastore.config.DataStoreConfig; import org.apache.mina.core.session.IoSession;
import com.fangjia.datastore.handler.DeleteMessageHandler; import org.apache.mina.transport.socket.SocketSessionConfig;
import com.fangjia.datastore.handler.GetMoreMessageHandler; import java.net.SocketAddress;
import com.fangjia.datastore.handler.InsertMessageHandler; import java.net.InetSocketAddress;
import com.fangjia.datastore.handler.KillCursorsMessageHandler; import org.apache.mina.core.session.IdleStatus;
import com.fangjia.datastore.handler.MessageHandler; import org.apache.mina.core.service.IoHandler;
import com.fangjia.datastore.handler.QueryMessageHandler;
import com.fangjia.datastore.handler.UpdateMessageHandler; import com.fangjia.datastore.handler.UpdateMessageHandler;
import com.fangjia.datastore.mongo.codec.BSONIoBufferAllocator; import com.fangjia.datastore.mongo.protocol.UpdateMessage;
import com.fangjia.datastore.handler.DeleteMessageHandler;
import com.fangjia.datastore.mongo.protocol.DeleteMessage;
import com.fangjia.datastore.handler.KillCursorsMessageHandler;
import com.fangjia.datastore.mongo.protocol.KillCursorsMessage;
import com.fangjia.datastore.handler.GetMoreMessageHandler;
import com.fangjia.datastore.mongo.protocol.GetMoreMessage;
import com.fangjia.datastore.handler.QueryMessageHandler;
import com.fangjia.datastore.mongo.protocol.QueryMessage;
import com.fangjia.datastore.handler.InsertMessageHandler;
import com.fangjia.datastore.mongo.protocol.InsertMessage;
import java.util.concurrent.ExecutorService;
import org.apache.mina.filter.logging.LogLevel;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import com.fangjia.datastore.mongo.codec.MongoProtocolDecoder; import com.fangjia.datastore.mongo.codec.MongoProtocolDecoder;
import com.fangjia.datastore.mongo.codec.MongoProtocolEncoder; import com.fangjia.datastore.mongo.codec.MongoProtocolEncoder;
import com.fangjia.datastore.mongo.protocol.DeleteMessage; import org.apache.mina.core.service.IoProcessor;
import com.fangjia.datastore.mongo.protocol.GetMoreMessage; import java.util.concurrent.Executor;
import com.fangjia.datastore.mongo.protocol.InsertMessage; import org.apache.mina.core.service.SimpleIoProcessorPool;
import com.fangjia.datastore.mongo.protocol.KillCursorsMessage; import org.apache.mina.transport.socket.nio.NioProcessor;
import java.util.concurrent.Executors;
import org.apache.mina.core.buffer.IoBufferAllocator;
import org.apache.mina.core.buffer.IoBuffer;
import com.fangjia.datastore.mongo.codec.BSONIoBufferAllocator;
import com.fangjia.datastore.config.DataStoreConfig;
import java.util.HashMap;
import com.fangjia.datastore.handler.MessageHandler;
import java.util.Map;
import com.fangjia.datastore.mongo.protocol.MongoMessage; import com.fangjia.datastore.mongo.protocol.MongoMessage;
import com.fangjia.datastore.mongo.protocol.QueryMessage; import org.slf4j.Logger;
import com.fangjia.datastore.mongo.protocol.ReplyMessage; import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import com.fangjia.datastore.mongo.protocol.UpdateMessage; import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.service.IoHandlerAdapter;
public class DataStoreServer extends IoHandlerAdapter implements IoServiceListener {
private final NioSocketAcceptor acceptor;
private final DataStoreContext context;
private static final Logger LOGGER = LoggerFactory.getLogger(DataStoreServer.class);
private static ThreadLocal<MongoMessage> CURRENT_MESSAGE = new ThreadLocal<MongoMessage>();
private final Map<Class<? extends MongoMessage>, MessageHandler<? extends MongoMessage>> handlerMap = new HashMap<Class<? extends MongoMessage>, MessageHandler<? extends MongoMessage>>();
public DataStoreServer(String[] args) throws Exception {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("starting datastore...");
}
DataStoreConfig config = new DataStoreConfig(System.getProperty("datastore.home", "d:\\goojiaconfig\\datastore"));
config.setReadOnly(Boolean.getBoolean("datastore.readOnly"));
if (LOGGER.isInfoEnabled()) {
LOGGER.info(config.toString());
}
context = new DataStoreContextImpl(config);
IoBuffer.setAllocator(new BSONIoBufferAllocator());
final ExecutorService executorService = Executors.newCachedThreadPool();
acceptor = new NioSocketAcceptor(executorService, new SimpleIoProcessorPool<NioSession>(NioProcessor.class, config
.getServerConfig().getMaxConnections()));
acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new MongoProtocolEncoder(), new MongoProtocolDecoder()));
acceptor.getFilterChain().addLast("performance",
new PerformanceLogFilter(config.getServerConfig().getPerformanceLogFilterMaxTime()));
if (!config.getServerConfig().isDisableLogging()) {
LoggingFilter loggingFilter = new LoggingFilter(DataStoreServer.class);
loggingFilter.setExceptionCaughtLogLevel(LogLevel.NONE);
acceptor.getFilterChain().addLast("logger", loggingFilter);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
LOGGER.info("shutting down...");
acceptor.unbind();
executorService.shutdown();
LOGGER.info("shut down");
}
});
// register message handlers
register(InsertMessage.class, new InsertMessageHandler(context));
register(QueryMessage.class, new QueryMessageHandler(context));
register(GetMoreMessage.class, new GetMoreMessageHandler(context));
register(KillCursorsMessage.class, new KillCursorsMessageHandler(context));
register(DeleteMessage.class, new DeleteMessageHandler(context));
register(UpdateMessage.class, new UpdateMessageHandler(context));
acceptor.setHandler(this);
acceptor.addListener(this);
acceptor.setReuseAddress(true);
SocketSessionConfig sessionConfig = acceptor.getSessionConfig();
sessionConfig.setTcpNoDelay(true);
sessionConfig.setKeepAlive(true);
sessionConfig.setReuseAddress(true);
sessionConfig.setReadBufferSize(config.getServerConfig().getMinaReadBufferSize());
sessionConfig.setIdleTime(IdleStatus.BOTH_IDLE, 300);
acceptor.bind(new InetSocketAddress(config.getServerConfig().getPort()));
}
private void register(Class<? extends MongoMessage> messageClass, MessageHandler<? extends MongoMessage> handler) {
this.handlerMap.put(messageClass, handler);
}
/**
* @param args
* @throws Exception
* @throws
*/
public static void main(String[] args) throws Exception {
new DataStoreServer(args);
}
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
if (cause instanceof IOException && null != cause.getMessage() && cause.getMessage().contains("Connection reset by peer")) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("connection closed on session: {}", session);
}
} else if (cause instanceof ProtocolCodecException) {
// ProtocolDecoderException or ProtocolEncoderException
MongoMessage message = CURRENT_MESSAGE.get();
if (null != message) {
if (message instanceof QueryMessage) {
QueryMessage queryMessage = (QueryMessage) message;
ReplyMessage reply = new ReplyMessage();
reply.setNumberReturned(1);
reply.setResponseFlag(8);
reply.getMessageHeader().setResponseTo(queryMessage.getMessageHeader().getRequestID());
BSONObject msg = new BasicBSONObject("$err", cause.getMessage());
reply.setDocuments(Arrays.asList(msg));
session.write(reply);
}
}
} else if (LOGGER.isErrorEnabled()) {
LOGGER.error("exception caught on session:{" + session + "}", cause);
}
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
if (message instanceof MongoMessage) {
MongoMessage mongoMessage = (MongoMessage) message;
CURRENT_MESSAGE.set(mongoMessage);
MessageHandler<? extends MongoMessage> handler = this.handlerMap.get(mongoMessage.getClass());
if (null != handler) {
handler.messageReceived(session, mongoMessage);
} else {
throw new RuntimeException("unknown message received:" + message);
}
} else {
throw new RuntimeException("unknown message received:" + message);
}
}
public void serviceActivated(IoService service) throws Exception {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("datastore started");
LOGGER.info("listening at " + this.context.getDataStoreConfig().getServerConfig().getPort());
}
}
public void serviceIdle(IoService service, IdleStatus idleStatus) throws Exception {
// empty
}
public void serviceDeactivated(IoService service) throws Exception {
// empty
}
public void sessionDestroyed(IoSession session) throws Exception {
// empty
}
public class DataStoreServer extends IoHandlerAdapter implements IoServiceListener
{
private final NioSocketAcceptor acceptor;
private final DataStoreContext context;
private static final Logger LOGGER;
private static ThreadLocal<MongoMessage> CURRENT_MESSAGE;
private final Map<Class<? extends MongoMessage>, MessageHandler<? extends MongoMessage>> handlerMap;
public DataStoreServer(final String[] args) throws Exception {
this.handlerMap = new HashMap<Class<? extends MongoMessage>, MessageHandler<? extends MongoMessage>>();
if (DataStoreServer.LOGGER.isInfoEnabled()) {
DataStoreServer.LOGGER.info("starting datastore...");
}
final DataStoreConfig config = new DataStoreConfig(System.getProperty("datastore.home", "D:\\goojiaconfig\\seaweedsolr6"));
config.setReadOnly(Boolean.getBoolean("datastore.readOnly"));
if (DataStoreServer.LOGGER.isInfoEnabled()) {
DataStoreServer.LOGGER.info(config.toString());
}
this.context = new DataStoreContextImpl(config);
IoBuffer.setAllocator(new BSONIoBufferAllocator());
final ExecutorService executorService = Executors.newCachedThreadPool();
this.acceptor = new NioSocketAcceptor(executorService, new SimpleIoProcessorPool(NioProcessor.class, config.getServerConfig().getMaxConnections()));
this.acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MongoProtocolEncoder(), new MongoProtocolDecoder()));
this.acceptor.getFilterChain().addLast("performance", new PerformanceLogFilter(config.getServerConfig().getPerformanceLogFilterMaxTime()));
if (!config.getServerConfig().isDisableLogging()) {
final LoggingFilter loggingFilter = new LoggingFilter(DataStoreServer.class);
loggingFilter.setExceptionCaughtLogLevel(LogLevel.NONE);
this.acceptor.getFilterChain().addLast("logger", loggingFilter);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
DataStoreServer.LOGGER.info("shutting down...");
DataStoreServer.this.acceptor.unbind();
executorService.shutdown();
DataStoreServer.LOGGER.info("shut down");
}
});
this.register(InsertMessage.class, new InsertMessageHandler(this.context));
this.register(QueryMessage.class, new QueryMessageHandler(this.context));
this.register(GetMoreMessage.class, new GetMoreMessageHandler(this.context));
this.register(KillCursorsMessage.class, new KillCursorsMessageHandler(this.context));
this.register(DeleteMessage.class, new DeleteMessageHandler(this.context));
this.register(UpdateMessage.class, new UpdateMessageHandler(this.context));
this.acceptor.setHandler(this);
this.acceptor.addListener(this);
this.acceptor.setReuseAddress(true);
final SocketSessionConfig sessionConfig = this.acceptor.getSessionConfig();
sessionConfig.setTcpNoDelay(true);
sessionConfig.setKeepAlive(true);
sessionConfig.setReuseAddress(true);
sessionConfig.setReadBufferSize(config.getServerConfig().getMinaReadBufferSize());
sessionConfig.setIdleTime(IdleStatus.BOTH_IDLE, 300);
this.acceptor.bind(new InetSocketAddress(config.getServerConfig().getPort()));
}
private void register(final Class<? extends MongoMessage> messageClass, final MessageHandler<? extends MongoMessage> handler) {
this.handlerMap.put(messageClass, handler);
}
public static void main(final String[] args) throws Exception {
new DataStoreServer(args);
}
public void exceptionCaught(final IoSession session, final Throwable cause) throws Exception {
if (cause instanceof IOException && null != cause.getMessage() && cause.getMessage().contains("Connection reset by peer")) {
if (DataStoreServer.LOGGER.isInfoEnabled()) {
DataStoreServer.LOGGER.info("connection closed on session: {}", (Object)session);
}
}
else if (cause instanceof ProtocolCodecException) {
final MongoMessage message = DataStoreServer.CURRENT_MESSAGE.get();
if (null != message && message instanceof QueryMessage) {
final QueryMessage queryMessage = (QueryMessage)message;
final ReplyMessage reply = new ReplyMessage();
reply.setNumberReturned(1);
reply.setResponseFlag(8);
reply.getMessageHeader().setResponseTo(queryMessage.getMessageHeader().getRequestID());
final BSONObject msg = (BSONObject)new BasicBSONObject("$err", cause.getMessage());
reply.setDocuments(Arrays.<BSONObject>asList(msg));
session.write((Object)reply);
}
}
else if (DataStoreServer.LOGGER.isErrorEnabled()) {
DataStoreServer.LOGGER.error("exception caught on session:{" + session + "}", cause);
}
}
public void messageReceived(final IoSession session, final Object message) throws Exception {
if (!(message instanceof MongoMessage)) {
throw new RuntimeException("unknown message received:" + message);
}
final MongoMessage mongoMessage = (MongoMessage)message;
DataStoreServer.CURRENT_MESSAGE.set(mongoMessage);
final MessageHandler<? extends MongoMessage> handler = this.handlerMap.get(mongoMessage.getClass());
if (null != handler) {
handler.messageReceived(session, mongoMessage);
return;
}
throw new RuntimeException("unknown message received:" + message);
}
public void serviceActivated(final IoService service) throws Exception {
if (DataStoreServer.LOGGER.isInfoEnabled()) {
DataStoreServer.LOGGER.info("datastore started");
DataStoreServer.LOGGER.info("listening at " + this.context.getDataStoreConfig().getServerConfig().getPort());
}
}
public void serviceIdle(final IoService service, final IdleStatus idleStatus) throws Exception {
}
public void serviceDeactivated(final IoService service) throws Exception {
}
public void sessionDestroyed(final IoSession session) throws Exception {
}
static {
LOGGER = LoggerFactory.getLogger((Class)DataStoreServer.class);
DataStoreServer.CURRENT_MESSAGE = new ThreadLocal<MongoMessage>();
}
} }
@@ -1,64 +1,22 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Set;
import org.bson.BSONObject; import org.bson.BSONObject;
import java.util.Set;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import java.util.List;
public interface FileStore { public interface FileStore
public final static String DEFAULT_CHARSET = "UTF-8"; {
public static final String DEFAULT_CHARSET = "UTF-8";
/**
* void save(final List<DBObject> p0, final List<DBObject> p1) throws DataStoreException;
* @param fileList
* 仅包含大字段的文档列表 void remove(final List<ObjectId> p0, final Set<String> p1);
* @param dbObjList
* 已经保存到数据库的主对象列表 void remove(final List<ObjectId> p0);
* @throws IllegalArgumentException
* 大字段数据不支持默认编码时抛出 void update(final List<ObjectId> p0, final BSONObject p1) throws DataStoreException;
*/
void save(List<DBObject> fileList, List<DBObject> dbObjList) throws DataStoreException; List<DBObject> find(final List<DBObject> p0, final BSONObject p1) throws DataStoreException;
/**
* 删除指定的大字段内容
*
* @param objIdList
* 删除的主对象的id列表
* @param removeFields
* 需要删除的大字段名集合
*/
public void remove(List<ObjectId> objIdList, Set<String> removeFields);
/**
* 删除所有大字段内容
*
* @param objIdList
*/
public void remove(List<ObjectId> objIdList);
/**
* @param objIdList
* 待更新的主对象id列表
* @param data
* 更新文档
* @throws UnsupportedEncodingException
* 大字段数据不支持默认编码时抛出
*/
public void update(List<ObjectId> objIdList, BSONObject data) throws DataStoreException;
/**
* @param docList
* 查询的结果文档
* @param fields
* 查询字段对象
* @return
* @throws IOException
* 读取大字段数据异常时、大字段数据不支持默认编码时抛出
*/
public List<DBObject> find(List<DBObject> docList, BSONObject fields) throws DataStoreException;
} }
@@ -1,249 +1,229 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import com.mongodb.gridfs.GridFSDBFile;
import java.util.HashSet;
import com.mongodb.BasicDBObject;
import java.util.ArrayList;
import java.util.Set;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import java.io.ByteArrayOutputStream;
import com.mongodb.gridfs.GridFSFile;
import java.util.Date;
import java.io.IOException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import com.fangjia.datastore.config.FieldTypeEnum;
import org.bson.BSONObject; import org.bson.BSONObject;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import com.fangjia.datastore.config.Field;
import com.fangjia.datastore.config.FieldTypeEnum;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import java.util.List;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Collection;
import com.fangjia.datastore.config.Field;
import java.util.Map;
import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
public class FileStoreImpl implements FileStore { public class FileStoreImpl implements FileStore
{
private GridFS gridFS; private GridFS gridFS;
private Map<String, Field> bigFieldSet; private Map<String, Field> bigFieldSet;
public FileStoreImpl(GridFS gridFS, Collection<Field> fields) { public FileStoreImpl(final GridFS gridFS, final Collection<Field> fields) {
this.gridFS = gridFS; this.gridFS = gridFS;
this.bigFieldSet = new HashMap<String, Field>();
// 把大字段的字段名放入set for (final Field field : fields) {
bigFieldSet = new HashMap<String, Field>(); if (field.isBigField()) {
for (Field field : fields) { this.bigFieldSet.put(field.getName(), field);
if (field.isBigField()) { }
bigFieldSet.put(field.getName(), field); }
} }
}
} @Override
public void save(final List<DBObject> fileList, final List<DBObject> dbObjList) {
public void save(List<DBObject> fileList, List<DBObject> dbObjList) { if (null == fileList || null == dbObjList || fileList.size() != dbObjList.size()) {
if (null == fileList || null == dbObjList || fileList.size() != dbObjList.size()) throw new IllegalArgumentException("empty list or unequal length list is not allowed!");
throw new IllegalArgumentException("empty list or unequal length list is not allowed!"); }
final Iterator<DBObject> dbObjIt = dbObjList.iterator();
Iterator<DBObject> dbObjIt = dbObjList.iterator(); final Iterator<DBObject> fileIt = fileList.iterator();
for (Iterator<DBObject> fileIt = fileList.iterator(); fileIt.hasNext();) { while (fileIt.hasNext()) {
// 取得已保存主对象的id final String id = ((ObjectId)dbObjIt.next().get("_id")).toString();
String id = ((ObjectId) dbObjIt.next().get("_id")).toString(); final BSONObject file = (BSONObject)fileIt.next();
for (final String fieldName : file.keySet()) {
BSONObject file = fileIt.next(); byte[] bytes = null;
for (String fieldName : file.keySet()) { final Field field = this.bigFieldSet.get(fieldName);
byte[] bytes = null; if (null == field) {
continue;
Field field = bigFieldSet.get(fieldName); }
if (null == field) { final FieldTypeEnum fieldType = field.getType();
continue; if (FieldTypeEnum.TEXT == fieldType) {
} final String value = (String)file.get(fieldName);
FieldTypeEnum fieldType = field.getType(); if (!StringUtils.isBlank(value)) {
if (FieldTypeEnum.TEXT == fieldType) { try {
String value = (String) file.get(fieldName); bytes = this.gzip(value);
if (!StringUtils.isBlank(value)) { }
try { catch (IOException e) {
bytes = gzip(value); throw new IllegalArgumentException("unsupported encoding value!");
} catch (IOException e) { }
throw new IllegalArgumentException("unsupported encoding value!"); }
} }
} if (null == bytes || bytes.length <= 0) {
} continue;
}
if (null != bytes && bytes.length > 0) { final GridFSFile mongofile = (GridFSFile)this.gridFS.createFile(bytes);
GridFSFile mongofile = gridFS.createFile(bytes); mongofile.put("uploadDate", (Object)new Date());
mongofile.put("uploadDate", new Date()); mongofile.put("filename", (Object)id);
mongofile.put("filename", id); mongofile.put("contentType", (Object)fieldName);
mongofile.put("contentType", fieldName); mongofile.save();
mongofile.save(); }
} }
} }
}
} private byte[] gzip(final String string) throws IOException {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private byte[] gzip(String string) throws IOException { final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); gzipOutputStream.write(string.getBytes("UTF-8"));
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream); return outputStream.toByteArray();
gzipOutputStream.write(string.getBytes(DEFAULT_CHARSET)); }
return outputStream.toByteArray();
} @Override
public void remove(final List<ObjectId> objIdList) {
public void remove(List<ObjectId> objIdList) { this.remove(objIdList, null);
remove(objIdList, null); }
}
@Override
public void remove(List<ObjectId> objIdList, Set<String> removeFields) { public void remove(final List<ObjectId> objIdList, Set<String> removeFields) {
// 删除表的所有大字段 if (null == removeFields) {
if (null == removeFields) removeFields = this.bigFieldSet.keySet();
removeFields = bigFieldSet.keySet(); }
if (removeFields.size() == 0) {
// 若到删除的字段中没有大字段,直接返回 return;
if (removeFields.size() == 0) }
return; final List<String> idList = new ArrayList<String>(objIdList.size());
for (final ObjectId objId : objIdList) {
List<String> idList = new ArrayList<String>(objIdList.size()); idList.add(objId.toString());
for (ObjectId objId : objIdList) { }
idList.add(objId.toString()); final DBObject fileSeletor = (DBObject)new BasicDBObject();
} fileSeletor.put("filename", (Object)new BasicDBObject("$in", (Object)idList));
fileSeletor.put("contentType", (Object)new BasicDBObject("$in", (Object)removeFields));
// 删除大字段关联的GridFS this.gridFS.remove(fileSeletor);
DBObject fileSeletor = new BasicDBObject(); }
fileSeletor.put("filename", new BasicDBObject("$in", idList));
fileSeletor.put("contentType", new BasicDBObject("$in", removeFields)); @Override
gridFS.remove(fileSeletor); public void update(final List<ObjectId> objIdList, final BSONObject data) throws DataStoreException {
} final BSONObject unset = (BSONObject)data.get("$unset");
if (null != unset) {
public void update(List<ObjectId> objIdList, BSONObject data) throws DataStoreException { final Set<String> removeSet = new HashSet<String>();
// 待删除的字段 for (final String field : unset.keySet()) {
BSONObject unset = (BSONObject) data.get("$unset"); if (this.bigFieldSet.containsKey(field)) {
if (null != unset) { removeSet.add(field);
// 待删除的大字段set }
Set<String> removeSet = new HashSet<String>(); }
for (String field : unset.keySet()) { if (removeSet.size() > 0) {
if (bigFieldSet.containsKey(field)) this.remove(objIdList, removeSet);
removeSet.add(field); }
} }
final BSONObject set = (BSONObject)data.get("$set");
if (removeSet.size() > 0) if (null == set) {
remove(objIdList, removeSet); return;
} }
final Map<String, Object> fileMap = new HashMap<String, Object>();
// 更新数据 for (final String field2 : set.keySet()) {
BSONObject set = (BSONObject) data.get("$set"); if (this.bigFieldSet.containsKey(field2)) {
if (null == set) fileMap.put(field2, set.get(field2));
return; }
}
Map<String, Object> fileMap = new HashMap<String, Object>(); if (fileMap.size() == 0) {
for (String field : set.keySet()) { return;
if (bigFieldSet.containsKey(field)) { }
fileMap.put(field, set.get(field)); this.remove(objIdList, fileMap.keySet());
} for (final ObjectId objId : objIdList) {
} final String id = objId.toString();
for (final String fieldName : fileMap.keySet()) {
// 更新数据中没有大字段 byte[] bytes = null;
if (fileMap.size() == 0) final Field field3 = this.bigFieldSet.get(fieldName);
return; if (null == field3) {
continue;
// 删除大字段关联的GridFS }
remove(objIdList, fileMap.keySet()); final FieldTypeEnum fieldType = field3.getType();
if (FieldTypeEnum.TEXT == fieldType) {
// 将新的内容存入GridFS final String value = (String)fileMap.get(fieldName);
for (ObjectId objId : objIdList) { if (!StringUtils.isBlank(value)) {
String id = objId.toString(); try {
for (String fieldName : fileMap.keySet()) { bytes = this.gzip(value);
byte[] bytes = null; }
catch (IOException e) {
Field field = bigFieldSet.get(fieldName); throw new IllegalArgumentException("unsupported encoding value!");
if (null == field) { }
continue; }
} }
FieldTypeEnum fieldType = field.getType(); if (null == bytes || bytes.length <= 0) {
if (FieldTypeEnum.TEXT == fieldType) { continue;
String value = (String) fileMap.get(fieldName); }
if (!StringUtils.isBlank(value)) { final GridFSFile mongofile = (GridFSFile)this.gridFS.createFile(bytes);
try { mongofile.put("uploadDate", (Object)new Date());
bytes = gzip(value); mongofile.put("filename", (Object)id);
} catch (IOException e) { mongofile.put("contentType", (Object)fieldName);
throw new IllegalArgumentException("unsupported encoding value!"); mongofile.save();
} }
} }
} }
if (null != bytes && bytes.length > 0) { @Override
GridFSFile mongofile = gridFS.createFile(bytes); public List<DBObject> find(final List<DBObject> docList, final BSONObject fields) throws DataStoreException {
mongofile.put("uploadDate", new Date()); Set<String> queryBigField = new HashSet<String>();
mongofile.put("filename", id); if (null == fields) {
mongofile.put("contentType", fieldName); queryBigField = this.bigFieldSet.keySet();
mongofile.save(); }
} else {
} for (final String field : fields.keySet()) {
} if (this.bigFieldSet.containsKey(field)) {
queryBigField.add(field);
} }
}
public List<DBObject> find(List<DBObject> docList, BSONObject fields) throws DataStoreException { }
// 判断查询的字段中有没有大字段 if (queryBigField.size() == 0) {
Set<String> queryBigField = new HashSet<String>(); return docList;
if (null == fields) { }
queryBigField = bigFieldSet.keySet(); final Map<String, DBObject> docMap = new HashMap<String, DBObject>(docList.size());
} else { final List<String> idList = new ArrayList<String>(docList.size());
for (String field : fields.keySet()) { for (final DBObject dbObj : docList) {
if (bigFieldSet.containsKey(field)) { final ObjectId objId = (ObjectId)dbObj.get("_id");
queryBigField.add(field); if (null != objId) {
} final String id = objId.toString();
} idList.add(id);
} docMap.put(id, dbObj);
}
// 没有大字段,则返回原结果文档 }
if (queryBigField.size() == 0) final DBObject fileSeletor = (DBObject)new BasicDBObject();
return docList; fileSeletor.put("filename", (Object)new BasicDBObject("$in", (Object)idList));
fileSeletor.put("contentType", (Object)new BasicDBObject("$in", (Object)queryBigField));
Map<String, DBObject> docMap = new HashMap<String, DBObject>(docList.size()); final List<GridFSDBFile> fileList = (List<GridFSDBFile>)this.gridFS.find(fileSeletor);
List<String> idList = new ArrayList<String>(docList.size()); for (final GridFSDBFile file : fileList) {
for (DBObject dbObj : docList) { final String id2 = file.getFilename();
ObjectId objId = (ObjectId) dbObj.get("_id"); final String fieldName = file.getContentType();
if (null != objId) { final DBObject obj = docMap.get(id2);
String id = objId.toString(); if (obj.keySet().contains(fieldName)) {
idList.add(id); try {
docMap.put(id, dbObj); final ByteArrayOutputStream data = new ByteArrayOutputStream();
} final GZIPOutputStream out = new GZIPOutputStream(data);
} IOUtils.copy(file.getInputStream(), (OutputStream)out);
final Field field2 = this.bigFieldSet.get(fieldName);
DBObject fileSeletor = new BasicDBObject(); if (null == field2) {
fileSeletor.put("filename", new BasicDBObject("$in", idList)); continue;
fileSeletor.put("contentType", new BasicDBObject("$in", queryBigField)); }
List<GridFSDBFile> fileList = gridFS.find(fileSeletor); final FieldTypeEnum fieldType = field2.getType();
if (FieldTypeEnum.TEXT != fieldType) {
for (GridFSDBFile file : fileList) { continue;
// 对应主记录id }
String id = file.getFilename(); obj.put(fieldName, (Object)new String(data.toByteArray(), "UTF-8"));
// 对应主记录大字段名 }
String fieldName = file.getContentType(); catch (IOException e) {
throw new DataStoreException("error extract text field[" + fieldName + "]:", e);
DBObject obj = docMap.get(id); }
if (obj.keySet().contains(fieldName)) { }
}
try { return docList;
ByteArrayOutputStream data = new ByteArrayOutputStream(); }
GZIPOutputStream out = new GZIPOutputStream(data);
IOUtils.copy(file.getInputStream(), out);
Field field = bigFieldSet.get(fieldName);
if (null == field) {
continue;
}
FieldTypeEnum fieldType = field.getType();
if (FieldTypeEnum.TEXT == fieldType) {
obj.put(fieldName, new String(data.toByteArray(), DEFAULT_CHARSET));
}
} catch (IOException e) {
throw new DataStoreException("error extract text field[" + fieldName + "]:", e);
}
}
}
return docList;
}
} }
@@ -1,46 +1,46 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import java.util.List;
import com.fangjia.datastore.config.MongoConfig;
import com.mongodb.DB;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern; import com.mongodb.WriteConcern;
import com.mongodb.MongoException;
import java.util.List;
import com.mongodb.DB;
import com.fangjia.datastore.config.MongoConfig;
public class Mongo { public class Mongo
{
private final MongoConfig mongoConfig; private final MongoConfig mongoConfig;
public Mongo(MongoConfig mongoConfig) { public Mongo(final MongoConfig mongoConfig) {
this.mongoConfig = mongoConfig; this.mongoConfig = mongoConfig;
} }
private com.mongodb.Mongo getMongo() { private com.mongodb.Mongo getMongo() {
try { try {
return mongoConfig.getMongo(); return this.mongoConfig.getMongo();
} catch (ConfigurationException e) { }
throw new RuntimeException(e); catch (ConfigurationException e) {
} throw new RuntimeException(e);
} }
}
public DB getDB(String dbname) {
return getMongo().getDB(dbname); public DB getDB(final String dbname) {
} return this.getMongo().getDB(dbname);
}
public List<String> getDatabaseNames() throws MongoException {
return getMongo().getDatabaseNames(); public List<String> getDatabaseNames() throws MongoException {
} return (List<String>)this.getMongo().getDatabaseNames();
}
public void setWriteConcern(WriteConcern concern) {
getMongo().setWriteConcern(concern); public void setWriteConcern(final WriteConcern concern) {
} this.getMongo().setWriteConcern(concern);
}
public WriteConcern getWriteConcern() {
return getMongo().getWriteConcern(); public WriteConcern getWriteConcern() {
} return this.getMongo().getWriteConcern();
}
public String toString() {
return getMongo().toString(); @Override
} public String toString() {
return this.getMongo().toString();
}
} }
@@ -1,114 +1,119 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.slf4j.Logger;
import com.fangjia.datastore.mongo.protocol.MongoMessage;
import com.fangjia.datastore.utils.LoggerFactory; import com.fangjia.datastore.utils.LoggerFactory;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.write.WriteRequest;
import org.apache.mina.core.filterchain.IoFilter;
import com.fangjia.datastore.mongo.protocol.MongoMessage;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.apache.mina.core.filterchain.IoFilterAdapter;
public class PerformanceLogFilter extends IoFilterAdapter { public class PerformanceLogFilter extends IoFilterAdapter
private final long maxTime; {
private final long maxTime;
private static final Logger LOGGER = LoggerFactory.getPerformanceLogger(PerformanceLogFilter.class); private static final Logger LOGGER;
public PerformanceLogFilter(long maxTime) { public PerformanceLogFilter(final long maxTime) {
this.maxTime = maxTime; this.maxTime = maxTime;
} }
private void logPerformace(long time, String methodName, IoSession session, Object message) { private void logPerformace(final long time, final String methodName, final IoSession session, final Object message) {
Object[] params; Object[] params;
if (message instanceof MongoMessage) { if (message instanceof MongoMessage) {
MongoMessage mongoMessage = (MongoMessage) message; final MongoMessage mongoMessage = (MongoMessage)message;
params = new Object[] { time, methodName, session, mongoMessage.toPrettyString() }; params = new Object[] { time, methodName, session, mongoMessage.toPrettyString() };
} else { }
params = new Object[] { time, methodName, session, message }; else {
} params = new Object[] { time, methodName, session, message };
if (time < maxTime * 3) { }
LOGGER.warn("time={}, methodName={}, session={}, message={}", params); if (time < this.maxTime * 3L) {
} else { PerformanceLogFilter.LOGGER.warn("time={}, methodName={}, session={}, message={}", params);
LOGGER.error("time={}, methodName={}, session={}, message={}", params); }
} else {
} PerformanceLogFilter.LOGGER.error("time={}, methodName={}, session={}, message={}", params);
}
@Override }
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
long time = System.currentTimeMillis(); public void messageReceived(final NextFilter nextFilter, final IoSession session, final Object message) throws Exception {
try { long time = System.currentTimeMillis();
nextFilter.messageReceived(session, message); try {
} finally { nextFilter.messageReceived(session, message);
time = System.currentTimeMillis() - time; }
if (time >= maxTime) { finally {
logPerformace(time, "messageReceived", session, message); time = System.currentTimeMillis() - time;
} if (time >= this.maxTime) {
} this.logPerformace(time, "messageReceived", session, message);
} }
}
@Override }
public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
long time = System.currentTimeMillis(); public void messageSent(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest) throws Exception {
try { long time = System.currentTimeMillis();
nextFilter.messageSent(session, writeRequest); try {
} finally { nextFilter.messageSent(session, writeRequest);
time = System.currentTimeMillis() - time; }
if (time >= maxTime) { finally {
logPerformace(time, "messageSent", session, writeRequest); time = System.currentTimeMillis() - time;
} if (time >= this.maxTime) {
} this.logPerformace(time, "messageSent", session, writeRequest);
} }
}
@Override }
public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
long time = System.currentTimeMillis(); public void sessionCreated(final NextFilter nextFilter, final IoSession session) throws Exception {
try { long time = System.currentTimeMillis();
nextFilter.sessionCreated(session); try {
} finally { nextFilter.sessionCreated(session);
time = System.currentTimeMillis() - time; }
if (time >= maxTime) { finally {
logPerformace(time, "sessionCreated", session, null); time = System.currentTimeMillis() - time;
} if (time >= this.maxTime) {
} this.logPerformace(time, "sessionCreated", session, null);
} }
}
@Override }
public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
long time = System.currentTimeMillis(); public void sessionOpened(final NextFilter nextFilter, final IoSession session) throws Exception {
try { long time = System.currentTimeMillis();
nextFilter.sessionOpened(session); try {
} finally { nextFilter.sessionOpened(session);
time = System.currentTimeMillis() - time; }
if (time >= maxTime) { finally {
logPerformace(time, "sessionOpened", session, null); time = System.currentTimeMillis() - time;
} if (time >= this.maxTime) {
} this.logPerformace(time, "sessionOpened", session, null);
} }
}
@Override }
public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception {
long time = System.currentTimeMillis(); public void sessionIdle(final NextFilter nextFilter, final IoSession session, final IdleStatus status) throws Exception {
try { long time = System.currentTimeMillis();
nextFilter.sessionIdle(session, status); try {
} finally { nextFilter.sessionIdle(session, status);
time = System.currentTimeMillis() - time; }
if (time >= maxTime) { finally {
logPerformace(time, "sessionIdle", session, status); time = System.currentTimeMillis() - time;
} if (time >= this.maxTime) {
} this.logPerformace(time, "sessionIdle", session, status);
} }
}
@Override }
public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
long time = System.currentTimeMillis(); public void sessionClosed(final NextFilter nextFilter, final IoSession session) throws Exception {
try { long time = System.currentTimeMillis();
nextFilter.sessionClosed(session); try {
} finally { nextFilter.sessionClosed(session);
time = System.currentTimeMillis() - time; }
if (time >= maxTime) { finally {
logPerformace(time, "sessionClosed", session, null); time = System.currentTimeMillis() - time;
} if (time >= this.maxTime) {
} this.logPerformace(time, "sessionClosed", session, null);
} }
}
}
static {
LOGGER = LoggerFactory.getPerformanceLogger(PerformanceLogFilter.class);
}
} }
@@ -1,72 +1,80 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import java.util.Collections; import java.util.Collections;
import org.apache.solr.client.solrj.response.FacetField;
import com.mongodb.DBObject;
import org.bson.types.ObjectId;
import java.util.List; import java.util.List;
import org.apache.solr.client.solrj.response.FacetField; public class QueryResponse
import org.bson.types.ObjectId; {
private List<ObjectId> idList;
import com.mongodb.DBObject; private List<DBObject> docList;
private List<FacetField> facetFieldList;
public class QueryResponse { private int numFound;
private List<ObjectId> idList = Collections.emptyList(); private int numReturned;
private List<DBObject> docList = Collections.emptyList(); private int numToSkip;
private List<FacetField> facetFieldList = null; public static final QueryResponse EMPTY_RESPONSE;
private int numFound;
private int numReturned; public QueryResponse() {
private int numToSkip; this.idList = Collections.<ObjectId>emptyList();
public final static QueryResponse EMPTY_RESPONSE = new QueryResponse(); this.docList = Collections.<DBObject>emptyList();
this.facetFieldList = null;
public List<ObjectId> getIdList() { }
return idList;
} public List<ObjectId> getIdList() {
return this.idList;
public void setIdList(List<ObjectId> idList) { }
this.idList = idList;
} public void setIdList(final List<ObjectId> idList) {
this.idList = idList;
public boolean hasMore() { }
return this.numFound > numReturned + numToSkip;
} public boolean hasMore() {
return this.numFound > this.numReturned + this.numToSkip;
public int getNumFound() { }
return numFound;
} public int getNumFound() {
return this.numFound;
public void setNumFound(int numFound) { }
this.numFound = numFound;
} public void setNumFound(final int numFound) {
this.numFound = numFound;
public int getNumReturned() { }
return numReturned;
} public int getNumReturned() {
return this.numReturned;
public void setNumReturned(int numReturned) { }
this.numReturned = numReturned;
} public void setNumReturned(final int numReturned) {
this.numReturned = numReturned;
public int getNumToSkip() { }
return numToSkip;
} public int getNumToSkip() {
return this.numToSkip;
public void setNumToSkip(int numToSkip) { }
this.numToSkip = numToSkip;
} public void setNumToSkip(final int numToSkip) {
this.numToSkip = numToSkip;
public List<FacetField> getFacetFieldList() { }
return facetFieldList;
} public List<FacetField> getFacetFieldList() {
return this.facetFieldList;
public void setFacetFieldList(List<FacetField> facetFieldList) { }
this.facetFieldList = facetFieldList;
} public void setFacetFieldList(final List<FacetField> facetFieldList) {
this.facetFieldList = facetFieldList;
public List<DBObject> getDocList() { }
return docList;
} public List<DBObject> getDocList() {
return this.docList;
public void setDocList(List<DBObject> docList) { }
this.docList = docList;
} public void setDocList(final List<DBObject> docList) {
this.docList = docList;
}
static {
EMPTY_RESPONSE = new QueryResponse();
}
} }
@@ -1,22 +1,21 @@
package com.fangjia.datastore; package com.fangjia.datastore;
public class TriggerExecuteException extends Exception { public class TriggerExecuteException extends Exception
{
private static final long serialVersionUID = -1165411196743370433L; private static final long serialVersionUID = -1165411196743370433L;
public TriggerExecuteException() { public TriggerExecuteException() {
} }
public TriggerExecuteException(String message) { public TriggerExecuteException(final String message) {
super(message); super(message);
} }
public TriggerExecuteException(Throwable cause) { public TriggerExecuteException(final Throwable cause) {
super(cause); super(cause);
} }
public TriggerExecuteException(String message, Throwable cause) { public TriggerExecuteException(final String message, final Throwable cause) {
super(message, cause); super(message, cause);
} }
} }
@@ -1,165 +1,161 @@
package com.fangjia.datastore; package com.fangjia.datastore;
import java.io.IOException; import org.slf4j.LoggerFactory;
import org.apache.http.HttpRequest;
import java.io.InputStream; import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import com.mongodb.DBObject;
import org.apache.http.client.HttpClient; import org.bson.BasicBSONDecoder;
import org.apache.http.client.methods.HttpPost; import org.apache.http.protocol.HttpContext;
import org.apache.http.client.params.AllClientPNames; import org.apache.http.HttpHost;
import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.HttpEntity;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ByteArrayEntity;
import org.sothis.core.util.GZIPUtils;
import org.bson.BasicBSONEncoder;
import com.mongodb.BasicDBObject;
import org.apache.http.client.methods.HttpPost;
import java.net.URL;
import java.net.URISyntaxException;
import java.io.IOException;
import org.bson.BSONObject;
import java.util.List;
import com.fangjia.datastore.config.Trigger;
import org.apache.http.params.HttpParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams; import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames; import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.params.HttpParams; import org.apache.http.conn.scheme.Scheme;
import org.apache.http.protocol.HttpContext; import org.apache.http.conn.scheme.PlainSocketFactory;
import org.bson.BSONEncoder; import org.apache.http.conn.scheme.SchemeRegistry;
import org.bson.BSONObject; import org.apache.http.client.HttpClient;
import org.bson.BasicBSONDecoder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sothis.core.util.GZIPUtils;
import com.fangjia.datastore.config.Trigger; public class TriggerExecutor
import com.mongodb.BasicDBObject; {
import com.mongodb.DBObject; private static final int MAX_TOTAL = 200;
private static final int MAX_FOR_ROUTE = 200;
public class TriggerExecutor { private static final String DEFAULT_CHARSET = "UTF-8";
private static final int DEFAULT_PORT = 80;
private final static int MAX_TOTAL = 200; private static final int MAX_RETRY_COUNT = 10;
private final static int MAX_FOR_ROUTE = 200; private static final Logger LOGGER;
private final static String DEFAULT_CHARSET = "UTF-8"; private static final TriggerExecutor TRIGGER_EXECUTOR;
private final static int DEFAULT_PORT = 80; private final HttpClient httpClient;
private final static int MAX_RETRY_COUNT = 10;
private TriggerExecutor() {
private final static Logger LOGGER = LoggerFactory.getLogger(TriggerExecutor.class); if (TriggerExecutor.LOGGER.isDebugEnabled()) {
private final static TriggerExecutor TRIGGER_EXECUTOR = new TriggerExecutor(); TriggerExecutor.LOGGER.debug("init trigger executor");
}
private final HttpClient httpClient; final SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, (SchemeSocketFactory)new PlainSocketFactory()));
private TriggerExecutor() { final HttpParams httpParams = (HttpParams)new BasicHttpParams();
if (LOGGER.isDebugEnabled()) { httpParams.setParameter("http.protocol.content-charset", (Object)"UTF-8");
LOGGER.debug("init trigger executor"); httpParams.setParameter("http.socket.timeout", (Object)300000);
} httpParams.setParameter("http.connection.timeout", (Object)60000);
SchemeRegistry schemeRegistry = new SchemeRegistry(); final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(schemeRegistry);
schemeRegistry.register(new Scheme("http", DEFAULT_PORT, new PlainSocketFactory())); connManager.setMaxTotal(200);
connManager.setDefaultMaxPerRoute(200);
HttpParams httpParams = new BasicHttpParams(); this.httpClient = (HttpClient)new DefaultHttpClient((ClientConnectionManager)connManager, httpParams);
httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, DEFAULT_CHARSET); if (TriggerExecutor.LOGGER.isDebugEnabled()) {
httpParams.setParameter(AllClientPNames.SO_TIMEOUT, 300000); TriggerExecutor.LOGGER.debug("trigger executor initialized[{}]", (Object)this.toString());
httpParams.setParameter(AllClientPNames.CONNECTION_TIMEOUT, 60000); }
}
ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(schemeRegistry);
connManager.setMaxTotal(MAX_TOTAL); public static TriggerExecutor getInstance() {
connManager.setDefaultMaxPerRoute(MAX_FOR_ROUTE); return TriggerExecutor.TRIGGER_EXECUTOR;
}
httpClient = new DefaultHttpClient(connManager, httpParams);
if (LOGGER.isDebugEnabled()) { public List<BSONObject> execute(final Trigger trigger, final List<BSONObject> docList) throws TriggerExecuteException {
LOGGER.debug("trigger executor initialized[{}]", toString()); try {
} final List<BSONObject> ret = this.doExecute(trigger, docList);
} if (TriggerExecutor.LOGGER.isDebugEnabled()) {
TriggerExecutor.LOGGER.debug("execute trigger: " + trigger + ", doc size:" + docList.size() + ", return size:" + ret.size());
public static TriggerExecutor getInstance() { }
return TRIGGER_EXECUTOR; return ret;
} }
catch (IOException e) {
public List<BSONObject> execute(Trigger trigger, List<BSONObject> docList) throws TriggerExecuteException { throw new TriggerExecuteException("error execute trigger: " + trigger, e);
try { }
List<BSONObject> ret = doExecute(trigger, docList); catch (URISyntaxException e2) {
if (LOGGER.isDebugEnabled()) { throw new TriggerExecuteException("error execute trigger: " + trigger, e2);
LOGGER.debug("execute trigger: " + trigger + ", doc size:" + docList.size() + ", return size:" + ret.size()); }
} }
return ret;
} catch (IOException e) { private List<BSONObject> doExecute(final Trigger trigger, final List<BSONObject> docList) throws IOException, URISyntaxException, TriggerExecuteException {
throw new TriggerExecuteException("error execute trigger: " + trigger, e); final URL url = new URL(trigger.getInterface());
} catch (URISyntaxException e) { final HttpPost httpPost = new HttpPost(url.toURI());
throw new TriggerExecuteException("error execute trigger: " + trigger, e); final DBObject object = (DBObject)new BasicDBObject();
} object.put("doc_list_size", (Object)docList.size());
} object.put("doc_list", (Object)docList);
httpPost.setEntity((HttpEntity)new ByteArrayEntity(GZIPUtils.makeAsByteArray(new BasicBSONEncoder().encode((BSONObject)object))));
private List<BSONObject> doExecute(Trigger trigger, List<BSONObject> docList) throws IOException, URISyntaxException, final HttpHost host = new HttpHost(url.getHost(), (url.getPort() == -1) ? 80 : url.getPort());
TriggerExecuteException { final HttpResponse httpResponse = this.executeWithRetry(host, httpPost, null, trigger);
URL url = new URL(trigger.getInterface()); final InputStream inputStream = httpResponse.getEntity().getContent();
HttpPost httpPost = new HttpPost(url.toURI()); try {
DBObject object = new BasicDBObject(); if (httpResponse.getStatusLine().getStatusCode() != 200) {
object.put("doc_list_size", docList.size()); throw new TriggerExecuteException("error execute trigger:" + trigger + ", get http code:" + httpResponse.getStatusLine().getStatusCode());
object.put("doc_list", docList); }
httpPost.setEntity(new ByteArrayEntity(GZIPUtils.makeAsByteArray(new BSONEncoder().encode(object)))); final BSONObject returnObject = new BasicBSONDecoder().readObject(GZIPUtils.wrap(inputStream));
HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? DEFAULT_PORT : url.getPort()); if (null == returnObject) {
HttpResponse httpResponse = executeWithRetry(host, httpPost, null, trigger); throw new TriggerExecuteException("trigger" + trigger + " returns nothing at all !");
InputStream inputStream = httpResponse.getEntity().getContent(); }
try { final List<BSONObject> ret = (List<BSONObject>)returnObject.get("doc_list");
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { if (ret == null) {
BSONObject returnObject = new BasicBSONDecoder().readObject(GZIPUtils.wrap(inputStream)); throw new TriggerExecuteException("trigger" + trigger + " return an null doc_list[" + ret + "]");
if (null != returnObject) { }
List<BSONObject> ret = (List<BSONObject>) returnObject.get("doc_list"); return ret;
if (ret == null) { }
throw new TriggerExecuteException("trigger" + trigger + " return an null doc_list[" + ret + "]"); finally {
} if (null != inputStream) {
return ret; inputStream.close();
} else { }
throw new TriggerExecuteException("trigger" + trigger + " returns nothing at all !"); }
} }
} else {
throw new TriggerExecuteException("error execute trigger:" + trigger + ", get http code:" private HttpResponse executeWithRetry(final HttpHost host, final HttpPost httpPost, final HttpContext httpContext, final Trigger trigger) throws IOException, TriggerExecuteException {
+ httpResponse.getStatusLine().getStatusCode()); int retryCounter = 0;
} HttpResponse httpResponse = null;
} finally { while (true) {
if (null != inputStream) { try {
inputStream.close(); httpResponse = this.httpClient.execute(host, (HttpRequest)httpPost, (HttpContext)null);
} if (httpResponse.getStatusLine().getStatusCode() == 200) {
} return httpResponse;
} }
++retryCounter;
private HttpResponse executeWithRetry(HttpHost host, HttpPost httpPost, HttpContext httpContext, Trigger trigger) this.sleepAndRetry(new IllegalStateException("invalid http status code: " + httpResponse.getStatusLine().getStatusCode()), retryCounter, trigger);
throws IOException, TriggerExecuteException { }
int retryCounter = 0; catch (Exception e) {
HttpResponse httpResponse = null; ++retryCounter;
while (true) { this.sleepAndRetry(e, retryCounter, trigger);
try { }
httpResponse = httpClient.execute(host, httpPost, (HttpContext) null); finally {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { if (null != httpResponse && httpResponse.getStatusLine().getStatusCode() != 200) {
return httpResponse; httpResponse.getEntity().getContent().close();
} else { }
retryCounter++; }
sleepAndRetry(new IllegalStateException("invalid http status code: " }
+ httpResponse.getStatusLine().getStatusCode()), retryCounter, trigger); }
}
} catch (Exception e) { private void sleepAndRetry(final Exception e, final int retryCounter, final Trigger trigger) throws TriggerExecuteException {
retryCounter++; if (retryCounter > 10) {
sleepAndRetry(e, retryCounter, trigger); throw new TriggerExecuteException("error execute trigger[" + trigger + "] after " + 10 + " times retry!", e);
} finally { }
if (null != httpResponse && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { if (TriggerExecutor.LOGGER.isErrorEnabled()) {
httpResponse.getEntity().getContent().close(); TriggerExecutor.LOGGER.error("error execute trigger[" + trigger + "]:(" + e.getMessage() + "), retry for the " + retryCounter + "th time after " + retryCounter * 30 + " seconds...");
} }
} try {
} Thread.sleep(retryCounter * 30000);
} }
catch (InterruptedException e2) {
private void sleepAndRetry(Exception e, int retryCounter, Trigger trigger) throws TriggerExecuteException { if (TriggerExecutor.LOGGER.isWarnEnabled()) {
if (retryCounter > MAX_RETRY_COUNT) { TriggerExecutor.LOGGER.warn("", (Throwable)e);
throw new TriggerExecuteException( }
"error execute trigger[" + trigger + "] after " + MAX_RETRY_COUNT + " times retry!", e); }
} }
if (LOGGER.isErrorEnabled()) {
LOGGER.error("error execute trigger[" + trigger + "]:(" + e.getMessage() + "), retry for the " + retryCounter static {
+ "th time after " + (retryCounter * 30) + " seconds..."); LOGGER = LoggerFactory.getLogger((Class)TriggerExecutor.class);
} TRIGGER_EXECUTOR = new TriggerExecutor();
try { }
Thread.sleep(retryCounter * 30000);
} catch (InterruptedException e1) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("", e);
}
}
}
} }
@@ -1,170 +1,172 @@
package com.fangjia.datastore.config; package com.fangjia.datastore.config;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.dom4j.Document;
import org.dom4j.DocumentException; import org.dom4j.DocumentException;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Element; import org.dom4j.Element;
import org.dom4j.Node; import org.dom4j.Node;
import org.dom4j.Document;
import java.util.Collections;
import java.util.Set;
import com.fangjia.datastore.ConfigurationException;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.io.SAXReader; import org.dom4j.io.SAXReader;
import com.fangjia.datastore.ConfigurationException; public class DataStoreConfig implements Reloadable
{
public class DataStoreConfig implements Reloadable { private final SAXReader reader;
private final SAXReader reader = new SAXReader(); private final String serverConfigFile;
private final String serverConfigFile; private final String storeConfigFile;
private final String storeConfigFile; private final ServerConfig serverConfig;
private final ServerConfig serverConfig; private final Map<String, StoreConfig> storeConfigs;
private final Map<String, StoreConfig> storeConfigs; private final Map<String, SolrConfig> solrConfigs;
private final Map<String, SolrConfig> solrConfigs; private final Map<String, MongoConfig> mongoConfigs;
private final Map<String, MongoConfig> mongoConfigs; private boolean readOnly;
private boolean readOnly = false;
public DataStoreConfig(final String datastoreHome) throws ConfigurationException {
public DataStoreConfig(String datastoreHome) throws ConfigurationException { this.reader = new SAXReader();
this.serverConfigFile = datastoreHome + "/conf/server.xml"; this.readOnly = false;
this.storeConfigFile = datastoreHome + "/conf/store.xml"; this.serverConfigFile = datastoreHome + "/conf/server.xml";
this.serverConfig = new ServerConfig(); this.storeConfigFile = datastoreHome + "/conf/store.xml";
this.storeConfigs = new HashMap<String, StoreConfig>(); this.serverConfig = new ServerConfig();
this.solrConfigs = new HashMap<String, SolrConfig>(); this.storeConfigs = new HashMap<String, StoreConfig>();
this.mongoConfigs = new HashMap<String, MongoConfig>(); this.solrConfigs = new HashMap<String, SolrConfig>();
load(); this.mongoConfigs = new HashMap<String, MongoConfig>();
} this.load();
}
public ServerConfig getServerConfig() {
return serverConfig; public ServerConfig getServerConfig() {
} return this.serverConfig;
}
public SolrConfig getSolrConfigById(String id) {
return solrConfigs.get(id); public SolrConfig getSolrConfigById(final String id) {
} return this.solrConfigs.get(id);
}
public MongoConfig getMongoConfigById(String id) {
return this.mongoConfigs.get(id); public MongoConfig getMongoConfigById(final String id) {
} return this.mongoConfigs.get(id);
}
public StoreConfig getStoreConfig(String storeName) {
return this.storeConfigs.get(storeName); public StoreConfig getStoreConfig(final String storeName) {
} return this.storeConfigs.get(storeName);
}
public Set<String> getStoreNames() {
return Collections.unmodifiableSet(this.storeConfigs.keySet()); public Set<String> getStoreNames() {
} return Collections.<String>unmodifiableSet((Set<? extends String>)this.storeConfigs.keySet());
}
public void reload() throws ConfigurationException {
load(); @Override
} public void reload() throws ConfigurationException {
this.load();
private synchronized void load() throws ConfigurationException { }
Document document = read(this.serverConfigFile);
serverConfig.reload(document.selectSingleNode("//datastore//server")); private synchronized void load() throws ConfigurationException {
initSolrConfigs(document); Document document = this.read(this.serverConfigFile);
initMongoConfigs(document); this.serverConfig.reload(document.selectSingleNode("//datastore//server"));
document = read(this.storeConfigFile); this.initSolrConfigs(document);
initStoreConfigs(document, solrConfigs, mongoConfigs); this.initMongoConfigs(document);
} document = this.read(this.storeConfigFile);
this.initStoreConfigs(document, this.solrConfigs, this.mongoConfigs);
synchronized StoreConfig getOrCreateStoreConfig(String storeName) { }
StoreConfig ret = this.storeConfigs.get(storeName);
if (null == ret) { synchronized StoreConfig getOrCreateStoreConfig(final String storeName) {
ret = new StoreConfig(this, storeName); StoreConfig ret = this.storeConfigs.get(storeName);
storeConfigs.put(storeName, ret); if (null == ret) {
} ret = new StoreConfig(this, storeName);
return ret; this.storeConfigs.put(storeName, ret);
} }
return ret;
private synchronized SolrConfig getOrCreateSolrConfig(String solrId) { }
SolrConfig ret = this.solrConfigs.get(solrId);
if (null == ret) { private synchronized SolrConfig getOrCreateSolrConfig(final String solrId) {
ret = new SolrConfig(this, solrId); SolrConfig ret = this.solrConfigs.get(solrId);
solrConfigs.put(solrId, ret); if (null == ret) {
} ret = new SolrConfig(this, solrId);
return ret; this.solrConfigs.put(solrId, ret);
} }
return ret;
private synchronized MongoConfig getOrCreateMongoConfig(String mongoId) throws ConfigurationException { }
MongoConfig ret = this.mongoConfigs.get(mongoId);
if (null == ret) { private synchronized MongoConfig getOrCreateMongoConfig(final String mongoId) throws ConfigurationException {
ret = new MongoConfig(mongoId); MongoConfig ret = this.mongoConfigs.get(mongoId);
mongoConfigs.put(mongoId, ret); if (null == ret) {
} ret = new MongoConfig(mongoId);
return ret; this.mongoConfigs.put(mongoId, ret);
} }
return ret;
private void initSolrConfigs(Document document) throws ConfigurationException { }
List<Node> solrNodes = document.selectNodes("//datastore//solr");
if (null == solrNodes || solrNodes.isEmpty()) { private void initSolrConfigs(final Document document) throws ConfigurationException {
throw new ConfigurationException("no solr is configured in " + serverConfigFile + " !"); final List<Node> solrNodes = (List<Node>)document.selectNodes("//datastore//solr");
} if (null == solrNodes || solrNodes.isEmpty()) {
Map<String, SolrConfig> newSolrConfigs = new HashMap<String, SolrConfig>(); throw new ConfigurationException("no solr is configured in " + this.serverConfigFile + " !");
for (Node solrNode : solrNodes) { }
String id = ((Element) solrNode).attributeValue("id"); final Map<String, SolrConfig> newSolrConfigs = new HashMap<String, SolrConfig>();
SolrConfig config = getOrCreateSolrConfig(id); for (final Node solrNode : solrNodes) {
config.reload(solrNode); final String id = ((Element)solrNode).attributeValue("id");
newSolrConfigs.put(id, config); final SolrConfig config = this.getOrCreateSolrConfig(id);
} config.reload(solrNode);
this.solrConfigs.clear(); newSolrConfigs.put(id, config);
this.solrConfigs.putAll(newSolrConfigs); }
} this.solrConfigs.clear();
this.solrConfigs.putAll(newSolrConfigs);
private void initMongoConfigs(Document document) throws ConfigurationException { }
List<Node> mongoNodes = document.selectNodes("//datastore//mongo");
if (null == mongoNodes || mongoNodes.isEmpty()) { private void initMongoConfigs(final Document document) throws ConfigurationException {
throw new ConfigurationException("no mongo is configured in " + serverConfigFile + " !"); final List<Node> mongoNodes = (List<Node>)document.selectNodes("//datastore//mongo");
} if (null == mongoNodes || mongoNodes.isEmpty()) {
Map<String, MongoConfig> newMongoConfigs = new HashMap<String, MongoConfig>(); throw new ConfigurationException("no mongo is configured in " + this.serverConfigFile + " !");
for (Node mongoNode : mongoNodes) { }
String id = ((Element) mongoNode).attributeValue("id"); final Map<String, MongoConfig> newMongoConfigs = new HashMap<String, MongoConfig>();
MongoConfig mongoConfig = getOrCreateMongoConfig(id); for (final Node mongoNode : mongoNodes) {
mongoConfig.reload(mongoNode); final String id = ((Element)mongoNode).attributeValue("id");
newMongoConfigs.put(id, mongoConfig); final MongoConfig mongoConfig = this.getOrCreateMongoConfig(id);
} mongoConfig.reload(mongoNode);
this.mongoConfigs.clear(); newMongoConfigs.put(id, mongoConfig);
this.mongoConfigs.putAll(newMongoConfigs); }
} this.mongoConfigs.clear();
this.mongoConfigs.putAll(newMongoConfigs);
private void initStoreConfigs(Document document, Map<String, SolrConfig> solrConfigMap, }
Map<String, MongoConfig> mongoConfigMap) throws ConfigurationException {
List<Node> storeNodes = document.selectNodes("//datastore//store"); private void initStoreConfigs(final Document document, final Map<String, SolrConfig> solrConfigMap, final Map<String, MongoConfig> mongoConfigMap) throws ConfigurationException {
if (null == storeNodes || storeNodes.isEmpty()) { final List<Node> storeNodes = (List<Node>)document.selectNodes("//datastore//store");
throw new ConfigurationException("no store is configured in " + storeConfigFile + " !"); if (null == storeNodes || storeNodes.isEmpty()) {
} throw new ConfigurationException("no store is configured in " + this.storeConfigFile + " !");
Map<String, StoreConfig> newStoreConfigs = new HashMap<String, StoreConfig>(); }
for (Node storeNode : storeNodes) { final Map<String, StoreConfig> newStoreConfigs = new HashMap<String, StoreConfig>();
String name = ((Element) storeNode).attributeValue("name"); for (final Node storeNode : storeNodes) {
final StoreConfig storeConfig = getOrCreateStoreConfig(name); final String name = ((Element)storeNode).attributeValue("name");
storeConfig.reload(storeNode); final StoreConfig storeConfig = this.getOrCreateStoreConfig(name);
newStoreConfigs.put(name, storeConfig); storeConfig.reload(storeNode);
} newStoreConfigs.put(name, storeConfig);
this.storeConfigs.clear(); }
this.storeConfigs.putAll(newStoreConfigs); this.storeConfigs.clear();
} this.storeConfigs.putAll(newStoreConfigs);
}
private Document read(String configFile) throws ConfigurationException {
try { private Document read(final String configFile) throws ConfigurationException {
return reader.read(new File(configFile)); try {
} catch (DocumentException e) { return this.reader.read(new File(configFile));
throw new ConfigurationException("error read datastore config file: " + configFile, e); }
} catch (DocumentException e) {
} throw new ConfigurationException("error read datastore config file: " + configFile, (Throwable)e);
}
@Override }
public String toString() {
StringBuilder ret = new StringBuilder(); @Override
ret.append("server config file:").append(this.serverConfigFile).append(", store config file: ").append( public String toString() {
this.storeConfigFile).append(", readOnly:").append(this.readOnly); final StringBuilder ret = new StringBuilder();
return ret.toString(); ret.append("server config file:").append(this.serverConfigFile).append(", store config file: ").append(this.storeConfigFile).append(", readOnly:").append(this.readOnly);
} return ret.toString();
}
public boolean isReadOnly() {
return readOnly; public boolean isReadOnly() {
} return this.readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly; public void setReadOnly(final boolean readOnly) {
} this.readOnly = readOnly;
}
} }
@@ -1,127 +1,118 @@
package com.fangjia.datastore.config; package com.fangjia.datastore.config;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.HashCodeBuilder;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import java.util.regex.Pattern;
import java.util.Date;
import java.util.Map;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class Field { public class Field
private String name; {
private FieldTypeEnum type; private String name;
private boolean required; private FieldTypeEnum type;
private boolean required;
Field() {
} Field() {
}
public String getName() {
return name; public String getName() {
} return this.name;
}
public FieldTypeEnum getType() {
return type; public FieldTypeEnum getType() {
} return this.type;
}
void setName(String name) {
if (StringUtils.isEmpty(name)) { void setName(final String name) {
throw new IllegalArgumentException("invalid field name:" + name); if (StringUtils.isEmpty(name)) {
} throw new IllegalArgumentException("invalid field name:" + name);
this.name = name; }
} this.name = name;
}
void setType(FieldTypeEnum type) {
if (null == type) { void setType(final FieldTypeEnum type) {
throw new IllegalArgumentException("invalid type of field[" + name + "]:" + type); if (null == type) {
} throw new IllegalArgumentException("invalid type of field[" + this.name + "]:" + type);
this.type = type; }
} this.type = type;
}
public boolean isRequired() {
return required; public boolean isRequired() {
} return this.required;
}
void setRequired(boolean required) {
this.required = required; void setRequired(final boolean required) {
} this.required = required;
}
public boolean isBigField() {
return this.type == FieldTypeEnum.TEXT; public boolean isBigField() {
} return this.type == FieldTypeEnum.TEXT;
}
/**
* 验证一个值是否匹配其对应的类型 public boolean validate(final Object value) {
* if (this.required && value == null) {
* @param value return false;
* @return 匹配则返回true,不匹配返回false }
*/ if (value == null) {
public boolean validate(Object value) { return true;
if (this.required && value == null) { }
return false; final Class<?> valueClass = value.getClass();
} switch (this.type) {
if (value == null) { case BOOLEAN:
return true; return valueClass == Boolean.TYPE || valueClass == Boolean.class;
} case BYTE:
Class<?> valueClass = value.getClass(); return valueClass == Byte.TYPE || valueClass == Byte.class;
switch (this.type) { case INTEGER:
case BOOLEAN: return valueClass == Integer.TYPE || valueClass == Integer.class;
return valueClass == boolean.class || valueClass == Boolean.class; case LONG:
case BYTE: return valueClass == Long.TYPE || valueClass == Long.class;
return valueClass == byte.class || valueClass == Byte.class; case DOUBLE:
case INTEGER: return valueClass == Double.TYPE || valueClass == Double.class;
return valueClass == int.class || valueClass == Integer.class; case STRING:
case LONG: case TEXT:
return valueClass == long.class || valueClass == Long.class; return valueClass == String.class;
case DOUBLE: case LIST:
return valueClass == double.class || valueClass == Double.class; return value instanceof List;
case STRING: case MAP:
case TEXT: return value instanceof Map;
return valueClass == String.class; case DATETIME:
case LIST: return value instanceof Date;
return value instanceof List; case BINARY:
case MAP: return valueClass == byte[].class;
return value instanceof Map; case REGEXP:
case DATETIME: return valueClass == Pattern.class;
return value instanceof Date; case OBJECTID:
case BINARY: return valueClass == ObjectId.class;
return valueClass == byte[].class; default:
case REGEXP: throw new RuntimeException("un cased type:" + this);
return valueClass == Pattern.class; }
case OBJECTID: }
return valueClass == ObjectId.class;
default: @Override
throw new RuntimeException("un cased type:" + this); public int hashCode() {
} return new HashCodeBuilder().append((Object)this.name).append((Object)this.type).append(this.required).toHashCode();
} }
@Override @Override
public int hashCode() { public boolean equals(final Object obj) {
return new HashCodeBuilder().append(this.name).append(this.type).append(this.required).toHashCode(); if (obj == this) {
} return true;
}
@Override if (null == obj) {
public boolean equals(Object obj) { return false;
if (obj == this) { }
return true; if (!(obj instanceof Field)) {
} return false;
if (null == obj) { }
return false; final Field other = (Field)obj;
} return new EqualsBuilder().append((Object)this.name, (Object)other.name).append((Object)this.type, (Object)other.type).append(this.required, other.required).isEquals();
if (!(obj instanceof Field)) { }
return false;
} @Override
Field other = (Field) obj; public String toString() {
return new EqualsBuilder().append(this.name, other.name).append(this.type, other.type) return "{field:" + this.name + ", type:" + this.type + ", required:" + this.required + "}";
.append(this.required, other.required).isEquals(); }
}
@Override
public String toString() {
return new StringBuilder().append("{field:").append(name).append(", type:").append(type).append(", required:")
.append(required).append("}").toString();
}
} }
@@ -1,22 +1,31 @@
package com.fangjia.datastore.config; package com.fangjia.datastore.config;
public enum FieldTypeEnum { public enum FieldTypeEnum
BOOLEAN, BYTE, INTEGER, LONG, DOUBLE, STRING, TEXT, LIST, MAP, DATETIME, BINARY, REGEXP, OBJECTID; {
BOOLEAN,
private FieldTypeEnum() { BYTE,
} INTEGER,
LONG,
public String getType() { DOUBLE,
return this.name().toLowerCase(); STRING,
} TEXT,
LIST,
public static FieldTypeEnum parse(String type) { MAP,
for (FieldTypeEnum typeEnum : FieldTypeEnum.values()) { DATETIME,
if (typeEnum.name().toLowerCase().equals(type)) { BINARY,
return typeEnum; REGEXP,
} OBJECTID;
}
return null; public String getType() {
} return this.name().toLowerCase();
}
public static FieldTypeEnum parse(final String type) {
for (final FieldTypeEnum typeEnum : values()) {
if (typeEnum.name().toLowerCase().equals(type)) {
return typeEnum;
}
}
return null;
}
} }
@@ -2,87 +2,98 @@ package com.fangjia.datastore.config;
import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.HashCodeBuilder;
import org.dom4j.Node;
import com.fangjia.datastore.ConfigurationException;
import com.fangjia.datastore.utils.XmlUtils; import com.fangjia.datastore.utils.XmlUtils;
import org.dom4j.Node;
import com.mongodb.MongoURI;
import org.apache.commons.lang.StringUtils;
import com.fangjia.datastore.ConfigurationException;
import com.mongodb.Mongo; import com.mongodb.Mongo;
public final class MongoConfig { public final class MongoConfig
{
private String host; private String host;
private int port; private String uri;
private final String id; private int port;
private Mongo mongo; private final String id;
private Mongo mongo;
MongoConfig(String id) throws ConfigurationException {
this.id = id; MongoConfig(final String id) throws ConfigurationException {
} this.id = id;
}
private synchronized void init() throws ConfigurationException {
if (null == mongo) { private synchronized void init() throws ConfigurationException {
try { if (null == this.mongo) {
mongo = new Mongo(host, port); try {
} catch (Exception e) { MongoURI mongoURI;
throw new ConfigurationException("error init mongo[" + host + ":" + port, e); if (StringUtils.isNotBlank(this.uri)) {
} mongoURI = new MongoURI(this.uri);
} }
} else {
mongoURI = new MongoURI("mongodb://" + this.host + ":" + this.port);
public Mongo getMongo() throws ConfigurationException { }
if (null == mongo) { this.mongo = new Mongo(mongoURI);
init(); }
} catch (Exception e) {
return mongo; throw new ConfigurationException("error init mongo[" + this.host + ":" + this.port, e);
} }
}
synchronized void reload(Node mongoNode) throws ConfigurationException { }
String host = XmlUtils.getNodeValue(mongoNode, "host", "datastore.mongo.db.fangjia.com");
int port = XmlUtils.getNodeValueAsInt(mongoNode, "port", 27017); public Mongo getMongo() throws ConfigurationException {
if (host.equals(this.host) && this.port == port) { if (null == this.mongo) {
return; this.init();
} }
this.host = host; return this.mongo;
this.port = port; }
if (null != mongo) {
try { synchronized void reload(final Node mongoNode) throws ConfigurationException {
init(); final String host = XmlUtils.getNodeValue(mongoNode, "host", "datastore.mongo.db.fangjia.com");
} catch (Exception e) { final int port = XmlUtils.getNodeValueAsInt(mongoNode, "port", 27017);
throw new ConfigurationException("error init mongo[" + host + ":" + port, e); final String uri = XmlUtils.getNodeValue(mongoNode, "uri", "");
} if (host.equals(this.host) && this.port == port) {
} return;
} }
this.host = host;
@Override this.port = port;
public int hashCode() { this.uri = uri;
return new HashCodeBuilder().append(this.host).append(this.port).append(this.id).toHashCode(); if (null != this.mongo) {
} try {
this.init();
@Override }
public boolean equals(Object obj) { catch (Exception e) {
if (obj == this) { throw new ConfigurationException("error init mongo[" + host + ":" + port, e);
return true; }
} }
if (null == obj) { }
return false;
} @Override
if (!(obj instanceof MongoConfig)) { public int hashCode() {
return false; return new HashCodeBuilder().append((Object)this.host).append(this.port).append((Object)this.id).toHashCode();
} }
MongoConfig other = (MongoConfig) obj;
return new EqualsBuilder().append(this.id, other.id).append(this.host, other.host).append(this.port, other.port) @Override
.isEquals(); public boolean equals(final Object obj) {
} if (obj == this) {
return true;
@Override }
public String toString() { if (null == obj) {
StringBuilder ret = new StringBuilder(); return false;
ret.append('{'); }
ret.append("id:").append(this.id); if (!(obj instanceof MongoConfig)) {
ret.append(", host:").append(this.host); return false;
ret.append(", port:").append(this.port); }
ret.append('}'); final MongoConfig other = (MongoConfig)obj;
return ret.toString(); return new EqualsBuilder().append((Object)this.id, (Object)other.id).append((Object)this.host, (Object)other.host).append(this.port, other.port).isEquals();
} }
@Override
public String toString() {
final StringBuilder ret = new StringBuilder();
ret.append('{');
ret.append("id:").append(this.id);
ret.append(", host:").append(this.host);
ret.append(", port:").append(this.port);
ret.append('}');
return ret.toString();
}
} }
@@ -2,6 +2,7 @@ package com.fangjia.datastore.config;
import com.fangjia.datastore.ConfigurationException; import com.fangjia.datastore.ConfigurationException;
public interface Reloadable { public interface Reloadable
void reload() throws ConfigurationException; {
void reload() throws ConfigurationException;
} }
@@ -1,74 +1,72 @@
package com.fangjia.datastore.config; package com.fangjia.datastore.config;
import com.fangjia.datastore.utils.XmlUtils;
import com.fangjia.datastore.ConfigurationException;
import org.dom4j.Node; import org.dom4j.Node;
import com.fangjia.datastore.ConfigurationException; public final class ServerConfig
import com.fangjia.datastore.utils.XmlUtils; {
private int port;
public final class ServerConfig { private boolean disableLogging;
private int port; private long performanceLogFilterMaxTime;
private boolean disableLogging; private int minaReadBufferSize;
private long performanceLogFilterMaxTime; private int cursorExpirationMinutes;
private int minaReadBufferSize; private int defaultCursorLimit;
private int cursorExpirationMinutes; private int maxConnections;
private int defaultCursorLimit; private int triggerBatchSize;
private int maxConnections; private int reIndexBatchSize;
private int triggerBatchSize;
private int reIndexBatchSize; ServerConfig() {
}
ServerConfig() {
super(); void reload(final Node server) throws ConfigurationException {
} if (null == server) {
throw new ConfigurationException("no server is configured!");
void reload(Node server) throws ConfigurationException { }
if (null == server) { this.port = XmlUtils.getNodeValueAsInt(server, "port", 27017);
throw new ConfigurationException("no server is configured!"); this.disableLogging = XmlUtils.getNodeValueAsBoolean(server, "disableLogging", false);
} this.performanceLogFilterMaxTime = XmlUtils.getNodeValueAsLong(server, "performanceLogFilterMaxTime", 1000L);
this.port = XmlUtils.getNodeValueAsInt(server, "port", 27017); this.minaReadBufferSize = XmlUtils.getNodeValueAsInt(server, "minaReadBufferSize", 20480);
this.disableLogging = XmlUtils.getNodeValueAsBoolean(server, "disableLogging", false); this.cursorExpirationMinutes = XmlUtils.getNodeValueAsInt(server, "cursorExpirationMinutes", 5);
this.performanceLogFilterMaxTime = XmlUtils.getNodeValueAsLong(server, "performanceLogFilterMaxTime", 1000); this.defaultCursorLimit = XmlUtils.getNodeValueAsInt(server, "defaultCursorLimit", 20);
this.minaReadBufferSize = XmlUtils.getNodeValueAsInt(server, "minaReadBufferSize", 20480); this.maxConnections = XmlUtils.getNodeValueAsInt(server, "maxConnections", 10);
this.cursorExpirationMinutes = XmlUtils.getNodeValueAsInt(server, "cursorExpirationMinutes", 5); this.triggerBatchSize = XmlUtils.getNodeValueAsInt(server, "triggerBatchSize", 200);
this.defaultCursorLimit = XmlUtils.getNodeValueAsInt(server, "defaultCursorLimit", 20); this.reIndexBatchSize = XmlUtils.getNodeValueAsInt(server, "reIndexBatchSize", 200);
this.maxConnections = XmlUtils.getNodeValueAsInt(server, "maxConnections", 10); }
this.triggerBatchSize = XmlUtils.getNodeValueAsInt(server, "triggerBatchSize", 200);
this.reIndexBatchSize = XmlUtils.getNodeValueAsInt(server, "reIndexBatchSize", 200); public int getPort() {
} return this.port;
}
public int getPort() {
return port; public boolean isDisableLogging() {
} return this.disableLogging;
}
public boolean isDisableLogging() {
return disableLogging; public long getPerformanceLogFilterMaxTime() {
} return this.performanceLogFilterMaxTime;
}
public long getPerformanceLogFilterMaxTime() {
return performanceLogFilterMaxTime; public int getMinaReadBufferSize() {
} return this.minaReadBufferSize;
}
public int getMinaReadBufferSize() {
return minaReadBufferSize; public int getCursorExpirationMinutes() {
} return this.cursorExpirationMinutes;
}
public int getCursorExpirationMinutes() {
return cursorExpirationMinutes; public int getDefaultCursorLimit() {
} return this.defaultCursorLimit;
}
public int getDefaultCursorLimit() {
return defaultCursorLimit; public int getMaxConnections() {
} return this.maxConnections;
}
public int getMaxConnections() {
return maxConnections; public int getTriggerBatchSize() {
} return this.triggerBatchSize;
}
public int getTriggerBatchSize() {
return triggerBatchSize; public int getReIndexBatchSize() {
} return this.reIndexBatchSize;
}
public int getReIndexBatchSize() {
return reIndexBatchSize;
}
} }
@@ -1,132 +1,132 @@
package com.fangjia.datastore.config; package com.fangjia.datastore.config;
import com.fangjia.datastore.ConfigurationException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import com.fangjia.datastore.utils.XmlUtils;
import org.dom4j.Node; import org.dom4j.Node;
import com.fangjia.datastore.ConfigurationException; public class SolrConfig
import com.fangjia.datastore.utils.XmlUtils; {
private final String id;
public class SolrConfig { private String host;
private final String id; private String home;
private String host; private final DataStoreConfig dataStoreConfig;
private String home; private String shards;
private final DataStoreConfig dataStoreConfig; private String slaves;
private String shards; private SolrConfig[] shardConfigs;
private String slaves; private SolrConfig[] slaveConfigs;
private SolrConfig[] shardConfigs; private String filter;
private SolrConfig[] slaveConfigs;
private String filter; SolrConfig(final DataStoreConfig dataStoreConfig, final String id) {
this.dataStoreConfig = dataStoreConfig;
SolrConfig(DataStoreConfig dataStoreConfig, String id) { this.id = id;
this.dataStoreConfig = dataStoreConfig; }
this.id = id;
} synchronized void reload(final Node solrNode) throws ConfigurationException {
this.host = this.removeLastSlash(XmlUtils.getNodeValue(solrNode, "host", null));
synchronized void reload(Node solrNode) throws ConfigurationException { this.shards = XmlUtils.getNodeValue(solrNode, "shards", null);
this.host = removeLastSlash(XmlUtils.getNodeValue(solrNode, "host", null)); this.slaves = XmlUtils.getNodeValue(solrNode, "slaves", null);
this.shards = XmlUtils.getNodeValue(solrNode, "shards", null); this.home = XmlUtils.getNodeValue(solrNode, "home", null);
this.slaves = XmlUtils.getNodeValue(solrNode, "slaves", null); if (StringUtils.isNotEmpty(this.shards) && StringUtils.isEmpty(this.home)) {
this.home = XmlUtils.getNodeValue(solrNode, "home", null); throw new ConfigurationException("[" + this.id + "] invalid home attribute:" + this.home);
if (StringUtils.isNotEmpty(shards) && StringUtils.isEmpty(home)) { }
throw new ConfigurationException("[" + id + "] invalid home attribute:" + home); if (StringUtils.isEmpty(this.shards) && StringUtils.isEmpty(this.slaves) && StringUtils.isEmpty(this.host)) {
} throw new ConfigurationException("[" + this.id + "] invalid host attribute:" + this.host);
if (StringUtils.isEmpty(shards) && StringUtils.isEmpty(slaves) && StringUtils.isEmpty(host)) { }
throw new ConfigurationException("[" + id + "] invalid host attribute:" + host); this.filter = this.removeLastSlash(XmlUtils.getNodeValue(solrNode, "filter", null));
} }
this.filter = removeLastSlash(XmlUtils.getNodeValue(solrNode, "filter", null));
} private SolrConfig[] getConfigs(final String ids) {
SolrConfig[] ret;
private SolrConfig[] getConfigs(String ids) { if (StringUtils.isBlank(ids)) {
SolrConfig[] ret; ret = new SolrConfig[0];
if (StringUtils.isBlank(ids)) { }
ret = new SolrConfig[0]; else {
} else { final String[] idSplit = ids.split(",");
String[] idSplit = ids.split(","); ret = new SolrConfig[idSplit.length];
ret = new SolrConfig[idSplit.length]; for (int i = 0; i < idSplit.length; ++i) {
for (int i = 0; i < idSplit.length; i++) { ret[i] = this.dataStoreConfig.getSolrConfigById(idSplit[i]);
ret[i] = dataStoreConfig.getSolrConfigById(idSplit[i]); }
} }
} return ret;
return ret; }
}
public SolrConfig[] getShardsConfigs() {
public SolrConfig[] getShardsConfigs() { if (null == this.shardConfigs) {
if (null == shardConfigs) { this.shardConfigs = this.getConfigs(this.shards);
shardConfigs = this.getConfigs(shards); }
} return this.shardConfigs;
return shardConfigs; }
}
public SolrConfig[] getSlaveConfigs() {
public SolrConfig[] getSlaveConfigs() { if (null == this.slaveConfigs) {
if (null == slaveConfigs) { this.slaveConfigs = this.getConfigs(this.slaves);
slaveConfigs = this.getConfigs(slaves); }
} return this.slaveConfigs;
return slaveConfigs; }
}
private String removeLastSlash(final String s) {
private String removeLastSlash(String s) { if (StringUtils.isEmpty(s)) {
if (StringUtils.isEmpty(s)) { return s;
return s; }
} if (s.charAt(s.length() - 1) == '/') {
if (s.charAt(s.length() - 1) == '/') { return s.substring(0, s.length() - 1);
return s.substring(0, s.length() - 1); }
} return s;
return s; }
}
public String getShardsParam(final String coreName) {
public String getShardsParam(String coreName) { final SolrConfig[] shardConfigs = this.getShardsConfigs();
SolrConfig[] shardConfigs = getShardsConfigs(); if (shardConfigs.length == 0) {
if (shardConfigs.length == 0) { return "";
return ""; }
} final StringBuilder ret = new StringBuilder();
StringBuilder ret = new StringBuilder(); for (int i = 0; i < shardConfigs.length; ++i) {
for (int i = 0; i < shardConfigs.length; i++) { ret.append(shardConfigs[i].host).append('/').append(coreName);
ret.append(shardConfigs[i].host).append('/').append(coreName); if (i < shardConfigs.length - 1) {
if (i < shardConfigs.length - 1) { ret.append(',');
ret.append(','); }
} }
} return ret.toString();
return ret.toString(); }
}
public String getId() {
public String getId() { return this.id;
return id; }
}
public String getHost() {
public String getHost() { return this.host;
return host; }
}
public DataStoreConfig getDataStoreConfig() {
public DataStoreConfig getDataStoreConfig() { return this.dataStoreConfig;
return dataStoreConfig; }
}
public String getShards() {
public String getShards() { return this.shards;
return shards; }
}
public String getFilter() {
public String getFilter() { return this.filter;
return filter; }
}
public String getHome() {
public String getHome() { return this.home;
return home; }
}
@Override
@Override public String toString() {
public String toString() { final StringBuilder ret = new StringBuilder();
StringBuilder ret = new StringBuilder(); ret.append('{');
ret.append('{'); ret.append("id: ").append(this.id);
ret.append("id: ").append(this.id); ret.append(", host: ").append(this.host);
ret.append(", host: ").append(this.host); ret.append(", shards: ").append(this.shards);
ret.append(", shards: ").append(this.shards); ret.append(", slaves: ").append(this.slaves);
ret.append(", slaves: ").append(this.slaves); ret.append('}');
ret.append('}'); return ret.toString();
return ret.toString(); }
}
public String getSlaves() {
public String getSlaves() { return this.slaves;
return slaves; }
}
} }
@@ -1,229 +1,208 @@
package com.fangjia.datastore.config; package com.fangjia.datastore.config;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import java.util.Iterator;
import java.util.List;
import com.fangjia.datastore.utils.XmlUtils;
import com.fangjia.datastore.ConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Element; import org.dom4j.Element;
import org.dom4j.Node; import org.dom4j.Node;
import java.util.HashMap;
import java.util.Map;
import com.fangjia.datastore.ConfigurationException; public final class StoreConfig
import com.fangjia.datastore.utils.XmlUtils; {
private final String name;
public final class StoreConfig { private int solrMaxTotalConnections;
private int solrMaxConnectionsPerHost;
private final String name; private SolrConfig[] masterSolrConfigs;
private int solrMaxTotalConnections; private SolrConfig masterSolrConfig;
private int solrMaxConnectionsPerHost; private SolrConfig slaveSolrConfig;
private SolrConfig[] masterSolrConfigs; private MongoConfig mongoConfig;
private SolrConfig masterSolrConfig; private boolean textFieldToGridFS;
private SolrConfig slaveSolrConfig; private final Trigger trigger;
private MongoConfig mongoConfig; private final Map<String, Field> fields;
private boolean textFieldToGridFS; private final DataStoreConfig dataStoreConfig;
private final Trigger trigger;
private final Map<String, Field> fields; StoreConfig(final DataStoreConfig dataStoreConfig, final String name) {
private final DataStoreConfig dataStoreConfig; this.dataStoreConfig = dataStoreConfig;
this.fields = new HashMap<String, Field>();
StoreConfig(DataStoreConfig dataStoreConfig, String name) { this.trigger = new Trigger();
this.dataStoreConfig = dataStoreConfig; this.name = name;
fields = new HashMap<String, Field>(); }
trigger = new Trigger();
this.name = name; synchronized void reload(final Node storeNode) throws ConfigurationException {
} final String solrMastersAttr = ((Element)storeNode).attributeValue("solrMasters");
if (StringUtils.isEmpty(solrMastersAttr)) {
synchronized void reload(Node storeNode) throws ConfigurationException { throw new ConfigurationException("[" + this.name + "] invalid solrMasters attribute:" + solrMastersAttr);
// init solr }
String solrMastersAttr = ((Element) storeNode).attributeValue("solrMasters"); final String[] solrMasterIds = solrMastersAttr.split(",");
if (StringUtils.isEmpty(solrMastersAttr)) { if (solrMasterIds.length > 2) {
throw new ConfigurationException("[" + name + "] invalid solrMasters attribute:" + solrMastersAttr); throw new ConfigurationException("[" + this.name + "] too many solr server configured:" + solrMastersAttr);
} }
String[] solrMasterIds = solrMastersAttr.split(","); this.masterSolrConfigs = new SolrConfig[solrMasterIds.length];
if (solrMasterIds.length > 2) { for (int i = 0; i < solrMasterIds.length; ++i) {
throw new ConfigurationException("[" + name + "] too many solr server configured:" + solrMastersAttr); this.masterSolrConfigs[i] = this.dataStoreConfig.getSolrConfigById(solrMasterIds[i]);
} if (null == this.masterSolrConfigs[i]) {
masterSolrConfigs = new SolrConfig[solrMasterIds.length]; throw new ConfigurationException("[" + this.name + "] unknown solr id: " + solrMasterIds[i]);
for (int i = 0; i < solrMasterIds.length; i++) { }
masterSolrConfigs[i] = dataStoreConfig.getSolrConfigById(solrMasterIds[i]); }
if (null == masterSolrConfigs[i]) { final String solrSlaveAttr = System.getProperty("datastore." + this.name + ".solrSlave", ((Element)storeNode).attributeValue("solrSlave"));
throw new ConfigurationException("[" + name + "] unknown solr id: " + solrMasterIds[i]); if (StringUtils.isEmpty(solrSlaveAttr)) {
} throw new ConfigurationException("[" + this.name + "] invalid solrSlave attribute:" + solrSlaveAttr);
} }
this.slaveSolrConfig = this.dataStoreConfig.getSolrConfigById(solrSlaveAttr);
String solrSlaveAttr = System.getProperty("datastore." + name + ".solrSlave", ((Element) storeNode) if (null == this.slaveSolrConfig) {
.attributeValue("solrSlave")); throw new ConfigurationException("[" + this.name + "] unknown solr id: " + solrSlaveAttr);
if (StringUtils.isEmpty(solrSlaveAttr)) { }
throw new ConfigurationException("[" + name + "] invalid solrSlave attribute:" + solrSlaveAttr); final String solrMasterAttr = System.getProperty("datastore." + this.name + ".solrMaster", ((Element)storeNode).attributeValue("solrMaster"));
} if (StringUtils.isEmpty(solrMasterAttr)) {
slaveSolrConfig = dataStoreConfig.getSolrConfigById(solrSlaveAttr); throw new ConfigurationException("[" + this.name + "] invalid solrMaster attribute:" + solrMasterAttr);
if (null == slaveSolrConfig) { }
throw new ConfigurationException("[" + name + "] unknown solr id: " + solrSlaveAttr); this.masterSolrConfig = this.dataStoreConfig.getSolrConfigById(solrMasterAttr);
} if (null == this.masterSolrConfig) {
throw new ConfigurationException("[" + this.name + "] unknown solr id: " + solrMasterAttr);
String solrMasterAttr = System.getProperty("datastore." + name + ".solrMaster", ((Element) storeNode) }
.attributeValue("solrMaster")); if (this.slaveSolrConfig.getShardsConfigs().length != this.masterSolrConfig.getShardsConfigs().length) {
if (StringUtils.isEmpty(solrMasterAttr)) { throw new ConfigurationException("[" + this.name + "] master and slave shard count must equals !");
throw new ConfigurationException("[" + name + "] invalid solrMaster attribute:" + solrMasterAttr); }
} this.solrMaxConnectionsPerHost = XmlUtils.getNodeValueAsInt(storeNode, "solrMaxConnectionsPerHost", 300);
masterSolrConfig = dataStoreConfig.getSolrConfigById(solrMasterAttr); if (this.slaveSolrConfig.getShardsConfigs().length > 0) {
if (null == masterSolrConfig) { this.solrMaxTotalConnections = XmlUtils.getNodeValueAsInt(storeNode, "solrMaxTotalConnections", this.slaveSolrConfig.getShardsConfigs().length * this.solrMaxConnectionsPerHost);
throw new ConfigurationException("[" + name + "] unknown solr id: " + solrMasterAttr); }
} else {
this.solrMaxTotalConnections = XmlUtils.getNodeValueAsInt(storeNode, "solrMaxTotalConnections", this.solrMaxConnectionsPerHost);
if (slaveSolrConfig.getShardsConfigs().length != masterSolrConfig.getShardsConfigs().length) { }
throw new ConfigurationException("[" + name + "] master and slave shard count must equals !"); final String mongoId = ((Element)storeNode).attributeValue("mongo");
} final MongoConfig mongoConfig = this.dataStoreConfig.getMongoConfigById(mongoId);
if (null == mongoConfig) {
// solr connections defaults throw new ConfigurationException("[" + this.name + "] unknown mongo id: " + mongoId);
this.solrMaxConnectionsPerHost = XmlUtils.getNodeValueAsInt(storeNode, "solrMaxConnectionsPerHost", 300); }
if (slaveSolrConfig.getShardsConfigs().length > 0) { this.mongoConfig = mongoConfig;
this.solrMaxTotalConnections = XmlUtils.getNodeValueAsInt(storeNode, "solrMaxTotalConnections", slaveSolrConfig this.textFieldToGridFS = XmlUtils.getNodeValueAsBoolean(storeNode, "textFieldToGridFS", false);
.getShardsConfigs().length final Map<String, Field> newFields = new HashMap<String, Field>();
* solrMaxConnectionsPerHost); final List<Node> fieldNodes = (List<Node>)storeNode.selectNodes("schema//field");
} else { for (final Node fieldNode : fieldNodes) {
this.solrMaxTotalConnections = XmlUtils.getNodeValueAsInt(storeNode, "solrMaxTotalConnections", final Element element = (Element)fieldNode;
solrMaxConnectionsPerHost); final String fieldName = element.attributeValue("name");
} final Field field = this.getOrCreateField(fieldName);
field.setName(fieldName);
// init mongo field.setRequired(Boolean.parseBoolean(element.attributeValue("required")));
String mongoId = ((Element) storeNode).attributeValue("mongo"); field.setType(FieldTypeEnum.parse(element.attributeValue("type")));
MongoConfig mongoConfig = dataStoreConfig.getMongoConfigById(mongoId); newFields.put(fieldName, field);
if (null == mongoConfig) { }
throw new ConfigurationException("[" + name + "] unknown mongo id: " + mongoId); this.fields.clear();
} this.fields.putAll(newFields);
this.mongoConfig = mongoConfig; final Element triggerNode = (Element)storeNode.selectSingleNode("trigger");
if (triggerNode != null) {
// init other config this.trigger.setInterface(triggerNode.attributeValue("interface"));
this.textFieldToGridFS = XmlUtils.getNodeValueAsBoolean(storeNode, "textFieldToGridFS", false); }
}
// init fields
Map<String, Field> newFields = new HashMap<String, Field>(); public Trigger getTrigger() {
List<Node> fieldNodes = storeNode.selectNodes("schema//field"); return this.trigger;
for (Node fieldNode : fieldNodes) { }
Element element = (Element) fieldNode;
String fieldName = element.attributeValue("name"); public Field getField(final String fieldName) {
Field field = getOrCreateField(fieldName); return this.fields.get(fieldName);
field.setName(fieldName); }
field.setRequired(Boolean.parseBoolean(element.attributeValue("required")));
field.setType(FieldTypeEnum.parse(element.attributeValue("type"))); public boolean containsField(final String fieldName) {
newFields.put(fieldName, field); return this.fields.containsKey(fieldName);
} }
this.fields.clear();
this.fields.putAll(newFields); public boolean isFieldValueLegal(final String fieldName, final Object value) {
if ("_id".equals(fieldName)) {
// init triggers return value instanceof ObjectId;
Element triggerNode = (Element) storeNode.selectSingleNode("trigger"); }
if(triggerNode != null) { if (this.fields.containsKey(fieldName)) {
trigger.setInterface(triggerNode.attributeValue("interface")); final Field field = this.fields.get(fieldName);
} return field.validate(value);
}
} return false;
}
public Trigger getTrigger() {
return this.trigger; public boolean isBigField(final String fieldName) {
} return this.fields.get(fieldName).isBigField();
}
public Field getField(String fieldName) {
return this.fields.get(fieldName); public Collection<Field> getFields() {
} return Collections.<Field>unmodifiableCollection((Collection<? extends Field>)this.fields.values());
}
public boolean containsField(String fieldName) {
return this.fields.containsKey(fieldName); synchronized Field getOrCreateField(final String fieldName) {
} if (StringUtils.isEmpty(fieldName)) {
throw new IllegalArgumentException("fieldName can not be null or empty!");
public boolean isFieldValueLegal(String fieldName, Object value) { }
if ("_id".equals(fieldName)) { Field ret = this.fields.get(fieldName);
return value instanceof ObjectId; if (null == ret) {
} ret = new Field();
if (fields.containsKey(fieldName)) { ret.setName(fieldName);
Field field = fields.get(fieldName); this.fields.put(fieldName, ret);
return field.validate(value); }
} return ret;
return false; }
}
public String getName() {
public boolean isBigField(String fieldName) { return this.name;
return fields.get(fieldName).isBigField(); }
}
public MongoConfig getMongoConfig() {
public Collection<Field> getFields() { return this.mongoConfig;
return Collections.unmodifiableCollection(this.fields.values()); }
}
public DataStoreConfig getDataStoreConfig() {
synchronized Field getOrCreateField(String fieldName) { return this.dataStoreConfig;
if (StringUtils.isEmpty(fieldName)) { }
throw new IllegalArgumentException("fieldName can not be null or empty!");
} public boolean isTextFieldToGridFS() {
Field ret = this.fields.get(fieldName); return this.textFieldToGridFS;
if (null == ret) { }
ret = new Field();
ret.setName(fieldName); public SolrConfig getSlaveSolrConfig() {
this.fields.put(fieldName, ret); return this.slaveSolrConfig;
} }
return ret;
} public SolrConfig[] getMasterSolrConfigs() {
return this.masterSolrConfigs;
public String getName() { }
return name;
} public SolrConfig getMasterSolrConfig() {
return this.masterSolrConfig;
public MongoConfig getMongoConfig() { }
return mongoConfig;
} public int getSolrMaxTotalConnections() {
return this.solrMaxTotalConnections;
public DataStoreConfig getDataStoreConfig() { }
return dataStoreConfig;
} public int getSolrMaxConnectionsPerHost() {
return this.solrMaxConnectionsPerHost;
public boolean isTextFieldToGridFS() { }
return textFieldToGridFS;
} @Override
public String toString() {
public SolrConfig getSlaveSolrConfig() { final StringBuilder ret = new StringBuilder();
return slaveSolrConfig; ret.append("\n{");
} ret.append("\n\tname: ").append(this.name);
ret.append(",\n\tmasterSolrConfig: ").append(this.masterSolrConfig);
public SolrConfig[] getMasterSolrConfigs() { ret.append(",\n\tslaveSolrConfig: ").append(this.slaveSolrConfig);
return masterSolrConfigs; ret.append(",\n\tmongoConfig: ").append(this.mongoConfig);
} ret.append(",\n\tsolrMaxTotalConnections: ").append(this.solrMaxTotalConnections);
ret.append(",\n\tsolrMaxConnectionsPerHost: ").append(this.solrMaxConnectionsPerHost);
public SolrConfig getMasterSolrConfig() { ret.append(",\n\ttextFieldToGridFS: ").append(this.textFieldToGridFS);
return masterSolrConfig; ret.append(",\n\ttrigger: ").append(this.trigger);
} ret.append(",\n\tmasterSolrConfigs: [\n");
for (int i = 0; i < this.masterSolrConfigs.length; ++i) {
public int getSolrMaxTotalConnections() { ret.append('\t').append('\t').append(this.masterSolrConfigs[i]);
return solrMaxTotalConnections; if (i < this.masterSolrConfigs.length - 1) {
} ret.append(',');
}
public int getSolrMaxConnectionsPerHost() { ret.append('\n');
return solrMaxConnectionsPerHost; }
} ret.append("\t]\n}");
return ret.toString();
@Override }
public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("\n{");
ret.append("\n\tname: ").append(name);
ret.append(",\n\tmasterSolrConfig: ").append(masterSolrConfig);
ret.append(",\n\tslaveSolrConfig: ").append(this.slaveSolrConfig);
ret.append(",\n\tmongoConfig: ").append(mongoConfig);
ret.append(",\n\tsolrMaxTotalConnections: ").append(solrMaxTotalConnections);
ret.append(",\n\tsolrMaxConnectionsPerHost: ").append(this.solrMaxConnectionsPerHost);
ret.append(",\n\ttextFieldToGridFS: ").append(this.textFieldToGridFS);
ret.append(",\n\ttrigger: ").append(trigger);
ret.append(",\n\tmasterSolrConfigs: [\n");
for (int i = 0; i < this.masterSolrConfigs.length; i++) {
ret.append('\t').append('\t').append(this.masterSolrConfigs[i]);
if (i < this.masterSolrConfigs.length - 1) {
ret.append(',');
}
ret.append('\n');
}
ret.append("\t]\n}");
return ret.toString();
}
} }
@@ -1,49 +1,49 @@
package com.fangjia.datastore.config; package com.fangjia.datastore.config;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.StringUtils;
public final class Trigger { public final class Trigger
private String interface_; {
private String interface_;
Trigger() {
} Trigger() {
}
public String getInterface() {
return interface_; public String getInterface() {
} return this.interface_;
}
void setInterface(String interface_) {
if (StringUtils.isEmpty(interface_) || !interface_.startsWith("http://")) { void setInterface(final String interface_) {
throw new IllegalArgumentException("invalid trigger interface: " + interface_); if (StringUtils.isEmpty(interface_) || !interface_.startsWith("http://")) {
} throw new IllegalArgumentException("invalid trigger interface: " + interface_);
this.interface_ = interface_; }
} this.interface_ = interface_;
}
@Override
public int hashCode() { @Override
return new HashCodeBuilder().append(this.interface_).toHashCode(); public int hashCode() {
} return new HashCodeBuilder().append((Object)this.interface_).toHashCode();
}
@Override
public boolean equals(Object obj) { @Override
if (null == obj) { public boolean equals(final Object obj) {
return false; if (null == obj) {
} return false;
if (this == obj) { }
return true; if (this == obj) {
} return true;
if (!(obj instanceof Trigger)) { }
return false; if (!(obj instanceof Trigger)) {
} return false;
Trigger other = (Trigger) obj; }
return new EqualsBuilder().append(this.interface_, other.interface_).isEquals(); final Trigger other = (Trigger)obj;
} return new EqualsBuilder().append((Object)this.interface_, (Object)other.interface_).isEquals();
}
@Override
public String toString() { @Override
return new StringBuilder().append("{interface=").append(interface_).append("}").toString(); public String toString() {
} return "{interface=" + this.interface_ + "}";
}
} }
@@ -1,19 +1,20 @@
package com.fangjia.datastore.handler; package com.fangjia.datastore.handler;
import com.fangjia.datastore.mongo.protocol.MongoMessage;
import com.fangjia.datastore.DataStore; import com.fangjia.datastore.DataStore;
import com.fangjia.datastore.DataStoreContext; import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.mongo.protocol.DeleteMessage; import com.fangjia.datastore.mongo.protocol.DeleteMessage;
public class DeleteMessageHandler extends MessageHandler<DeleteMessage> { public class DeleteMessageHandler extends MessageHandler<DeleteMessage>
{
public DeleteMessageHandler(DataStoreContext dataStoreContext) { public DeleteMessageHandler(final DataStoreContext dataStoreContext) {
super(dataStoreContext); super(dataStoreContext);
} }
public void messageReceived(DeleteMessage message,String ip) throws Exception { @Override
assertNotReadOnly(); public void messageReceived(final DeleteMessage message) throws Exception {
DataStore dataStore = this.dataStoreContext.getDataStore(message.getFullCollectionName()); this.assertNotReadOnly();
dataStore.remove(message.getSelector()); final DataStore dataStore = this.dataStoreContext.getDataStore(message.getFullCollectionName());
} dataStore.remove(message.getSelector());
}
} }
@@ -1,54 +1,59 @@
package com.fangjia.datastore.handler; package com.fangjia.datastore.handler;
import java.util.List; import com.fangjia.datastore.mongo.protocol.MongoMessage;
import com.mongodb.DBObject;
import org.bson.BSONObject; import com.fangjia.datastore.QueryResponse;
import com.fangjia.datastore.mongo.protocol.QueryMessage;
import com.fangjia.datastore.Cursor; import com.fangjia.datastore.Cursor;
import com.fangjia.datastore.DataStore; import com.fangjia.datastore.DataStore;
import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.QueryResponse;
import com.fangjia.datastore.mongo.protocol.GetMoreMessage;
import com.fangjia.datastore.mongo.protocol.QueryMessage;
import com.fangjia.datastore.mongo.protocol.ReplyMessage; import com.fangjia.datastore.mongo.protocol.ReplyMessage;
import org.bson.BSONObject;
import java.util.List;
import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.mongo.protocol.GetMoreMessage;
public class GetMoreMessageHandler extends MessageHandler<GetMoreMessage> { public class GetMoreMessageHandler extends MessageHandler<GetMoreMessage>
{
public GetMoreMessageHandler(DataStoreContext dataStoreContext) { public GetMoreMessageHandler(final DataStoreContext dataStoreContext) {
super(dataStoreContext); super(dataStoreContext);
} }
public void messageReceived(GetMoreMessage message) throws Exception { @Override
String fullCollectionName = message.getFullCollectionName(); public void messageReceived(final GetMoreMessage message) throws Exception {
if(fullCollectionName.contains("$cmd")){ final String fullCollectionName = message.getFullCollectionName();
ReplyMessage reply = prepareReplyMessage(message.getMessageHeader().getRequestID(), (List<? extends BSONObject>) null); if (fullCollectionName.contains("$cmd")) {
reply.setStartingFrom(0); final ReplyMessage reply = this.prepareReplyMessage(message.getMessageHeader().getRequestID(), (List<? extends BSONObject>)null);
this.writeMessage(reply); reply.setStartingFrom(0);
this.dataStoreContext.removeCursor(message.getCursorID()); this.writeMessage(reply);
return; this.dataStoreContext.removeCursor(message.getCursorID());
} return;
DataStore dataStore = this.dataStoreContext.getDataStore(message.getFullCollectionName()); }
Cursor cursor = this.dataStoreContext.getCursor(message.getCursorID()); final DataStore dataStore = this.dataStoreContext.getDataStore(message.getFullCollectionName());
if (null == cursor) { final Cursor cursor = this.dataStoreContext.getCursor(message.getCursorID());
ReplyMessage reply = prepareReplyMessage(message.getMessageHeader().getRequestID(), (List<? extends BSONObject>) null); if (null == cursor) {
reply.setStartingFrom(0); final ReplyMessage reply2 = this.prepareReplyMessage(message.getMessageHeader().getRequestID(), (List<? extends BSONObject>)null);
this.writeMessage(reply); reply2.setStartingFrom(0);
} else { this.writeMessage(reply2);
QueryMessage queryMessage = cursor.getQueryMessage(); }
QueryResponse response = dataStore.find(queryMessage.getRealQuery(), queryMessage.getReturnFieldSelector(), else {
queryMessage.getOrderByQuery(), queryMessage.getFacetQuery(), cursor.nextSkip(), final QueryMessage queryMessage = cursor.getQueryMessage();
message.getNumberToReturn() - 1, queryMessage.isBulkQuery(), queryMessage.isFromMaster()); final QueryResponse response = dataStore.find(queryMessage.getRealQuery(), queryMessage.getReturnFieldSelector(), queryMessage.getOrderByQuery(), queryMessage.getFacetQuery(), cursor.nextSkip(), this.useCursor() ? message.getNumberToReturn() : (message.getNumberToReturn() - 1), queryMessage.isBulkQuery(), queryMessage.isFromMaster());
ReplyMessage reply = prepareReplyMessage(message.getMessageHeader().getRequestID(), response.getDocList()); final List<DBObject> doc = response.getDocList();
reply.setStartingFrom(cursor.getSkip()); if (this.useCursor()) {
if (response.hasMore()) { doc.remove(0);
// cursor.setTotalCount(response.getNumFound()); }
// cursor.setLimit((int) response.getNumReturned()); final ReplyMessage reply3 = this.prepareReplyMessage(message.getMessageHeader().getRequestID(), (List<? extends BSONObject>)doc);
// this.dataStoreContext.addCursor(cursor); reply3.setStartingFrom(cursor.getSkip());
// reply.setCursorID(cursor.getId()); if (response.hasMore() && this.useCursor()) {
} else { cursor.setTotalCount(response.getNumFound());
this.dataStoreContext.removeCursor(cursor.getId()); cursor.setLimit(response.getNumReturned());
} this.dataStoreContext.addCursor(cursor);
this.writeMessage(reply); reply3.setCursorID(cursor.getId());
} }
} else {
this.dataStoreContext.removeCursor(cursor.getId());
}
this.writeMessage(reply3);
}
}
} }
@@ -1,115 +1,117 @@
package com.fangjia.datastore.handler; package com.fangjia.datastore.handler;
import java.util.ArrayList; import com.fangjia.datastore.mongo.protocol.MongoMessage;
import java.util.List; import java.util.Iterator;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.bson.BSONObject; import java.util.ArrayList;
import com.fangjia.datastore.solr.Index;
import java.util.Collection;
import com.fangjia.datastore.DataStore; import com.fangjia.datastore.DataStore;
import org.bson.BSONObject;
import java.util.List;
import com.fangjia.datastore.DataStoreContext; import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.mongo.protocol.InsertMessage; import com.fangjia.datastore.mongo.protocol.InsertMessage;
import com.fangjia.datastore.solr.Index;
import com.fangjia.datastore.solr.Index.IndexTypeEnum;
public class InsertMessageHandler extends MessageHandler<InsertMessage> { public class InsertMessageHandler extends MessageHandler<InsertMessage>
{
public InsertMessageHandler(DataStoreContext dataStoreContext) { public InsertMessageHandler(final DataStoreContext dataStoreContext) {
super(dataStoreContext); super(dataStoreContext);
} }
public void messageReceived(InsertMessage message,String ip) throws Exception { @Override
if (message.getFullCollectionName().endsWith("system.indexes")) { public void messageReceived(final InsertMessage message) throws Exception {
ensureIndex(message); if (message.getFullCollectionName().endsWith("system.indexes")) {
} else { this.ensureIndex(message);
insert(message); }
} else {
} this.insert(message);
}
/** }
* db.foo.insert()
* private void insert(final InsertMessage message) throws Exception {
* @param message this.assertNotReadOnly();
* @throws Exception final DataStore dataStore = this.dataStoreContext.getDataStore(message.getFullCollectionName());
*/ dataStore.save(message.getDocuments());
private void insert(InsertMessage message) throws Exception { }
assertNotReadOnly();
DataStore dataStore = this.dataStoreContext.getDataStore(message.getFullCollectionName()); private void ensureIndex(final InsertMessage message) throws Exception {
dataStore.save(message.getDocuments()); this.assertNotReadOnly();
} final DataStore dataStore = this.dataStoreContext.getDataStore(String.valueOf(message.getDocuments().get(0).get("ns")));
final List<Index> indexList = this.addToIndexList(message.getDocuments());
/** dataStore.ensureIndex(indexList);
* db.foo.ensureIndex() }
*
* @param message private List<Index> addToIndexList(final List<BSONObject> docList) {
* @throws Exception if (null == docList || docList.isEmpty()) {
*/ return null;
private void ensureIndex(InsertMessage message) throws Exception { }
assertNotReadOnly(); final List<Index> indexList = new ArrayList<Index>();
DataStore dataStore = this.dataStoreContext.getDataStore(String.valueOf(message.getDocuments().get(0).get("ns"))); for (final BSONObject bson : docList) {
List<Index> indexList = addToIndexList(message.getDocuments()); final BSONObject keys = (BSONObject)bson.get("key");
dataStore.ensureIndex(indexList); if (null == keys) {
} continue;
}
private List<Index> addToIndexList(List<BSONObject> docList) { for (final String key : keys.keySet()) {
if (null == docList || docList.isEmpty()) { final Object value = keys.get(key);
return null; if (value instanceof String) {
} final Index index = new Index(key, Index.IndexTypeEnum.parse((String)value));
List<Index> indexList = new ArrayList<Index>(); indexList.add(index);
for (BSONObject bson : docList) { }
BSONObject keys = (BSONObject) bson.get("key"); else if (value instanceof BSONObject) {
if (null == keys) { final Index index = new Index();
continue; index.setName(key);
} for (final String k : ((BSONObject)value).keySet()) {
for (String key : keys.keySet()) { final Object v = ((BSONObject)value).get(k);
Object value = keys.get(key); if (StringUtils.equalsIgnoreCase(k, "type")) {
if (value instanceof String) { if (!(v instanceof String)) {
Index index = new Index(key, IndexTypeEnum.parse((String) value)); continue;
indexList.add(index); }
} else if (value instanceof BSONObject) { index.setType(Index.IndexTypeEnum.parse((String)v));
// TODO: }
Index index = new Index(); else if (StringUtils.equalsIgnoreCase(k, "stored")) {
index.setName(key); if (!(v instanceof Boolean)) {
for (String k : ((BSONObject) value).keySet()) { continue;
Object v = ((BSONObject) value).get(k); }
if (StringUtils.equalsIgnoreCase(k, "type")) { index.setStored((Boolean) v);
if (v instanceof String) { }
index.setType(IndexTypeEnum.parse((String) v)); else if (StringUtils.equalsIgnoreCase(k, "indexed")) {
} if (!(v instanceof Boolean)) {
} else if (StringUtils.equalsIgnoreCase(k, "stored")) { continue;
if (v instanceof Boolean) { }
index.setStored((Boolean) v); index.setIndexed((Boolean)v);
} }
} else if (StringUtils.equalsIgnoreCase(k, "indexed")) { else if (StringUtils.equalsIgnoreCase(k, "multiValued")) {
if (v instanceof Boolean) { if (!(v instanceof Boolean)) {
index.setIndexed((Boolean) v); continue;
} }
index.setMultiValued((Boolean)v);
} else if (StringUtils.equalsIgnoreCase(k, "multiValued")) { }
if (v instanceof Boolean) { else if (StringUtils.equalsIgnoreCase(k, "dynamic")) {
index.setMultiValued((Boolean) v); if (!(v instanceof Boolean)) {
} continue;
} else if (StringUtils.equalsIgnoreCase(k, "dynamic")) { }
if (v instanceof Boolean) { index.setDynamic((Boolean)v);
index.setDynamic((Boolean) v); }
} else {
} else if (StringUtils.equalsIgnoreCase(k, "comments")) { if (!StringUtils.equalsIgnoreCase(k, "comments") || !(v instanceof String)) {
if (v instanceof String) { continue;
index.setComments((String) v); }
} index.setComments((String)v);
} }
} }
if (index.getType() == null) { if (index.getType() == null) {
throw new IllegalArgumentException("illegal schema field: type"); throw new IllegalArgumentException("illegal schema field: type");
} }
indexList.add(index); indexList.add(index);
} else { }
if (logger.isErrorEnabled()) { else {
logger.error("invalid key value of ensureIndex:{}", value); if (!this.logger.isErrorEnabled()) {
} continue;
} }
} this.logger.error("invalid key value of ensureIndex:{}", value);
} }
return indexList; }
} }
return indexList;
}
} }
@@ -1,23 +1,24 @@
package com.fangjia.datastore.handler; package com.fangjia.datastore.handler;
import com.fangjia.datastore.mongo.protocol.MongoMessage;
import java.util.Iterator;
import java.util.List; import java.util.List;
import com.fangjia.datastore.DataStoreContext; import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.mongo.protocol.KillCursorsMessage; import com.fangjia.datastore.mongo.protocol.KillCursorsMessage;
public class KillCursorsMessageHandler extends MessageHandler<KillCursorsMessage> { public class KillCursorsMessageHandler extends MessageHandler<KillCursorsMessage>
{
public KillCursorsMessageHandler(DataStoreContext dataStoreContext) { public KillCursorsMessageHandler(final DataStoreContext dataStoreContext) {
super(dataStoreContext); super(dataStoreContext);
} }
public void messageReceived(KillCursorsMessage message,String ip) { @Override
List<Long> cursorIds = message.getCursorIDs(); public void messageReceived(final KillCursorsMessage message) {
if (cursorIds != null) { final List<Long> cursorIds = message.getCursorIDs();
for (Long cursorId : cursorIds) { if (cursorIds != null) {
this.dataStoreContext.removeCursor(cursorId); for (final Long cursorId : cursorIds) {
} this.dataStoreContext.removeCursor(cursorId);
} }
} }
}
} }
@@ -1,184 +1,180 @@
package com.fangjia.datastore.handler; package com.fangjia.datastore.handler;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.mina.core.session.IoSession;
import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.DataStoreException; import com.fangjia.datastore.DataStoreException;
import com.fangjia.datastore.mongo.protocol.MongoMessage; import java.util.Arrays;
import org.bson.BasicBSONObject;
import java.util.ArrayList;
import org.bson.BSONObject;
import java.util.List;
import com.fangjia.datastore.mongo.protocol.ReplyMessage; import com.fangjia.datastore.mongo.protocol.ReplyMessage;
import java.net.InetSocketAddress;
import org.apache.mina.core.session.IoSession;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.fangjia.datastore.DataStoreContext;
import java.util.Map;
import com.fangjia.datastore.mongo.protocol.MongoMessage;
public abstract class MessageHandler<T extends MongoMessage> { public abstract class MessageHandler<T extends MongoMessage>
private final static String LAST_ERROR_KEY = "com.goojia.datastore.LAST_ERROR_KEY"; {
private final static String PREV_ERROR_KEY = "com.goojia.datastore.PREV_ERROR_KEY"; private static final String LAST_ERROR_KEY = "com.goojia.datastore.LAST_ERROR_KEY";
private static final String PREV_ERROR_KEY = "com.goojia.datastore.PREV_ERROR_KEY";
private final static String SESSION_KEY = "com.goojia.datastore.SESSION_KEY"; private static final String SESSION_KEY = "com.goojia.datastore.SESSION_KEY";
private final static String ERROR_OCCURRED_KEY = "com.goojia.datastore.ERROR_OCCURRED_KEY"; private static final String ERROR_OCCURRED_KEY = "com.goojia.datastore.ERROR_OCCURRED_KEY";
private final static ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<Map<String, Object>>() { private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL;
@Override protected final DataStoreContext dataStoreContext;
protected Map<String, Object> initialValue() { protected final Logger logger = LoggerFactory.getLogger(this.getClass());
return new HashMap<String, Object>();
} public MessageHandler(final DataStoreContext dataStoreContext) {
}; this.dataStoreContext = dataStoreContext;
}
protected final DataStoreContext dataStoreContext;
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
public MessageHandler(DataStoreContext dataStoreContext) {
this.dataStoreContext = dataStoreContext;
}
/**
* ´¦ÀíÌØ¶¨µÄÏûÏ¢
*
* @param message
*/
public abstract void messageReceived(T message,String ip) throws Exception;
@SuppressWarnings("unchecked")
public void messageReceived(IoSession session, MongoMessage message) throws Exception {
System.out.println(session.getRemoteAddress());
try {
setSession(session);
messageReceived((T) message,session.getRemoteAddress().toString());
if (!isErrorOccured()) {
this.clearLastError();
}
} catch (Throwable e) {
String hostAddress = "";
if(session.getRemoteAddress() instanceof InetSocketAddress) {
hostAddress = ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();
}
this.setLastError(buildExceptionMessage(e));
logger.error("error processing host:" + hostAddress + ",message: " + message, e);
} finally {
clearErrorOccured();
}
}
private void clearErrorOccured() {
THREAD_LOCAL.get().remove(ERROR_OCCURRED_KEY);
}
private void setErrorOccured() {
THREAD_LOCAL.get().put(ERROR_OCCURRED_KEY, true);
}
private boolean isErrorOccured() {
Boolean b = (Boolean) THREAD_LOCAL.get().get(ERROR_OCCURRED_KEY);
return null == b ? false : b;
}
protected IoSession getSession() {
return (IoSession) THREAD_LOCAL.get().get(SESSION_KEY);
}
private void setSession(IoSession session) {
THREAD_LOCAL.get().put(SESSION_KEY, session);
}
protected void setLastError(Object error) {
if (null != error) {
IoSession session = getSession();
Object lastError = session.getAttribute(LAST_ERROR_KEY);
if (null != lastError) {
session.setAttribute(PREV_ERROR_KEY, lastError);
}
setErrorOccured();
session.setAttribute(LAST_ERROR_KEY, String.valueOf(error));
}
}
private void clearLastError() {
getSession().removeAttribute(LAST_ERROR_KEY);
}
protected Object getLastError() {
return getSession().getAttribute(LAST_ERROR_KEY);
}
protected Object getPrevError() {
return getSession().getAttribute(PREV_ERROR_KEY);
}
protected void writeMessage(ReplyMessage message) {
getSession().write(message);
}
protected void writeAsReplyMessage(int responseTo, List<? extends BSONObject> docs) {
writeMessage(prepareReplyMessage(responseTo, docs));
}
@SuppressWarnings("unchecked")
protected ReplyMessage prepareReplyMessage(int responseTo, List<? extends BSONObject> docs) {
ReplyMessage reply = new ReplyMessage();
reply.setNumberReturned(null == docs ? 0 : docs.size());
reply.setResponseFlag(8);
reply.getMessageHeader().setResponseTo(responseTo);
if (null != docs && docs.size() > 0) {
reply.setDocuments((List<BSONObject>) docs);
}
return reply;
}
protected void writeAsReplyMessage(int responseTo, BSONObject... docs) {
writeMessage(prepareReplyMessage(responseTo, docs));
}
protected ReplyMessage prepareReplyMessage(int responseTo, BSONObject... docs) {
if (null != docs && docs.length > 0) {
List<BSONObject> docList = new ArrayList<BSONObject>(docs.length);
for (BSONObject doc : docs) {
docList.add(doc);
}
return prepareReplyMessage(responseTo, docList);
} else {
return prepareReplyMessage(responseTo, (List<? extends BSONObject>) null);
}
}
protected void writeAsErrorMessage(int responseTo, Object errorMessage) {
writeMessage(prepareErrorMessage(responseTo, errorMessage));
}
protected ReplyMessage prepareErrorMessage(int responseTo, Object errorMessage) {
ReplyMessage reply = new ReplyMessage();
reply.setNumberReturned(1);
reply.setResponseFlag(8);
reply.getMessageHeader().setResponseTo(responseTo);
BSONObject msg = new BasicBSONObject("$err", errorMessage == null ? null : errorMessage.toString());
msg.put("err", errorMessage == null ? null : errorMessage.toString());
msg.put("errmsg", errorMessage == null ? null : errorMessage.toString());
msg.put("ok", 0.0);
reply.setDocuments(Arrays.asList(msg));
return reply;
}
protected String buildExceptionMessage(Throwable e) {
StringBuilder ret = new StringBuilder();
ret.append(e.getClass().getName()).append(": ").append(e.getMessage());
Throwable cause = e;
while ((cause = cause.getCause()) != null) {
ret.append(", caused by ").append(cause.getClass().getName()).append(": ").append(cause.getMessage());
}
return ret.toString();
}
protected void assertNotReadOnly() throws DataStoreException {
if (this.dataStoreContext.getDataStoreConfig().isReadOnly()) {
throw new DataStoreException("read only server !");
}
}
public abstract void messageReceived(T message) throws Exception;
public void messageReceived(final IoSession session, final MongoMessage message) throws Exception {
try {
this.setSession(session);
this.messageReceived((T)message);
if (!this.isErrorOccured()) {
this.clearLastError();
}
}
catch (Throwable e) {
String hostAddress = "";
if (session.getRemoteAddress() instanceof InetSocketAddress) {
hostAddress = ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();
}
this.setLastError(this.buildExceptionMessage(e));
this.logger.error("error processing host:" + hostAddress + ",message: " + message, e);
}
finally {
this.clearErrorOccured();
}
}
private void clearErrorOccured() {
MessageHandler.THREAD_LOCAL.get().remove("com.goojia.datastore.ERROR_OCCURRED_KEY");
}
private void setErrorOccured() {
MessageHandler.THREAD_LOCAL.get().put("com.goojia.datastore.ERROR_OCCURRED_KEY", true);
}
private boolean isErrorOccured() {
final Boolean b = (Boolean) MessageHandler.THREAD_LOCAL.get().get("com.goojia.datastore.ERROR_OCCURRED_KEY");
return null != b && b;
}
protected IoSession getSession() {
return (IoSession)MessageHandler.THREAD_LOCAL.get().get("com.goojia.datastore.SESSION_KEY");
}
private void setSession(final IoSession session) {
MessageHandler.THREAD_LOCAL.get().put("com.goojia.datastore.SESSION_KEY", session);
}
protected void setLastError(final Object error) {
if (null != error) {
final IoSession session = this.getSession();
final Object lastError = session.getAttribute((Object)"com.goojia.datastore.LAST_ERROR_KEY");
if (null != lastError) {
session.setAttribute((Object)"com.goojia.datastore.PREV_ERROR_KEY", lastError);
}
this.setErrorOccured();
session.setAttribute((Object)"com.goojia.datastore.LAST_ERROR_KEY", (Object)String.valueOf(error));
}
}
private void clearLastError() {
this.getSession().removeAttribute((Object)"com.goojia.datastore.LAST_ERROR_KEY");
}
protected Object getLastError() {
return this.getSession().getAttribute((Object)"com.goojia.datastore.LAST_ERROR_KEY");
}
protected Object getPrevError() {
return this.getSession().getAttribute((Object)"com.goojia.datastore.PREV_ERROR_KEY");
}
protected void writeMessage(final ReplyMessage message) {
this.getSession().write((Object)message);
}
protected void writeAsReplyMessage(final int responseTo, final List<? extends BSONObject> docs) {
this.writeMessage(this.prepareReplyMessage(responseTo, docs));
}
protected ReplyMessage prepareReplyMessage(final int responseTo, final List<? extends BSONObject> docs) {
final ReplyMessage reply = new ReplyMessage();
reply.setNumberReturned((null == docs) ? 0 : docs.size());
reply.setResponseFlag(8);
reply.getMessageHeader().setResponseTo(responseTo);
if (null != docs && docs.size() > 0) {
reply.setDocuments((List<BSONObject>)docs);
}
return reply;
}
protected void writeAsReplyMessage(final int responseTo, final BSONObject... docs) {
this.writeMessage(this.prepareReplyMessage(responseTo, docs));
}
protected ReplyMessage prepareReplyMessage(final int responseTo, final BSONObject... docs) {
if (null != docs && docs.length > 0) {
final List<BSONObject> docList = new ArrayList<BSONObject>(docs.length);
for (final BSONObject doc : docs) {
docList.add(doc);
}
return this.prepareReplyMessage(responseTo, docList);
}
return this.prepareReplyMessage(responseTo, (List<? extends BSONObject>)null);
}
protected void writeAsErrorMessage(final int responseTo, final Object errorMessage) {
this.writeMessage(this.prepareErrorMessage(responseTo, errorMessage));
}
protected ReplyMessage prepareErrorMessage(final int responseTo, final Object errorMessage) {
final ReplyMessage reply = new ReplyMessage();
reply.setNumberReturned(1);
reply.setResponseFlag(8);
reply.getMessageHeader().setResponseTo(responseTo);
final BSONObject msg = (BSONObject)new BasicBSONObject("$err", (Object)((errorMessage == null) ? null : errorMessage.toString()));
msg.put("err", (Object)((errorMessage == null) ? null : errorMessage.toString()));
msg.put("errmsg", (Object)((errorMessage == null) ? null : errorMessage.toString()));
msg.put("ok", (Object)0.0);
reply.setDocuments(Arrays.<BSONObject>asList(msg));
return reply;
}
protected String buildExceptionMessage(final Throwable e) {
final StringBuilder ret = new StringBuilder();
ret.append(e.getClass().getName()).append(": ").append(e.getMessage());
Throwable cause = e;
while ((cause = cause.getCause()) != null) {
ret.append(", caused by ").append(cause.getClass().getName()).append(": ").append(cause.getMessage());
}
return ret.toString();
}
protected void assertNotReadOnly() throws DataStoreException {
if (this.dataStoreContext.getDataStoreConfig().isReadOnly()) {
throw new DataStoreException("read only server !");
}
}
protected boolean useCursor() {
return (Boolean) this.getSession().getAttribute((Object)"useCursor", false);
}
static {
THREAD_LOCAL = new ThreadLocal<Map<String, Object>>() {
@Override
protected Map<String, Object> initialValue() {
return new HashMap<String, Object>();
}
};
}
} }
@@ -1,490 +1,501 @@
package com.fangjia.datastore.handler; package com.fangjia.datastore.handler;
import java.net.InetSocketAddress; import com.fangjia.datastore.mongo.protocol.MongoMessage;
import java.util.ArrayList; import org.apache.commons.lang.StringUtils;
import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.mongodb.BasicDBList;
import org.apache.mina.core.session.IoSession;
import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import com.fangjia.datastore.ConfigurationException;
import com.fangjia.datastore.DataStore;
import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.DataStoreException;
import com.fangjia.datastore.QueryResponse;
import com.fangjia.datastore.config.Field;
import com.fangjia.datastore.config.StoreConfig; import com.fangjia.datastore.config.StoreConfig;
import com.fangjia.datastore.mongo.protocol.QueryMessage; import com.fangjia.datastore.config.Field;
import com.fangjia.datastore.mongo.protocol.ReplyMessage; import com.fangjia.datastore.mongo.protocol.ReplyMessage;
import com.fangjia.datastore.QueryResponse;
import com.fangjia.datastore.Cursor;
import java.util.Collection;
import com.fangjia.datastore.solr.Index; import com.fangjia.datastore.solr.Index;
import com.fangjia.datastore.utils.MongoUtils; import java.util.Iterator;
import java.util.Set;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import java.util.ArrayList;
import com.fangjia.datastore.ConfigurationException;
import com.mongodb.BasicDBList;
import java.util.List;
import com.fangjia.datastore.DataStore;
import org.bson.types.BasicBSONList;
import org.bson.BasicBSONObject;
import org.bson.BSONObject;
import com.fangjia.datastore.DataStoreException;
import org.apache.mina.core.session.IoSession;
import java.net.InetSocketAddress;
import com.fangjia.datastore.utils.MongoUtils;
import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.mongo.protocol.QueryMessage;
public class QueryMessageHandler extends MessageHandler<QueryMessage> { public class QueryMessageHandler extends MessageHandler<QueryMessage>
{
public QueryMessageHandler(DataStoreContext dataStoreContext) { public QueryMessageHandler(final DataStoreContext dataStoreContext) {
super(dataStoreContext); super(dataStoreContext);
} }
public void messageReceived(QueryMessage message,String ip) throws Exception { @Override
Object error = null; public void messageReceived(final QueryMessage message) throws Exception {
try { Object error = null;
String[] nameSplit = MongoUtils.parseFullCollectionName(message.getFullCollectionName()); try {
if (null == nameSplit) { final String[] nameSplit = MongoUtils.parseFullCollectionName(message.getFullCollectionName());
error = "invalid full collection name: " + message.getFullCollectionName(); if (null == nameSplit) {
} else { error = "invalid full collection name: " + message.getFullCollectionName();
doMessageReceived(message, nameSplit[0], nameSplit[1]); }
} else {
} catch (Throwable e) { this.doMessageReceived(message, nameSplit[0], nameSplit[1]);
IoSession session = getSession(); }
String hostAddress = ""; }
if(session != null && session.getRemoteAddress() instanceof InetSocketAddress) { catch (Throwable e) {
hostAddress = ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress(); final IoSession session = this.getSession();
} String hostAddress = "";
if (session != null && session.getRemoteAddress() instanceof InetSocketAddress) {
error = buildExceptionMessage(e); hostAddress = ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();
this.writeAsErrorMessage(message.getMessageHeader().getRequestID(), error); }
if (logger.isErrorEnabled()) { error = this.buildExceptionMessage(e);
logger.error("error process host:" + hostAddress + ",message: " + message, e); this.writeAsErrorMessage(message.getMessageHeader().getRequestID(), error);
} if (this.logger.isErrorEnabled()) {
} finally { this.logger.error("error process host:" + hostAddress + ",message: " + message, e);
this.setLastError(error); }
} }
} finally {
this.setLastError(error);
private void doMessageReceived(QueryMessage message, String dbName, String collectionName) throws DataStoreException { }
if (collectionName.equals("$cmd")) { }
onCommand(message, dbName);
return; private void doMessageReceived(final QueryMessage message, final String dbName, final String collectionName) throws DataStoreException {
} if (collectionName.equals("$cmd")) {
if (collectionName.equals("system.namespaces")) { this.onCommand(message, dbName);
showCollections(message, dbName, collectionName); return;
} else if (collectionName.equals("system.indexes")) { }
getIndexes(message, dbName, collectionName); if (collectionName.equals("system.namespaces")) {
} else { this.showCollections(message, dbName, collectionName);
find(message, dbName, collectionName); }
} else if (collectionName.equals("system.indexes")) {
} this.getIndexes(message, dbName, collectionName);
}
private void onCommand(QueryMessage message, String dbName) throws DataStoreException { else {
if (dbName.equals("admin")) { this.find(message, dbName, collectionName);
onAdminCommand(message); }
return; }
}
BSONObject query = message.getQuery(); private void onCommand(final QueryMessage message, final String dbName) throws DataStoreException {
if (query.containsField("getlasterror")) { if (dbName.equals("admin")) {
getLastError(message, dbName); this.onAdminCommand(message);
} else if (query.containsField("getpreverror")) { return;
getPrevError(message, dbName); }
} else if (query.containsField("count")) { final BSONObject query = message.getQuery();
count(message, dbName); if (query.containsField("getlasterror")) {
} else if (query.containsField("getSchema")) { this.getLastError(message, dbName);
getSchema(message, dbName); }
} else if (query.containsField("reIndex")) { else if (query.containsField("getpreverror")) {
reIndex(message, dbName); this.getPrevError(message, dbName);
} else if (query.containsField("reload")) { }
reload(message, dbName); else if (query.containsField("count")) {
} else if(query.containsField("dbStats")){ this.count(message, dbName);
dbStats(message, dbName); }
} else if(query.containsField("listCollections")){ else if (query.containsField("getSchema")) {
listCollections(message, dbName); this.getSchema(message, dbName);
} else if (query.containsField("isMaster") || query.containsField("ismaster")) { }
isMaster(message); else if (query.containsField("reIndex")) {
} else if(query.containsField("buildinfo") || query.containsField("buildInfo")){ this.reIndex(message, dbName);
buildinfo(message); }
} else if(query.containsField("serverStatus")){ else if (query.containsField("reload")) {
serverStatus(message); this.reload(message, dbName);
} else if(query.containsField("connectionStatus")){ }
connectionStatus(message); else if (query.containsField("dbStats")) {
} else if (query.containsField("find")) { this.dbStats(message, dbName);
find(message, dbName, query.get("find").toString() ); }
} else { else if (query.containsField("listCollections")) {
delegateCommand(message, dbName); this.listCollections(message, dbName);
} }
} else if (query.containsField("isMaster") || query.containsField("ismaster")) {
this.isMaster(message);
private void onAdminCommand(QueryMessage message) throws DataStoreException { }
BSONObject query = message.getQuery(); else if (query.containsField("buildinfo") || query.containsField("buildInfo")) {
if (query.containsField("whatsmyuri")) { this.buildinfo(message);
whatsMyUri(message); }
} else if (query.containsField("listDatabases")) { else if (query.containsField("serverStatus")) {
listDatabases(message); this.serverStatus(message);
} else if (query.containsField("nonce")) { }
nonce(message); else if (query.containsField("connectionStatus")) {
} else if (query.containsField("isMaster") || query.containsField("ismaster")) { this.connectionStatus(message);
isMaster(message); }
} else if(query.containsField("buildinfo") || query.containsField("buildInfo")){ else if (query.containsField("update")) {
buildinfo(message); this.update(message, dbName);
} else if (query.containsField("replSetGetStatus")) { }
replSetGetStatus(message); else if (query.containsField("insert")) {
} else if(query.containsField("getlasterror")){ this.insert(message, dbName);
getLastError(message, "admin"); }
} else if(query.containsField("serverStatus")){ else if (query.containsField("ping")) {
serverStatus(message); this.ping(message);
} else if(query.containsField("connectionStatus")){ }
connectionStatus(message); else if (query.containsField("find")) {
} else if (query.containsField("getLog")) { this.find(message, dbName, query.get("find").toString());
getLog(message); }
} else { else {
delegateAdminCommand(message); this.delegateCommand(message, dbName);
} }
} }
private void replSetGetStatus(QueryMessage message) { private void onAdminCommand(final QueryMessage message) throws DataStoreException {
BSONObject doc = new BasicBSONObject(); final BSONObject query = message.getQuery();
doc.put("ok", 0); if (query.containsField("whatsmyuri")) {
doc.put("errmsg", "not running with --replSet"); this.whatsMyUri(message);
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); }
} else if (query.containsField("listDatabases")) {
this.listDatabases(message);
private void delegateCommand(QueryMessage message, String dbName) throws DataStoreException { }
throw new DataStoreException("unsupported command:" + message.getQuery()); else if (query.containsField("nonce")) {
} this.nonce(message);
}
private void getLog(QueryMessage message){ else if (query.containsField("isMaster") || query.containsField("ismaster")) {
this.isMaster(message);
BasicDBList names = new BasicDBList(); }
names.add("global"); else if (query.containsField("buildinfo") || query.containsField("buildInfo")) {
names.add("startupWarnings"); this.buildinfo(message);
}
BSONObject doc = new BasicBSONObject(); else if (query.containsField("replSetGetStatus")) {
doc.put("ok", 1); this.replSetGetStatus(message);
doc.put("names", names); }
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); else if (query.containsField("getlasterror")) {
this.getLastError(message, "admin");
} }
else if (query.containsField("serverStatus")) {
private void dbStats(QueryMessage message, String dbName) throws DataStoreException { this.serverStatus(message);
}
BSONObject doc = new BasicBSONObject(); else if (query.containsField("connectionStatus")) {
doc.put("db", dbName); this.connectionStatus(message);
doc.put("collections", this.dataStoreContext.getDataStoreConfig().getStoreNames()); }
doc.put("ok", 1.0); else if (query.containsField("collstats")) {
InetSocketAddress localAddress = (InetSocketAddress) this.getSession().getLocalAddress(); this.collstats(message);
doc.put("primary", localAddress.getAddress().getHostAddress()); }
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); else if (query.containsField("getLog")) {
} this.getLog(message);
}
else if (query.containsField("ping")) {
this.ping(message);
private void delegateAdminCommand(QueryMessage message) throws DataStoreException { }
throw new DataStoreException("unsupported command:" + message.getQuery()); else {
} this.delegateAdminCommand(message);
}
private void reload(QueryMessage message, String dbName) throws DataStoreException { }
assertNotReadOnly();
try { private void replSetGetStatus(final QueryMessage message) {
this.dataStoreContext.reload(); final BSONObject doc = (BSONObject)new BasicBSONObject();
this.dataStoreContext.getDataStore(dbName + "." + message.getQuery().get("reload")).reload(); doc.put("ok", (Object)0);
BSONObject doc = new BasicBSONObject(); doc.put("errmsg", (Object)"not running with --replSet");
doc.put("ok", 1.0); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); }
} catch (ConfigurationException e) {
throw new DataStoreException("error reload config: ", e); private void delegateCommand(final QueryMessage message, final String dbName) throws DataStoreException {
} throw new DataStoreException("unsupported command:" + message.getQuery());
} }
/** private void collstats(final QueryMessage message) {
* show collections final BSONObject doc = (BSONObject)new BasicBSONObject();
* doc.put("ok", (Object)1);
* @param message doc.put("ns", (Object)message.getFullCollectionName());
*/ this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
private void showCollections(QueryMessage message, String dbName, String collectionName) throws DataStoreException { }
Set<String> storeNames = this.dataStoreContext.getDataStoreConfig().getStoreNames();
List<DBObject> docList = new ArrayList<DBObject>(storeNames.size()); private void ping(final QueryMessage message) throws DataStoreException {
for (String sn : storeNames) { final BSONObject doc = (BSONObject)new BasicBSONObject();
if (sn.startsWith(dbName + ".")) { doc.put("ok", (Object)1);
docList.add(new BasicDBObject("name", sn)); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
} }
}
writeAsReplyMessage(message.getMessageHeader().getRequestID(), docList); private void update(final QueryMessage message, final String dbName) throws DataStoreException {
} final DataStore dataStore = this.dataStoreContext.getDataStore(dbName + "." + message.getQuery().get("update"));
final BasicBSONList updates = (BasicBSONList)message.getQuery().get("updates");
/** final BSONObject selector = (BSONObject)((BasicBSONObject)updates.get(0)).get("q");
* db.foo.getIndexes() final BSONObject update = (BSONObject)((BasicBSONObject)updates.get(0)).get("u");
* final int count = dataStore.update(selector, update);
* @param message final BSONObject doc = (BSONObject)new BasicBSONObject();
* @param dbName doc.put("nModified", (Object)count);
* @param collectionName doc.put("n", (Object)count);
* @throwstion doc.put("ok", (Object)1);
*/ this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
private void getIndexes(QueryMessage message, String dbName, String collectionName) throws DataStoreException { }
String ns = (String) message.getQuery().get("ns");
Collection<Index> indexes = this.dataStoreContext.getDataStore(ns).getIndexes(); private void insert(final QueryMessage message, final String dbName) throws DataStoreException {
List<BSONObject> docList = new ArrayList<BSONObject>(indexes.size()); final DataStore dataStore = this.dataStoreContext.getDataStore(dbName + "." + message.getQuery().get("insert"));
for (Index i : indexes) { final List documents = (List)message.getQuery().get("documents");
docList.add(i.toBSONObject()); dataStore.save(documents);
} final BSONObject doc = (BSONObject)new BasicBSONObject();
writeAsReplyMessage(message.getMessageHeader().getRequestID(), docList); doc.put("n", (Object)documents.size());
} doc.put("ok", (Object)1);
this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
/** }
* db.foo.find()
* private void getLog(final QueryMessage message) {
* @param message final BasicDBList names = new BasicDBList();
* @param dbName names.add((Object)"global");
* @param collectionName names.add((Object)"startupWarnings");
* @throws DataStoreException final BSONObject doc = (BSONObject)new BasicBSONObject();
*/ doc.put("ok", (Object)1);
private void find(QueryMessage message, String dbName, String collectionName) throws DataStoreException { doc.put("names", (Object)names);
this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
String fullCollectionName; }
if(message.getFullCollectionName().contains("$cmd")){
fullCollectionName = dbName + "." + collectionName; private void dbStats(final QueryMessage message, final String dbName) throws DataStoreException {
}else{ final BSONObject doc = (BSONObject)new BasicBSONObject();
fullCollectionName = message.getFullCollectionName(); doc.put("db", (Object)dbName);
} doc.put("collections", (Object)this.dataStoreContext.getDataStoreConfig().getStoreNames());
DataStore dataStore = this.dataStoreContext.getDataStore(fullCollectionName); doc.put("ok", (Object)1.0);
QueryResponse response = dataStore.find(message.getRealQuery(), message.getReturnFieldSelector(), message final InetSocketAddress localAddress = (InetSocketAddress)this.getSession().getLocalAddress();
.getOrderByQuery(), message.getFacetQuery(), message.getNumberToSkip(), message.getNumberToReturn() - 1, message doc.put("primary", (Object)localAddress.getAddress().getHostAddress());
.isBulkQuery(), message.isFromMaster()); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
ReplyMessage reply = prepareReplyMessage(message.getMessageHeader().getRequestID(), response.getDocList()); }
reply.setStartingFrom(message.getNumberToSkip());
// if (response.hasMore()) { private void delegateAdminCommand(final QueryMessage message) throws DataStoreException {
// Cursor cursor = new Cursor((int) message.getNumberToSkip(), (int) throw new DataStoreException("unsupported command:" + message.getQuery());
// response.getNumReturned(), message, }
// response.getNumFound());
// this.dataStoreContext.addCursor(cursor); private void reload(final QueryMessage message, final String dbName) throws DataStoreException {
// reply.setCursorID(cursor.getId()); this.assertNotReadOnly();
// } try {
this.writeMessage(reply); this.dataStoreContext.reload();
} this.dataStoreContext.getDataStore(dbName + "." + message.getQuery().get("reload")).reload();
final BSONObject doc = (BSONObject)new BasicBSONObject();
/** doc.put("ok", (Object)1.0);
* db.getLastError() this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
* }
* @param message catch (ConfigurationException e) {
* @param dbName throw new DataStoreException("error reload config: ", e);
*/ }
private void getLastError(QueryMessage message, String dbName) { }
Object lastError = this.getLastError();
BSONObject doc = new BasicBSONObject(); private void showCollections(final QueryMessage message, final String dbName, final String collectionName) throws DataStoreException {
doc.put("ok", 1.0); final Set<String> storeNames = this.dataStoreContext.getDataStoreConfig().getStoreNames();
doc.put("n", 1); final List<DBObject> docList = new ArrayList<DBObject>(storeNames.size());
doc.put("$err", lastError == null ? null : lastError.toString()); for (final String sn : storeNames) {
doc.put("err", lastError == null ? null : lastError.toString()); if (sn.startsWith(dbName + ".")) {
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); docList.add((DBObject)new BasicDBObject("name", (Object)sn));
} }
}
/** this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), (List<? extends BSONObject>)docList);
* db.getPrevError() }
*
* @param message private void getIndexes(final QueryMessage message, final String dbName, final String collectionName) throws DataStoreException {
* @param dbName final String ns = (String)message.getQuery().get("ns");
*/ final Collection<Index> indexes = this.dataStoreContext.getDataStore(ns).getIndexes();
private void getPrevError(QueryMessage message, String dbName) { final List<BSONObject> docList = new ArrayList<BSONObject>(indexes.size());
Object prevError = this.getPrevError(); for (final Index i : indexes) {
BSONObject doc = new BasicBSONObject(); docList.add(i.toBSONObject());
doc.put("ok", 1.0); }
doc.put("n", 0); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), docList);
doc.put("$err", prevError == null ? null : prevError.toString()); }
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
} private void find(final QueryMessage message, final String dbName, final String collectionName) throws DataStoreException {
String fullCollectionName;
/** if (message.getFullCollectionName().contains("$cmd")) {
* db.foo.count() fullCollectionName = dbName + "." + collectionName;
* }
* @param message else {
* @param dbName fullCollectionName = message.getFullCollectionName();
* @throws DataStoreException }
*/ final DataStore dataStore = this.dataStoreContext.getDataStore(fullCollectionName);
private void count(QueryMessage message, String dbName) throws DataStoreException { QueryResponse response;
BSONObject query = message.getQuery(); if (this.useCursor()) {
int count = this.dataStoreContext.getDataStore(dbName + "." + query.get("count")).count(message.getRealQuery(), response = dataStore.find(message.getRealQuery(), message.getReturnFieldSelector(), message.getOrderByQuery(), message.getFacetQuery(), message.getNumberToSkip(), message.getNumberToReturn(), message.isBulkQuery(), message.isFromMaster());
message.isFromMaster()); }
BSONObject doc = new BasicBSONObject(); else {
doc.put("ok", 1.0); response = dataStore.find(message.getRealQuery(), message.getReturnFieldSelector(), message.getOrderByQuery(), message.getFacetQuery(), message.getNumberToSkip(), message.getNumberToReturn() - 1, message.isBulkQuery(), message.isFromMaster());
doc.put("n", (double) count); }
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); final List<DBObject> doc = response.getDocList();
} if (this.useCursor()) {
doc.remove(0);
/** }
* db.foo.rumCommnad('getSchema') final ReplyMessage reply = this.prepareReplyMessage(message.getMessageHeader().getRequestID(), (List<? extends BSONObject>)doc);
* reply.setStartingFrom(message.getNumberToSkip());
* @param message if (response.hasMore() && this.useCursor()) {
* @param dbName final Cursor cursor = new Cursor(message.getNumberToSkip(), message.getNumberToReturn(), message, response.getNumFound());
*/ this.dataStoreContext.addCursor(cursor);
private void getSchema(QueryMessage message, String dbName) throws DataStoreException { reply.setCursorID(cursor.getId());
BSONObject query = message.getQuery(); }
String collectionName = (String) query.get("getSchema"); this.writeMessage(reply);
StoreConfig storeConfig = this.dataStoreContext.getDataStore(dbName + "." + collectionName).getStoreConfig(); }
Collection<Field> fields = storeConfig.getFields();
List<DBObject> docList = new ArrayList<DBObject>(fields.size()); private void getLastError(final QueryMessage message, final String dbName) {
for (Field field : fields) { final Object lastError = this.getLastError();
BasicDBObject f = new BasicDBObject(); final BSONObject doc = (BSONObject)new BasicBSONObject();
f.put("name", field.getName()); doc.put("ok", (Object)1.0);
f.put("type", field.getType().getType()); doc.put("n", (Object)1);
docList.add(f); doc.put("$err", (Object)((lastError == null) ? null : lastError.toString()));
} doc.put("err", (Object)((lastError == null) ? null : lastError.toString()));
BSONObject doc = new BasicBSONObject(); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
doc.put("ok", 1.0); }
doc.put("schema", docList);
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); private void getPrevError(final QueryMessage message, final String dbName) {
} final Object prevError = this.getPrevError();
final BSONObject doc = (BSONObject)new BasicBSONObject();
/** doc.put("ok", (Object)1.0);
* <p> doc.put("n", (Object)0);
* 不带参数重建:db.foo.reIndex() 或 db.foo.runCommand('reIndex') doc.put("$err", (Object)((prevError == null) ? null : prevError.toString()));
* </P> this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
* }
* <p>
* 带参数重建:db.foo.runCommand('reIndex',{query:{cat:'sell',city:'上海'}}) private void count(final QueryMessage message, final String dbName) throws DataStoreException {
* <p> final BSONObject query = message.getQuery();
* final int count = this.dataStoreContext.getDataStore(dbName + "." + query.get("count")).count(message.getRealQuery(), message.isFromMaster());
* @param message final BSONObject doc = (BSONObject)new BasicBSONObject();
* @param dbName doc.put("ok", (Object)1.0);
* @throws Exception doc.put("n", (Object)(double)count);
*/ this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
private void reIndex(QueryMessage message, String dbName) throws DataStoreException { }
assertNotReadOnly();
BSONObject query = message.getQuery(); private void getSchema(final QueryMessage message, final String dbName) throws DataStoreException {
String collectionName = (String) query.get("reIndex"); final BSONObject query = message.getQuery();
DataStore dataStore = this.dataStoreContext.getDataStore(dbName + "." + collectionName); final String collectionName = (String)query.get("getSchema");
// 新增查询条件 add by yukai 2011/07/14 final StoreConfig storeConfig = this.dataStoreContext.getDataStore(dbName + "." + collectionName).getStoreConfig();
BSONObject doc = new BasicBSONObject(); final Collection<Field> fields = storeConfig.getFields();
Object realQuery = query.get("query"); final List<DBObject> docList = new ArrayList<DBObject>(fields.size());
if (null == realQuery) for (final Field field : fields) {
doc.put("version", dataStore.reIndex(null)); final BasicDBObject f = new BasicDBObject();
else if (realQuery instanceof BSONObject) f.put("name", field.getName());
dataStore.reIndex((BSONObject) realQuery); f.put("type", field.getType().getType());
else docList.add(f);
throw new DataStoreException("invalid re-index query: " + realQuery); }
doc.put("ok", 1.0); final BSONObject doc = new BasicBSONObject();
doc.put("n", 0D); doc.put("ok", 1.0);
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); doc.put("schema", docList);
} this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
}
/**
* db.runCommand('whatsmyuri') private void reIndex(final QueryMessage message, final String dbName) throws DataStoreException {
* this.assertNotReadOnly();
* @param message final BSONObject query = message.getQuery();
*/ final String collectionName = (String)query.get("reIndex");
private void whatsMyUri(QueryMessage message) { final DataStore dataStore = this.dataStoreContext.getDataStore(dbName + "." + collectionName);
BSONObject doc = new BasicBSONObject(); final BSONObject doc = (BSONObject)new BasicBSONObject();
InetSocketAddress address = (InetSocketAddress) getSession().getRemoteAddress(); final Object realQuery = query.get("query");
doc.put("you", address.getAddress().getHostAddress() + ":" + address.getPort()); if (null == realQuery) {
doc.put("ok", 1.0); doc.put("version", (Object)dataStore.reIndex(null));
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); }
} else {
if (!(realQuery instanceof BSONObject)) {
/** throw new DataStoreException("invalid re-index query: " + realQuery);
* show dbs }
* dataStore.reIndex((BSONObject)realQuery);
* @param message }
*/ doc.put("ok", (Object)1.0);
private void listDatabases(QueryMessage message) { doc.put("n", (Object)0.0);
BSONObject doc = new BasicBSONObject(); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
doc.put("ok", 1.0); }
Set<String> storeNames = this.dataStoreContext.getDataStoreConfig().getStoreNames();
Set<String> dbNames = new HashSet<String>(); private void whatsMyUri(final QueryMessage message) {
for (String sn : storeNames) { final BSONObject doc = (BSONObject)new BasicBSONObject();
int i = sn.indexOf('.'); final InetSocketAddress address = (InetSocketAddress)this.getSession().getRemoteAddress();
if (i > 0) { doc.put("you", (Object)(address.getAddress().getHostAddress() + ":" + address.getPort()));
String name = sn.substring(0, i); doc.put("ok", (Object)1.0);
dbNames.add(name); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
} }
}
List<DBObject> docs = new ArrayList<DBObject>(dbNames.size()); private void listDatabases(final QueryMessage message) {
for (String dn : dbNames) { final BSONObject doc = (BSONObject)new BasicBSONObject();
docs.add(new BasicDBObject("name", dn)); doc.put("ok", (Object)1.0);
} final Set<String> storeNames = this.dataStoreContext.getDataStoreConfig().getStoreNames();
doc.put("databases", docs); final Set<String> dbNames = new HashSet<String>();
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); for (final String sn : storeNames) {
} final int i = sn.indexOf(46);
if (i > 0) {
/** final String name = sn.substring(0, i);
* show dbs dbNames.add(name);
* }
* @param message }
*/ final List<DBObject> docs = new ArrayList<DBObject>(dbNames.size());
private void listCollections(QueryMessage message, String dbName) { for (final String dn : dbNames) {
System.out.println(message.getMessageHeader().getRequestID()); docs.add((DBObject)new BasicDBObject("name", (Object)dn));
BSONObject doc = new BasicBSONObject(); }
doc.put("ok", 1.0); doc.put("databases", (Object)docs);
BSONObject cursor = new BasicDBObject(); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
doc.put("cursor", cursor); }
cursor.put("id", (long)message.getMessageHeader().getRequestID()); private void listCollections(final QueryMessage message, final String dbName) {
cursor.put("ns", dbName + ".$cmd.listCollections"); final BSONObject doc = (BSONObject)new BasicBSONObject();
BasicDBList firstBatch = new BasicDBList(); doc.put("ok", (Object)1.0);
cursor.put("firstBatch", firstBatch); final BSONObject cursor = (BSONObject)new BasicDBObject();
Set<String> storeNames = this.dataStoreContext.getDataStoreConfig().getStoreNames(); doc.put("cursor", (Object)cursor);
for (String sn : storeNames) { cursor.put("id", (Object)(long)message.getMessageHeader().getRequestID());
if (sn.startsWith(dbName + ".")) { cursor.put("ns", (Object)(dbName + ".$cmd.listCollections"));
BSONObject collection = new BasicDBObject(); final BasicDBList firstBatch = new BasicDBList();
collection.put("name", sn.replace(dbName + ".", "")); cursor.put("firstBatch", (Object)firstBatch);
collection.put("options", new BasicDBObject()); final Set<String> storeNames = this.dataStoreContext.getDataStoreConfig().getStoreNames();
firstBatch.add(collection); for (final String sn : storeNames) {
} if (sn.startsWith(dbName + ".")) {
} final BSONObject collection = (BSONObject)new BasicDBObject();
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); collection.put("name", (Object)sn.replace(dbName + ".", ""));
} collection.put("options", (Object)new BasicDBObject());
firstBatch.add((Object)collection);
}
}
this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
/** }
* db.runCommand('nonce')
* private void nonce(final QueryMessage message) {
* @param message final BSONObject doc = (BSONObject)new BasicBSONObject();
*/ doc.put("ok", (Object)1.0);
private void nonce(QueryMessage message) { doc.put("errmsg", (Object)"no such cmd");
BSONObject doc = new BasicBSONObject(); doc.put("bad cmd", (Object)new BasicBSONObject("nonce", (Object)true));
doc.put("ok", 1.0); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
doc.put("errmsg", "no such cmd"); }
doc.put("bad cmd", new BasicBSONObject("nonce", true));
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); private void isMaster(final QueryMessage message) {
} final BSONObject doc = (BSONObject)new BasicBSONObject();
doc.put("ok", (Object)1.0);
private void isMaster(QueryMessage message) { doc.put("ismaster", (Object)true);
BSONObject doc = new BasicBSONObject(); doc.put("secondary", (Object)false);
doc.put("ok", 1.0); final InetSocketAddress localAddress = (InetSocketAddress)this.getSession().getLocalAddress();
doc.put("ismaster", true); doc.put("primary", (Object)localAddress.getAddress().getHostAddress());
doc.put("secondary", false); doc.put("maxWireVersion", (Object)2);
InetSocketAddress localAddress = (InetSocketAddress) this.getSession().getLocalAddress(); doc.put("minWireVersion", (Object)0);
doc.put("primary", localAddress.getAddress().getHostAddress()); final BasicBSONObject client = (BasicBSONObject)message.getQuery().get("client");
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); if (client != null) {
} final String platform = client.getString("platform");
if (platform != null && (platform.contains("python") || platform.contains("Python"))) {
private void buildinfo(QueryMessage message) { this.getSession().setAttribute((Object)"useCursor", (Object)true);
BasicDBList versionArray = new BasicDBList(); }
versionArray.add(3); final BasicBSONObject applicationInfo = (BasicBSONObject)client.get("application");
versionArray.add(2); if (applicationInfo != null && StringUtils.isNotBlank(applicationInfo.getString("name"))) {
versionArray.add(9); this.getSession().setAttribute((Object)"useCursor", (Object)true);
versionArray.add(0); }
BSONObject doc = new BasicBSONObject(); }
doc.put("ok", 1.0); this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
doc.put("bits", 64.0); }
doc.put("debug", false);
doc.put("version" ,"3.2.9"); private void buildinfo(final QueryMessage message) {
doc.put("versionArray" ,versionArray); final BasicDBList versionArray = new BasicDBList();
doc.put("javascriptEngine", "V8"); versionArray.add((Object)2);
InetSocketAddress localAddress = (InetSocketAddress) this.getSession().getLocalAddress(); versionArray.add((Object)6);
doc.put("primary", localAddress.getAddress().getHostAddress()); versionArray.add((Object)8);
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); versionArray.add((Object)0);
} final BSONObject doc = (BSONObject)new BasicBSONObject();
doc.put("ok", (Object)1.0);
private void serverStatus(QueryMessage message){ doc.put("bits", (Object)64.0);
BSONObject doc = new BasicBSONObject(); doc.put("debug", (Object)false);
doc.put("ok", 1.0); doc.put("version", (Object)"2.6.8");
InetSocketAddress localAddress = (InetSocketAddress) this.getSession().getLocalAddress(); doc.put("versionArray", (Object)versionArray);
doc.put("primary", localAddress.getAddress().getHostAddress()); doc.put("javascriptEngine", (Object)"V8");
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); final InetSocketAddress localAddress = (InetSocketAddress)this.getSession().getLocalAddress();
} doc.put("primary", (Object)localAddress.getAddress().getHostAddress());
this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
private void connectionStatus(QueryMessage message){ }
BSONObject doc = new BasicBSONObject();
doc.put("ok", 1.0); private void serverStatus(final QueryMessage message) {
InetSocketAddress localAddress = (InetSocketAddress) this.getSession().getLocalAddress(); final BSONObject doc = (BSONObject)new BasicBSONObject();
doc.put("primary", localAddress.getAddress().getHostAddress()); doc.put("ok", (Object)1.0);
writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc); final InetSocketAddress localAddress = (InetSocketAddress)this.getSession().getLocalAddress();
} doc.put("primary", (Object)localAddress.getAddress().getHostAddress());
this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
}
private void connectionStatus(final QueryMessage message) {
final BSONObject doc = (BSONObject)new BasicBSONObject();
doc.put("ok", (Object)1.0);
final InetSocketAddress localAddress = (InetSocketAddress)this.getSession().getLocalAddress();
doc.put("primary", (Object)localAddress.getAddress().getHostAddress());
this.writeAsReplyMessage(message.getMessageHeader().getRequestID(), doc);
}
} }
@@ -1,27 +1,27 @@
package com.fangjia.datastore.handler; package com.fangjia.datastore.handler;
import com.fangjia.datastore.mongo.protocol.MongoMessage;
import com.fangjia.datastore.DataStore; import com.fangjia.datastore.DataStore;
import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.DataStoreException; import com.fangjia.datastore.DataStoreException;
import com.fangjia.datastore.DataStoreContext;
import com.fangjia.datastore.mongo.protocol.UpdateMessage; import com.fangjia.datastore.mongo.protocol.UpdateMessage;
public class UpdateMessageHandler extends MessageHandler<UpdateMessage> { public class UpdateMessageHandler extends MessageHandler<UpdateMessage>
{
public UpdateMessageHandler(DataStoreContext dataStoreContext) { public UpdateMessageHandler(final DataStoreContext dataStoreContext) {
super(dataStoreContext); super(dataStoreContext);
} }
public void messageReceived(UpdateMessage message,String ip) throws Exception { @Override
assertNotReadOnly(); public void messageReceived(final UpdateMessage message) throws Exception {
if (message.isUpsert()) { this.assertNotReadOnly();
throw new DataStoreException("upsert is not supported."); if (message.isUpsert()) {
} throw new DataStoreException("upsert is not supported.");
if (!message.isMultiUpdate()) { }
throw new DataStoreException("only multi update is supported."); if (!message.isMultiUpdate()) {
} throw new DataStoreException("only multi update is supported.");
}
DataStore dataStore = this.dataStoreContext.getDataStore(message.getFullCollectionName()); final DataStore dataStore = this.dataStoreContext.getDataStore(message.getFullCollectionName());
dataStore.update(message.getSelector(), message.getUpdate(),ip); dataStore.update(message.getSelector(), message.getUpdate());
} }
} }
@@ -1,92 +1,75 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.codec; package com.fangjia.datastore.mongo.codec;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.ByteArrayOutputStream;
import org.apache.mina.core.buffer.IoBuffer;
import java.io.InputStream; import java.io.InputStream;
import org.apache.mina.core.buffer.IoBuffer; public class BSONInputStream extends InputStream
{
public class BSONInputStream extends InputStream { private final IoBuffer buffer;
private final IoBuffer buffer;
public BSONInputStream(final IoBuffer buffer) {
public BSONInputStream(IoBuffer buffer) { this.buffer = buffer;
this.buffer = buffer; }
}
@Override
@Override public int read() {
public int read() { return this.buffer.get();
return buffer.get(); }
}
@Override
public synchronized int read(byte b[], int off, int len) { public synchronized int read(final byte[] b, final int off, final int len) {
if (b == null) { if (b == null) {
throw new NullPointerException(); throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) { }
throw new IndexOutOfBoundsException(); if (off < 0 || len < 0 || len > b.length - off) {
} throw new IndexOutOfBoundsException();
buffer.get(b, off, len); }
return len; this.buffer.get(b, off, len);
} return len;
}
public int readInteger() {
return this.buffer.getInt(); public int readInteger() {
} return this.buffer.getInt();
}
public long readLong() {
return this.buffer.getLong(); public long readLong() {
} return this.buffer.getLong();
}
public double readDouble() {
return this.buffer.getDouble(); public double readDouble() {
} return this.buffer.getDouble();
}
public String readCString() throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); public String readCString() throws IOException {
int b; final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
while (true) { while (true) {
b = read(); final int b = this.read();
if (b != 0) { if (b == 0) {
byteStream.write(b); break;
} else { }
return new String(byteStream.toByteArray(), "UTF-8"); byteStream.write(b);
} }
} return new String(byteStream.toByteArray(), "UTF-8");
} }
public String readString() throws IOException { public String readString() throws IOException {
int len = readInteger(); final int len = this.readInteger();
if (len < 0) { if (len < 0) {
throw new IOException("can not read string from the stream"); throw new IOException("can not read string from the stream");
} }
if (len == 0) { if (len == 0) {
read(); this.read();
return ""; return "";
} }
byte[] buf = new byte[len]; final byte[] buf = new byte[len];
read(buf); this.read(buf);
return new String(buf, 0, len - 1, "UTF-8"); return new String(buf, 0, len - 1, "UTF-8");
} }
@Override @Override
public int available() throws IOException { public int available() throws IOException {
return buffer.remaining(); return this.buffer.remaining();
} }
} }
@@ -1,95 +1,83 @@
package com.fangjia.datastore.mongo.codec; package com.fangjia.datastore.mongo.codec;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.apache.mina.core.buffer.AbstractIoBuffer; import org.apache.mina.core.buffer.AbstractIoBuffer;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.buffer.IoBufferAllocator; import org.apache.mina.core.buffer.IoBufferAllocator;
public class BSONIoBufferAllocator implements IoBufferAllocator { public class BSONIoBufferAllocator implements IoBufferAllocator
{
public IoBuffer allocate(int capacity, boolean direct) { public IoBuffer allocate(final int capacity, final boolean direct) {
return wrap(allocateNioBuffer(capacity, direct)); return this.wrap(this.allocateNioBuffer(capacity, direct));
} }
public ByteBuffer allocateNioBuffer(int capacity, boolean direct) { public ByteBuffer allocateNioBuffer(final int capacity, final boolean direct) {
ByteBuffer nioBuffer; ByteBuffer nioBuffer;
if (direct) { if (direct) {
nioBuffer = ByteBuffer.allocateDirect(capacity); nioBuffer = ByteBuffer.allocateDirect(capacity);
} else { }
nioBuffer = ByteBuffer.allocate(capacity); else {
} nioBuffer = ByteBuffer.allocate(capacity);
nioBuffer.order(ByteOrder.LITTLE_ENDIAN); }
return nioBuffer; nioBuffer.order(ByteOrder.LITTLE_ENDIAN);
} return nioBuffer;
}
public IoBuffer wrap(ByteBuffer nioBuffer) {
return new SimpleBuffer(nioBuffer); public IoBuffer wrap(final ByteBuffer nioBuffer) {
} return (IoBuffer)new SimpleBuffer(nioBuffer);
}
public void dispose() {
// Do nothing public void dispose() {
} }
private class SimpleBuffer extends AbstractIoBuffer { private class SimpleBuffer extends AbstractIoBuffer
private ByteBuffer buf; {
private ByteBuffer buf;
protected SimpleBuffer(ByteBuffer buf) {
super(BSONIoBufferAllocator.this, buf.capacity()); protected SimpleBuffer(final ByteBuffer buf) {
this.buf = buf; super((IoBufferAllocator)BSONIoBufferAllocator.this, buf.capacity());
this.buf.order(ByteOrder.LITTLE_ENDIAN); (this.buf = buf).order(ByteOrder.LITTLE_ENDIAN);
} }
protected SimpleBuffer(SimpleBuffer parent, ByteBuffer buf) { protected SimpleBuffer(final SimpleBuffer parent, final ByteBuffer buf) {
super(parent); super((AbstractIoBuffer)parent);
this.buf = buf; (this.buf = buf).order(ByteOrder.LITTLE_ENDIAN);
this.buf.order(ByteOrder.LITTLE_ENDIAN); }
}
public ByteBuffer buf() {
@Override return this.buf;
public ByteBuffer buf() { }
return buf;
} protected void buf(final ByteBuffer buf) {
this.buf = buf;
@Override }
protected void buf(ByteBuffer buf) {
this.buf = buf; protected IoBuffer duplicate0() {
} return (IoBuffer)new SimpleBuffer(this, this.buf.duplicate());
}
@Override
protected IoBuffer duplicate0() { protected IoBuffer slice0() {
return new SimpleBuffer(this, this.buf.duplicate()); return (IoBuffer)new SimpleBuffer(this, this.buf.slice());
} }
@Override protected IoBuffer asReadOnlyBuffer0() {
protected IoBuffer slice0() { return (IoBuffer)new SimpleBuffer(this, this.buf.asReadOnlyBuffer());
return new SimpleBuffer(this, this.buf.slice()); }
}
public byte[] array() {
@Override return this.buf.array();
protected IoBuffer asReadOnlyBuffer0() { }
return new SimpleBuffer(this, this.buf.asReadOnlyBuffer());
} public int arrayOffset() {
return this.buf.arrayOffset();
@Override }
public byte[] array() {
return buf.array(); public boolean hasArray() {
} return this.buf.hasArray();
}
@Override
public int arrayOffset() { public void free() {
return buf.arrayOffset(); }
} }
@Override
public boolean hasArray() {
return buf.hasArray();
}
@Override
public void free() {
// Do nothing
}
}
} }
@@ -1,102 +1,84 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.codec; package com.fangjia.datastore.mongo.codec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
public class BSONOutputStream extends ByteArrayOutputStream { public class BSONOutputStream extends ByteArrayOutputStream
{
private static final String ENCDOING = "UTF-8"; private static final String ENCDOING = "UTF-8";
public BSONOutputStream() { public BSONOutputStream() {
super(); }
}
public BSONOutputStream(final int size) {
public BSONOutputStream(int size) { super(size);
super(size); }
}
public void writeCString(final String s) throws IOException {
public void writeCString(String s) throws IOException { this.write(s.getBytes("UTF-8"));
write(s.getBytes(ENCDOING)); this.write(0);
write(0); }
}
public void writeInteger(final int i) throws IOException {
public void writeInteger(int i) throws IOException { this.write(i);
write(i); this.write(i >> 8);
write(i >> 8); this.write(i >> 16);
write(i >> 16); this.write(i >> 24);
write(i >> 24); }
}
public void writeLong(final long l) throws IOException {
public void writeLong(long l) throws IOException { this.write((byte)l);
write((byte) l); this.write((byte)(l >> 8));
write((byte) (l >> 8)); this.write((byte)(l >> 16));
write((byte) (l >> 16)); this.write((byte)(l >> 24));
write((byte) (l >> 24)); this.write((byte)(l >> 32));
write((byte) (l >> 32)); this.write((byte)(l >> 40));
write((byte) (l >> 40)); this.write((byte)(l >> 48));
write((byte) (l >> 48)); this.write((byte)(l >> 56));
write((byte) (l >> 56)); }
}
public void writeString(final String s) throws IOException {
public void writeString(String s) throws IOException { final byte[] bs = s.getBytes("UTF-8");
byte[] bs = s.getBytes(ENCDOING); this.writeInteger(bs.length + 1);
writeInteger(bs.length + 1); this.write(bs);
write(bs); this.write(0);
write(0); }
}
public void set(final int index, final int i) {
public void set(int index, int i) { final int newcount = Math.max(this.count, index + 4);
int newcount = Math.max(count, index + 4); if (newcount > this.buf.length) {
if (newcount > buf.length) { this.buf = Arrays.copyOf(this.buf, Math.max(this.buf.length << 1, newcount));
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount)); }
} this.buf[index] = (byte)i;
buf[index] = (byte) i; this.buf[index + 1] = (byte)(i >> 8);
buf[index + 1] = (byte) (i >> 8); this.buf[index + 2] = (byte)(i >> 16);
buf[index + 2] = (byte) (i >> 16); this.buf[index + 3] = (byte)(i >> 24);
buf[index + 3] = (byte) (i >> 24); this.count = newcount;
count = newcount; }
}
public void set(final int index, final byte[] b, final int off, final int len) {
public void set(int index, byte[] b, int off, int len) { if (off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0) {
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException();
throw new IndexOutOfBoundsException(); }
} else if (len == 0) { if (len == 0) {
return; return;
} }
int newcount = Math.max(count, index + len); final int newcount = Math.max(this.count, index + len);
if (newcount > buf.length) { if (newcount > this.buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount)); this.buf = Arrays.copyOf(this.buf, Math.max(this.buf.length << 1, newcount));
} }
System.arraycopy(b, off, buf, index, len); System.arraycopy(b, off, this.buf, index, len);
count = newcount; this.count = newcount;
} }
public void setInteger(int index, int i) { public void setInteger(final int index, final int i) {
byte[] b = new byte[] { (byte) i, (byte) (i >> 8), (byte) (i >> 16), (byte) (i >> 24) }; final byte[] b = { (byte)i, (byte)(i >> 8), (byte)(i >> 16), (byte)(i >> 24) };
set(index, b, 0, b.length); this.set(index, b, 0, b.length);
} }
public void setLong(int index, long l) { public void setLong(final int index, final long l) {
byte[] b = new byte[] { (byte) l, (byte) (l >> 8), (byte) (l >> 16), (byte) (l >> 24), (byte) (l >> 32), final byte[] b = { (byte)l, (byte)(l >> 8), (byte)(l >> 16), (byte)(l >> 24), (byte)(l >> 32), (byte)(l >> 40), (byte)(l >> 48), (byte)(l >> 56) };
(byte) (l >> 40), (byte) (l >> 48), (byte) (l >> 56) }; this.set(index, b, 0, b.length);
set(index, b, 0, b.length); }
}
} }
@@ -1,111 +1,108 @@
package com.fangjia.datastore.mongo.codec; package com.fangjia.datastore.mongo.codec;
import org.slf4j.LoggerFactory;
import org.apache.mina.core.buffer.BufferDataException; import org.apache.mina.core.buffer.BufferDataException;
import com.fangjia.datastore.mongo.protocol.UpdateMessage;
import com.fangjia.datastore.mongo.protocol.ReplyMessage;
import com.fangjia.datastore.mongo.protocol.QueryMessage;
import com.fangjia.datastore.mongo.protocol.KillCursorsMessage;
import com.fangjia.datastore.mongo.protocol.InsertMessage;
import com.fangjia.datastore.mongo.protocol.GetMoreMessage;
import com.fangjia.datastore.mongo.protocol.DeleteMessage;
import com.fangjia.datastore.mongo.protocol.MongoMessage;
import org.apache.mina.filter.codec.ProtocolDecoderException;
import com.fangjia.datastore.mongo.protocol.OperationCode;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession; import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderException;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import com.fangjia.datastore.mongo.protocol.DeleteMessage;
import com.fangjia.datastore.mongo.protocol.GetMoreMessage;
import com.fangjia.datastore.mongo.protocol.InsertMessage;
import com.fangjia.datastore.mongo.protocol.KillCursorsMessage;
import com.fangjia.datastore.mongo.protocol.MongoMessage;
import com.fangjia.datastore.mongo.protocol.OperationCode;
import com.fangjia.datastore.mongo.protocol.QueryMessage;
import com.fangjia.datastore.mongo.protocol.ReplyMessage;
import com.fangjia.datastore.mongo.protocol.UpdateMessage;
public class MongoProtocolDecoder extends CumulativeProtocolDecoder {
private final static Logger LOGGER = LoggerFactory.getLogger(MongoProtocolDecoder.class);
@Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
try {
if (!prefixedDataAvailable(in, 4, true)) {
return false;
}
int start = in.position();
int limit = in.limit();
int messageSize = in.getInt(start);
in.limit(start + messageSize);
try {
final IoBuffer buf = in.slice();
int opCodeValue = buf.getInt(buf.position() + 12);
OperationCode opCode = OperationCode.valueOf(opCodeValue);
MongoMessage message = newInstance(opCode);
BSONInputStream input = new BSONInputStream(buf);
message.read(input);
out.write(message);
return true;
} finally {
in.position(start + messageSize);
in.limit(limit);
}
} catch (Exception e) {
ProtocolDecoderException pde = new ProtocolDecoderException("error decode message:", e);
pde.setHexdump(in.getHexDump());
LOGGER.error("", pde);
throw pde;
}
}
private MongoMessage newInstance(OperationCode opCode) {
switch (opCode) {
case OP_DELETE:
return new DeleteMessage();
case OP_GET_MORE:
return new GetMoreMessage();
case OP_INSERT:
return new InsertMessage();
case OP_KILL_CURSORS:
return new KillCursorsMessage();
case OP_QUERY:
return new QueryMessage();
case OP_REPLY:
return new ReplyMessage();
case OP_UPDATE:
return new UpdateMessage();
case OP_MSG:
case RESERVED:
default:
return null;
}
}
public boolean prefixedDataAvailable(IoBuffer buffer, int prefixLength, boolean includePrefix) {
if (buffer.remaining() < prefixLength) {
return false;
}
int dataLength;
switch (prefixLength) {
case 1:
dataLength = buffer.getUnsigned(buffer.position());
break;
case 2:
dataLength = buffer.getUnsignedShort(buffer.position());
break;
case 4:
dataLength = buffer.getInt(buffer.position());
break;
default:
throw new IllegalArgumentException("prefixLength: " + prefixLength);
}
if (dataLength < 0) {
throw new BufferDataException("dataLength: " + dataLength);
}
if (includePrefix) {
return buffer.remaining() >= dataLength;
} else {
return buffer.remaining() - prefixLength >= dataLength;
}
}
public class MongoProtocolDecoder extends CumulativeProtocolDecoder
{
private static final Logger LOGGER;
protected boolean doDecode(final IoSession session, final IoBuffer in, final ProtocolDecoderOutput out) throws Exception {
try {
if (!this.prefixedDataAvailable(in, 4, true)) {
return false;
}
final int start = in.position();
final int limit = in.limit();
final int messageSize = in.getInt(start);
in.limit(start + messageSize);
try {
final IoBuffer buf = in.slice();
final int opCodeValue = buf.getInt(buf.position() + 12);
final OperationCode opCode = OperationCode.valueOf(opCodeValue);
final MongoMessage message = this.newInstance(opCode);
final BSONInputStream input = new BSONInputStream(buf);
message.read(input);
out.write((Object)message);
return true;
}
finally {
in.position(start + messageSize);
in.limit(limit);
}
}
catch (Exception e) {
final ProtocolDecoderException pde = new ProtocolDecoderException("error decode message:", (Throwable)e);
pde.setHexdump(in.getHexDump());
MongoProtocolDecoder.LOGGER.error("", (Throwable)pde);
throw pde;
}
}
private MongoMessage newInstance(final OperationCode opCode) {
switch (opCode) {
case OP_DELETE:
return new DeleteMessage();
case OP_GET_MORE:
return new GetMoreMessage();
case OP_INSERT:
return new InsertMessage();
case OP_KILL_CURSORS:
return new KillCursorsMessage();
case OP_QUERY:
return new QueryMessage();
case OP_REPLY:
return new ReplyMessage();
case OP_UPDATE:
return new UpdateMessage();
default:
return null;
}
}
public boolean prefixedDataAvailable(final IoBuffer buffer, final int prefixLength, final boolean includePrefix) {
if (buffer.remaining() < prefixLength) {
return false;
}
int dataLength = 0;
switch (prefixLength) {
case 1:
dataLength = buffer.getUnsigned(buffer.position());
break;
case 2:
dataLength = buffer.getUnsignedShort(buffer.position());
break;
case 4:
dataLength = buffer.getInt(buffer.position());
break;
default:
throw new IllegalArgumentException("prefixLength: " + prefixLength);
}
if (dataLength < 0) {
throw new BufferDataException("dataLength: " + dataLength);
}
if (includePrefix) {
return buffer.remaining() >= dataLength;
}
return buffer.remaining() - prefixLength >= dataLength;
}
static {
LOGGER = LoggerFactory.getLogger((Class)MongoProtocolDecoder.class);
}
} }
@@ -1,36 +1,38 @@
package com.fangjia.datastore.mongo.codec; package com.fangjia.datastore.mongo.codec;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderException;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.apache.mina.filter.codec.ProtocolEncoderException;
import org.apache.mina.core.buffer.IoBuffer;
import com.fangjia.datastore.mongo.protocol.MongoMessage; import com.fangjia.datastore.mongo.protocol.MongoMessage;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.apache.mina.filter.codec.ProtocolEncoder;
public class MongoProtocolEncoder implements ProtocolEncoder { public class MongoProtocolEncoder implements ProtocolEncoder
{
private final static Logger LOGGER = LoggerFactory.getLogger(MongoProtocolEncoder.class); private static final Logger LOGGER;
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { public void encode(final IoSession session, final Object message, final ProtocolEncoderOutput out) throws Exception {
try { try {
if (message instanceof MongoMessage) { if (message instanceof MongoMessage) {
MongoMessage mongoMessage = (MongoMessage) message; final MongoMessage mongoMessage = (MongoMessage)message;
BSONOutputStream output = new BSONOutputStream(mongoMessage.getMessageHeader().getMessageLength()); final BSONOutputStream output = new BSONOutputStream(mongoMessage.getMessageHeader().getMessageLength());
mongoMessage.write(output); mongoMessage.write(output);
out.write(IoBuffer.wrap(output.toByteArray())); out.write((Object)IoBuffer.wrap(output.toByteArray()));
} }
} catch (Exception e) { }
ProtocolEncoderException pe = new ProtocolEncoderException("error encode message: " + message, e); catch (Exception e) {
LOGGER.error("", pe); final ProtocolEncoderException pe = new ProtocolEncoderException("error encode message: " + message, (Throwable)e);
throw pe; MongoProtocolEncoder.LOGGER.error("", (Throwable)pe);
} throw pe;
} }
}
public void dispose(IoSession session) throws Exception {
// empty public void dispose(final IoSession session) throws Exception {
} }
static {
LOGGER = LoggerFactory.getLogger((Class)MongoProtocolEncoder.class);
}
} }
@@ -1,111 +1,98 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException;
import org.bson.BSONDecoder;
import org.bson.BSONEncoder;
import org.bson.BSONObject;
import org.bson.BasicBSONDecoder;
import org.bson.BasicBSONObject;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import com.fangjia.datastore.utils.BSONUtils; import com.fangjia.datastore.utils.BSONUtils;
import org.bson.BSONDecoder;
import java.io.InputStream;
import org.bson.BasicBSONDecoder;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import java.io.IOException;
import org.bson.BSONEncoder;
import org.bson.BasicBSONEncoder;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import org.bson.BasicBSONObject;
import org.bson.BSONObject;
public class DeleteMessage implements MongoMessage { public class DeleteMessage implements MongoMessage
{
private static final long serialVersionUID = -3350216587439425208L; private static final long serialVersionUID = -3350216587439425208L;
private MessageHeader messageHeader; private MessageHeader messageHeader;
private String fullCollectionName; private String fullCollectionName;
private int flags; private int flags;
private BSONObject selector; private BSONObject selector;
public DeleteMessage() { public DeleteMessage() {
messageHeader = new MessageHeader(OperationCode.OP_DELETE); this.messageHeader = new MessageHeader(OperationCode.OP_DELETE);
selector = new BasicBSONObject(); this.selector = (BSONObject)new BasicBSONObject();
} }
public void write(BSONOutputStream out) throws IOException { @Override
messageHeader.write(out); public void write(final BSONOutputStream out) throws IOException {
out.writeInteger(0); this.messageHeader.write(out);
out.writeCString(this.fullCollectionName); out.writeInteger(0);
out.writeInteger(this.flags); out.writeCString(this.fullCollectionName);
BSONEncoder encoder = new BSONEncoder(); out.writeInteger(this.flags);
out.write(encoder.encode(selector)); final BSONEncoder encoder = (BSONEncoder)new BasicBSONEncoder();
out.set(0, out.size()); out.write(encoder.encode(this.selector));
} out.set(0, out.size());
}
public void read(BSONInputStream in) throws IOException {
messageHeader.read(in); @Override
in.readInteger(); public void read(final BSONInputStream in) throws IOException {
this.fullCollectionName = in.readCString(); this.messageHeader.read(in);
this.flags = in.readInteger(); in.readInteger();
BSONDecoder decoder = new BasicBSONDecoder(); this.fullCollectionName = in.readCString();
selector = decoder.readObject(in); this.flags = in.readInteger();
} final BSONDecoder decoder = (BSONDecoder)new BasicBSONDecoder();
this.selector = decoder.readObject((InputStream)in);
public MessageHeader getMessageHeader() { }
return messageHeader;
} @Override
public MessageHeader getMessageHeader() {
public String getFullCollectionName() { return this.messageHeader;
return fullCollectionName; }
}
public String getFullCollectionName() {
public void setFullCollectionName(String fullCollectionName) { return this.fullCollectionName;
this.fullCollectionName = fullCollectionName; }
}
public void setFullCollectionName(final String fullCollectionName) {
public int getFlags() { this.fullCollectionName = fullCollectionName;
return flags; }
}
public int getFlags() {
public void setFlags(int flags) { return this.flags;
this.flags = flags; }
}
public void setFlags(final int flags) {
public void setSingleRemove(boolean b) { this.flags = flags;
this.flags = (int) BSONUtils.bitSet(this.flags, 0, b); }
}
public void setSingleRemove(final boolean b) {
public BSONObject getSelector() { this.flags = (int)BSONUtils.bitSet(this.flags, 0, b);
return selector; }
}
public BSONObject getSelector() {
public void setSelector(BSONObject selector) { return this.selector;
this.selector = selector; }
}
public void setSelector(final BSONObject selector) {
public String toString() { this.selector = selector;
StringBuilder builder = new StringBuilder(); }
builder.append("{");
builder.append("messageHeader:").append(messageHeader); @Override
builder.append(", fullCollectionName:").append(fullCollectionName); public String toString() {
builder.append(", flags:").append(flags); final StringBuilder builder = new StringBuilder();
builder.append(", selector:").append(selector); builder.append("{");
builder.append("}"); builder.append("messageHeader:").append(this.messageHeader);
return builder.toString(); builder.append(", fullCollectionName:").append(this.fullCollectionName);
} builder.append(", flags:").append(this.flags);
builder.append(", selector:").append(this.selector);
public String toPrettyString() { builder.append("}");
return toString(); return builder.toString();
} }
@Override
public String toPrettyString() {
return this.toString();
}
} }
@@ -1,97 +1,83 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException;
import com.fangjia.datastore.mongo.codec.BSONInputStream; import com.fangjia.datastore.mongo.codec.BSONInputStream;
import java.io.IOException;
import com.fangjia.datastore.mongo.codec.BSONOutputStream; import com.fangjia.datastore.mongo.codec.BSONOutputStream;
public class GetMoreMessage implements MongoMessage { public class GetMoreMessage implements MongoMessage
{
private static final long serialVersionUID = -3350216587439425208L; private static final long serialVersionUID = -3350216587439425208L;
private MessageHeader messageHeader; private MessageHeader messageHeader;
private String fullCollectionName; private String fullCollectionName;
private int numberToReturn; private int numberToReturn;
private long cursorID; private long cursorID;
public GetMoreMessage() { public GetMoreMessage() {
messageHeader = new MessageHeader(OperationCode.OP_GET_MORE); this.messageHeader = new MessageHeader(OperationCode.OP_GET_MORE);
} }
public void write(BSONOutputStream out) throws IOException { @Override
messageHeader.write(out); public void write(final BSONOutputStream out) throws IOException {
out.writeInteger(0); this.messageHeader.write(out);
out.writeCString(this.fullCollectionName); out.writeInteger(0);
out.writeInteger(this.numberToReturn); out.writeCString(this.fullCollectionName);
out.writeLong(cursorID); out.writeInteger(this.numberToReturn);
out.set(0, out.size()); out.writeLong(this.cursorID);
} out.set(0, out.size());
}
public void read(BSONInputStream in) throws IOException {
messageHeader.read(in); @Override
in.readInteger(); public void read(final BSONInputStream in) throws IOException {
this.fullCollectionName = in.readCString(); this.messageHeader.read(in);
this.numberToReturn = in.readInteger(); in.readInteger();
this.cursorID = in.readLong(); this.fullCollectionName = in.readCString();
} this.numberToReturn = in.readInteger();
this.cursorID = in.readLong();
public MessageHeader getMessageHeader() { }
return messageHeader;
} @Override
public MessageHeader getMessageHeader() {
public String getFullCollectionName() { return this.messageHeader;
return fullCollectionName; }
}
public String getFullCollectionName() {
public void setFullCollectionName(String fullCollectionName) { return this.fullCollectionName;
this.fullCollectionName = fullCollectionName; }
}
public void setFullCollectionName(final String fullCollectionName) {
public int getNumberToReturn() { this.fullCollectionName = fullCollectionName;
return numberToReturn; }
}
public int getNumberToReturn() {
public void setNumberToReturn(int numberToReturn) { return this.numberToReturn;
this.numberToReturn = numberToReturn; }
}
public void setNumberToReturn(final int numberToReturn) {
public long getCursorID() { this.numberToReturn = numberToReturn;
return cursorID; }
}
public long getCursorID() {
public void setCursorID(long cursorID) { return this.cursorID;
this.cursorID = cursorID; }
}
public void setCursorID(final long cursorID) {
public String toString() { this.cursorID = cursorID;
StringBuilder builder = new StringBuilder(); }
builder.append("{");
builder.append("messageHeader:").append(messageHeader); @Override
builder.append(", fullCollectionName:").append(fullCollectionName); public String toString() {
builder.append(", numberToReturn:").append(numberToReturn); final StringBuilder builder = new StringBuilder();
builder.append(", cursorID:").append(cursorID); builder.append("{");
builder.append("}"); builder.append("messageHeader:").append(this.messageHeader);
return builder.toString(); builder.append(", fullCollectionName:").append(this.fullCollectionName);
} builder.append(", numberToReturn:").append(this.numberToReturn);
builder.append(", cursorID:").append(this.cursorID);
public String toPrettyString() { builder.append("}");
return toString(); return builder.toString();
} }
@Override
public String toPrettyString() {
return this.toString();
}
} }
@@ -1,116 +1,105 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException; import org.bson.BSONDecoder;
import java.io.InputStream;
import org.bson.BasicBSONDecoder;
import java.util.ArrayList; import java.util.ArrayList;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.bson.BSONEncoder;
import org.bson.BasicBSONEncoder;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import org.bson.BSONObject;
import java.util.List; import java.util.List;
import org.bson.BSONDecoder; public class InsertMessage implements MongoMessage
import org.bson.BSONEncoder; {
import org.bson.BSONObject; private static final long serialVersionUID = -3350216587439425208L;
import org.bson.BasicBSONDecoder; private MessageHeader messageHeader;
private String fullCollectionName;
import com.fangjia.datastore.mongo.codec.BSONInputStream; private List<BSONObject> documents;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
public InsertMessage() {
public class InsertMessage implements MongoMessage { this.messageHeader = new MessageHeader(OperationCode.OP_INSERT);
}
private static final long serialVersionUID = -3350216587439425208L;
private MessageHeader messageHeader; @Override
private String fullCollectionName; public void write(final BSONOutputStream out) throws IOException {
private List<BSONObject> documents; this.messageHeader.write(out);
out.writeInteger(0);
public InsertMessage() { out.writeCString(this.fullCollectionName);
messageHeader = new MessageHeader(OperationCode.OP_INSERT); if (null != this.documents && this.documents.size() > 0) {
} final BSONEncoder encoder = (BSONEncoder)new BasicBSONEncoder();
for (final BSONObject doc : this.documents) {
public void write(BSONOutputStream out) throws IOException { out.write(encoder.encode(doc));
messageHeader.write(out); }
out.writeInteger(0); }
out.writeCString(this.fullCollectionName); out.setInteger(0, out.size());
if (null != documents && documents.size() > 0) { }
BSONEncoder encoder = new BSONEncoder();
for (BSONObject doc : documents) { @Override
out.write(encoder.encode(doc)); public void read(final BSONInputStream in) throws IOException {
} this.messageHeader.read(in);
} in.readInteger();
out.setInteger(0, out.size()); this.fullCollectionName = in.readCString();
} while (in.available() > 0) {
if (null == this.documents) {
public void read(BSONInputStream in) throws IOException { this.documents = new ArrayList<BSONObject>();
messageHeader.read(in); }
in.readInteger(); final BSONDecoder decoder = (BSONDecoder)new BasicBSONDecoder();
this.fullCollectionName = in.readCString(); this.documents.add(decoder.readObject((InputStream)in));
while (in.available() > 0) { }
if (null == documents) { }
documents = new ArrayList<BSONObject>();
} @Override
BSONDecoder decoder = new BasicBSONDecoder(); public MessageHeader getMessageHeader() {
documents.add(decoder.readObject(in)); return this.messageHeader;
} }
}
public String getFullCollectionName() {
public MessageHeader getMessageHeader() { return this.fullCollectionName;
return messageHeader; }
}
public void setFullCollectionName(final String fullCollectionName) {
public String getFullCollectionName() { this.fullCollectionName = fullCollectionName;
return fullCollectionName; }
}
public List<BSONObject> getDocuments() {
public void setFullCollectionName(String fullCollectionName) { return this.documents;
this.fullCollectionName = fullCollectionName; }
}
public void setDocuments(final List<BSONObject> documents) {
public List<BSONObject> getDocuments() { this.documents = documents;
return documents; }
}
@Override
public void setDocuments(List<BSONObject> documents) { public String toString() {
this.documents = documents; final StringBuilder builder = new StringBuilder();
} builder.append("{");
builder.append("messageHeader:").append(this.messageHeader);
public String toString() { builder.append(", fullCollectionName:").append(this.fullCollectionName);
StringBuilder builder = new StringBuilder(); builder.append(", documents:").append(this.documents);
builder.append("{"); builder.append("}");
builder.append("messageHeader:").append(messageHeader); return builder.toString();
builder.append(", fullCollectionName:").append(fullCollectionName); }
builder.append(", documents:").append(documents);
builder.append("}"); @Override
return builder.toString(); public String toPrettyString() {
} final StringBuilder builder = new StringBuilder();
builder.append("{");
public String toPrettyString() { builder.append("messageHeader:").append(this.messageHeader);
StringBuilder builder = new StringBuilder(); builder.append(", fullCollectionName:").append(this.fullCollectionName);
builder.append("{"); if (null != this.documents && this.documents.size() > 0) {
builder.append("messageHeader:").append(messageHeader); builder.append(", documents:").append(this.documents.get(0).get("_id"));
builder.append(", fullCollectionName:").append(fullCollectionName); if (this.documents.size() > 1) {
if (null != documents && documents.size() > 0) { builder.append("...").append(this.documents.size() - 1).append(" more");
builder.append(", documents:").append(documents.get(0).get("_id")); }
if (documents.size() > 1) { }
builder.append("...").append(documents.size() - 1).append(" more"); else {
} builder.append(", documents:").append(this.documents);
} else { }
builder.append(", documents:").append(documents); builder.append("}");
} return builder.toString();
builder.append("}"); }
return builder.toString();
}
} }
@@ -1,96 +1,83 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import java.io.IOException;
import java.util.Iterator;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import java.util.List; import java.util.List;
import com.fangjia.datastore.mongo.codec.BSONInputStream; public class KillCursorsMessage implements MongoMessage
import com.fangjia.datastore.mongo.codec.BSONOutputStream; {
private static final long serialVersionUID = -3350216587439425208L;
public class KillCursorsMessage implements MongoMessage { private MessageHeader messageHeader;
private int numberOfCursorIDs;
private static final long serialVersionUID = -3350216587439425208L; private List<Long> cursorIDs;
private MessageHeader messageHeader;
private int numberOfCursorIDs; public KillCursorsMessage() {
private List<Long> cursorIDs; this.messageHeader = new MessageHeader(OperationCode.OP_KILL_CURSORS);
}
public KillCursorsMessage() {
messageHeader = new MessageHeader(OperationCode.OP_KILL_CURSORS); @Override
} public MessageHeader getMessageHeader() {
return this.messageHeader;
public MessageHeader getMessageHeader() { }
return messageHeader;
} @Override
public void write(final BSONOutputStream out) throws IOException {
public void write(BSONOutputStream out) throws IOException { this.messageHeader.write(out);
messageHeader.write(out); out.writeInteger(0);
out.writeInteger(0); out.writeInteger(this.numberOfCursorIDs);
out.writeInteger(numberOfCursorIDs); if (null != this.cursorIDs) {
if (null != cursorIDs) { for (final Long id : this.cursorIDs) {
for (Long id : cursorIDs) { out.writeLong(id);
out.writeLong(id); }
} }
} out.set(0, out.size());
out.set(0, out.size()); }
}
@Override
public void read(BSONInputStream in) throws IOException { public void read(final BSONInputStream in) throws IOException {
messageHeader.read(in); this.messageHeader.read(in);
in.readInteger(); in.readInteger();
numberOfCursorIDs = in.readInteger(); this.numberOfCursorIDs = in.readInteger();
while (in.available() > 0) { while (in.available() > 0) {
if (null == cursorIDs) { if (null == this.cursorIDs) {
cursorIDs = new ArrayList<Long>(); this.cursorIDs = new ArrayList<Long>();
} }
cursorIDs.add(in.readLong()); this.cursorIDs.add(in.readLong());
} }
} }
public int getNumberOfCursorIDs() { public int getNumberOfCursorIDs() {
return numberOfCursorIDs; return this.numberOfCursorIDs;
} }
public void setNumberOfCursorIDs(int numberOfCursorIDs) { public void setNumberOfCursorIDs(final int numberOfCursorIDs) {
this.numberOfCursorIDs = numberOfCursorIDs; this.numberOfCursorIDs = numberOfCursorIDs;
} }
public List<Long> getCursorIDs() { public List<Long> getCursorIDs() {
return cursorIDs; return this.cursorIDs;
} }
public void setCursorIDs(List<Long> cursorIDs) { public void setCursorIDs(final List<Long> cursorIDs) {
this.cursorIDs = cursorIDs; this.cursorIDs = cursorIDs;
} }
public String toString() { @Override
StringBuilder builder = new StringBuilder(); public String toString() {
builder.append("{"); final StringBuilder builder = new StringBuilder();
builder.append("messageHeader:").append(messageHeader); builder.append("{");
builder.append(", numberOfCursorIDs:").append(numberOfCursorIDs); builder.append("messageHeader:").append(this.messageHeader);
builder.append(", cursorIDs:").append(cursorIDs); builder.append(", numberOfCursorIDs:").append(this.numberOfCursorIDs);
builder.append("}"); builder.append(", cursorIDs:").append(this.cursorIDs);
return builder.toString(); builder.append("}");
} return builder.toString();
}
public String toPrettyString() {
return toString(); @Override
} public String toPrettyString() {
return this.toString();
}
} }
@@ -1,106 +1,93 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import com.fangjia.datastore.mongo.codec.BSONOutputStream; import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import java.io.IOException;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.Serializable;
public final class MessageHeader implements Writable, Readable, Serializable { public final class MessageHeader implements Writable, Readable, Serializable
private static final long serialVersionUID = 8505270142383450097L; {
private static final AtomicInteger ID_GENERATOR = new AtomicInteger(1); private static final long serialVersionUID = 8505270142383450097L;
private static final AtomicInteger ID_GENERATOR;
private int messageLength; private int messageLength;
private int requestID; private int requestID;
private int responseTo; private int responseTo;
private OperationCode opCode; private OperationCode opCode;
public MessageHeader(OperationCode opCode) { public MessageHeader(final OperationCode opCode) {
this.opCode = opCode; this.opCode = opCode;
this.requestID = ID_GENERATOR.getAndIncrement(); this.requestID = MessageHeader.ID_GENERATOR.getAndIncrement();
} }
public MessageHeader() { public MessageHeader() {
} }
public void read(BSONInputStream in) throws IOException { @Override
messageLength = in.readInteger(); public void read(final BSONInputStream in) throws IOException {
requestID = in.readInteger(); this.messageLength = in.readInteger();
responseTo = in.readInteger(); this.requestID = in.readInteger();
opCode = OperationCode.valueOf(in.readInteger()); this.responseTo = in.readInteger();
} this.opCode = OperationCode.valueOf(in.readInteger());
}
public void write(BSONOutputStream out) throws IOException {
out.writeInteger(messageLength); @Override
out.writeInteger(requestID); public void write(final BSONOutputStream out) throws IOException {
out.writeInteger(responseTo); out.writeInteger(this.messageLength);
out.writeInteger(opCode.getValue()); out.writeInteger(this.requestID);
} out.writeInteger(this.responseTo);
out.writeInteger(this.opCode.getValue());
public int size() { }
return 16;
} public int size() {
return 16;
public int getMessageLength() { }
return messageLength;
} public int getMessageLength() {
return this.messageLength;
public void setMessageLength(int messageLength) { }
this.messageLength = messageLength;
} public void setMessageLength(final int messageLength) {
this.messageLength = messageLength;
public int getRequestID() { }
return requestID;
} public int getRequestID() {
return this.requestID;
public void setRequestID(int requestID) { }
this.requestID = requestID;
} public void setRequestID(final int requestID) {
this.requestID = requestID;
public int getResponseTo() { }
return responseTo;
} public int getResponseTo() {
return this.responseTo;
public void setResponseTo(int responseTo) { }
this.responseTo = responseTo;
} public void setResponseTo(final int responseTo) {
this.responseTo = responseTo;
public OperationCode getOpCode() { }
return opCode;
} public OperationCode getOpCode() {
return this.opCode;
public void setOpCode(OperationCode opCode) { }
this.opCode = opCode;
} public void setOpCode(final OperationCode opCode) {
this.opCode = opCode;
@Override }
public String toString() {
StringBuilder builder = new StringBuilder(); @Override
builder.append("{"); public String toString() {
builder.append("messageLength:").append(messageLength); final StringBuilder builder = new StringBuilder();
builder.append(", requestID:").append(requestID); builder.append("{");
builder.append(", responseTo:").append(responseTo); builder.append("messageLength:").append(this.messageLength);
builder.append(", opCode:").append(opCode); builder.append(", requestID:").append(this.requestID);
builder.append("}"); builder.append(", responseTo:").append(this.responseTo);
return builder.toString(); builder.append(", opCode:").append(this.opCode);
} builder.append("}");
return builder.toString();
}
static {
ID_GENERATOR = new AtomicInteger(1);
}
} }
@@ -1,26 +1,10 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.Serializable; import java.io.Serializable;
public interface MongoMessage extends Readable, Writable, Serializable { public interface MongoMessage extends Readable, Writable, Serializable
public MessageHeader getMessageHeader(); {
MessageHeader getMessageHeader();
public String toPrettyString();
String toPrettyString();
} }
@@ -1,82 +1,39 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public enum OperationCode { public enum OperationCode
/** {
* Reply to a client request. responseTo is set OP_REPLY(1),
*/ OP_MSG(1000),
OP_REPLY(1), OP_UPDATE(2001),
/** OP_INSERT(2002),
* generic msg command followed by a string RESERVED(2003),
*/ OP_QUERY(2004),
OP_MSG(1000), OP_GET_MORE(2005),
/** OP_DELETE(2006),
* update document OP_KILL_CURSORS(2007);
*/
OP_UPDATE(2001), private final int value;
/** private static final Map<Integer, OperationCode> TYPE_MAP;
* insert new document
*/ private OperationCode(final int value) {
OP_INSERT(2002), this.value = value;
/** }
* formerly used for OP_GET_BY_OID
*/ public int getValue() {
RESERVED(2003), return this.value;
/** }
* query a collection
*/ public static OperationCode valueOf(final int value) {
OP_QUERY(2004), return OperationCode.TYPE_MAP.get(value);
/** }
* Get more data from a query. See Cursors
*/ static {
OP_GET_MORE(2005), TYPE_MAP = new HashMap<Integer, OperationCode>();
/** for (final OperationCode e : values()) {
* Delete documents OperationCode.TYPE_MAP.put(e.value, e);
*/ }
OP_DELETE(2006), }
/**
* Tell database client is done with a cursor
*/
OP_KILL_CURSORS(2007);
private final int value;
private final static Map<Integer, OperationCode> TYPE_MAP = new HashMap<Integer, OperationCode>();
static {
for (OperationCode e : OperationCode.values()) {
TYPE_MAP.put(e.value, e);
}
}
private OperationCode(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static OperationCode valueOf(int value) {
return TYPE_MAP.get(value);
}
} }
@@ -1,213 +1,197 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException;
import org.bson.BSONDecoder;
import org.bson.BSONEncoder;
import org.bson.BSONObject;
import org.bson.BasicBSONDecoder;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import com.fangjia.datastore.utils.BSONUtils; import com.fangjia.datastore.utils.BSONUtils;
import org.bson.BSONDecoder;
import java.io.InputStream;
import org.bson.BasicBSONDecoder;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import java.io.IOException;
import org.bson.BSONEncoder;
import org.bson.BasicBSONEncoder;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import org.bson.BSONObject;
public class QueryMessage implements MongoMessage { public class QueryMessage implements MongoMessage
{
private static final long serialVersionUID = -3350216587439425208L; private static final long serialVersionUID = -3350216587439425208L;
private MessageHeader messageHeader; private MessageHeader messageHeader;
private int options; private int options;
private int numberToSkip; private int numberToSkip;
private int numberToReturn; private int numberToReturn;
private String fullCollectionName; private String fullCollectionName;
private BSONObject query; private BSONObject query;
private BSONObject returnFieldSelector; private BSONObject returnFieldSelector;
public QueryMessage() { public QueryMessage() {
messageHeader = new MessageHeader(OperationCode.OP_QUERY); this.messageHeader = new MessageHeader(OperationCode.OP_QUERY);
} }
public void write(BSONOutputStream out) throws IOException { @Override
messageHeader.write(out); public void write(final BSONOutputStream out) throws IOException {
out.writeInteger(options); this.messageHeader.write(out);
out.writeCString(this.fullCollectionName); out.writeInteger(this.options);
out.writeInteger(numberToSkip); out.writeCString(this.fullCollectionName);
out.writeInteger(numberToReturn); out.writeInteger(this.numberToSkip);
BSONEncoder encoder = new BSONEncoder(); out.writeInteger(this.numberToReturn);
out.write(encoder.encode(query)); final BSONEncoder encoder = (BSONEncoder)new BasicBSONEncoder();
if (null != returnFieldSelector) { out.write(encoder.encode(this.query));
out.write(encoder.encode(returnFieldSelector)); if (null != this.returnFieldSelector) {
} out.write(encoder.encode(this.returnFieldSelector));
out.set(0, out.size()); }
} out.set(0, out.size());
}
public void read(BSONInputStream in) throws IOException {
messageHeader.read(in); @Override
options = in.readInteger(); public void read(final BSONInputStream in) throws IOException {
this.fullCollectionName = in.readCString(); this.messageHeader.read(in);
this.numberToSkip = in.readInteger(); this.options = in.readInteger();
this.numberToReturn = in.readInteger(); this.fullCollectionName = in.readCString();
BSONDecoder decoder = new BasicBSONDecoder(); this.numberToSkip = in.readInteger();
query = decoder.readObject(in); this.numberToReturn = in.readInteger();
if (in.available() > 0) { final BSONDecoder decoder = (BSONDecoder)new BasicBSONDecoder();
returnFieldSelector = decoder.readObject(in); this.query = decoder.readObject((InputStream)in);
} if (in.available() > 0) {
} this.returnFieldSelector = decoder.readObject((InputStream)in);
}
public MessageHeader getMessageHeader() { }
return messageHeader;
} @Override
public MessageHeader getMessageHeader() {
public String getFullCollectionName() { return this.messageHeader;
return fullCollectionName; }
}
public String getFullCollectionName() {
public void setFullCollectionName(String fullCollectionName) { return this.fullCollectionName;
this.fullCollectionName = fullCollectionName; }
}
public void setFullCollectionName(final String fullCollectionName) {
public int getOptions() { this.fullCollectionName = fullCollectionName;
return options; }
}
public int getOptions() {
public void setOptions(int options) { return this.options;
this.options = options; }
}
public void setOptions(final int options) {
public void setNoCursorTimeout(boolean b) { this.options = options;
this.options = (int) BSONUtils.bitSet(options, 4, b); }
}
public void setNoCursorTimeout(final boolean b) {
public void setTailable(boolean b) { this.options = (int)BSONUtils.bitSet(this.options, 4, b);
this.options = (int) BSONUtils.bitSet(options, 1, b); }
}
public void setTailable(final boolean b) {
public void setSlaveOk(boolean b) { this.options = (int)BSONUtils.bitSet(this.options, 1, b);
this.options = (int) BSONUtils.bitSet(options, 2, b); }
}
public void setSlaveOk(final boolean b) {
public void setAwaitData(boolean b) { this.options = (int)BSONUtils.bitSet(this.options, 2, b);
this.options = (int) BSONUtils.bitSet(options, 5, b); }
}
public void setAwaitData(final boolean b) {
public int getNumberToSkip() { this.options = (int)BSONUtils.bitSet(this.options, 5, b);
return numberToSkip; }
}
public int getNumberToSkip() {
public void setNumberToSkip(int numberToSkip) { return this.numberToSkip;
this.numberToSkip = numberToSkip; }
}
public void setNumberToSkip(final int numberToSkip) {
public int getNumberToReturn() { this.numberToSkip = numberToSkip;
return numberToReturn; }
}
public int getNumberToReturn() {
public void setNumberToReturn(int numberToReturn) { return this.numberToReturn;
this.numberToReturn = numberToReturn; }
}
public void setNumberToReturn(final int numberToReturn) {
public BSONObject getQuery() { this.numberToReturn = numberToReturn;
return query; }
}
public BSONObject getQuery() {
public void setQuery(BSONObject query) { return this.query;
this.query = query; }
}
public void setQuery(final BSONObject query) {
public BSONObject getRealQuery() { this.query = query;
if (null == query) { }
return null;
} public BSONObject getRealQuery() {
BSONObject q = (BSONObject) query.get("$query"); if (null == this.query) {
if (null == q) { return null;
q = (BSONObject) query.get("query"); }
if (null == q) { BSONObject q = (BSONObject)this.query.get("$query");
q = query; if (null == q) {
} q = (BSONObject)this.query.get("query");
} if (null == q) {
return q; q = this.query;
} }
}
public BSONObject getOrderByQuery() { return q;
if (null == query) { }
return null;
} public BSONObject getOrderByQuery() {
BSONObject q = (BSONObject) query.get("$orderby"); if (null == this.query) {
if (null == q) { return null;
q = (BSONObject) query.get("orderby"); }
} BSONObject q = (BSONObject)this.query.get("$orderby");
return q; if (null == q) {
} q = (BSONObject)this.query.get("orderby");
}
public BSONObject getFacetQuery() { return q;
BSONObject q = getRealQuery(); }
if (null == q) {
return null; public BSONObject getFacetQuery() {
} final BSONObject q = this.getRealQuery();
return (BSONObject) q.get("$facet"); if (null == q) {
} return null;
}
public boolean isBulkQuery() { return (BSONObject)q.get("$facet");
BSONObject q = getRealQuery(); }
if (null == q) {
return true; public boolean isBulkQuery() {
} final BSONObject q = this.getRealQuery();
Boolean bulk = (Boolean) q.get("$bulk"); if (null == q) {
return true;
return null == bulk ? true : bulk; }
} final Boolean bulk = (Boolean)q.get("$bulk");
return null == bulk || bulk;
public boolean isFromMaster() { }
BSONObject q = getRealQuery();
if (null == q) { public boolean isFromMaster() {
return false; final BSONObject q = this.getRealQuery();
} if (null == q) {
Boolean master = (Boolean) q.get("$master"); return false;
}
return null == master ? false : master; final Boolean master = (Boolean)q.get("$master");
} return null != master && master;
}
public BSONObject getReturnFieldSelector() {
return returnFieldSelector; public BSONObject getReturnFieldSelector() {
} return this.returnFieldSelector;
}
public void setReturnFieldSelector(BSONObject returnFieldSelector) {
this.returnFieldSelector = returnFieldSelector; public void setReturnFieldSelector(final BSONObject returnFieldSelector) {
} this.returnFieldSelector = returnFieldSelector;
}
@Override
public String toString() { @Override
StringBuilder builder = new StringBuilder(); public String toString() {
builder.append("{"); final StringBuilder builder = new StringBuilder();
builder.append("messageHeader:").append(messageHeader); builder.append("{");
builder.append(", options:").append(options); builder.append("messageHeader:").append(this.messageHeader);
builder.append(", numberToSkip:").append(numberToSkip); builder.append(", options:").append(this.options);
builder.append(", numberToReturn:").append(numberToReturn); builder.append(", numberToSkip:").append(this.numberToSkip);
builder.append(", fullCollectionName:").append(fullCollectionName); builder.append(", numberToReturn:").append(this.numberToReturn);
builder.append(", query:").append(query); builder.append(", fullCollectionName:").append(this.fullCollectionName);
builder.append(", returnFieldSelector:").append(returnFieldSelector); builder.append(", query:").append(this.query);
builder.append("}"); builder.append(", returnFieldSelector:").append(this.returnFieldSelector);
return builder.toString(); builder.append("}");
} return builder.toString();
}
public String toPrettyString() {
return toString(); @Override
} public String toPrettyString() {
return this.toString();
}
} }
@@ -1,26 +1,9 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException; import java.io.IOException;
import com.fangjia.datastore.mongo.codec.BSONInputStream; import com.fangjia.datastore.mongo.codec.BSONInputStream;
public interface Readable { public interface Readable
public void read(BSONInputStream in) throws IOException; {
void read(final BSONInputStream p0) throws IOException;
} }
@@ -1,138 +1,125 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException; import org.bson.BSONDecoder;
import java.io.InputStream;
import org.bson.BasicBSONDecoder;
import java.util.ArrayList; import java.util.ArrayList;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.bson.BSONEncoder;
import org.bson.BasicBSONEncoder;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import org.bson.BSONObject;
import java.util.List; import java.util.List;
import org.bson.BSONDecoder; public class ReplyMessage implements MongoMessage
import org.bson.BSONEncoder; {
import org.bson.BSONObject; private static final long serialVersionUID = -3350216587439425208L;
import org.bson.BasicBSONDecoder; private MessageHeader messageHeader;
private int responseFlag;
import com.fangjia.datastore.mongo.codec.BSONInputStream; private long cursorID;
import com.fangjia.datastore.mongo.codec.BSONOutputStream; private int startingFrom;
private int numberReturned;
public class ReplyMessage implements MongoMessage { private List<BSONObject> documents;
private static final long serialVersionUID = -3350216587439425208L; public ReplyMessage() {
private MessageHeader messageHeader; this.messageHeader = new MessageHeader(OperationCode.OP_REPLY);
private int responseFlag; }
private long cursorID;
private int startingFrom; @Override
private int numberReturned; public void write(final BSONOutputStream out) throws IOException {
private List<BSONObject> documents; this.messageHeader.write(out);
out.writeInteger(this.responseFlag);
public ReplyMessage() { out.writeLong(this.cursorID);
messageHeader = new MessageHeader(OperationCode.OP_REPLY); out.writeInteger(this.startingFrom);
} out.writeInteger(this.numberReturned);
if (null != this.documents) {
public void write(BSONOutputStream out) throws IOException { final BSONEncoder encoder = (BSONEncoder)new BasicBSONEncoder();
messageHeader.write(out); for (final BSONObject doc : this.documents) {
out.writeInteger(responseFlag); out.write(encoder.encode(doc));
out.writeLong(cursorID); }
out.writeInteger(startingFrom); }
out.writeInteger(numberReturned); out.set(0, out.size());
if (null != this.documents) { }
BSONEncoder encoder = new BSONEncoder();
for (BSONObject doc : this.documents) { @Override
out.write(encoder.encode(doc)); public void read(final BSONInputStream in) throws IOException {
} this.messageHeader.read(in);
} this.responseFlag = in.readInteger();
out.set(0, out.size()); this.cursorID = in.readLong();
} this.startingFrom = in.readInteger();
this.numberReturned = in.readInteger();
public void read(BSONInputStream in) throws IOException { this.documents = new ArrayList<BSONObject>(this.numberReturned);
messageHeader.read(in); if (this.numberReturned > 0) {
responseFlag = in.readInteger(); final BSONDecoder decoder = (BSONDecoder)new BasicBSONDecoder();
cursorID = in.readLong(); for (int i = 0; i < this.numberReturned; ++i) {
startingFrom = in.readInteger(); this.documents.add(decoder.readObject((InputStream)in));
numberReturned = in.readInteger(); }
documents = new ArrayList<BSONObject>(numberReturned); }
if (numberReturned > 0) { }
BSONDecoder decoder = new BasicBSONDecoder();
for (int i = 0; i < numberReturned; i++) { @Override
documents.add(decoder.readObject(in)); public MessageHeader getMessageHeader() {
} return this.messageHeader;
} }
}
public int getResponseFlag() {
public MessageHeader getMessageHeader() { return this.responseFlag;
return messageHeader; }
}
public void setResponseFlag(final int responseFlag) {
public int getResponseFlag() { this.responseFlag = responseFlag;
return responseFlag; }
}
public long getCursorID() {
public void setResponseFlag(int responseFlag) { return this.cursorID;
this.responseFlag = responseFlag; }
}
public void setCursorID(final long cursorID) {
public long getCursorID() { this.cursorID = cursorID;
return cursorID; }
}
public int getStartingFrom() {
public void setCursorID(long cursorID) { return this.startingFrom;
this.cursorID = cursorID; }
}
public void setStartingFrom(final int startingFrom) {
public int getStartingFrom() { this.startingFrom = startingFrom;
return startingFrom; }
}
public int getNumberReturned() {
public void setStartingFrom(int startingFrom) { return this.numberReturned;
this.startingFrom = startingFrom; }
}
public void setNumberReturned(final int numberReturned) {
public int getNumberReturned() { this.numberReturned = numberReturned;
return numberReturned; }
}
public List<BSONObject> getDocuments() {
public void setNumberReturned(int numberReturned) { return this.documents;
this.numberReturned = numberReturned; }
}
public void setDocuments(final List<BSONObject> documents) {
public List<BSONObject> getDocuments() { this.documents = documents;
return documents; }
}
@Override
public void setDocuments(List<BSONObject> documents) { public String toString() {
this.documents = documents; final StringBuilder builder = new StringBuilder();
} builder.append("{");
builder.append("messageHeader:").append(this.messageHeader);
@Override builder.append(", responseFlag:").append(this.responseFlag);
public String toString() { builder.append(", cursorID:").append(this.cursorID);
StringBuilder builder = new StringBuilder(); builder.append(", startingFrom:").append(this.startingFrom);
builder.append("{"); builder.append(", numberReturned:").append(this.numberReturned);
builder.append("messageHeader:").append(messageHeader); builder.append(", documents:").append(this.documents);
builder.append(", responseFlag:").append(responseFlag); builder.append("}");
builder.append(", cursorID:").append(cursorID); return builder.toString();
builder.append(", startingFrom:").append(startingFrom); }
builder.append(", numberReturned:").append(numberReturned);
builder.append(", documents:").append(documents); @Override
builder.append("}"); public String toPrettyString() {
return builder.toString(); return this.toString();
} }
public String toPrettyString() {
return toString();
}
} }
@@ -1,137 +1,123 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException;
import org.bson.BSONDecoder;
import org.bson.BSONEncoder;
import org.bson.BSONObject;
import org.bson.BasicBSONDecoder;
import org.bson.BasicBSONObject;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import com.fangjia.datastore.utils.BSONUtils; import com.fangjia.datastore.utils.BSONUtils;
import org.bson.BSONDecoder;
import java.io.InputStream;
import org.bson.BasicBSONDecoder;
import com.fangjia.datastore.mongo.codec.BSONInputStream;
import java.io.IOException;
import org.bson.BSONEncoder;
import org.bson.BasicBSONEncoder;
import com.fangjia.datastore.mongo.codec.BSONOutputStream;
import org.bson.BasicBSONObject;
import org.bson.BSONObject;
public class UpdateMessage implements MongoMessage { public class UpdateMessage implements MongoMessage
{
private static final long serialVersionUID = -5278293474222136247L; private static final long serialVersionUID = -5278293474222136247L;
private MessageHeader messageHeader;
private MessageHeader messageHeader; private String fullCollectionName;
private String fullCollectionName; private int flags;
private int flags; private BSONObject selector;
private BSONObject selector; private BSONObject update;
private BSONObject update;
public UpdateMessage() {
public UpdateMessage() { this.messageHeader = new MessageHeader(OperationCode.OP_UPDATE);
messageHeader = new MessageHeader(OperationCode.OP_UPDATE); this.selector = (BSONObject)new BasicBSONObject();
this.selector = new BasicBSONObject(); this.update = (BSONObject)new BasicBSONObject();
this.update = new BasicBSONObject(); }
}
@Override
public void write(BSONOutputStream out) throws IOException { public void write(final BSONOutputStream out) throws IOException {
messageHeader.write(out); this.messageHeader.write(out);
out.writeInteger(0); out.writeInteger(0);
out.writeCString(this.fullCollectionName); out.writeCString(this.fullCollectionName);
out.writeInteger(flags); out.writeInteger(this.flags);
BSONEncoder encoder = new BSONEncoder(); final BSONEncoder encoder = (BSONEncoder)new BasicBSONEncoder();
out.write(encoder.encode(selector)); out.write(encoder.encode(this.selector));
out.write(encoder.encode(update)); out.write(encoder.encode(this.update));
out.set(0, out.size()); out.set(0, out.size());
} }
public void read(BSONInputStream in) throws IOException { @Override
messageHeader.read(in); public void read(final BSONInputStream in) throws IOException {
in.readInteger(); this.messageHeader.read(in);
this.fullCollectionName = in.readCString(); in.readInteger();
this.flags = in.readInteger(); this.fullCollectionName = in.readCString();
BSONDecoder decoder = new BasicBSONDecoder(); this.flags = in.readInteger();
selector = decoder.readObject(in); final BSONDecoder decoder = (BSONDecoder)new BasicBSONDecoder();
update = decoder.readObject(in); this.selector = decoder.readObject((InputStream)in);
} this.update = decoder.readObject((InputStream)in);
}
public void setUpsert(boolean upsert) {
this.flags = (int) BSONUtils.bitSet(this.flags, 0, upsert); public void setUpsert(final boolean upsert) {
} this.flags = (int)BSONUtils.bitSet(this.flags, 0, upsert);
}
public boolean isUpsert() {
return BSONUtils.isBitSet(flags, 0); public boolean isUpsert() {
} return BSONUtils.isBitSet(this.flags, 0);
}
public void setMultiUpdate(boolean multiUpdate) {
this.flags = (int) BSONUtils.bitSet(this.flags, 1, multiUpdate); public void setMultiUpdate(final boolean multiUpdate) {
} this.flags = (int)BSONUtils.bitSet(this.flags, 1, multiUpdate);
}
public boolean isMultiUpdate() {
return BSONUtils.isBitSet(flags, 1); public boolean isMultiUpdate() {
} return BSONUtils.isBitSet(this.flags, 1);
}
public MessageHeader getMessageHeader() {
return messageHeader; @Override
} public MessageHeader getMessageHeader() {
return this.messageHeader;
public String getFullCollectionName() { }
return fullCollectionName;
} public String getFullCollectionName() {
return this.fullCollectionName;
public void setFullCollectionName(String fullCollectionName) { }
this.fullCollectionName = fullCollectionName;
} public void setFullCollectionName(final String fullCollectionName) {
this.fullCollectionName = fullCollectionName;
public int getFlags() { }
return flags;
} public int getFlags() {
return this.flags;
public void setFlags(int flags) { }
this.flags = flags;
} public void setFlags(final int flags) {
this.flags = flags;
public BSONObject getSelector() { }
return selector;
} public BSONObject getSelector() {
return this.selector;
public void setSelector(BSONObject selector) { }
this.selector = selector;
} public void setSelector(final BSONObject selector) {
this.selector = selector;
public BSONObject getUpdate() { }
return update;
} public BSONObject getUpdate() {
return this.update;
public void setUpdate(BSONObject update) { }
this.update = update;
} public void setUpdate(final BSONObject update) {
this.update = update;
public String toString() { }
StringBuilder builder = new StringBuilder();
builder.append("{"); @Override
builder.append("messageHeader:").append(messageHeader); public String toString() {
builder.append(", fullCollectionName:").append(fullCollectionName); final StringBuilder builder = new StringBuilder();
builder.append(", flags:").append(flags); builder.append("{");
builder.append(", selector:").append(selector); builder.append("messageHeader:").append(this.messageHeader);
builder.append(", update:").append(update); builder.append(", fullCollectionName:").append(this.fullCollectionName);
builder.append("}"); builder.append(", flags:").append(this.flags);
return builder.toString(); builder.append(", selector:").append(this.selector);
} builder.append(", update:").append(this.update);
builder.append("}");
public String toPrettyString() { return builder.toString();
return toString(); }
}
@Override
public String toPrettyString() {
return this.toString();
}
} }
@@ -1,26 +1,9 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.mongo.protocol; package com.fangjia.datastore.mongo.protocol;
import java.io.IOException; import java.io.IOException;
import com.fangjia.datastore.mongo.codec.BSONOutputStream; import com.fangjia.datastore.mongo.codec.BSONOutputStream;
public interface Writable { public interface Writable
public void write(BSONOutputStream out) throws IOException; {
void write(final BSONOutputStream p0) throws IOException;
} }
@@ -1,11 +1,7 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrRequest;
@@ -15,66 +11,61 @@ import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class CommonsHttpSolrServer extends HttpSolrServer { import java.io.IOException;
private static final long serialVersionUID = -3881911436089005421L; import java.net.MalformedURLException;
private final static Logger LOGGER = LoggerFactory.getLogger(CommonsHttpSolrServer.class); public class CommonsHttpSolrServer extends HttpSolrServer
{
private static final long serialVersionUID = -3881911436089005421L;
private static final Logger LOGGER;
private final HttpSolrClient solrServer;
private final String host;
private final String coreName;
public CommonsHttpSolrServer(final String host, final String coreName, final HttpClient httpClient) throws MalformedURLException {
this.host = host;
this.coreName = coreName;
(this.solrServer = new HttpSolrClient("http://" + host + '/' + coreName)).setAllowCompression(true);
}
@Override
public String getHost() {
return this.host;
}
@Override
public String getCoreName() {
return this.coreName;
}
@Override
public void reloadCore() throws SolrException {
try {
final HttpGet method = new HttpGet("http://" + this.host + "/admin/cores?action=RELOAD&core=" + this.coreName);
final HttpResponse response = this.solrServer.getHttpClient().execute(method);
if (response.getStatusLine().getStatusCode() != 200) {
throw new SolrException("[" + this.coreName + "] error reload core of solr[" + this.host + "]: " + IOUtils.toString(response.getEntity().getContent()));
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("[" + this.coreName + "] solr core of server[" + this.host + "] reloaded.");
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("[" + this.coreName + "] core reload success");
}
}
catch (IOException e) {
throw new SolrException("[" + this.coreName + "] error reload core", e);
}
}
private final HttpSolrClient solrServer; public NamedList<Object> request(final SolrRequest request, final String arg1) throws SolrServerException, IOException {
private final String host; return this.solrServer.request(request);
private final String coreName; }
public CommonsHttpSolrServer(String host, String coreName, HttpClient httpClient) throws MalformedURLException { public void shutdown() {
this.host = host; }
this.coreName = coreName;
this.solrServer = new HttpSolrClient("http://" + host + '/' + coreName);
this.solrServer.setAllowCompression(true);
}
@Override
public String getHost() {
return host;
}
@Override
public String getCoreName() {
return coreName;
}
@Override
public void reloadCore() throws SolrException {
try {
HttpGet method = new HttpGet("http://" + host + "/admin/cores?action=RELOAD&core=" + this.coreName);
HttpResponse response = solrServer.getHttpClient().execute(method);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new SolrException("[" + this.coreName + "] error reload core of solr[" + host + "]: "
+ IOUtils.toString(response.getEntity().getContent()));
} else if (LOGGER.isInfoEnabled()) {
LOGGER.info("[" + this.coreName + "] solr core of server[" + host + "] reloaded.");
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("[" + this.coreName + "] core reload success");
}
} catch (IOException e) {
throw new SolrException("[" + this.coreName + "] error reload core", e);
}
}
/*@Override
public NamedList<Object> request(SolrRequest request) throws SolrServerException, IOException {
return solrServer.request(request);
}*/
@Override
public NamedList<Object> request(SolrRequest request, String arg1)
throws SolrServerException, IOException {
return solrServer.request(request);
}
@Override
public void shutdown() {
}
static {
LOGGER = LoggerFactory.getLogger(CommonsHttpSolrServer.class);
}
} }
@@ -1,138 +1,32 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.time.FastDateFormat;
import org.bson.BSONObject;
import org.bson.types.ObjectId;
import com.fangjia.datastore.QueryResponse; import com.fangjia.datastore.QueryResponse;
import org.bson.types.ObjectId;
import java.util.List;
import org.bson.BSONObject;
import java.util.Iterator;
import java.util.Collection;
import org.apache.commons.lang.time.FastDateFormat;
import com.fangjia.datastore.config.Reloadable; import com.fangjia.datastore.config.Reloadable;
/** public interface Core extends Reloadable
* 一个Core对应一个solr索引 {
* public static final int INDEX_BATCH_SIZE = 30000;
* @author velna public static final FastDateFormat VERSION_DATE_FORMAT = FastDateFormat.getInstance("yyMMddHHmmssSSS");
*
*/ String getName();
public interface Core extends Reloadable {
Collection<Index> getIndexes() throws SolrException;
public final static int INDEX_BATCH_SIZE = 30000;
public final static FastDateFormat VERSION_DATE_FORMAT = FastDateFormat.getInstance("yyMMddHHmmssSSS"); void ensureIndex(final Collection<Index> p0, final Iterator<? extends BSONObject> p1) throws SolrException;
/** void ensureIndex(final Index p0, final Iterator<? extends BSONObject> p1) throws SolrException;
* 得到索引名称
* void reIndex(final List<ObjectId> p0, final Iterator<? extends BSONObject> p1) throws SolrException;
* @return
*/ void save(final Iterator<? extends BSONObject> p0) throws SolrException;
public String getName();
void deleteByQuery(final BSONObject p0) throws SolrException;
/**
* 得到所有索引字段 QueryResponse find(final BSONObject p0, final BSONObject p1, final BSONObject p2, final int p3, final int p4, final boolean p5, final boolean p6) throws SolrException;
*
* @return
* @throws SolrException
*/
Collection<Index> getIndexes() throws SolrException;
/**
* 添加索引字段,必要的话重建索引
*
* @param indexes
* 添加的索引字段列表
* @param iterator
* 用于遍历数据
* @throws SolrException
*/
void ensureIndex(Collection<Index> indexes, Iterator<? extends BSONObject> iterator) throws SolrException;
/**
* 添加索引字段,必要的话重建索引
*
* @param index
* 添加的索引字段列表
* @param iterator
* 用于遍历数据
* @throws SolrException
*/
void ensureIndex(Index index, Iterator<? extends BSONObject> iterator) throws SolrException;
/**
* 重建索引
*
* @param objIdList
* 待重建的ObjIdList,全部重建时为null
* @param iterator
* 用于遍历数据
*/
void reIndex(List<ObjectId> objIdList, Iterator<? extends BSONObject> iterator) throws SolrException;
/**
* 保存索引文档
*
* @param doc
* @throws SolrException
*/
// void save(BSONObject doc) throws SolrException;
/**
* 保存多个索引文档
*
* @param docList
* @throws SolrException
*/
// void save(List<? extends BSONObject> docList) throws SolrException;
/**
* 保存多个索引文档
*
* @param iterator
* @throws SolrException
*/
void save(Iterator<? extends BSONObject> iterator) throws SolrException;
/**
* 根据ID删除索引文档
*
* @param id
* @throws SolrException
*/
// void deleteById(String id) throws SolrException;
/**
* 根据ID列表删除索引文档
*
* @param ids
* @throws SolrException
*/
// void deleteById(List<String> ids) throws SolrException;
/**
* 根据查询删除索引文档
*
* @param query
* @throws SolrException
*/
void deleteByQuery(BSONObject query) throws SolrException;
/**
* 查询索引
*
* @param query
* 查询条件
* @param sort
* 排序条件
* @param facet
* facet查询条件
* @param skip
* 从第skip条开始返回结果
* @param limit
* 返回limit条结果
* @param fromMaster
* 是否从主索引中读取数据
* @param bulk
* 是否使用bulk查询
* @return
* @throws SolrException
*/
QueryResponse find(BSONObject query, BSONObject sort, BSONObject facet, int skip, int limit, boolean fromMaster, boolean bulk)
throws SolrException;
} }
@@ -1,485 +1,480 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import com.fangjia.datastore.utils.LoggerFactory;
import com.fangjia.datastore.TriggerExecuteException;
import com.fangjia.datastore.config.Trigger;
import com.fangjia.datastore.TriggerExecutor;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.common.SolrDocument;
import java.util.ArrayList; import java.util.ArrayList;
import com.fangjia.datastore.QueryResponse;
import org.apache.commons.lang.StringUtils;
import com.mongodb.BasicDBObject;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.commons.collections.CollectionUtils;
import org.bson.types.ObjectId;
import java.util.List;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.SpatialParams;
import org.bson.BSONObject;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.sothis.core.util.BlockingThreadPoolExecutor;
import com.fangjia.datastore.ConfigurationException; import com.fangjia.datastore.ConfigurationException;
import com.fangjia.datastore.QueryResponse; import java.util.concurrent.LinkedBlockingQueue;
import com.fangjia.datastore.TriggerExecuteException; import org.sothis.core.util.BlockingThreadPoolExecutor;
import com.fangjia.datastore.TriggerExecutor; import java.util.concurrent.Executor;
import com.fangjia.datastore.config.ServerConfig; import org.bson.BSONObject;
import com.fangjia.datastore.config.StoreConfig; import java.util.concurrent.BlockingQueue;
import com.fangjia.datastore.config.Trigger;
import com.fangjia.datastore.utils.AsyncOperation; import com.fangjia.datastore.utils.AsyncOperation;
import com.fangjia.datastore.utils.LoggerFactory; import com.fangjia.datastore.config.StoreConfig;
import com.mongodb.BasicDBObject; import com.fangjia.datastore.config.ServerConfig;
import org.slf4j.Logger;
public class CoreImpl implements Core { public class CoreImpl implements Core
private final static Logger LOGGER = LoggerFactory.getLogger(CoreImpl.class); {
private final static Logger PERFORMANCE_LOGGER = LoggerFactory.getPerformanceLogger(CoreImpl.class); private static final Logger LOGGER;
private final static int TRIIGER_POOL_SIZE = Integer.getInteger("datastore.triggerPoolSize", 10); private static final Logger PERFORMANCE_LOGGER;
private static final int TRIIGER_POOL_SIZE;
private final String name;
private final SolrServer solrServer;
private final ServerConfig serverConfig;
private final StoreConfig storeConfig;
private final AsyncOperation asynchOperation;
private final BlockingQueue<BSONObject> solrAddQueue;
private final BlockingQueue<BSONObject> triggerQueue;
private final Executor triggerExecutorService;
public CoreImpl(final StoreConfig storeConfig) throws ConfigurationException {
this.name = storeConfig.getName();
this.storeConfig = storeConfig;
this.solrServer = new SolrServerImpl(this.storeConfig);
this.serverConfig = storeConfig.getDataStoreConfig().getServerConfig();
if (CoreImpl.LOGGER.isInfoEnabled()) {
CoreImpl.LOGGER.info("init solr core: " + this.name + ", storeConfig: " + storeConfig);
}
this.asynchOperation = AsyncOperation.getInstance();
this.triggerExecutorService = new BlockingThreadPoolExecutor(this.name + "-Trigger", 1, CoreImpl.TRIIGER_POOL_SIZE, CoreImpl.TRIIGER_POOL_SIZE, 60000L);
this.solrAddQueue = new LinkedBlockingQueue<BSONObject>(60000);
final Thread solrIndexAddThread = new Thread(new SolrAddRunnable(), this.name + "-SolrAdd");
solrIndexAddThread.setDaemon(true);
solrIndexAddThread.start();
this.triggerQueue = new LinkedBlockingQueue<BSONObject>(this.serverConfig.getTriggerBatchSize() * 4);
final Thread triggerExecuteThread = new Thread(new TriggerRunnable(), this.name + "-Trigger");
triggerExecuteThread.setDaemon(true);
triggerExecuteThread.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
while (!CoreImpl.this.solrAddQueue.isEmpty()) {
CoreImpl.LOGGER.info(CoreImpl.this.name + ": wait for solr queue, current size: " + CoreImpl.this.solrAddQueue.size());
try {
Thread.sleep(1000L);
}
catch (InterruptedException e) {
CoreImpl.LOGGER.error("", (Throwable)e);
}
}
CoreImpl.LOGGER.info(CoreImpl.this.name + ": shutdown.");
}
});
if (CoreImpl.LOGGER.isInfoEnabled()) {
CoreImpl.LOGGER.info("solr core " + this.name + " initialized");
}
}
private void saveToSolr(final Iterator<? extends BSONObject> iterator, final String operationName) throws SolrException {
long c = 0L;
final long startTime = System.currentTimeMillis();
while (iterator.hasNext()) {
try {
this.triggerQueue.put(iterator.next());
}
catch (InterruptedException e) {
throw new SolrException("error put object: ", e);
}
++c;
if (null != operationName && c % this.serverConfig.getTriggerBatchSize() == 0L && CoreImpl.LOGGER.isInfoEnabled()) {
CoreImpl.LOGGER.info("{}: {}, {}/s", new Object[] { operationName, c, (int)(c / ((System.currentTimeMillis() - startTime) / 1000.0)) });
}
}
}
@Override
public void reload() throws ConfigurationException {
this.solrServer.reload();
try {
this.solrServer.reloadCores();
}
catch (SolrException e) {
throw new ConfigurationException(e);
}
}
@Override
public Collection<Index> getIndexes() throws SolrException {
return this.solrServer.getSolrSchema().getIndexes();
}
@Override
public void ensureIndex(final Collection<Index> indexes, final Iterator<? extends BSONObject> iterator) throws SolrException {
try {
final String operationName = "ensureIndex_" + System.currentTimeMillis();
if (CoreImpl.LOGGER.isInfoEnabled()) {
CoreImpl.LOGGER.info("{}: ensure index[{}] {} ...", new Object[] { this.getName(), operationName, indexes });
}
if (this.solrServer.getSolrSchema().saveIndex(indexes) > 0) {
this.solrServer.reloadCores();
}
this.saveToSolr(iterator, operationName);
if (CoreImpl.LOGGER.isInfoEnabled()) {
CoreImpl.LOGGER.info("{}: ensure index[{}] {} finished", new Object[] { this.getName(), operationName, indexes });
}
}
catch (SolrException e) {
CoreImpl.LOGGER.error("ensureIndex: ", (Throwable)e);
}
}
@Override
public void ensureIndex(final Index index, final Iterator<? extends BSONObject> iterator) throws SolrException {
this.ensureIndex(Arrays.<Index>asList(index), iterator);
}
@Override
public void reIndex(final List<ObjectId> objIdList, final Iterator<? extends BSONObject> iterator) throws SolrException {
final boolean logInfo = CollectionUtils.isEmpty((Collection)objIdList);
final long startTime = System.currentTimeMillis();
final String operationName = logInfo ? (this.getName() + "_re-index_" + startTime) : null;
if (logInfo && CoreImpl.LOGGER.isInfoEnabled()) {
CoreImpl.LOGGER.info(operationName + " started.");
}
this.saveToSolr(iterator, operationName);
if (logInfo && CoreImpl.LOGGER.isInfoEnabled()) {
CoreImpl.LOGGER.info("{} finished, total time: {}s.", operationName, (System.currentTimeMillis() - startTime) / 1000L);
}
}
@Override
public void save(final Iterator<? extends BSONObject> iterator) throws SolrException {
this.asynchOperation.run(new Runnable() {
@Override
public void run() {
try {
CoreImpl.this.saveToSolr(iterator, "save_" + System.currentTimeMillis());
}
catch (SolrException e) {
CoreImpl.LOGGER.error(CoreImpl.this.name + ": error save objects into solr:", (Throwable)e);
}
}
});
}
@Override
public void deleteByQuery(final BSONObject query) throws SolrException {
final String solrQuery = this.toSolrQuery(query).get("q");
if (CoreImpl.LOGGER.isDebugEnabled()) {
CoreImpl.LOGGER.debug("deleteByQuery: {}", (Object)solrQuery);
}
this.solrServer.deleteByQuery(solrQuery);
}
private SolrQuery toSolrQuery(final BSONObject query) throws SolrException {
return this.toSolrQuery(query, false);
}
private SolrQuery toSolrQuery(final BSONObject orgQuery, final boolean useFilterQuery) throws SolrException {
System.err.println(orgQuery.toString());
final BSONObject query = (BSONObject)new BasicDBObject();
query.putAll(orgQuery);
final SolrQueryBuilder queryBuilder = new SolrQueryBuilder();
final SolrQuery solrQuery = new SolrQuery();
if (useFilterQuery && query != null && query.containsField("visible") && query.containsField("city") && query.containsField("cat") && query.get("cat") instanceof String) {
final StringBuilder fq = new StringBuilder();
fq.append("+cat:").append(query.get("cat"));
fq.append(" +city:").append(query.get("city"));
fq.append(" +visible:").append(((Number)query.get("visible")).intValue());
solrQuery.addFilterQuery(fq.toString());
query.removeField("cat");
query.removeField("city");
query.removeField("visible");
}
for (final String key : query.keySet()) {
if (key.charAt(0) == '$') {
continue;
}
final Object value = query.get(key);
final Index index = this.assertFieldExistence(key);
if (value instanceof BSONObject) {
final BSONObject subQuery = (BSONObject)value;
Object g = subQuery.get("$gt");
boolean ge = false;
if (null == g) {
g = subQuery.get("$gte");
ge = (g != null);
}
Object l = subQuery.get("$lt");
boolean le = false;
if (null == l) {
l = subQuery.get("$lte");
le = (l != null);
}
if (ge && null == l) {
le = true;
}
if (le && null == g) {
ge = true;
}
if (null != g || null != l) {
queryBuilder.range(key, index.normalizeValue(g), index.normalizeValue(l), ge, le);
}
final Object in = subQuery.get("$in");
if (null != in) {
queryBuilder.in(key, index.normalizeValue((List<Object>)in));
}
final Object ne = subQuery.get("$ne");
if (null == ne) {
continue;
}
queryBuilder.ne(key, index.normalizeValue(ne));
}
else {
queryBuilder.eq(key, index.normalizeValue(value));
}
}
String q = queryBuilder.toQuery().toString();
if (query.get("$sr") != null) {
final Object value2 = query.get("$sr");
final BSONObject bsonObject = (BSONObject)value2;
final String val = bsonObject.get("sr.query").toString();
if (val != null && !"".equals(val)) {
q = q + " +(" + val + ")";
}
}
if (query.get("$sd") != null) {
final Object value2 = query.get("$sd");
final BSONObject bsonObject = (BSONObject)value2;
final String distance = (String)bsonObject.get("sd.distance");
final String field = (String)bsonObject.get("sd.sfield");
final String point = (String)bsonObject.get("sd.point");
if (!StringUtils.isNotBlank(point) || !StringUtils.isNotBlank(distance) || !StringUtils.isNotBlank(field)) {
throw new IllegalArgumentException("paramName $sd value illegal : " + value2);
}
solrQuery.setParam("sfield", field);
solrQuery.setParam("d", distance);
solrQuery.setParam("pt", point);
solrQuery.addSort("geodist()", SolrQuery.ORDER.asc);
solrQuery.addFilterQuery("{!geofilt}");
}
if (query.get("$fangjiawang_query_type") != null) {
final Object value2 = query.get("$fangjiawang_query_type");
solrQuery.add("q.op", value2.toString());
}
if (StringUtils.isEmpty(q)) {
solrQuery.setQuery("*:*");
}
else {
solrQuery.setQuery(q);
}
return solrQuery;
}
private Index assertFieldExistence(final String key) throws SolrException {
final Index index = this.solrServer.getSolrSchema().getIndex(key);
if (null == index) {
throw new SolrException("index '" + key + "' is not exist!");
}
return index;
}
@Override
public QueryResponse find(final BSONObject query, final BSONObject sort, final BSONObject facet, int skip, int limit, final boolean fromMaster, final boolean bulk) throws SolrException {
final long start = System.currentTimeMillis();
if (limit < 0) {
limit = this.serverConfig.getDefaultCursorLimit();
}
if (skip < 0) {
skip = 0;
}
final SolrQuery solrQuery = this.toSolrQuery(query, true);
solrQuery.setFields("_id");
solrQuery.setStart(skip);
solrQuery.setRows(limit);
if (null != sort) {
for (final String key : sort.keySet()) {
final int value = ((Number)sort.get(key)).intValue();
if (!"score".equals(key)) {
this.assertFieldExistence(key);
}
solrQuery.addSort(key, (value > 0) ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc);
}
}
if (null != facet) {
final List<String> fields = (List<String>)facet.get("fields");
if (null != fields) {
solrQuery.setFacet(true);
Integer facetMinCount = null;
if (null != facet.get("minCount")) {
facetMinCount = ((Number)facet.get("minCount")).intValue();
}
solrQuery.setFacetMinCount((null == facetMinCount) ? 1 : ((int)facetMinCount));
Integer facetLimit = null;
if (null != facet.get("limit")) {
facetLimit = ((Number)facet.get("limit")).intValue();
}
solrQuery.setFacetLimit((null == facetLimit) ? 100 : facetLimit);
for (final String field : fields) {
this.assertFieldExistence(field);
solrQuery.addFacetField(field);
}
}
}
final org.apache.solr.client.solrj.response.QueryResponse queryResponse = this.solrServer.query(solrQuery, fromMaster, bulk);
final long time = System.currentTimeMillis() - start;
if (time > 100L) {
String host = solrQuery.get("__host");
solrQuery.remove("__host");
final StringBuilder sb = new StringBuilder();
sb.append("query solr: ").append(solrQuery);
if(StringUtils.isNotBlank(host)){
sb.append(", host: ").append(host);
}
sb.append(", time: ").append(time);
sb.append(", qtime: ").append(queryResponse.getQTime());
sb.append(", numFound: ").append(queryResponse.getResults().getNumFound());
sb.append(", numReturned: ").append(queryResponse.getResults().size());
sb.append(", master: ").append(fromMaster);
CoreImpl.PERFORMANCE_LOGGER.info(sb.toString());
if (time < 1000L) {
CoreImpl.PERFORMANCE_LOGGER.info(sb.toString());
}
else if (time < 3000L) {
CoreImpl.PERFORMANCE_LOGGER.warn(sb.toString());
}
else {
CoreImpl.PERFORMANCE_LOGGER.error(sb.toString());
}
}
final QueryResponse response = this.toSolrResponse(queryResponse);
return response;
}
private QueryResponse toSolrResponse(final org.apache.solr.client.solrj.response.QueryResponse response) {
if (response == null) {
return QueryResponse.EMPTY_RESPONSE;
}
final SolrDocumentList solrDocumentList = response.getResults();
final int numReturned = solrDocumentList.size();
final List<ObjectId> idList = new ArrayList<ObjectId>(numReturned);
for (int i = 0; i < numReturned; ++i) {
final String value = ((SolrDocument)solrDocumentList.get(i)).getFirstValue("_id").toString();
idList.add(new ObjectId(value));
}
final QueryResponse solrResponse = new QueryResponse();
solrResponse.setNumFound((int)solrDocumentList.getNumFound());
solrResponse.setNumReturned(numReturned);
solrResponse.setNumToSkip((int)solrDocumentList.getStart());
solrResponse.setIdList(idList);
solrResponse.setFacetFieldList(response.getFacetFields());
return solrResponse;
}
@Override
public String getName() {
return this.name;
}
private List<BSONObject> executeTrigger(final List<BSONObject> list) throws TriggerExecuteException {
final Trigger trigger = this.storeConfig.getTrigger();
if (null == trigger) {
if (CoreImpl.LOGGER.isWarnEnabled()) {
CoreImpl.LOGGER.warn("null trigger!");
}
return list;
}
if (null == trigger.getInterface()) {
return list;
}
return TriggerExecutor.getInstance().execute(trigger, list);
}
static {
LOGGER = LoggerFactory.getLogger(CoreImpl.class);
PERFORMANCE_LOGGER = LoggerFactory.getPerformanceLogger(CoreImpl.class);
TRIIGER_POOL_SIZE = Integer.getInteger("datastore.triggerPoolSize", 10);
}
private final String name; private class TriggerRunnable implements Runnable {
private final SolrServer solrServer;
private final ServerConfig serverConfig;
private final StoreConfig storeConfig;
private final AsyncOperation asynchOperation;
private final BlockingQueue<BSONObject> solrAddQueue;
private final BlockingQueue<BSONObject> triggerQueue;
private final Executor triggerExecutorService;
public CoreImpl(StoreConfig storeConfig) throws ConfigurationException { public void run() {
this.name = storeConfig.getName(); int sleepTime = 0;
this.storeConfig = storeConfig; while (true) {
this.solrServer = new SolrServerImpl(this.storeConfig); try {
this.serverConfig = storeConfig.getDataStoreConfig().getServerConfig(); final List<BSONObject> dbObjects = new ArrayList<BSONObject>(serverConfig.getTriggerBatchSize());
if (LOGGER.isInfoEnabled()) { triggerQueue.drainTo(dbObjects, serverConfig.getTriggerBatchSize());
LOGGER.info("init solr core: " + name + ", storeConfig: " + storeConfig); if (!dbObjects.isEmpty()) {
} triggerExecutorService.execute(new Runnable() {
this.asynchOperation = AsyncOperation.getInstance(); public void run() {
try {
long time = System.currentTimeMillis();
List<BSONObject> list = executeTrigger(dbObjects);
time = System.currentTimeMillis() - time;
if (LOGGER.isInfoEnabled() && time > 0) {
LOGGER.info("execute trigger: {}/{} objects, {}ms, {}/s", new Object[] { list.size(),
dbObjects.size(), time, dbObjects.size() * 1000 / time });
}
for (BSONObject obj : list) {
solrAddQueue.put(obj);
}
} catch (Exception e) {
LOGGER.error("error execute trigger: ", e);
}
}
// trigger executor });
this.triggerExecutorService = new BlockingThreadPoolExecutor(name + "-Trigger", 1, TRIIGER_POOL_SIZE, TRIIGER_POOL_SIZE, sleepTime = serverConfig.getTriggerBatchSize() - dbObjects.size();
60000); if (sleepTime > 100) {
Thread.sleep(sleepTime * 3);
}
} else {
Thread.sleep(serverConfig.getTriggerBatchSize());
}
} catch (Exception e) {
LOGGER.error("error execute trigger: ", e);
}
}
}
// solr add thread }
this.solrAddQueue = new LinkedBlockingQueue<BSONObject>(INDEX_BATCH_SIZE * 2);
Thread solrIndexAddThread = new Thread(new SolrAddRunnable(), name + "-SolrAdd"); private class SolrAddRunnable implements Runnable
solrIndexAddThread.setDaemon(true); {
solrIndexAddThread.start(); @Override
public void run() {
// trigger thread final List<BSONObject> dbObjects = new ArrayList<BSONObject>(30000);
this.triggerQueue = new LinkedBlockingQueue<BSONObject>(this.serverConfig.getTriggerBatchSize() * 4); final int maxSleepTime = 10000;
Thread triggerExecuteThread = new Thread(new TriggerRunnable(), name + "-Trigger"); int sleepTime = 0;
triggerExecuteThread.setDaemon(true); while (true) {
triggerExecuteThread.start(); try {
CoreImpl.this.solrAddQueue.drainTo(dbObjects, 30000);
// shutdown hook if (!dbObjects.isEmpty()) {
Runtime.getRuntime().addShutdownHook(new Thread() { CoreImpl.this.solrServer.add(dbObjects);
sleepTime = 10000 - dbObjects.size();
@Override if (sleepTime <= 100) {
public void run() { continue;
while (!solrAddQueue.isEmpty()) { }
LOGGER.info(CoreImpl.this.name + ": wait for solr queue, current size: " + solrAddQueue.size()); Thread.sleep(sleepTime);
try { }
Thread.sleep(1000); else {
} catch (InterruptedException e) { Thread.sleep(10000L);
LOGGER.error("", e); }
} }
} catch (Exception e) {
LOGGER.info(CoreImpl.this.name + ": shutdown."); CoreImpl.LOGGER.error("error save to solr: ", (Throwable)e);
} }
finally {
}); dbObjects.clear();
if (LOGGER.isInfoEnabled()) { }
LOGGER.info("solr core " + name + " initialized"); }
} }
} }
private class TriggerRunnable implements Runnable {
public void run() {
int sleepTime = 0;
while (true) {
try {
final List<BSONObject> dbObjects = new ArrayList<BSONObject>(serverConfig.getTriggerBatchSize());
triggerQueue.drainTo(dbObjects, serverConfig.getTriggerBatchSize());
if (!dbObjects.isEmpty()) {
triggerExecutorService.execute(new Runnable() {
public void run() {
try {
long time = System.currentTimeMillis();
List<BSONObject> list = executeTrigger(dbObjects);
time = System.currentTimeMillis() - time;
if (LOGGER.isInfoEnabled() && time > 0) {
LOGGER.info("execute trigger: {}/{} objects, {}ms, {}/s", new Object[] { list.size(),
dbObjects.size(), time, dbObjects.size() * 1000 / time });
}
for (BSONObject obj : list) {
solrAddQueue.put(obj);
}
} catch (Exception e) {
LOGGER.error("error execute trigger: ", e);
}
}
});
sleepTime = serverConfig.getTriggerBatchSize() - dbObjects.size();
if (sleepTime > 100) {
Thread.sleep(sleepTime * 3);
}
} else {
Thread.sleep(serverConfig.getTriggerBatchSize());
}
} catch (Exception e) {
LOGGER.error("error execute trigger: ", e);
}
}
}
}
private class SolrAddRunnable implements Runnable {
public void run() {
final List<BSONObject> dbObjects = new ArrayList<BSONObject>(INDEX_BATCH_SIZE);
final int maxSleepTime = 10000;
int sleepTime = 0;
while (true) {
try {
solrAddQueue.drainTo(dbObjects, INDEX_BATCH_SIZE);
if (!dbObjects.isEmpty()) {
solrServer.add(dbObjects);
sleepTime = maxSleepTime - dbObjects.size();
if (sleepTime > 100) {
Thread.sleep(sleepTime);
}
} else {
Thread.sleep(maxSleepTime);
}
} catch (Exception e) {
LOGGER.error("error save to solr: ", e);
} finally {
dbObjects.clear();
}
}
}
}
private void saveToSolr(final Iterator<? extends BSONObject> iterator, String operationName) throws SolrException {
long c = 0;
long startTime = System.currentTimeMillis();
while (iterator.hasNext()) {
try {
triggerQueue.put(iterator.next());
} catch (InterruptedException e) {
throw new SolrException("error put object: ", e);
}
c++;
if (null != operationName && c % serverConfig.getTriggerBatchSize() == 0 && LOGGER.isInfoEnabled()) {
LOGGER.info("{}: {}, {}/s", new Object[] { operationName, c,
(int) (c / ((System.currentTimeMillis() - startTime) / 1000.0)) });
}
}
}
public void reload() throws ConfigurationException {
this.solrServer.reload();
try {
this.solrServer.reloadCores();
} catch (SolrException e) {
throw new ConfigurationException(e);
}
}
public Collection<Index> getIndexes() throws SolrException {
return this.solrServer.getSolrSchema().getIndexes();
}
public void ensureIndex(final Collection<Index> indexes, final Iterator<? extends BSONObject> iterator) throws SolrException {
try {
String operationName = "ensureIndex_" + System.currentTimeMillis();
if (LOGGER.isInfoEnabled()) {
LOGGER.info("{}: ensure index[{}] {} ...", new Object[] { CoreImpl.this.getName(), operationName, indexes });
}
if (solrServer.getSolrSchema().saveIndex(indexes) > 0) {
this.solrServer.reloadCores();
}
saveToSolr(iterator, operationName);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("{}: ensure index[{}] {} finished", new Object[] { CoreImpl.this.getName(), operationName, indexes });
}
} catch (SolrException e) {
LOGGER.error("ensureIndex: ", e);
}
}
public void ensureIndex(Index index, Iterator<? extends BSONObject> iterator) throws SolrException {
ensureIndex(Arrays.asList(index), iterator);
}
public void reIndex(final List<ObjectId> objIdList, final Iterator<? extends BSONObject> iterator) throws SolrException {
boolean logInfo = CollectionUtils.isEmpty(objIdList);
long startTime = System.currentTimeMillis();
String operationName = logInfo ? CoreImpl.this.getName() + "_re-index_" + startTime : null;
if (logInfo && LOGGER.isInfoEnabled()) {
LOGGER.info(operationName + " started.");
}
saveToSolr(iterator, operationName);
if (logInfo && LOGGER.isInfoEnabled()) {
LOGGER.info("{} finished, total time: {}s.", operationName, (System.currentTimeMillis() - startTime) / 1000);
}
}
public void save(final Iterator<? extends BSONObject> iterator) throws SolrException {
asynchOperation.run(new Runnable() {
public void run() {
try {
saveToSolr(iterator, "save_" + System.currentTimeMillis());
} catch (SolrException e) {
LOGGER.error(name + ": error save objects into solr:", e);
}
}
});
}
public void deleteByQuery(final BSONObject query) throws SolrException {
String solrQuery = toSolrQuery(query).get(CommonParams.Q);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("deleteByQuery: {}", solrQuery);
}
this.solrServer.deleteByQuery(solrQuery);
}
private SolrQuery toSolrQuery(BSONObject query) throws SolrException {
return toSolrQuery(query, false);
}
private SolrQuery toSolrQuery(final BSONObject orgQuery, boolean useFilterQuery) throws SolrException {
System.err.println(orgQuery.toString());
BSONObject query = new BasicDBObject();
query.putAll(orgQuery);
SolrQueryBuilder queryBuilder = new SolrQueryBuilder();
SolrQuery solrQuery = new SolrQuery();
if (useFilterQuery && query != null && query.containsField("visible") && query.containsField("city")
&& query.containsField("cat") && query.get("cat") instanceof String) {
StringBuilder fq = new StringBuilder();
fq.append("+cat:").append(query.get("cat"));
fq.append(" +city:").append(query.get("city"));
fq.append(" +visible:").append(((Number) query.get("visible")).intValue());
solrQuery.addFilterQuery(fq.toString());
query.removeField("cat");
query.removeField("city");
query.removeField("visible");
}
if (null != query) {
for (String key : query.keySet()) {
if (key.charAt(0) == '$') {
continue;
}
Object value = query.get(key);
Index index = assertFieldExistence(key);
if (value instanceof BSONObject) {
BSONObject subQuery = (BSONObject) value;
Object g = subQuery.get("$gt");
boolean ge = false;
if (null == g) {
g = subQuery.get("$gte");
ge = g != null;
}
Object l = subQuery.get("$lt");
boolean le = false;
if (null == l) {
l = subQuery.get("$lte");
le = l != null;
}
if (ge && null == l) {
le = true;
}
if (le && null == g) {
ge = true;
}
if (null != g || null != l) {
queryBuilder.range(key, index.normalizeValue(g), index.normalizeValue(l), ge, le);
}
Object in = subQuery.get("$in");
if (null != in) {
queryBuilder.in(key, index.normalizeValue((List) in));
}
Object ne = subQuery.get("$ne");
if (null != ne) {
queryBuilder.ne(key, index.normalizeValue(ne));
}
} else {
queryBuilder.eq(key, index.normalizeValue(value));
}
}
}
String q = queryBuilder.toQuery().toString();
// $srģʽ
if (null != query) {
if (query.get("$sr") != null) {
Object value = query.get("$sr");
BSONObject bsonObject = (BSONObject) value;
String val = bsonObject.get("sr.query").toString();
if (val != null && !"".equals(val)) {
q += " +(" + val + ")";
}
}
if (query.get("$sd") != null) {
Object value = query.get("$sd");
BSONObject bsonObject = (BSONObject) value;
String distance = (String) bsonObject.get("sd.distance");
String field = (String) bsonObject.get("sd.sfield");
String point = (String) bsonObject.get("sd.point");
if (StringUtils.isNotBlank(point) && StringUtils.isNotBlank(distance) && StringUtils.isNotBlank(field)) {
solrQuery.setParam(SpatialParams.FIELD, field);
solrQuery.setParam(SpatialParams.DISTANCE, distance);
solrQuery.setParam(SpatialParams.POINT, point);
solrQuery.addSort("geodist()", ORDER.asc);
solrQuery.addFilterQuery("{!geofilt}");
} else {
throw new IllegalArgumentException("paramName $sd value illegal : " + value);
}
}
if (query.get("$fangjiawang_query_type") != null) {
Object value = query.get("$fangjiawang_query_type");
solrQuery.add("q.op", value.toString());
}
}
if (StringUtils.isEmpty(q)) {
solrQuery.setQuery("*:*");
} else {
solrQuery.setQuery(q);
}
return solrQuery;
}
private Index assertFieldExistence(String key) throws SolrException {
Index index = this.solrServer.getSolrSchema().getIndex(key);
if (null == index) {
throw new SolrException("index '" + key + "' is not exist!");
}
return index;
}
public QueryResponse find(BSONObject query, BSONObject sort, BSONObject facet, int skip, int limit, boolean fromMaster,
boolean bulk) throws SolrException {
long start = System.currentTimeMillis();
if (limit < 0) {
limit = serverConfig.getDefaultCursorLimit();
}
if (skip < 0) {
skip = 0;
}
SolrQuery solrQuery = toSolrQuery(query, true);
// fields, start, limit
solrQuery.setFields(SolrSchema.ID);
solrQuery.setStart(skip);
solrQuery.setRows(limit);
// sort
if (null != sort) {
for (String key : sort.keySet()) {
int value = ((Number) sort.get(key)).intValue();
if (!"score".equals(key)) { // pseudo-field score
assertFieldExistence(key);
}
solrQuery.addSort(key, value > 0 ? ORDER.asc : ORDER.desc);
}
}
// facet
if (null != facet) {
List<String> fields = (List<String>) facet.get("fields");
if (null != fields) {
solrQuery.setFacet(true);
Integer facetMinCount = null;
if (null != facet.get("minCount")) {
facetMinCount = ((Number) facet.get("minCount")).intValue();
}
solrQuery.setFacetMinCount(null == facetMinCount ? 1 : facetMinCount);
Integer facetLimit = null;
if (null != facet.get("limit")) {
facetLimit = ((Number) facet.get("limit")).intValue();
}
solrQuery.setFacetLimit(null == facetLimit ? 100 : facetLimit);
for (String field : fields) {
assertFieldExistence(field);
solrQuery.addFacetField(field);
}
}
}
org.apache.solr.client.solrj.response.QueryResponse queryResponse = this.solrServer.query(solrQuery, fromMaster, bulk);
long time = System.currentTimeMillis() - start;
if (time > 100) {
StringBuilder sb = new StringBuilder();
sb.append("query solr: ").append(solrQuery);
sb.append(", time: ").append(time);
sb.append(", qtime: ").append(queryResponse.getQTime());
sb.append(", numFound: ").append(queryResponse.getResults().getNumFound());
sb.append(", numReturned: ").append(queryResponse.getResults().size());
sb.append(", master: ").append(fromMaster);
if (time < 1000) {
PERFORMANCE_LOGGER.info(sb.toString());
} else if (time < 3000) {
PERFORMANCE_LOGGER.warn(sb.toString());
} else {
PERFORMANCE_LOGGER.error(sb.toString());
}
}
QueryResponse response = toSolrResponse(queryResponse);
return response;
}
private QueryResponse toSolrResponse(org.apache.solr.client.solrj.response.QueryResponse response) {
if (response == null) {
return QueryResponse.EMPTY_RESPONSE;
}
SolrDocumentList solrDocumentList = response.getResults();
int numReturned = solrDocumentList.size();
List<ObjectId> idList = new ArrayList<ObjectId>(numReturned);
for (int i = 0; i < numReturned; i++) {
String value = solrDocumentList.get(i).getFirstValue(SolrSchema.ID).toString();
idList.add(new ObjectId(value));
}
QueryResponse solrResponse = new QueryResponse();
solrResponse.setNumFound((int) solrDocumentList.getNumFound());
solrResponse.setNumReturned(numReturned);
solrResponse.setNumToSkip((int) solrDocumentList.getStart());
solrResponse.setIdList(idList);
solrResponse.setFacetFieldList(response.getFacetFields());
return solrResponse;
}
public String getName() {
return name;
}
private List<BSONObject> executeTrigger(List<BSONObject> list) throws TriggerExecuteException {
Trigger trigger = this.storeConfig.getTrigger();
if (null == trigger) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("null trigger!");
}
return list;
}
if (null == trigger.getInterface()) {
return list;
}
return TriggerExecutor.getInstance().execute(trigger, list);
}
} }
@@ -2,13 +2,13 @@ package com.fangjia.datastore.solr;
import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServer;
public abstract class HttpSolrServer extends SolrServer { public abstract class HttpSolrServer extends SolrServer
{
private static final long serialVersionUID = -3967599614339379847L; private static final long serialVersionUID = -3967599614339379847L;
abstract public void reloadCore() throws SolrException; public abstract void reloadCore() throws SolrException;
abstract public String getCoreName(); public abstract String getCoreName();
abstract public String getHost(); public abstract String getHost();
} }
@@ -1,191 +1,196 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.HashCodeBuilder;
import org.bson.BSONObject;
import org.bson.BasicBSONObject; import org.bson.BasicBSONObject;
import org.bson.BSONObject;
import java.util.Date;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
public class Index { public class Index
public static enum IndexTypeEnum { {
STRING, INTEGER, INT, DOUBLE, TEXT_STD, TEXT_CJK, DATE, LONG, LOCATION; private String name;
public String getType() { private IndexTypeEnum type;
return this.name().toLowerCase(); private boolean stored;
} private boolean indexed;
private boolean multiValued;
public static IndexTypeEnum parse(String type) { private String comments;
for (IndexTypeEnum e : IndexTypeEnum.values()) { private boolean dynamic;
if (e.getType().equals(type)) {
return e; public Index(final String name, final IndexTypeEnum type, final boolean stored, final boolean indexed, final boolean multiValued, final boolean dynamic, final String comments) {
} this.name = name;
} this.type = type;
return null; this.stored = stored;
} this.indexed = indexed;
} this.multiValued = multiValued;
this.dynamic = dynamic;
private String name; this.comments = comments;
private IndexTypeEnum type; }
private boolean stored;
private boolean indexed; public Index(final String name, final IndexTypeEnum type) {
private boolean multiValued; this.name = name;
private String comments; this.type = type;
private boolean dynamic; this.stored = false;
this.indexed = true;
public Index(String name, IndexTypeEnum type, boolean stored, boolean indexed, boolean multiValued, boolean dynamic, this.multiValued = false;
String comments) { this.dynamic = false;
this.name = name; this.comments = "";
this.type = type; }
this.stored = stored;
this.indexed = indexed; public List<Object> normalizeValue(final List<Object> values) {
this.multiValued = multiValued; if (null == values) {
this.dynamic = dynamic; return null;
this.comments = comments; }
} final List<Object> ret = new ArrayList<Object>(values.size());
for (final Object v : values) {
public Index(String name, IndexTypeEnum type) { ret.add(this.normalizeValue(v));
this.name = name; }
this.type = type; return ret;
this.stored = false; }
this.indexed = true;
this.multiValued = false; public Object normalizeValue(final Object value) {
this.dynamic = false; if (null == value) {
this.comments = ""; return null;
} }
switch (this.type) {
public List<Object> normalizeValue(List<Object> values) { case STRING:
if (null == values) { case TEXT_STD:
return null; return value.toString();
} case INTEGER:
List<Object> ret = new ArrayList<Object>(values.size()); return ((Number)value).intValue();
for (Object v : values) { case LONG:
ret.add(normalizeValue(v)); return ((Number)value).longValue();
} case DOUBLE:
return ret; return ((Number)value).doubleValue();
} case DATE:
return value;
public Object normalizeValue(Object value) { default:
if (null == value) { return value;
return null; }
} }
switch (this.type) {
case STRING: public Index() {
case TEXT_STD: this(null, null);
return value.toString(); }
case INTEGER:
return ((Number) value).intValue(); public String getName() {
case LONG: return this.name;
return ((Number) value).longValue(); }
case DOUBLE:
return ((Number) value).doubleValue(); public IndexTypeEnum getType() {
case DATE: return this.type;
return (Date) value; }
}
return value; public boolean isStored() {
} return this.stored;
}
public Index() {
this(null, null); public boolean isIndexed() {
} return this.indexed;
}
public String getName() {
return name; public boolean isMultiValued() {
} return this.multiValued;
}
public IndexTypeEnum getType() {
return type; public String getComments() {
} return this.comments;
}
public boolean isStored() {
return stored; public boolean isDynamic() {
} return this.dynamic;
}
public boolean isIndexed() {
return indexed; public void setName(final String name) {
} this.name = name;
}
public boolean isMultiValued() {
return multiValued; public void setType(final IndexTypeEnum type) {
} this.type = type;
}
public String getComments() {
return comments; public void setStored(final boolean stored) {
} this.stored = stored;
}
public boolean isDynamic() {
return dynamic; public void setIndexed(final boolean indexed) {
} this.indexed = indexed;
}
public void setName(String name) {
this.name = name; public void setMultiValued(final boolean multiValued) {
} this.multiValued = multiValued;
}
public void setType(IndexTypeEnum type) {
this.type = type; public void setComments(final String comments) {
} this.comments = comments;
}
public void setStored(boolean stored) {
this.stored = stored; public void setDynamic(final boolean dynamic) {
} this.dynamic = dynamic;
}
public void setIndexed(boolean indexed) {
this.indexed = indexed; public BSONObject toBSONObject() {
} final BSONObject ret = (BSONObject)new BasicBSONObject();
ret.put("name", (Object)this.name);
public void setMultiValued(boolean multiValued) { ret.put("type", (Object)this.type.getType());
this.multiValued = multiValued; ret.put("stored", (Object)this.stored);
} ret.put("indexed", (Object)this.indexed);
ret.put("multiValued", (Object)this.multiValued);
public void setComments(String comments) { ret.put("dynamic", (Object)this.dynamic);
this.comments = comments; ret.put("comments", (Object)this.comments);
} return ret;
}
public void setDynamic(boolean dynamic) {
this.dynamic = dynamic; @Override
} public int hashCode() {
return new HashCodeBuilder().append(this.dynamic).append(this.indexed).append(this.multiValued).append(this.stored).append((Object)this.comments).append((Object)this.name).append((Object)this.type).toHashCode();
public BSONObject toBSONObject() { }
BSONObject ret = new BasicBSONObject();
ret.put("name", name); @Override
ret.put("type", this.type.getType()); public boolean equals(final Object obj) {
ret.put("stored", this.stored); if (null == obj) {
ret.put("indexed", this.indexed); return false;
ret.put("multiValued", this.multiValued); }
ret.put("dynamic", this.dynamic); if (this == obj) {
ret.put("comments", this.comments); return true;
return ret; }
} if (!(obj instanceof Index)) {
return false;
@Override }
public int hashCode() { final Index other = (Index)obj;
return new HashCodeBuilder().append(this.dynamic).append(this.indexed).append(this.multiValued).append(this.stored) return new EqualsBuilder().append(this.dynamic, other.dynamic).append(this.indexed, other.indexed).append(this.multiValued, other.multiValued).append(this.stored, other.stored).append((Object)this.comments, (Object)other.comments).append((Object)this.name, (Object)other.name).append((Object)this.type, (Object)other.type).isEquals();
.append(this.comments).append(this.name).append(this.type).toHashCode(); }
}
@Override
@Override public String toString() {
public boolean equals(Object obj) { return "{name=" + this.name + ", type=" + this.type + ", stored=" + this.stored + ", indexed=" + this.indexed + ", multiValued=" + this.multiValued + ", dynamic=" + this.dynamic + ", comments=" + this.comments + "}";
if (null == obj) { }
return false;
} public enum IndexTypeEnum
if (this == obj) { {
return true; STRING,
} INTEGER,
if (!(obj instanceof Index)) { INT,
return false; DOUBLE,
} TEXT_STD,
Index other = (Index) obj; TEXT_CJK,
return new EqualsBuilder().append(this.dynamic, other.dynamic).append(this.indexed, other.indexed).append( DATE,
this.multiValued, other.multiValued).append(this.stored, other.stored).append(this.comments, other.comments) LONG,
.append(this.name, other.name).append(this.type, other.type).isEquals(); LOCATION;
}
public String getType() {
@Override return this.name().toLowerCase();
public String toString() { }
return new StringBuilder().append("{name=").append(name).append(", type=").append(type).append(", stored=")
.append(stored).append(", indexed=").append(indexed).append(", multiValued=").append(multiValued).append( public static IndexTypeEnum parse(final String type) {
", dynamic=").append(dynamic).append(", comments=").append(this.comments).append("}").toString(); for (final IndexTypeEnum e : values()) {
} if (e.getType().equals(type)) {
return e;
}
}
return null;
}
}
} }
@@ -1,262 +1,223 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock; import com.fangjia.datastore.utils.LoggerFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse; import java.io.IOException;
import org.apache.solr.common.params.ShardParams; import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.NamedList;
import org.apache.solr.client.solrj.SolrRequest;
import java.util.concurrent.TimeUnit;
import java.lang.ref.WeakReference;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.Executors;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.SolrParams;
import java.util.Iterator;
import org.apache.commons.lang.math.RandomUtils;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.solr.client.solrj.SolrQuery;
import org.slf4j.Logger; import org.slf4j.Logger;
import com.fangjia.datastore.utils.LoggerFactory; public class LBHttpSolrServer extends HttpSolrServer
{
/** private static final long serialVersionUID = -6175098554678462150L;
* private static final Logger LOGGER;
* @author velna private static final SolrQuery SOLR_QUERY;
* @see org.apache.solr.client.solrj.impl.LBHttpSolrServer private static final int CHECK_INTERVAL = 10000;
*/ private final String coreName;
public class LBHttpSolrServer extends HttpSolrServer { private final ReentrantLock checkLock;
private static final long serialVersionUID = -6175098554678462150L; private ScheduledExecutorService aliveCheckExecutor;
private final static Logger LOGGER = LoggerFactory.getLogger(LBHttpSolrServer.class); private final CopyOnWriteArrayList<WrappedHttpSolrServer> aliveServers;
private final CopyOnWriteArrayList<WrappedHttpSolrServer> zombieServers;
private static final SolrQuery SOLR_QUERY = new SolrQuery("*:*");
private static final int CHECK_INTERVAL = 10 * 1000; public LBHttpSolrServer(final HttpSolrServer... httpSolrServers) {
this.checkLock = new ReentrantLock();
private final String coreName; this.aliveServers = new CopyOnWriteArrayList<WrappedHttpSolrServer>();
this.zombieServers = new CopyOnWriteArrayList<WrappedHttpSolrServer>();
private final ReentrantLock checkLock = new ReentrantLock(); if (null == httpSolrServers || httpSolrServers.length == 0) {
private ScheduledExecutorService aliveCheckExecutor; throw new IllegalArgumentException("length of httpSolrServers must greater than 0");
private final CopyOnWriteArrayList<WrappedHttpSolrServer> aliveServers = new CopyOnWriteArrayList<WrappedHttpSolrServer>(); }
private final CopyOnWriteArrayList<WrappedHttpSolrServer> zombieServers = new CopyOnWriteArrayList<WrappedHttpSolrServer>(); for (final HttpSolrServer httpSolrServer : httpSolrServers) {
this.aliveServers.add(new WrappedHttpSolrServer(httpSolrServer));
public LBHttpSolrServer(HttpSolrServer... httpSolrServers) { }
if (null == httpSolrServers || httpSolrServers.length == 0) { this.coreName = httpSolrServers[0].getCoreName();
throw new IllegalArgumentException("length of httpSolrServers must greater than 0"); }
}
for (HttpSolrServer httpSolrServer : httpSolrServers) { private WrappedHttpSolrServer selectRandomServer() {
this.aliveServers.add(new WrappedHttpSolrServer(httpSolrServer)); while (!this.aliveServers.isEmpty()) {
} try {
coreName = httpSolrServers[0].getCoreName(); if (this.aliveServers.size() == 1) {
} return this.aliveServers.get(0);
}
private WrappedHttpSolrServer selectRandomServer() { return this.aliveServers.get(RandomUtils.nextInt(this.aliveServers.size()));
for (;;) { }
if (aliveServers.isEmpty()) { catch (IndexOutOfBoundsException e) {}
throw new RuntimeException("no solr server available, all are down!"); }
} throw new RuntimeException("no solr server available, all are down!");
try { }
if (aliveServers.size() == 1) {
return aliveServers.get(0); @Override
} public String getHost() {
return aliveServers.get(RandomUtils.nextInt(aliveServers.size())); for (final WrappedHttpSolrServer server : this.aliveServers) {
} catch (IndexOutOfBoundsException e) { LBHttpSolrServer.LOGGER.info("---" + server.httpSolrServer.getHost());
continue; }
} return this.selectRandomServer().httpSolrServer.getHost();
} }
}
@Override
/*@Override public String getCoreName() {
public NamedList<Object> request(final SolrRequest request) throws SolrServerException, IOException { return this.coreName;
int attempts = 0; }
int startSize = aliveServers.size();
Exception ex; @Override
String zombieHost = null; public void reloadCore() throws SolrException {
for (;;) { }
WrappedHttpSolrServer httpSolrServer = selectRandomServer();
try { private void moveAliveToDead(final WrappedHttpSolrServer solrServer) {
if (null != zombieHost && request.getParams() instanceof SolrQuery) { this.checkLock.lock();
SolrQuery query = (SolrQuery) request.getParams(); try {
String shards = query.get(ShardParams.SHARDS); final boolean result = this.aliveServers.remove(solrServer);
if (null != shards) { if (result && this.zombieServers.addIfAbsent(solrServer)) {
shards = StringUtils.replace(shards, zombieHost, httpSolrServer.httpSolrServer.getHost()); if (LBHttpSolrServer.LOGGER.isWarnEnabled()) {
query.set(ShardParams.SHARDS, shards); LBHttpSolrServer.LOGGER.warn("solr server [" + solrServer.httpSolrServer.getHost() + "] is marked as down.");
} }
} this.startAliveCheckExecutor();
return httpSolrServer.httpSolrServer.request(request); }
} catch (SolrServerException e) { }
if (e.getRootCause() instanceof IOException) { finally {
ex = e; this.checkLock.unlock();
zombieHost = httpSolrServer.httpSolrServer.getHost(); }
LOGGER.error("error request solr server: " + zombieHost, e); }
moveAliveToDead(httpSolrServer);
} else { private void checkAZombieServer(final WrappedHttpSolrServer zombieServer) {
throw e; this.checkLock.lock();
} try {
} if (LBHttpSolrServer.LOGGER.isInfoEnabled()) {
attempts++; LBHttpSolrServer.LOGGER.info("check solr server [" + zombieServer.httpSolrServer.getHost() + "] ...");
if (attempts >= startSize) }
throw new SolrServerException("No live SolrServers available to handle this request", ex); final QueryResponse resp = zombieServer.httpSolrServer.query((SolrParams)LBHttpSolrServer.SOLR_QUERY);
} if (resp.getStatus() == 0) {
}*/ this.zombieServers.remove(zombieServer);
this.aliveServers.add(zombieServer);
@Override if (LBHttpSolrServer.LOGGER.isInfoEnabled()) {
public String getHost() { LBHttpSolrServer.LOGGER.info("solr server [" + zombieServer.httpSolrServer.getHost() + "] has come back.");
for (WrappedHttpSolrServer server : aliveServers) { }
LOGGER.info("---"+server.httpSolrServer.getHost()); zombieServer.failedPings = 0;
} }
return selectRandomServer().httpSolrServer.getHost(); }
} catch (Exception e) {
zombieServer.failedPings++;
@Override }
public String getCoreName() { finally {
return coreName; this.checkLock.unlock();
} }
}
@Override
public void reloadCore() throws com.fangjia.datastore.solr.SolrException { private void startAliveCheckExecutor() {
// does noting if (this.aliveCheckExecutor == null) {
} synchronized (this) {
if (this.aliveCheckExecutor == null) {
private void moveAliveToDead(WrappedHttpSolrServer solrServer) { (this.aliveCheckExecutor = Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory())).scheduleAtFixedRate(getAliveCheckRunner(new WeakReference<LBHttpSolrServer>(this)), 10000L, 10000L, TimeUnit.MILLISECONDS);
checkLock.lock(); }
try { }
boolean result = aliveServers.remove(solrServer); }
if (result) { }
if (zombieServers.addIfAbsent(solrServer)) {
if (LOGGER.isWarnEnabled()) { private static Runnable getAliveCheckRunner(final WeakReference<LBHttpSolrServer> lbHttpSolrServer) {
LOGGER.warn("solr server [" + solrServer.httpSolrServer.getHost() + "] is marked as down."); return new Runnable() {
} @Override
startAliveCheckExecutor(); public void run() {
} final LBHttpSolrServer solrServer = (LBHttpSolrServer)lbHttpSolrServer.get();
} if (solrServer != null && solrServer.zombieServers != null) {
} finally { for (final WrappedHttpSolrServer zombieServer : solrServer.zombieServers) {
checkLock.unlock(); solrServer.checkAZombieServer(zombieServer);
} }
} }
}
private void checkAZombieServer(WrappedHttpSolrServer zombieServer) { };
checkLock.lock(); }
try {
if (LOGGER.isInfoEnabled()) { public NamedList<Object> request(final SolrRequest paramSolrRequest, final String paramString) throws SolrServerException, IOException {
LOGGER.info("check solr server [" + zombieServer.httpSolrServer.getHost() + "] ..."); int attempts = 0;
} final int startSize = this.aliveServers.size();
QueryResponse resp = zombieServer.httpSolrServer.query(SOLR_QUERY); String zombieHost = null;
if (resp.getStatus() == 0) { while (true) {
// server has come back up final WrappedHttpSolrServer httpSolrServer = this.selectRandomServer();
zombieServers.remove(zombieServer); try {
aliveServers.add(zombieServer); if (null != zombieHost && paramSolrRequest.getParams() instanceof SolrQuery) {
if (LOGGER.isInfoEnabled()) { final SolrQuery query = (SolrQuery)paramSolrRequest.getParams();
LOGGER.info("solr server [" + zombieServer.httpSolrServer.getHost() + "] has come back."); String shards = query.get("shards");
} if (null != shards) {
zombieServer.failedPings = 0; shards = StringUtils.replace(shards, zombieHost, httpSolrServer.httpSolrServer.getHost());
} query.set("shards", shards);
} catch (Exception e) { }
zombieServer.failedPings++; }
// Expected . The server is still down return httpSolrServer.httpSolrServer.request(paramSolrRequest);
} finally { }
checkLock.unlock(); catch (SolrServerException e) {
} if (!(e.getRootCause() instanceof IOException)) {
} throw e;
}
private void startAliveCheckExecutor() { final Exception ex = (Exception)e;
if (aliveCheckExecutor == null) { zombieHost = httpSolrServer.httpSolrServer.getHost();
synchronized (this) { LBHttpSolrServer.LOGGER.error("error request solr server: " + zombieHost, (Throwable)e);
if (aliveCheckExecutor == null) { this.moveAliveToDead(httpSolrServer);
aliveCheckExecutor = Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory()); if (++attempts >= startSize) {
aliveCheckExecutor.scheduleAtFixedRate(getAliveCheckRunner(new WeakReference<LBHttpSolrServer>(this)), throw new SolrServerException("No live SolrServers available to handle this request", (Throwable)ex);
CHECK_INTERVAL, CHECK_INTERVAL, TimeUnit.MILLISECONDS); }
} continue;
} }
} }
} }
private static Runnable getAliveCheckRunner(final WeakReference<LBHttpSolrServer> lbHttpSolrServer) { public void shutdown() {
return new Runnable() { }
public void run() {
LBHttpSolrServer solrServer = lbHttpSolrServer.get(); static {
if (solrServer != null && solrServer.zombieServers != null) { LOGGER = LoggerFactory.getLogger(LBHttpSolrServer.class);
for (WrappedHttpSolrServer zombieServer : solrServer.zombieServers) { SOLR_QUERY = new SolrQuery("*:*");
solrServer.checkAZombieServer(zombieServer); }
}
} static class DefaultThreadFactory implements ThreadFactory
} {
}; static final AtomicInteger poolNumber;
} final ThreadGroup group;
final AtomicInteger threadNumber;
/** final String namePrefix;
* The default thread factory
*/ DefaultThreadFactory() {
static class DefaultThreadFactory implements ThreadFactory { this.threadNumber = new AtomicInteger(1);
static final AtomicInteger poolNumber = new AtomicInteger(1); final SecurityManager s = System.getSecurityManager();
final ThreadGroup group; this.group = ((s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup());
final AtomicInteger threadNumber = new AtomicInteger(1); this.namePrefix = "solrcheck-" + DefaultThreadFactory.poolNumber.getAndIncrement() + "-thread-";
final String namePrefix; }
DefaultThreadFactory() { @Override
SecurityManager s = System.getSecurityManager(); public Thread newThread(final Runnable r) {
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); final Thread t = new Thread(this.group, r, this.namePrefix + this.threadNumber.getAndIncrement(), 0L);
namePrefix = "solrcheck-" + poolNumber.getAndIncrement() + "-thread-"; t.setDaemon(true);
} if (t.getPriority() != 5) {
t.setPriority(5);
public Thread newThread(Runnable r) { }
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); return t;
t.setDaemon(true); }
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY); static {
return t; poolNumber = new AtomicInteger(1);
} }
} }
private class WrappedHttpSolrServer { private class WrappedHttpSolrServer
private final HttpSolrServer httpSolrServer; {
private int failedPings = 0; private final HttpSolrServer httpSolrServer;
private int failedPings;
public WrappedHttpSolrServer(HttpSolrServer httpSolrServer) {
this.httpSolrServer = httpSolrServer; public WrappedHttpSolrServer(final HttpSolrServer httpSolrServer) {
} this.failedPings = 0;
this.httpSolrServer = httpSolrServer;
} }
}
@Override }
public NamedList<Object> request(SolrRequest paramSolrRequest,
String paramString) throws SolrServerException, IOException {
int attempts = 0;
int startSize = aliveServers.size();
Exception ex;
String zombieHost = null;
for (;;) {
WrappedHttpSolrServer httpSolrServer = selectRandomServer();
try {
if (null != zombieHost && paramSolrRequest.getParams() instanceof SolrQuery) {
SolrQuery query = (SolrQuery) paramSolrRequest.getParams();
String shards = query.get(ShardParams.SHARDS);
if (null != shards) {
shards = StringUtils.replace(shards, zombieHost, httpSolrServer.httpSolrServer.getHost());
query.set(ShardParams.SHARDS, shards);
}
}
return httpSolrServer.httpSolrServer.request(paramSolrRequest);
} catch (SolrServerException e) {
if (e.getRootCause() instanceof IOException) {
ex = e;
zombieHost = httpSolrServer.httpSolrServer.getHost();
LOGGER.error("error request solr server: " + zombieHost, e);
moveAliveToDead(httpSolrServer);
} else {
throw e;
}
}
attempts++;
if (attempts >= startSize)
throw new SolrServerException("No live SolrServers available to handle this request", ex);
}
}
@Override
public void shutdown() {
// TODO Auto-generated method stub
}
}
@@ -1,23 +1,21 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
public class SolrException extends Exception { public class SolrException extends Exception
{
private static final long serialVersionUID = -1105081175581071875L; private static final long serialVersionUID = -1105081175581071875L;
public SolrException() { public SolrException() {
super(); }
}
public SolrException(final String message, final Throwable cause) {
public SolrException(String message, Throwable cause) { super(message, cause);
super(message, cause); }
}
public SolrException(final String message) {
public SolrException(String message) { super(message);
super(message); }
}
public SolrException(final Throwable cause) {
public SolrException(Throwable cause) { super(cause);
super(cause); }
}
} }
@@ -1,177 +1,176 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.commons.lang.StringUtils;
import java.util.Iterator;
import java.util.List;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermRangeQuery;
import java.util.Date;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.lucene.search.BooleanQuery;
public class SolrQueryBuilder { public class SolrQueryBuilder
private BooleanQuery booleanQuery = new BooleanQuery(); {
public final static FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone private BooleanQuery booleanQuery;
.getTimeZone("UTC")); public static final FastDateFormat DATE_FORMAT;
/** public static final String NO_ESCAPSE = "$$";
* 约定:以$$开头的字符串不需要特殊字符转义
*/ public SolrQueryBuilder() {
public final static String NO_ESCAPSE = "$$"; this.booleanQuery = new BooleanQuery();
}
public SolrQueryBuilder range(String field, Object min, Object max, boolean minInclusive, boolean maxInclusive,
BooleanClause.Occur occur) { public SolrQueryBuilder range(final String field, final Object min, final Object max, final boolean minInclusive, final boolean maxInclusive, final BooleanClause.Occur occur) {
if (min != null || max != null) { if (min != null || max != null) {
Object obj = null == min ? max : min; final Object obj = (null == min) ? max : min;
Query query = null; Query query = null;
if (Integer.class.isInstance(obj)) { if (Integer.class.isInstance(obj)) {
query = NumericRangeQuery.newIntRange(field, (Integer) min, (Integer) max, minInclusive, maxInclusive); query = (Query)NumericRangeQuery.newIntRange(field, (Integer)min, (Integer)max, minInclusive, maxInclusive);
} else if (Long.class.isInstance(obj)) { }
query = NumericRangeQuery.newLongRange(field, (Long) min, (Long) max, minInclusive, maxInclusive); else if (Long.class.isInstance(obj)) {
} else if (Double.class.isInstance(obj)) { query = (Query)NumericRangeQuery.newLongRange(field, (Long)min, (Long)max, minInclusive, maxInclusive);
query = NumericRangeQuery.newDoubleRange(field, (Double) min, (Double) max, minInclusive, maxInclusive); }
} else if (Float.class.isInstance(obj)) { else if (Double.class.isInstance(obj)) {
query = NumericRangeQuery.newFloatRange(field, (Float) min, (Float) max, minInclusive, maxInclusive); query = (Query)NumericRangeQuery.newDoubleRange(field, (Double)min, (Double)max, minInclusive, maxInclusive);
} else if (Date.class.isInstance(obj)) { }
query = new TermRangeQuery(field, null == min ? null : DATE_FORMAT.format((Date) min), null == max ? null else if (Float.class.isInstance(obj)) {
: DATE_FORMAT.format((Date) max), minInclusive, maxInclusive); query = (Query)NumericRangeQuery.newFloatRange(field, (Float)min, (Float)max, minInclusive, maxInclusive);
} else { }
query = new TermRangeQuery(field, null == min ? (String) min : min.toString(), null == max ? (String) max : max else if (Date.class.isInstance(obj)) {
.toString(), minInclusive, maxInclusive); query = (Query)new TermRangeQuery(field, (null == min) ? null : SolrQueryBuilder.DATE_FORMAT.format((Date)min), (null == max) ? null : SolrQueryBuilder.DATE_FORMAT.format((Date)max), minInclusive, maxInclusive);
} }
booleanQuery.add(query, occur); else {
} query = (Query)new TermRangeQuery(field, (null == min) ? ((String)min) : min.toString(), (null == max) ? ((String)max) : max.toString(), minInclusive, maxInclusive);
return this; }
} this.booleanQuery.add(query, occur);
}
public SolrQueryBuilder range(String field, Object min, Object max, boolean minInclusive, boolean maxInclusive) { return this;
return range(field, min, max, minInclusive, maxInclusive, BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder range(final String field, final Object min, final Object max, final boolean minInclusive, final boolean maxInclusive) {
public SolrQueryBuilder range(String field, Object min, Object max) { return this.range(field, min, max, minInclusive, maxInclusive, BooleanClause.Occur.MUST);
return range(field, min, max, true, true, BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder range(final String field, final Object min, final Object max) {
public SolrQueryBuilder range(String field, Object min, Object max, BooleanClause.Occur occur) { return this.range(field, min, max, true, true, BooleanClause.Occur.MUST);
return range(field, min, max, true, true, occur); }
}
public SolrQueryBuilder range(final String field, final Object min, final Object max, final BooleanClause.Occur occur) {
public SolrQueryBuilder gt(String field, Object value) { return this.range(field, min, max, true, true, occur);
return range(field, value, null, false, true, BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder gt(final String field, final Object value) {
public SolrQueryBuilder gt(String field, Object value, BooleanClause.Occur occur) { return this.range(field, value, null, false, true, BooleanClause.Occur.MUST);
return range(field, value, null, false, true, occur); }
}
public SolrQueryBuilder gt(final String field, final Object value, final BooleanClause.Occur occur) {
public SolrQueryBuilder gte(String field, Object value) { return this.range(field, value, null, false, true, occur);
return range(field, value, null, true, true, BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder gte(final String field, final Object value) {
public SolrQueryBuilder gte(String field, Object value, BooleanClause.Occur occur) { return this.range(field, value, null, true, true, BooleanClause.Occur.MUST);
return range(field, value, null, true, true, occur); }
}
public SolrQueryBuilder gte(final String field, final Object value, final BooleanClause.Occur occur) {
public SolrQueryBuilder lt(String field, Object value) { return this.range(field, value, null, true, true, occur);
return range(field, null, value, true, false, BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder lt(final String field, final Object value) {
public SolrQueryBuilder lt(String field, Object value, BooleanClause.Occur occur) { return this.range(field, null, value, true, false, BooleanClause.Occur.MUST);
return range(field, null, value, true, false, occur); }
}
public SolrQueryBuilder lt(final String field, final Object value, final BooleanClause.Occur occur) {
public SolrQueryBuilder lte(String field, Object value) { return this.range(field, null, value, true, false, occur);
return range(field, null, value, true, true, BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder lte(final String field, final Object value) {
public SolrQueryBuilder lte(String field, Object value, BooleanClause.Occur occur) { return this.range(field, null, value, true, true, BooleanClause.Occur.MUST);
return range(field, null, value, true, true, occur); }
}
public SolrQueryBuilder lte(final String field, final Object value, final BooleanClause.Occur occur) {
public SolrQueryBuilder eq(String field, Object value, BooleanClause.Occur occur) { return this.range(field, null, value, true, true, occur);
if (null != value) { }
Query query = new TermQuery(new Term(field, value.toString()));
booleanQuery.add(query, occur); public SolrQueryBuilder eq(final String field, final Object value, final BooleanClause.Occur occur) {
} if (null != value) {
return this; final Query query = (Query)new TermQuery(new Term(field, value.toString()));
} this.booleanQuery.add(query, occur);
}
public SolrQueryBuilder eq(String field, Object value) { return this;
return eq(field, getRealValue(value), BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder eq(final String field, final Object value) {
public SolrQueryBuilder eq(String field, Object value, boolean escapse) { return this.eq(field, this.getRealValue(value), BooleanClause.Occur.MUST);
return eq(field, escapse ? QueryParser.escape(value.toString()) : value.toString(), BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder eq(final String field, final Object value, final boolean escapse) {
public SolrQueryBuilder ne(String field, Object value) { return this.eq(field, escapse ? QueryParser.escape(value.toString()) : value.toString(), BooleanClause.Occur.MUST);
return eq(field, getRealValue(value), BooleanClause.Occur.MUST_NOT); }
}
public SolrQueryBuilder ne(final String field, final Object value) {
public SolrQueryBuilder in(String field, List<Object> value, boolean escapse, BooleanClause.Occur occur) { return this.eq(field, this.getRealValue(value), BooleanClause.Occur.MUST_NOT);
if (null == value || value.isEmpty()) { }
throw new IllegalArgumentException("in query with null or empty list!!");
} public SolrQueryBuilder in(final String field, final List<Object> value, final boolean escapse, final BooleanClause.Occur occur) {
BooleanQuery bQuery = new BooleanQuery(); if (null == value || value.isEmpty()) {
for (Object v : value) { throw new IllegalArgumentException("in query with null or empty list!!");
Query query = new TermQuery(new Term(field, escapse ? QueryParser.escape(v.toString()) : v.toString())); }
bQuery.add(query, BooleanClause.Occur.SHOULD); final BooleanQuery bQuery = new BooleanQuery();
} for (final Object v : value) {
booleanQuery.add(bQuery, occur); final Query query = (Query)new TermQuery(new Term(field, escapse ? QueryParser.escape(v.toString()) : v.toString()));
return this; bQuery.add(query, BooleanClause.Occur.SHOULD);
} }
this.booleanQuery.add((Query)bQuery, occur);
public SolrQueryBuilder in(String field, List<Object> value) { return this;
return in(field, getRealValue(value), false, BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder in(final String field, final List<Object> value) {
public SolrQueryBuilder in(String field, List<Object> value, BooleanClause.Occur occur) { return this.in(field, this.getRealValue(value), false, BooleanClause.Occur.MUST);
return in(field, getRealValue(value), false, occur); }
}
public SolrQueryBuilder in(final String field, final List<Object> value, final BooleanClause.Occur occur) {
public SolrQueryBuilder in(String field, List<Object> value, boolean escapse) { return this.in(field, this.getRealValue(value), false, occur);
return in(field, value, escapse, BooleanClause.Occur.MUST); }
}
public SolrQueryBuilder in(final String field, final List<Object> value, final boolean escapse) {
public Query toQuery() { return this.in(field, value, escapse, BooleanClause.Occur.MUST);
return this.booleanQuery; }
}
public Query toQuery() {
/** return (Query)this.booleanQuery;
* 获取真实value<br/> }
* 如果是非string的value,返回转义后的原值<br/>
* 如果是string型,如果以$$开头,则截取$$后面的字符且不需要转义 private Object getRealValue(final Object value) {
* if (value instanceof String) {
* @param value if ("$$".equals(value)) {
* @return return value;
*/ }
private Object getRealValue(Object value) { if (StringUtils.startsWith((String)value, "$$")) {
if (value instanceof String) { return StringUtils.substring((String)value, "$$".length());
if (NO_ESCAPSE.equals(value)) { }
return value; }
} else if (StringUtils.startsWith((String) value, NO_ESCAPSE)) { return ClientUtils.escapeQueryChars(value.toString());
return StringUtils.substring((String) value, NO_ESCAPSE.length()); }
}
} private List<Object> getRealValue(final List<Object> value) {
return ClientUtils.escapeQueryChars(value.toString()); if (null == value || value.isEmpty()) {
// return QueryParser.escape(value.toString()); return value;
} }
final List<Object> ret = new ArrayList<Object>(value.size());
private List<Object> getRealValue(List<Object> value) { for (final Object v : value) {
if (null == value || value.isEmpty()) { ret.add(this.getRealValue(v));
return value; }
} return ret;
List<Object> ret = new ArrayList<Object>(value.size()); }
for (Object v : value) {
ret.add(getRealValue(v)); static {
} DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("UTC"));
return ret; }
}
} }
@@ -1,26 +1,26 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.io.File; import java.io.File;
import java.util.Collection;
import java.util.Set; import java.util.Set;
import java.util.Collection;
import com.fangjia.datastore.config.Reloadable; import com.fangjia.datastore.config.Reloadable;
public interface SolrSchema extends Reloadable { public interface SolrSchema extends Reloadable
public final static String VERTION = "_version"; {
public final static String ID = "_id"; public static final String VERTION = "_version";
public static final String ID = "_id";
int saveIndex(Collection<Index> indexes) throws SolrException;
int saveIndex(final Collection<Index> p0) throws SolrException;
boolean removeIndex(String name) throws SolrException;
boolean removeIndex(final String p0) throws SolrException;
Index getIndex(String name);
Index getIndex(final String p0);
Collection<Index> getIndexes();
Collection<Index> getIndexes();
Set<String> getIndexNames();
Set<String> getIndexNames();
File getSchemaFile();
File getSchemaFile();
void setSchemaFile(File schemaFile);
} void setSchemaFile(final File p0);
}
@@ -1,189 +1,194 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.io.File; import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.io.OutputStream;
import java.util.HashMap; import org.dom4j.io.XMLWriter;
import java.util.List; import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException; import org.dom4j.DocumentException;
import java.util.Set;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Node;
import java.util.Iterator;
import org.dom4j.DocumentHelper; import org.dom4j.DocumentHelper;
import org.dom4j.Element; import org.dom4j.Element;
import org.dom4j.Node; import java.util.Collection;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fangjia.datastore.ConfigurationException; import com.fangjia.datastore.ConfigurationException;
import com.fangjia.datastore.solr.Index.IndexTypeEnum; import java.util.HashMap;
import org.slf4j.Logger;
import org.dom4j.Document;
import java.util.Map;
import java.io.File;
import org.dom4j.io.SAXReader;
public class SolrSchemaImpl implements SolrSchema { public class SolrSchemaImpl implements SolrSchema
private final SAXReader reader = new SAXReader(); {
private File schemaFile; private final SAXReader reader;
private final Map<String, Index> indexes = new HashMap<String, Index>(); private File schemaFile;
private Document document; private final Map<String, Index> indexes;
private final static Logger LOGGER = LoggerFactory.getLogger(SolrSchemaImpl.class); private Document document;
private static final Logger LOGGER;
public static void main(String[] args) throws Exception {
new SolrSchemaImpl(new File("D:\\viewstore\\solrhome\\house\\conf\\schema.xml")); public static void main(final String[] args) throws Exception {
} new SolrSchemaImpl(new File("D:\\viewstore\\solrhome\\house\\conf\\schema.xml"));
}
public SolrSchemaImpl(File schemaFile) throws ConfigurationException {
if (!schemaFile.exists() || schemaFile.isDirectory()) { public SolrSchemaImpl(final File schemaFile) throws ConfigurationException {
throw new IllegalArgumentException("schema file not exists or is a directory:" + schemaFile); this.reader = new SAXReader();
} this.indexes = new HashMap<String, Index>();
this.schemaFile = schemaFile; if (!schemaFile.exists() || schemaFile.isDirectory()) {
reload(); throw new IllegalArgumentException("schema file not exists or is a directory:" + schemaFile);
} }
this.schemaFile = schemaFile;
public int saveIndex(Collection<Index> newIndexes) throws SolrException { this.reload();
int ret = 0; }
try {
for (Index index : newIndexes) { @Override
Index i = indexes.get(index.getName()); public int saveIndex(final Collection<Index> newIndexes) throws SolrException {
if (index.equals(i)) { int ret = 0;
continue; try {
} for (final Index index : newIndexes) {
ret++; final Index i = this.indexes.get(index.getName());
Element e; if (index.equals(i)) {
if (indexes.containsKey(index.getName())) { continue;
String xpath = "//schema//fields//" + (index.isDynamic() ? "dynamicField" : "field") + "[name=\"" }
+ index.getName() + "\"]"; ++ret;
e = (Element) this.document.selectSingleNode(xpath); Element e;
} else { if (this.indexes.containsKey(index.getName())) {
e = DocumentHelper.createElement(index.isDynamic() ? "dynamicField" : "field"); final String xpath = "//schema//fields//" + (index.isDynamic() ? "dynamicField" : "field") + "[name=\"" + index.getName() + "\"]";
Element fields = (Element) document.selectSingleNode("//schema//fields"); e = (Element)this.document.selectSingleNode(xpath);
fields.add(e); }
} else {
e.addAttribute("name", index.getName()); e = DocumentHelper.createElement(index.isDynamic() ? "dynamicField" : "field");
e.addAttribute("type", index.getType().getType()); final Element fields = (Element)this.document.selectSingleNode("//schema//fields");
e.addAttribute("stored", String.valueOf(index.isStored())); fields.add(e);
e.addAttribute("indexed", String.valueOf(index.isIndexed())); }
e.addAttribute("multiValued", String.valueOf(index.isMultiValued())); e.addAttribute("name", index.getName());
e.addAttribute("comments", String.valueOf(index.getComments())); e.addAttribute("type", index.getType().getType());
this.indexes.put(index.getName(), index); e.addAttribute("stored", String.valueOf(index.isStored()));
} e.addAttribute("indexed", String.valueOf(index.isIndexed()));
} finally { e.addAttribute("multiValued", String.valueOf(index.isMultiValued()));
write(); e.addAttribute("comments", String.valueOf(index.getComments()));
} this.indexes.put(index.getName(), index);
return ret; }
} }
finally {
public synchronized boolean removeIndex(String name) throws SolrException { this.write();
Index index = this.indexes.get(name); }
if (null == index) { return ret;
return false; }
}
if (ID.equals(name) || VERTION.equals(name)) { @Override
throw new SolrException("delete of field \"" + name + "\" is not allowed!"); public synchronized boolean removeIndex(final String name) throws SolrException {
} final Index index = this.indexes.get(name);
String xpath = "//schema//fields//" + (index.isDynamic() ? "dynamicField" : "field") + "[name=\"" + index.getName() if (null == index) {
+ "\"]"; return false;
Element e = (Element) this.document.selectSingleNode(xpath); }
if (null != e) { if ("_id".equals(name) || "_version".equals(name)) {
e.detach(); throw new SolrException("delete of field \"" + name + "\" is not allowed!");
} }
write(); final String xpath = "//schema//fields//" + (index.isDynamic() ? "dynamicField" : "field") + "[name=\"" + index.getName() + "\"]";
this.indexes.remove(name); final Element e = (Element)this.document.selectSingleNode(xpath);
return true; if (null != e) {
} e.detach();
}
public Collection<Index> getIndexes() { this.write();
return indexes.values(); this.indexes.remove(name);
} return true;
}
@SuppressWarnings("unchecked")
public void reload() throws ConfigurationException { @Override
if (LOGGER.isDebugEnabled()) { public Collection<Index> getIndexes() {
LOGGER.debug("refresh solr schema: {}", this.schemaFile); return this.indexes.values();
} }
Map<String, Index> newIndexes = new HashMap<String, Index>();
@Override
Document newDocument = read(); public void reload() throws ConfigurationException {
if (SolrSchemaImpl.LOGGER.isDebugEnabled()) {
List<Node> list = newDocument.selectNodes("//schema"); SolrSchemaImpl.LOGGER.debug("refresh solr schema: {}", (Object)this.schemaFile);
if (null == list || list.size() > 1) { }
throw new ConfigurationException("zero or more than one \"fields\" tag found, expect only one \"fields\" tag"); final Map<String, Index> newIndexes = new HashMap<String, Index>();
} final Document newDocument = this.read();
Node fieldsNode = list.get(0); List<Node> list = (List<Node>)newDocument.selectNodes("//schema");
list = fieldsNode.selectNodes("field"); if (null == list || list.size() > 1) {
for (Node node : list) { throw new ConfigurationException("zero or more than one \"fields\" tag found, expect only one \"fields\" tag");
Element e = (Element) node; }
final Node fieldsNode = list.get(0);
String name = e.attributeValue("name"); list = (List<Node>)fieldsNode.selectNodes("field");
if (StringUtils.isEmpty(name)) { for (final Node node : list) {
throw new ConfigurationException("invalid field name \"" + name + "\" in solr schema: " + this.schemaFile); final Element e = (Element)node;
} final String name = e.attributeValue("name");
if (StringUtils.isEmpty(name)) {
IndexTypeEnum type = IndexTypeEnum.parse(e.attributeValue("type")); throw new ConfigurationException("invalid field name \"" + name + "\" in solr schema: " + this.schemaFile);
if (null == type) { }
throw new ConfigurationException("invalid field type \"" + e.attributeValue("type") + "\" in solr schema: " final Index.IndexTypeEnum type = Index.IndexTypeEnum.parse(e.attributeValue("type"));
+ this.schemaFile); if (null == type) {
} throw new ConfigurationException("invalid field type \"" + e.attributeValue("type") + "\" in solr schema: " + this.schemaFile);
}
boolean stored = Boolean.parseBoolean(e.attributeValue("stored")); final boolean stored = Boolean.parseBoolean(e.attributeValue("stored"));
boolean indexed = Boolean.parseBoolean(e.attributeValue("indexed")); final boolean indexed = Boolean.parseBoolean(e.attributeValue("indexed"));
boolean multiValued = Boolean.parseBoolean(e.attributeValue("multiValued")); final boolean multiValued = Boolean.parseBoolean(e.attributeValue("multiValued"));
String comments = e.attributeValue("comments"); final String comments = e.attributeValue("comments");
boolean dynamic = e.getName().equals("dynamicField"); final boolean dynamic = e.getName().equals("dynamicField");
final Index index = new Index(name, type, stored, indexed, multiValued, dynamic, comments);
Index index = new Index(name, type, stored, indexed, multiValued, dynamic, comments); newIndexes.put(name, index);
newIndexes.put(name, index); }
} if (!newIndexes.containsKey("_id")) {
if (!newIndexes.containsKey(ID)) { throw new ConfigurationException("no field names \"_id\" find in schema: " + this.schemaFile);
throw new ConfigurationException("no field names \"" + ID + "\" find in schema: " + this.schemaFile); }
} if (!newIndexes.containsKey("_version")) {
if (!newIndexes.containsKey(VERTION)) { throw new ConfigurationException("no field names \"_version\" find in schema: " + this.schemaFile);
throw new ConfigurationException("no field names \"" + VERTION + "\" find in schema: " + this.schemaFile); }
} this.indexes.clear();
indexes.clear(); this.indexes.putAll(newIndexes);
indexes.putAll(newIndexes); this.document = newDocument;
this.document = newDocument; }
} @Override
public Set<String> getIndexNames() {
public Set<String> getIndexNames() { return this.indexes.keySet();
return this.indexes.keySet(); }
}
private Document read() throws ConfigurationException {
private Document read() throws ConfigurationException { try {
try { return this.reader.read(this.schemaFile);
return reader.read(schemaFile); }
} catch (DocumentException e) { catch (DocumentException e) {
throw new ConfigurationException("error read solr xml file: " + this, e); throw new ConfigurationException("error read solr xml file: " + this, (Throwable)e);
} }
} }
private void write() throws SolrException { private void write() throws SolrException {
if (LOGGER.isDebugEnabled()) { if (SolrSchemaImpl.LOGGER.isDebugEnabled()) {
LOGGER.debug("write solr schema: {}" + this.schemaFile); SolrSchemaImpl.LOGGER.debug("write solr schema: {}" + this.schemaFile);
} }
XMLWriter writer; try {
try { final XMLWriter writer = new XMLWriter((OutputStream)new FileOutputStream(this.schemaFile));
writer = new XMLWriter(new FileOutputStream(schemaFile)); writer.write(this.document);
writer.write(document); writer.close();
writer.close(); }
} catch (IOException e) { catch (IOException e) {
throw new SolrException("error write solr xml file: " + this, e); throw new SolrException("error write solr xml file: " + this, e);
} }
} }
public Index getIndex(String name) { @Override
return this.indexes.get(name); public Index getIndex(final String name) {
} return this.indexes.get(name);
}
public File getSchemaFile() {
return schemaFile; @Override
} public File getSchemaFile() {
return this.schemaFile;
public void setSchemaFile(File schemaFile) { }
this.schemaFile = schemaFile;
} @Override
public void setSchemaFile(final File schemaFile) {
} this.schemaFile = schemaFile;
}
static {
LOGGER = LoggerFactory.getLogger((Class)SolrSchemaImpl.class);
}
}
@@ -1,23 +1,22 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.util.List;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.bson.BSONObject; import org.bson.BSONObject;
import java.util.List;
import com.fangjia.datastore.ConfigurationException; import com.fangjia.datastore.ConfigurationException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.SolrQuery;
public interface SolrServer { public interface SolrServer
QueryResponse query(SolrQuery params, boolean fromMaster, boolean bulk) throws SolrException; {
QueryResponse query(final SolrQuery p0, final boolean p1, final boolean p2) throws SolrException;
void deleteByQuery(String query) throws SolrException;
void deleteByQuery(final String p0) throws SolrException;
void reload() throws ConfigurationException;
void reload() throws ConfigurationException;
void reloadCores() throws SolrException;
void reloadCores() throws SolrException;
SolrSchema getSolrSchema();
SolrSchema getSolrSchema();
void add(List<BSONObject> dbObjects) throws SolrException;
void add(final List<BSONObject> p0) throws SolrException;
} }
@@ -1,475 +1,455 @@
package com.fangjia.datastore.solr; package com.fangjia.datastore.solr;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
import org.apache.solr.common.params.ShardParams;
import org.bson.BSONObject;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.sothis.core.util.BlockingThreadPoolExecutor; import org.apache.solr.common.params.SolrParams;
import org.apache.solr.client.solrj.response.QueryResponse;
import com.fangjia.datastore.ConfigurationException; import org.apache.solr.client.solrj.SolrQuery;
import org.apache.commons.lang.math.RandomUtils;
import java.io.IOException;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.commons.lang.StringUtils;
import java.util.Collections;
import org.apache.commons.collections.CollectionUtils;
import org.bson.types.ObjectId;
import org.apache.solr.common.SolrInputField;
import java.util.Iterator;
import java.util.Date;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import org.bson.BSONObject;
import java.util.Collection;
import org.apache.solr.common.SolrInputDocument;
import java.util.List;
import java.util.HashMap;
import java.net.MalformedURLException;
import com.fangjia.datastore.config.SolrConfig; import com.fangjia.datastore.config.SolrConfig;
import com.fangjia.datastore.ConfigurationException;
import org.sothis.core.util.BlockingThreadPoolExecutor;
import java.io.File;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.Executor;
import java.util.Map;
import org.apache.http.client.HttpClient;
import com.fangjia.datastore.config.StoreConfig; import com.fangjia.datastore.config.StoreConfig;
import org.slf4j.Logger;
public class SolrServerImpl implements SolrServer { public class SolrServerImpl implements SolrServer
{
private final static Logger LOGGER = LoggerFactory.getLogger(SolrServerImpl.class); private static final Logger LOGGER;
private final static int SOLR_COMMIT_MAX_RETRY_COUNT = 3; private static final int SOLR_COMMIT_MAX_RETRY_COUNT = 3;
private final static int SOLR_QUERY_MAX_RETRY_COUNT = 3; private static final int SOLR_QUERY_MAX_RETRY_COUNT = 3;
private final static int MAX_NONE_BULK_SKIP = 100000; private static final int MAX_NONE_BULK_SKIP = 100000;
private final String name;
private final String name; private final StoreConfig storeConfig;
private final StoreConfig storeConfig; private final HttpClient httpClient;
private final HttpClient httpClient; private int masterCommitSolrServerCount;
private int masterCommitSolrServerCount; private final Map<String, HttpSolrServer> allSolrServers;
private final Map<String, HttpSolrServer> allSolrServers; private String[] masterCommitFilters;
private String[] masterCommitFilters; private HttpSolrServer[][] masterCommitSolrServers;
private HttpSolrServer[][] masterCommitSolrServers; private HttpSolrServer[] masterSolrServers;
private HttpSolrServer[] masterSolrServers; private HttpSolrServer[] slaveSolrServers;
private HttpSolrServer[] slaveSolrServers; private SolrSchema[] solrSchemas;
private SolrSchema[] solrSchemas; private final SolrSchema solrSchema;
private final SolrSchema solrSchema; private final Executor solrAddExecutorService;
private final Executor solrAddExecutorService; private final AtomicBoolean filtering;
private final AtomicBoolean filtering = new AtomicBoolean(false); private long lastFilterTime;
private long lastFilterTime = 0;
public SolrServerImpl(final StoreConfig storeConfig) throws ConfigurationException {
public SolrServerImpl(StoreConfig storeConfig) throws ConfigurationException { this.filtering = new AtomicBoolean(false);
this.storeConfig = storeConfig; this.lastFilterTime = 0L;
this.name = storeConfig.getName(); this.storeConfig = storeConfig;
this.name = storeConfig.getName();
/*MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
connectionManager.getParams().setTcpNoDelay(true); cm.setMaxTotal(50);
connectionManager.getParams().setStaleCheckingEnabled(true); this.httpClient = (HttpClient)new DefaultHttpClient();
this.httpClient = new HttpClient(connectionManager); this.allSolrServers = this.initSolrServers(this.storeConfig, this.httpClient);
httpClient.getParams().setConnectionManagerTimeout(0); this.solrSchema = new SolrSchemaImpl(new File(storeConfig.getMasterSolrConfig().getHome() + "/" + this.name + "/conf/managed-schema"));
DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false); final int size = (this.masterCommitSolrServerCount + 1) * 2;
this.httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler); this.solrAddExecutorService = (Executor)new BlockingThreadPoolExecutor(this.name + "-SolrAdd", 1, size, size, 60000L);
*/ }
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(5); private CommonsHttpSolrServer createSolrServer(final String coreName, final SolrConfig solronfig) throws ConfigurationException {
/* RequestConfig requestConfig = RequestConfig.custom() try {
.setConnectTimeout(1000 * 10) final CommonsHttpSolrServer solrServer = new CommonsHttpSolrServer(solronfig.getHost(), coreName, this.httpClient);
.setSocketTimeout(1000 * 10) return solrServer;
.setCookieSpec(CookieSpecs.IGNORE_COOKIES) }
.build(); catch (MalformedURLException e) {
throw new ConfigurationException("[" + this.name + "] error create solr server: ", e);
this.httpClient = HttpClients.custom() }
.setDefaultRequestConfig(requestConfig) }
.setConnectionManager(cm)
.build();*/ private HttpSolrServer[] initSolrServer(final Map<String, HttpSolrServer> allSolrServers, final SolrConfig solrConfig) throws ConfigurationException {
this.httpClient = new DefaultHttpClient(); SolrConfig[] shardsConfigs = solrConfig.getShardsConfigs();
this.allSolrServers = initSolrServers(this.storeConfig, httpClient); if (shardsConfigs.length == 0) {
this.solrSchema = new SolrSchemaImpl(new File(storeConfig.getMasterSolrConfig().getHome() + "/" + name shardsConfigs = new SolrConfig[] { solrConfig };
+ "/conf/managed-schema")); }
int size = (masterCommitSolrServerCount + 1) * 2; final HttpSolrServer[] shards = new HttpSolrServer[shardsConfigs.length];
this.solrAddExecutorService = new BlockingThreadPoolExecutor(name + "-SolrAdd", 1, size, size, 60000); for (int i = 0; i < shardsConfigs.length; ++i) {
} final SolrConfig shardConfig = shardsConfigs[i];
if (!allSolrServers.containsKey(shardConfig.getId())) {
private CommonsHttpSolrServer createSolrServer(String coreName, SolrConfig solronfig) throws ConfigurationException { final SolrConfig[] slaveConfigs = shardConfig.getSlaveConfigs();
try { if (slaveConfigs.length == 0) {
CommonsHttpSolrServer solrServer = new CommonsHttpSolrServer(solronfig.getHost(), coreName, httpClient); allSolrServers.put(shardConfig.getId(), this.createSolrServer(this.name, shardConfig));
return solrServer; }
} catch (MalformedURLException e) { else {
throw new ConfigurationException("[" + this.name + "] error create solr server: ", e); final CommonsHttpSolrServer[] slaveServers = new CommonsHttpSolrServer[slaveConfigs.length];
} for (int j = 0; j < slaveConfigs.length; ++j) {
} final SolrConfig slaveConfig = slaveConfigs[j];
if (!allSolrServers.containsKey(slaveConfig.getId())) {
private HttpSolrServer[] initSolrServer(Map<String, HttpSolrServer> allSolrServers, SolrConfig solrConfig) allSolrServers.put(slaveConfig.getId(), this.createSolrServer(this.name, slaveConfig));
throws ConfigurationException { }
SolrConfig[] shardsConfigs = solrConfig.getShardsConfigs(); slaveServers[j] = (CommonsHttpSolrServer)allSolrServers.get(slaveConfig.getId());
if (shardsConfigs.length == 0) { }
shardsConfigs = new SolrConfig[] { solrConfig }; allSolrServers.put(shardConfig.getId(), new LBHttpSolrServer((HttpSolrServer[])slaveServers));
} }
HttpSolrServer[] shards = new HttpSolrServer[shardsConfigs.length]; }
for (int i = 0; i < shardsConfigs.length; i++) { shards[i] = allSolrServers.get(shardConfig.getId());
SolrConfig shardConfig = shardsConfigs[i]; }
if (!allSolrServers.containsKey(shardConfig.getId())) { return shards;
SolrConfig[] slaveConfigs = shardConfig.getSlaveConfigs(); }
if (slaveConfigs.length == 0) {
allSolrServers.put(shardConfig.getId(), createSolrServer(name, shardConfig)); private synchronized Map<String, HttpSolrServer> initSolrServers(final StoreConfig storeConfig, final HttpClient httpClient) throws ConfigurationException {
} else { final Map<String, HttpSolrServer> solrServers = new HashMap<String, HttpSolrServer>();
CommonsHttpSolrServer[] slaveServers = new CommonsHttpSolrServer[slaveConfigs.length]; final SolrConfig[] masterConfigs = storeConfig.getMasterSolrConfigs();
for (int j = 0; j < slaveConfigs.length; j++) { this.masterCommitSolrServers = new HttpSolrServer[masterConfigs.length][];
SolrConfig slaveConfig = slaveConfigs[j]; this.masterCommitFilters = new String[masterConfigs.length];
if (!allSolrServers.containsKey(slaveConfig.getId())) { this.solrSchemas = new SolrSchema[masterConfigs.length];
allSolrServers.put(slaveConfig.getId(), createSolrServer(name, slaveConfig)); this.masterCommitSolrServerCount = 0;
} for (int i = 0; i < masterConfigs.length; ++i) {
slaveServers[j] = (CommonsHttpSolrServer) allSolrServers.get(slaveConfig.getId()); this.masterCommitSolrServers[i] = this.initSolrServer(solrServers, masterConfigs[i]);
} this.masterCommitFilters[i] = masterConfigs[i].getFilter();
allSolrServers.put(shardConfig.getId(), new LBHttpSolrServer(slaveServers)); this.solrSchemas[i] = new SolrSchemaImpl(new File(masterConfigs[i].getHome() + "/" + this.name + "/conf/managed-schema"));
} this.masterCommitSolrServerCount += this.masterCommitSolrServers[i].length;
} }
shards[i] = allSolrServers.get(shardConfig.getId()); this.masterSolrServers = this.initSolrServer(solrServers, storeConfig.getMasterSolrConfig());
} this.slaveSolrServers = this.initSolrServer(solrServers, storeConfig.getSlaveSolrConfig());
return shards; return solrServers;
} }
private synchronized Map<String, HttpSolrServer> initSolrServers(StoreConfig storeConfig, HttpClient httpClient) private void addToSolr0(final HttpSolrServer solrServer, final List<SolrInputDocument> documents, int errorCount) {
throws ConfigurationException { try {
// http connections if (null != documents && !documents.isEmpty()) {
//httpClient.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost( solrServer.add((Collection)documents);
//storeConfig.getSolrMaxConnectionsPerHost()); solrServer.commit();
//httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(storeConfig.getSolrMaxTotalConnections()); }
}
Map<String, HttpSolrServer> solrServers = new HashMap<String, HttpSolrServer>(); catch (Exception e) {
SolrConfig[] masterConfigs = storeConfig.getMasterSolrConfigs(); if (errorCount <= 3) {
masterCommitSolrServers = new HttpSolrServer[masterConfigs.length][]; final long sleepTime = ++errorCount * errorCount;
masterCommitFilters = new String[masterConfigs.length]; if (SolrServerImpl.LOGGER.isInfoEnabled()) {
solrSchemas = new SolrSchema[masterConfigs.length]; SolrServerImpl.LOGGER.info("[" + this.name + "] error commit to solr[" + solrServer.getHost() + "], sleep " + sleepTime + "s and retry(" + e.getMessage() + ")");
masterCommitSolrServerCount = 0; }
for (int i = 0; i < masterConfigs.length; i++) { try {
masterCommitSolrServers[i] = initSolrServer(solrServers, masterConfigs[i]); Thread.sleep(1000L * sleepTime);
masterCommitFilters[i] = masterConfigs[i].getFilter(); }
solrSchemas[i] = new SolrSchemaImpl(new File(masterConfigs[i].getHome() + "/" + name + "/conf/managed-schema")); catch (InterruptedException e2) {
masterCommitSolrServerCount += masterCommitSolrServers[i].length; SolrServerImpl.LOGGER.error("[" + this.name + "] error save to solr: ", (Throwable)e2);
} }
masterSolrServers = initSolrServer(solrServers, storeConfig.getMasterSolrConfig()); this.addToSolr0(solrServer, documents, errorCount);
slaveSolrServers = initSolrServer(solrServers, storeConfig.getSlaveSolrConfig()); }
else if (SolrServerImpl.LOGGER.isErrorEnabled()) {
return solrServers; SolrServerImpl.LOGGER.error("[" + this.name + "] error save to solr[" + solrServer.getHost() + "] after " + 3 + " times retry: ", (Throwable)e);
} }
}
private void addToSolr0(HttpSolrServer solrServer, List<SolrInputDocument> documents, int errorCount) { }
try {
if (null != documents && !documents.isEmpty()) { @Override
solrServer.add(documents); public void add(final List<BSONObject> dbObjects) throws SolrException {
solrServer.commit(); if (null == dbObjects || dbObjects.size() == 0) {
} return;
} catch (Exception e) { }
if (errorCount <= SOLR_COMMIT_MAX_RETRY_COUNT) { try {
errorCount++; long time = System.currentTimeMillis();
long sleepTime = errorCount * errorCount; this.checkFilter();
if (LOGGER.isInfoEnabled()) { final CountDownLatch countDownLatch = new CountDownLatch(this.masterCommitSolrServerCount);
LOGGER.info("[" + this.name + "] error commit to solr[" + solrServer.getHost() + "], sleep " + sleepTime for (int j = 0; j < this.masterCommitSolrServers.length; ++j) {
+ "s and retry(" + e.getMessage() + ")"); final int jndex = j;
} final Map<Integer, List<BSONObject>> shardedObjectMap = this.shard(dbObjects, this.masterCommitSolrServers[j].length);
try { for (int i = 0; i < this.masterCommitSolrServers[j].length; ++i) {
Thread.sleep(1000 * sleepTime); final int index = i;
} catch (InterruptedException e1) { this.solrAddExecutorService.execute(new Runnable() {
LOGGER.error("[" + this.name + "] error save to solr: ", e1); @Override
} public void run() {
addToSolr0(solrServer, documents, errorCount); try {
} else { final List<BSONObject> sharedObjects = shardedObjectMap.get(index);
if (LOGGER.isErrorEnabled()) { if (null == sharedObjects || sharedObjects.size() == 0) {
LOGGER.error("[" + this.name + "] error save to solr[" + solrServer.getHost() + "] after " return;
+ SOLR_COMMIT_MAX_RETRY_COUNT + " times retry: ", e); }
} final List<SolrInputDocument> documents = new ArrayList<SolrInputDocument>(sharedObjects.size());
} for (final BSONObject obj : sharedObjects) {
} final SolrInputDocument document = SolrServerImpl.this.toSolrInputDocument(obj, SolrServerImpl.this.solrSchemas[jndex]);
} if (!document.isEmpty()) {
document.addField("_version", (Object)Core.VERSION_DATE_FORMAT.format(new Date()));
public void add(List<BSONObject> dbObjects) throws SolrException { System.out.println("document:" + document.toString());
if (null == dbObjects || dbObjects.size() == 0) { documents.add(document);
return; }
} else {
try { if (!SolrServerImpl.LOGGER.isDebugEnabled()) {
long time = System.currentTimeMillis(); continue;
checkFilter(); }
final CountDownLatch countDownLatch = new CountDownLatch(masterCommitSolrServerCount); SolrServerImpl.LOGGER.debug("solr input document is empty:" + document);
for (int j = 0; j < this.masterCommitSolrServers.length; j++) { }
final int jndex = j; }
final Map<Integer, List<BSONObject>> shardedObjectMap = shard(dbObjects, this.masterCommitSolrServers[j].length); SolrServerImpl.this.addToSolr0(SolrServerImpl.this.masterCommitSolrServers[jndex][index], documents, 0);
for (int i = 0; i < this.masterCommitSolrServers[j].length; i++) { }
final int index = i; catch (Exception e) {
this.solrAddExecutorService.execute(new Runnable() { if (SolrServerImpl.LOGGER.isErrorEnabled()) {
public void run() { SolrServerImpl.LOGGER.error("[" + SolrServerImpl.this.name + "] error save to solr: ", (Throwable)e);
try { }
List<BSONObject> sharedObjects = shardedObjectMap.get(index); }
if (null == sharedObjects || sharedObjects.size() == 0) { finally {
return; countDownLatch.countDown();
} }
final List<SolrInputDocument> documents = new ArrayList<SolrInputDocument>(sharedObjects.size()); }
for (BSONObject obj : sharedObjects) { });
SolrInputDocument document = toSolrInputDocument(obj, solrSchemas[jndex]); }
if (!document.isEmpty()) { }
document.addField(SolrSchema.VERTION, Core.VERSION_DATE_FORMAT.format(new Date())); countDownLatch.await();
System.out.println("document:" + document.toString()); time = System.currentTimeMillis() - time;
documents.add(document); if (SolrServerImpl.LOGGER.isInfoEnabled()) {
} else if (LOGGER.isDebugEnabled()) { SolrServerImpl.LOGGER.info("[" + this.name + "] add {} documents to solr, {}ms, {}/s.", new Object[] { dbObjects.size(), time, dbObjects.size() * 1000 / time });
LOGGER.debug("solr input document is empty:" + document); }
} }
} catch (Exception e) {
addToSolr0(masterCommitSolrServers[jndex][index], documents, 0); if (SolrServerImpl.LOGGER.isErrorEnabled()) {
} catch (Exception e) { SolrServerImpl.LOGGER.error("[" + this.name + "] error save to solr: ", (Throwable)e);
if (LOGGER.isErrorEnabled()) { }
LOGGER.error("[" + name + "] error save to solr: ", e); }
} }
} finally {
countDownLatch.countDown(); private SolrInputDocument toSolrInputDocument(final BSONObject doc, final SolrSchema solrSchema) {
} final Collection<Index> indexes = solrSchema.getIndexes();
} final SolrInputDocument document = new SolrInputDocument();
}); Map<String, Float> boostsMap = null;
} if (doc.get("$boosts") != null && doc.get("$boosts") instanceof Map) {
} boostsMap = (Map<String, Float>)doc.get("$boosts");
countDownLatch.await(); if (boostsMap.containsKey("$doc_boost")) {
time = System.currentTimeMillis() - time; document.setDocumentBoost(boostsMap.get("$doc_boost").floatValue());
if (LOGGER.isInfoEnabled()) { }
LOGGER.info("[" + this.name + "] add {} documents to solr, {}ms, {}/s.", new Object[] { dbObjects.size(), time, }
dbObjects.size() * 1000 / (time) }); for (final Index index : indexes) {
} final String key = index.getName();
} catch (Exception e) { if (doc.containsField(key)) {
if (LOGGER.isErrorEnabled()) { final Object value = doc.get(key);
LOGGER.error("[" + this.name + "] error save to solr: ", e); final SolrInputField field = new SolrInputField(key);
} if (value instanceof ObjectId) {
} field.setValue((Object)value.toString(), 1.0f);
} }
else if (boostsMap != null && boostsMap.containsKey(key)) {
@SuppressWarnings("unchecked") field.setValue(value, boostsMap.get(key).floatValue());
private SolrInputDocument toSolrInputDocument(BSONObject doc, SolrSchema solrSchema) { }
Collection<Index> indexes = solrSchema.getIndexes(); else {
SolrInputDocument document = new SolrInputDocument(); field.setValue(value, 1.0f);
Map<String, Float> boostsMap = null; }
if (doc.get("$boosts") != null) { document.put(key, field);
if (doc.get("$boosts") instanceof Map) { }
boostsMap = (Map<String, Float>) doc.get("$boosts"); }
if (boostsMap.containsKey("$doc_boost")) { return document;
document.setDocumentBoost(((Number) boostsMap.get("$doc_boost")).floatValue()); }
}
} private Map<Integer, List<BSONObject>> shard(final List<BSONObject> dbObjects, final int shards) {
} if (CollectionUtils.isEmpty((Collection)dbObjects)) {
return Collections.<Integer, List<BSONObject>>emptyMap();
for (Index index : indexes) { }
String key = index.getName(); final Map<Integer, List<BSONObject>> ret = new HashMap<Integer, List<BSONObject>>();
if (doc.containsField(key)) { for (final BSONObject object : dbObjects) {
Object value = doc.get(key); final int hashMod = Math.abs(object.get("_id").hashCode()) % shards;
SolrInputField field = new SolrInputField(key); List<BSONObject> modObjects = ret.get(hashMod);
if (value instanceof ObjectId) { if (null == modObjects) {
field.setValue(value.toString(), 1.0f); modObjects = new ArrayList<BSONObject>();
} else { ret.put(hashMod, modObjects);
if (boostsMap != null && boostsMap.containsKey(key)) { }
field.setValue(value, ((Number) boostsMap.get(key)).floatValue()); modObjects.add(object);
} else { }
field.setValue(value, 1.0f); return ret;
} }
}
document.put(key, field); private void checkFilter() {
} if (System.currentTimeMillis() - this.lastFilterTime < 300000L) {
} return;
return document; }
} try {
if (this.filtering.compareAndSet(false, true)) {
private Map<Integer, List<BSONObject>> shard(final List<BSONObject> dbObjects, int shards) { final long start = System.currentTimeMillis();
if (CollectionUtils.isEmpty(dbObjects)) { for (int i = 0; i < this.masterCommitFilters.length; ++i) {
return Collections.emptyMap(); if (!StringUtils.isEmpty(this.masterCommitFilters[i])) {
} for (final HttpSolrServer server : this.masterCommitSolrServers[i]) {
Map<Integer, List<BSONObject>> ret = new HashMap<Integer, List<BSONObject>>(); try {
for (BSONObject object : dbObjects) { server.deleteByQuery(this.masterCommitFilters[i]);
int hashMod = Math.abs(object.get("_id").hashCode()) % shards; }
List<BSONObject> modObjects = ret.get(hashMod); catch (SolrServerException e) {
if (null == modObjects) { if (SolrServerImpl.LOGGER.isErrorEnabled()) {
modObjects = new ArrayList<BSONObject>(); SolrServerImpl.LOGGER.error("[" + this.name + "] error execute filter delete: ", (Throwable)e);
ret.put(hashMod, modObjects); }
} }
modObjects.add(object); catch (IOException e2) {
} if (SolrServerImpl.LOGGER.isErrorEnabled()) {
return ret; SolrServerImpl.LOGGER.error("[" + this.name + "] error execute filter delete: ", (Throwable)e2);
} }
}
private void checkFilter() { }
// 5·ÖÖÓÒ»´Î }
if (System.currentTimeMillis() - lastFilterTime < 300000) { }
return; if (SolrServerImpl.LOGGER.isInfoEnabled()) {
} SolrServerImpl.LOGGER.info("[" + this.name + "] execute filter delete, " + (System.currentTimeMillis() - start) / 1000L + "s.");
try { }
if (this.filtering.compareAndSet(false, true)) { this.lastFilterTime = System.currentTimeMillis();
final long start = System.currentTimeMillis(); }
for (int i = 0; i < masterCommitFilters.length; i++) { }
if (StringUtils.isEmpty(masterCommitFilters[i])) { catch (Exception e3) {
continue; if (SolrServerImpl.LOGGER.isErrorEnabled()) {
} SolrServerImpl.LOGGER.error("[" + this.name + "] error execute filter delete: ", (Throwable)e3);
for (HttpSolrServer server : masterCommitSolrServers[i]) { }
try { }
server.deleteByQuery(masterCommitFilters[i]); finally {
} catch (SolrServerException e) { this.filtering.compareAndSet(true, false);
if (LOGGER.isErrorEnabled()) { }
LOGGER.error("[" + this.name + "] error execute filter delete: ", e); }
}
} catch (IOException e) { @Override
if (LOGGER.isErrorEnabled()) { public void deleteByQuery(final String query) throws SolrException {
LOGGER.error("[" + this.name + "] error execute filter delete: ", e); try {
} for (final HttpSolrServer[] array : this.masterCommitSolrServers) {
} final HttpSolrServer[] servers = array;
} for (final HttpSolrServer server : array) {
} server.deleteByQuery(query);
if (LOGGER.isInfoEnabled()) { }
LOGGER.info("[" + this.name + "] execute filter delete, " + (System.currentTimeMillis() - start) / 1000 }
+ "s."); }
} catch (SolrServerException e) {
lastFilterTime = System.currentTimeMillis(); throw new SolrException("[" + this.name + "] error execute delete[" + query + "]: ", (Throwable)e);
} }
} catch (Exception e) { catch (IOException e2) {
if (LOGGER.isErrorEnabled()) { throw new SolrException("[" + this.name + "] error execute delete[" + query + "]: ", e2);
LOGGER.error("[" + this.name + "] error execute filter delete: ", e); }
} }
} finally {
this.filtering.compareAndSet(true, false); @Override
} public synchronized void reload() throws ConfigurationException {
} this.allSolrServers.clear();
this.allSolrServers.putAll(this.initSolrServers(this.storeConfig, this.httpClient));
public void deleteByQuery(String query) throws SolrException { final String schema = this.storeConfig.getMasterSolrConfig().getHome() + "/" + this.name + "/conf/managed-schema";
try { this.solrSchema.setSchemaFile(new File(schema));
for (HttpSolrServer[] servers : this.masterCommitSolrServers) { this.solrSchema.reload();
for (HttpSolrServer server : servers) { }
server.deleteByQuery(query);
} @Override
} public void reloadCores() throws SolrException {
} catch (SolrServerException e) { if (SolrServerImpl.LOGGER.isInfoEnabled()) {
throw new SolrException("[" + this.name + "] error execute delete[" + query + "]: ", e); SolrServerImpl.LOGGER.info("[" + this.name + "] reload core...");
} catch (IOException e) { }
throw new SolrException("[" + this.name + "] error execute delete[" + query + "]: ", e); for (final String id : this.allSolrServers.keySet()) {
} final HttpSolrServer solrServer = this.allSolrServers.get(id);
return; solrServer.reloadCore();
} }
if (SolrServerImpl.LOGGER.isInfoEnabled()) {
public synchronized void reload() throws ConfigurationException { SolrServerImpl.LOGGER.info("[" + this.name + "] core reload success");
this.allSolrServers.clear(); }
this.allSolrServers.putAll(initSolrServers(this.storeConfig, httpClient)); }
String schema = this.storeConfig.getMasterSolrConfig().getHome() + "/" + name + "/conf/managed-schema";
this.solrSchema.setSchemaFile(new File(schema)); private boolean isShardedServer() {
this.solrSchema.reload(); return this.slaveSolrServers.length > 1;
} }
public void reloadCores() throws SolrException { private HttpSolrServer selectRandomServer(final HttpSolrServer[] shards) {
if (LOGGER.isInfoEnabled()) { if (null == shards || shards.length == 0) {
LOGGER.info("[" + this.name + "] reload core..."); throw new IllegalArgumentException("no shards");
} }
for (String id : this.allSolrServers.keySet()) { if (shards.length == 1) {
HttpSolrServer solrServer = this.allSolrServers.get(id); SolrServerImpl.LOGGER.info("Choice:" + shards[0].getHost());
solrServer.reloadCore(); return shards[0];
} }
if (LOGGER.isInfoEnabled()) { final HttpSolrServer server = shards[RandomUtils.nextInt(shards.length)];
LOGGER.info("[" + this.name + "] core reload success"); SolrServerImpl.LOGGER.info("Choice:" + server.getHost());
} return server;
} }
private boolean isShardedServer() { private String buildShardsParam(final HttpSolrServer[] solrServers) {
return this.slaveSolrServers.length > 1; final StringBuilder ret = new StringBuilder();
} for (int i = 0; i < solrServers.length; ++i) {
ret.append(solrServers[i].getHost()).append('/').append(this.name);
private HttpSolrServer selectRandomServer(HttpSolrServer[] shards) { if (i < solrServers.length - 1) {
if (null == shards || shards.length == 0) { ret.append(',');
throw new IllegalArgumentException("no shards"); }
} }
if (shards.length == 1) { SolrServerImpl.LOGGER.info("slaveAddress:" + ret.toString());
LOGGER.info("Choice:" + shards[0].getHost()); return ret.toString();
return shards[0]; }
}
HttpSolrServer server = shards[RandomUtils.nextInt(shards.length)]; @Override
LOGGER.info("Choice:" + server.getHost()); public QueryResponse query(final SolrQuery solrQuery, final boolean fromMaster, final boolean bulk) throws SolrException {
return server; if (this.isShardedServer() && !bulk && solrQuery.getStart() > 100000) {
} throw new SolrException("[" + this.name + "] skip of none bulk query must not greater than " + 100000 + ", try set $bulk to true in the query !");
}
private String buildShardsParam(HttpSolrServer[] solrServers) { return this.queryWithRetry(solrQuery, fromMaster, bulk, 0);
StringBuilder ret = new StringBuilder(); }
for (int i = 0; i < solrServers.length; i++) {
ret.append(solrServers[i].getHost()).append('/').append(this.name); private QueryResponse queryWithRetry(final SolrQuery solrQuery, final boolean fromMaster, final boolean bulk, int retryCount) throws SolrException {
if (i < solrServers.length - 1) { SolrServerImpl.LOGGER.info("isShardedServer:" + this.isShardedServer());
ret.append(','); SolrServerImpl.LOGGER.info("fromMaster:" + fromMaster);
} if (this.isShardedServer()) {
} if (fromMaster) {
LOGGER.info("slaveAddress:" + ret.toString()); solrQuery.set("shards", this.buildShardsParam(this.masterSolrServers));
return ret.toString(); }
} else {
solrQuery.set("shards", this.buildShardsParam(this.slaveSolrServers));
public QueryResponse query(SolrQuery solrQuery, boolean fromMaster, boolean bulk) throws SolrException { }
if (isShardedServer() && !bulk && solrQuery.getStart() > MAX_NONE_BULK_SKIP) { if (bulk) {
throw new SolrException("[" + this.name + "] skip of none bulk query must not greater than " + MAX_NONE_BULK_SKIP final int numberShards = this.masterSolrServers.length;
+ ", try set $bulk to true in the query !"); solrQuery.set("shards.start", solrQuery.getStart() / numberShards);
} solrQuery.set("shards.rows", Math.max(solrQuery.getRows() / numberShards, 1));
return queryWithRetry(solrQuery, fromMaster, bulk, 0); solrQuery.setStart(0);
} }
}
private QueryResponse queryWithRetry(SolrQuery solrQuery, boolean fromMaster, boolean bulk, int retryCount) SolrServerImpl.LOGGER.info("solrQuery:" + solrQuery.toString());
throws SolrException { QueryResponse queryResponse = null;
// shards params HttpSolrServer httpSolrServer = null;
LOGGER.info("isShardedServer:"+isShardedServer()); try {
LOGGER.info("fromMaster:"+fromMaster); if (fromMaster) {
if (isShardedServer()) { httpSolrServer = this.selectRandomServer(this.masterSolrServers);
if (fromMaster) { try {
solrQuery.set(ShardParams.SHARDS, buildShardsParam(this.masterSolrServers)); queryResponse = httpSolrServer.query(solrQuery);
} else { }
solrQuery.set(ShardParams.SHARDS, buildShardsParam(this.slaveSolrServers)); catch (IOException e) {
} e.printStackTrace();
// bulk query }
if (bulk) { }
int numberShards = this.masterSolrServers.length; else {
solrQuery.set(ShardParams.SHARDS_START, solrQuery.getStart() / numberShards); httpSolrServer = this.selectRandomServer(this.slaveSolrServers);
solrQuery.set(ShardParams.SHARDS_ROWS, Math.max(solrQuery.getRows() / numberShards, 1)); try {
solrQuery.setStart(0); queryResponse = httpSolrServer.query(solrQuery);
} }
} catch (IOException e) {
LOGGER.info("solrQuery:"+solrQuery.toString()); e.printStackTrace();
QueryResponse queryResponse = null; }
HttpSolrServer httpSolrServer = null; }
try { solrQuery.add("__host", httpSolrServer.getHost());
if (fromMaster) { }
httpSolrServer = selectRandomServer(this.masterSolrServers); catch (SolrServerException ex) {
try { if (!(ex.getCause() instanceof org.apache.solr.common.SolrException)) {
queryResponse = httpSolrServer.query(solrQuery); throw new SolrException("*[" + this.name + "]* error query solr:", (Throwable)ex);
} catch (IOException e) { }
// TODO Auto-generated catch block final org.apache.solr.common.SolrException e2 = (org.apache.solr.common.SolrException)ex.getCause();
e.printStackTrace(); if (retryCount < 3 && org.apache.solr.common.SolrException.ErrorCode.getErrorCode(e2.code()) == org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR) {
} ++retryCount;
} else { if (SolrServerImpl.LOGGER.isErrorEnabled()) {
httpSolrServer = selectRandomServer(this.slaveSolrServers); SolrServerImpl.LOGGER.error("#[" + this.name + "]# error query solr[" + httpSolrServer.getHost() + "], code:" + org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR + "(" + org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR.code + "), retry for the " + retryCount + "th time...");
try { }
queryResponse = httpSolrServer.query(solrQuery); return this.queryWithRetry(solrQuery, fromMaster, bulk, retryCount);
} catch (IOException e) { }
// TODO Auto-generated catch block throw new SolrException("=[" + this.name + "]= error query solr[" + httpSolrServer.getHost() + "]:", (Throwable)e2);
e.printStackTrace(); }
} return queryResponse;
} }
} catch (SolrServerException ex) {
if (ex.getCause() instanceof org.apache.solr.common.SolrException) { @Override
org.apache.solr.common.SolrException e = (org.apache.solr.common.SolrException) ex.getCause(); public SolrSchema getSolrSchema() {
if (retryCount < SOLR_QUERY_MAX_RETRY_COUNT && ErrorCode.getErrorCode(e.code()) == ErrorCode.SERVER_ERROR) { return this.solrSchema;
retryCount++; }
if (LOGGER.isErrorEnabled()) {
LOGGER.error("#[" + this.name + "]# error query solr[" + httpSolrServer.getHost() + "], code:" static {
+ ErrorCode.SERVER_ERROR + "(" + ErrorCode.SERVER_ERROR.code + "), retry for the " + retryCount LOGGER = LoggerFactory.getLogger((Class)SolrServerImpl.class);
+ "th time..."); }
}
return queryWithRetry(solrQuery, fromMaster, bulk, retryCount);
} else {
throw new SolrException("=[" + this.name + "]= error query solr[" + httpSolrServer.getHost() + "]:", e);
}
}
throw new SolrException("*[" + this.name + "]* error query solr:", ex);
}
return queryResponse;
}
public SolrSchema getSolrSchema() {
return solrSchema;
}
} }
@@ -1,53 +1,34 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.utils; package com.fangjia.datastore.utils;
import java.io.IOException; import java.io.IOException;
public class BSONUtils { public class BSONUtils
{
public static long bitSet(long holder, int i, boolean set) { public static long bitSet(final long holder, final int i, final boolean set) {
if (i < 0 || i > 63) { if (i < 0 || i > 63) {
throw new IllegalArgumentException("i should from 0 inclusive and 64 exclusive"); throw new IllegalArgumentException("i should from 0 inclusive and 64 exclusive");
} }
if (set) { if (set) {
return holder | (1 << i); return holder | (long)(1 << i);
} else { }
int ii = 1 << i; final int ii = 1 << i;
return (holder | ii) ^ ii; return (holder | (long)ii) ^ (long)ii;
} }
}
public static boolean isBitSet(final long holder, final int i) {
public static boolean isBitSet(long holder, int i) { if (i < 0 || i > 63) {
if (i < 0 || i > 63) { throw new IllegalArgumentException("i should from 0 inclusive and 64 exclusive");
throw new IllegalArgumentException("i should from 0 inclusive and 64 exclusive"); }
} return (holder & (long)(1 << i)) > 0L;
return (holder & (1 << i)) > 0; }
}
public static int stringByteLength(final String s) throws IOException {
public static int stringByteLength(String s) throws IOException { final byte[] bs = s.getBytes("UTF-8");
byte[] bs = s.getBytes("UTF-8"); return bs.length + 5;
return bs.length + 5; }
}
public static int cstringByteLength(final String s) throws IOException {
public static int cstringByteLength(String s) throws IOException { final byte[] bs = s.getBytes("UTF-8");
byte[] bs = s.getBytes("UTF-8"); return bs.length + 1;
return bs.length + 1; }
}
} }
@@ -1,275 +1,106 @@
/**
* JMongo is a mongodb driver writtern in java.
* Copyright (C) 2010 Xiaohu Huang
*
* JMongo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JMongo 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 Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JMongo. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fangjia.datastore.utils; package com.fangjia.datastore.utils;
import java.io.PrintStream; import java.io.PrintStream;
/** public final class HexDump
* Hex dump class. {
*/ public static final void dump(final byte[] byt) {
public final class HexDump { dump(byt, byt.length, 0, System.out);
}
public static final void dump(byte[] byt) {
dump(byt, byt.length, 0, System.out); public static final void dump(final byte[] byt, final int len, final int offset) {
} dump(byt, len, offset, System.out);
}
/**
* Hex dump a byte array public static final void dump(final byte[] byt, final int len, final int offset, final PrintStream stream) {
* final StringBuffer ascBuf = new StringBuffer();
* @param byt final StringBuffer hexBuf = new StringBuffer();
* Byte array to dump int dlen = 0;
* @param len int doff = offset;
* Length of data to dump String posStr = null;
* @param offset while (dlen < len) {
* Offset to start data dump ascBuf.setLength(0);
*/ hexBuf.setLength(0);
public static final void dump(byte[] byt, int len, int offset) { posStr = generatePositionString(doff);
dump(byt, len, offset, System.out); doff = generateLine(byt, doff, ascBuf, hexBuf);
} stream.print(posStr);
stream.print(hexBuf.toString());
/** stream.println(ascBuf.toString());
* Hex dump a byte array dlen += 16;
* }
* @param byt }
* Byte array to dump
* @param len public static final String hexString(final String str) {
* Length of data to dump if (str != null) {
* @param offset return hexString(str.getBytes());
* Offset to start data dump }
* @param stream return "";
* Output stream to dump the output to. }
*/
public static final String hexString(final String str, final String gap) {
public static final void dump(byte[] byt, int len, int offset, PrintStream stream) { if (str != null) {
return hexString(str.getBytes(), gap);
// Create buffers for the ASCII and Hex output }
return "";
StringBuffer ascBuf = new StringBuffer(); }
StringBuffer hexBuf = new StringBuffer();
public static final String hexString(final byte[] buf) {
// dump 16 byte blocks from the array until the length has been return hexString(buf, buf.length, null);
// reached }
int dlen = 0; public static final String hexString(final byte[] buf, final String gap) {
int doff = offset; return hexString(buf, buf.length, gap);
String posStr = null; }
while (dlen < len) { public static final String hexString(final byte[] buf, final int len, final String gap) {
if (buf == null) {
// Reset the ASCII/Hex buffers return "";
}
ascBuf.setLength(0); int buflen = buf.length * 2;
hexBuf.setLength(0); if (gap != null) {
buflen += buf.length * gap.length();
posStr = generatePositionString(doff); }
final StringBuffer hex = new StringBuffer(buflen);
// dump a block of data, update the data offset for (int i = 0; i < len; ++i) {
final int curbyt = buf[i] & 0xFF;
doff = generateLine(byt, doff, ascBuf, hexBuf); hex.append(Integer.toHexString((curbyt & 0xF0) >> 4));
hex.append(Integer.toHexString(curbyt & 0xF));
// Output the current record if (gap != null && i < len - 1) {
hex.append(gap);
stream.print(posStr); }
stream.print(hexBuf.toString()); }
stream.println(ascBuf.toString()); return hex.toString();
}
// Update the dump length
private static final String generatePositionString(final int off) {
dlen += 16; final StringBuffer posStr = new StringBuffer("" + off + ": ");
} while (posStr.length() < 10) {
} posStr.insert(0, " ");
}
/** return posStr.toString();
* Generate a hex string for the specified string }
*
* @param str private static final int generateLine(final byte[] byt, int off, final StringBuffer ascBuf, final StringBuffer hexBuf) {
* String int dumplen = byt.length - off;
* @return String if (dumplen > 16) {
*/ dumplen = 16;
public static final String hexString(String str) { }
if (str != null) for (int i = 0; i < dumplen; ++i) {
return hexString(str.getBytes()); final int curbyt = byt[off++] & 0xFF;
return ""; hexBuf.append(Integer.toHexString((curbyt & 0xF0) >> 4));
} hexBuf.append(Integer.toHexString(curbyt & 0xF));
hexBuf.append(" ");
/** if (Character.isLetterOrDigit((char)curbyt) || Character.getType((char)curbyt) != 15) {
* Generate a hex string for the specified string ascBuf.append((char)curbyt);
* }
* @param str else {
* String ascBuf.append(".");
* @param gap }
* String }
* @return String for (int i = dumplen; i < 16; ++i) {
*/ hexBuf.append(" ");
public static final String hexString(String str, String gap) { }
if (str != null) hexBuf.append(" ");
return hexString(str.getBytes(), gap); return off;
return ""; }
}
/**
* Generate a hex string for the specified bytes
*
* @param buf
* byte[]
* @return String
*/
public static final String hexString(byte[] buf) {
return hexString(buf, buf.length, null);
}
/**
* Generate a hex string for the specified bytes
*
* @param buf
* byte[]
* @param gap
* String
* @return String
*/
public static final String hexString(byte[] buf, String gap) {
return hexString(buf, buf.length, gap);
}
/**
* Generate a hex string for the specified bytes
*
* @param buf
* byte[]
* @param len
* int
* @param gap
* String
* @return String
*/
public static final String hexString(byte[] buf, int len, String gap) {
// Check if the buffer is valid
if (buf == null)
return "";
// Create a string buffer for the hex string
int buflen = buf.length * 2;
if (gap != null)
buflen += buf.length * gap.length();
StringBuffer hex = new StringBuffer(buflen);
// Convert the bytes to hex-ASCII
for (int i = 0; i < len; i++) {
// Get the current byte
int curbyt = (int) (buf[i] & 0x00FF);
// Output the hex string
hex.append(Integer.toHexString((curbyt & 0xF0) >> 4));
hex.append(Integer.toHexString(curbyt & 0x0F));
// Add the gap string, if specified
if (gap != null && i < (len - 1))
hex.append(gap);
}
// Return the hex-ASCII string
return hex.toString();
}
/**
* Generate a buffer position string
*
* @param off
* int
* @return String
*/
private static final String generatePositionString(int off) {
// Create a buffer position string
StringBuffer posStr = new StringBuffer("" + off + ": ");
while (posStr.length() < 10)
posStr.insert(0, " ");
// Return the string
return posStr.toString();
}
/**
* Output a single line of the hex dump to a debug device
*
* @param byt
* Byte array to dump
* @param off
* Offset to start data dump
* @param ascBuf
* Buffer for ASCII output
* @param hexBuf
* Buffer for Hex output
* @return New offset value
*/
private static final int generateLine(byte[] byt, int off, StringBuffer ascBuf, StringBuffer hexBuf) {
// Check if there is enough buffer space to dump 16 bytes
int dumplen = byt.length - off;
if (dumplen > 16)
dumplen = 16;
// dump a 16 byte block of data
for (int i = 0; i < dumplen; i++) {
// Get the current byte
int curbyt = (int) (byt[off++] & 0x00FF);
// Output the hex string
hexBuf.append(Integer.toHexString((curbyt & 0xF0) >> 4));
hexBuf.append(Integer.toHexString(curbyt & 0x0F));
hexBuf.append(" ");
// Output the character equivalent, if printable
if (Character.isLetterOrDigit((char) curbyt) || Character.getType((char) curbyt) != Character.CONTROL)
ascBuf.append((char) curbyt);
else
ascBuf.append(".");
}
for (int i = dumplen; i < 16; i++) {
hexBuf.append(" ");
}
// Output the hex dump line
hexBuf.append(" ");
// Return the new data offset
return off;
}
} }
@@ -2,17 +2,17 @@ package com.fangjia.datastore.utils;
import org.slf4j.Logger; import org.slf4j.Logger;
public class LoggerFactory { public class LoggerFactory
{
public static Logger getLogger(Class<?> clazz) { public static Logger getLogger(final Class<?> clazz) {
return org.slf4j.LoggerFactory.getLogger(clazz); return org.slf4j.LoggerFactory.getLogger((Class)clazz);
} }
public static Logger getLogger(String name) { public static Logger getLogger(final String name) {
return org.slf4j.LoggerFactory.getLogger(name); return org.slf4j.LoggerFactory.getLogger(name);
} }
public static Logger getPerformanceLogger(Class<?> clazz) { public static Logger getPerformanceLogger(final Class<?> clazz) {
return org.slf4j.LoggerFactory.getLogger("performance." + clazz.getName()); return org.slf4j.LoggerFactory.getLogger("performance." + clazz.getName());
} }
} }
@@ -2,22 +2,23 @@ package com.fangjia.datastore.utils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
public class MongoUtils { public class MongoUtils
private MongoUtils() { {
} private MongoUtils() {
}
public static String[] parseFullCollectionName(String fullCollectionName) {
if (StringUtils.isEmpty(fullCollectionName)) { public static String[] parseFullCollectionName(final String fullCollectionName) {
return null; if (StringUtils.isEmpty(fullCollectionName)) {
} return null;
int i = fullCollectionName.indexOf('.'); }
if (i <= 0 || i >= fullCollectionName.length() - 1) { final int i = fullCollectionName.indexOf(46);
return null; if (i <= 0 || i >= fullCollectionName.length() - 1) {
} return null;
return new String[] { fullCollectionName.substring(0, i), fullCollectionName.substring(i + 1) }; }
} return new String[] { fullCollectionName.substring(0, i), fullCollectionName.substring(i + 1) };
}
public static void main(String[] args) {
System.out.println(parseFullCollectionName(".q")); public static void main(final String[] args) {
} System.out.println(parseFullCollectionName(".q"));
}
} }
@@ -2,45 +2,42 @@ package com.fangjia.datastore.utils;
import org.dom4j.Node; import org.dom4j.Node;
public class XmlUtils { public class XmlUtils
public static String getNodeValue(Node parentNode, String nodeName, String defaultValue) { {
Node node = parentNode.selectSingleNode(nodeName); public static String getNodeValue(final Node parentNode, final String nodeName, final String defaultValue) {
String ret = defaultValue; final Node node = parentNode.selectSingleNode(nodeName);
if (null == node) { String ret = defaultValue;
return ret; if (null == node) {
} else { return ret;
ret = node.getText(); }
if (null == ret) { ret = node.getText();
ret = defaultValue; if (null == ret) {
} ret = defaultValue;
} }
return ret; return ret;
} }
public static int getNodeValueAsInt(Node parentNode, String nodeName, int defaultValue) { public static int getNodeValueAsInt(final Node parentNode, final String nodeName, final int defaultValue) {
String value = getNodeValue(parentNode, nodeName, null); final String value = getNodeValue(parentNode, nodeName, null);
if (null == value) { if (null == value) {
return defaultValue; return defaultValue;
} else { }
return Integer.parseInt(value); return Integer.parseInt(value);
} }
}
public static long getNodeValueAsLong(final Node parentNode, final String nodeName, final long defaultValue) {
public static long getNodeValueAsLong(Node parentNode, String nodeName, long defaultValue) { final String value = getNodeValue(parentNode, nodeName, null);
String value = getNodeValue(parentNode, nodeName, null); if (null == value) {
if (null == value) { return defaultValue;
return defaultValue; }
} else { return Long.parseLong(value);
return Long.parseLong(value); }
}
} public static boolean getNodeValueAsBoolean(final Node parentNode, final String nodeName, final boolean defaultValue) {
final String value = getNodeValue(parentNode, nodeName, null);
public static boolean getNodeValueAsBoolean(Node parentNode, String nodeName, boolean defaultValue) { if (null == value) {
String value = getNodeValue(parentNode, nodeName, null); return defaultValue;
if (null == value) { }
return defaultValue; return Boolean.parseBoolean(value);
} else { }
return Boolean.parseBoolean(value);
}
}
} }
@@ -1,6 +1,39 @@
package com.fangjia.script.wenyan package com.fangjia.script.wenyan
//ExcelUtils.multiThreadingModify("D:\\Users\\wenyan\\Downloads\\国信达级联价格-上海.xlsx",{List item->
// if(item["AB"]){
// return
// }
// String region = null
// String name = item["F"]
// if(name.endsWith("小区")){
// name = name.replaceAll("小区\$", "")
// }
// region = RegionData.formatRegion(item["B"], item["D"])
// def results = []
// DbUtils.seaweed.find(DbUtils.buildSeaweedQuery(item["B"], region, name)).each {
// if(!results.contains(it)){
// results.add(it)
// }
// }
// DbUtils.seaweed.find(DbUtils.buildSeaweedQuery(item["B"], region).append("alias", name)).each {
// if(!results.contains(it)){
// results.add(it)
// }
// }
// if(results.size() == 1){
// item["Z"] = results[0]._id.toString()
// item["AA"] = results[0].region
// item["AB"] = results[0].name
// println(item)
// }
//})
import com.fangjia.core.ProvinceData import com.fangjia.core.ProvinceData
import com.fangjia.core.RegionData
import com.fangjia.script.util.CommonUtils import com.fangjia.script.util.CommonUtils
import com.fangjia.script.util.DataUtil import com.fangjia.script.util.DataUtil
import com.fangjia.script.util.DbUtils import com.fangjia.script.util.DbUtils
@@ -76,7 +109,48 @@ import org.apache.commons.lang.StringUtils
// }, new BasicDBObject("township", 1)) // }, new BasicDBObject("township", 1))
//} //}
//println(count) //println(count)
//def GXD_CCB = [:]
//def CCB_FJW = [:]
//ExcelUtils.read("D:\\Users\\wenyan\\Downloads\\4月级联待优化小区_3个城市.xlsx",sheetIndex = 1).each {List item->
// if(item["V"] == "级联"){
// if(item["Y"] == "国信达"){
// GXD_CCB[item['J']] = item["E"]
// }else if(item["Y"] == "房价网"){
// CCB_FJW[item['E']] = item["J"]
// }
// }
//}
//ExcelUtils.multiThreadingModify("D:\\Users\\wenyan\\Downloads\\4月级联待优化小区_3个城市.xlsx",{List item->
// if(item["V"] == "级联" && item["Y"] == "国信达"){
// def ccbId = GXD_CCB.get(item['J'], null)
// def fjwId = CCB_FJW.get(ccbId, null)
// if(fjwId != null){
// item["AB"] = fjwId
//// BasicDBObject seaweed = DbUtils.seaweed.findById(fjwId)
//// List results = DbUtils.findAroundDistrict(seaweed)
//// long total = 0
//// long count = 0
//// for(BasicDBObject s : results){
//// def avg = DbUtils.findDistrictAveragePrice(seaweed.city, seaweed.region, seaweed.name, Date.parse('yyyyMMdd', '20220619'), seaweed.estate_type2)
//// if(avg){
//// total += avg.avg_price
//// count += 1
//// }
//// }
//// if(count > 0){
//// item['Z'] = (int)(total/count)
//// println(item)
//// }
// }
// }
//},sheetIndex = 1)
ElasticUtils.executeSqlQuery("select count(*), p_date from seawater where p_date > 20210501 group by p_date",{ //ExcelUtils.multiThreadingModify("D:\\Users\\wenyan\\Downloads\\moban (3).xls",{List item->
println(it) // item["B"] = RegionData.formatRegion(item["A"], item["B"])
}) // println(item)
//})
int count = 0
DbUtils.seaweed.find(DbUtils.buildSeaweedQuery("东莞")).each {def a->
count += 1
}
println(count)
@@ -499,6 +499,7 @@ public class AddressParserServiceImpl implements AddressParserService {
addr.setAddressParserGoal(params.getAddressParserGoal()); addr.setAddressParserGoal(params.getAddressParserGoal());
addr.setProvince(params.getProvince()); addr.setProvince(params.getProvince());
addr.setDebugName(params.getDebugName()); addr.setDebugName(params.getDebugName());
addr.setUseMap(params.isUseMap());
return AddressProcessors.process(addr); return AddressProcessors.process(addr);
} }
@@ -63,6 +63,7 @@ public class Address {
private String suggestNamePinYin; private String suggestNamePinYin;
private String polygonSeaweedId; private String polygonSeaweedId;
private String geoRegion; private String geoRegion;
private boolean useMap;
private List<String> buildingNumbers; private List<String> buildingNumbers;
private PreciseLevel preciseLevel; private PreciseLevel preciseLevel;
private boolean pinYin; private boolean pinYin;
@@ -389,6 +390,14 @@ public class Address {
isStandardAddress = standardAddress; isStandardAddress = standardAddress;
} }
public boolean isUseMap() {
return useMap;
}
public void setUseMap(boolean useMap) {
this.useMap = useMap;
}
/** /**
* 获得有效地址 * 获得有效地址
* *
@@ -28,6 +28,9 @@ public class GeoProcessor extends AbstractAddressProcessor {
if (address.hasCoordinate()) { if (address.hasCoordinate()) {
return RepeatStatus.NEXT; return RepeatStatus.NEXT;
} }
if(!address.isUseMap()){
return RepeatStatus.NEXT;
}
String addr = address.getEffectiveAddress(); String addr = address.getEffectiveAddress();
if(addr == null || addr.length() < 3){ if(addr == null || addr.length() < 3){
addr = address.getOrgAddress(); addr = address.getOrgAddress();