Example usage for io.netty.util AttributeMap attr

List of usage examples for io.netty.util AttributeMap attr

Introduction

In this page you can find the example usage for io.netty.util AttributeMap attr.

Prototype

<T> Attribute<T> attr(AttributeKey<T> key);

Source Link

Document

Get the Attribute for the given AttributeKey .

Usage

From source file:com.torodb.mongowp.mongoserver.api.toro.ToroRequestProcessor.java

License:Open Source License

@Override
public void insert(InsertMessage insertMessage, MessageReplier messageReplier) throws Exception {
    AttributeMap attributeMap = messageReplier.getAttributeMap();
    ToroConnection connection = attributeMap.attr(ToroRequestProcessor.CONNECTION).get();

    String collection = insertMessage.getCollection();

    if (metaProcessor.isMetaCollection(collection)) {
        BSONObject insertQuery = new BasicBSONObject();
        insertQuery.put("insert", collection);
        insertQuery.put("ordered", insertMessage.isFlagSet(InsertMessage.Flag.CONTINUE_ON_ERROR));

        BasicBSONList docsToInsert = new BasicBSONList();
        for (BSONDocument document : insertMessage.getDocuments()) {
            docsToInsert.add(new BasicBSONObject(document.asMap()));
        }/*from   w  ww . jav a  2 s .  com*/
        insertQuery.put("documents", docsToInsert);

        Future<InsertResponse> future;
        try {
            Future<com.eightkdata.mongowp.mongoserver.api.pojos.InsertResponse> response = metaProcessor
                    .insert(messageReplier.getAttributeMap(), collection, new MongoBSONDocument(insertQuery));
            future = Futures.lazyTransform(response, new InsertResponseTransformFunction());
        } catch (Exception ex) {
            future = Futures.immediateFailedFuture(ex);
        }

        LastError lastError = new ToroLastError(RequestOpCode.OP_INSERT, null, future, null, false, null);
        attributeMap.attr(ToroRequestProcessor.LAST_ERROR).set(lastError);
    } else {
        WriteFailMode writeFailMode =
                //             insertMessage.getFlags().contains(InsertMessage.Flag.CONTINUE_ON_ERROR)?
                //                   WriteFailMode.ISOLATED:WriteFailMode.ORDERED;
                WriteFailMode.TRANSACTIONAL;
        List<BSONDocument> documents = insertMessage.getDocuments();
        List<ToroDocument> inserts = new ArrayList<ToroDocument>();
        Iterator<?> documentsIterator = documents.iterator();
        while (documentsIterator.hasNext()) {
            BSONObject object = ((MongoBSONDocument) documentsIterator.next()).getBSONObject();
            inserts.add(new BSONToroDocument(object));
        }
        ToroTransaction transaction = connection.createTransaction();

        try {
            Future<InsertResponse> futureInsertResponse = transaction.insertDocuments(collection, inserts,
                    writeFailMode);

            Future<?> futureCommitResponse = transaction.commit();

            LastError lastError = new ToroLastError(RequestOpCode.OP_INSERT, null, futureInsertResponse,
                    futureCommitResponse, false, null);
            attributeMap.attr(ToroRequestProcessor.LAST_ERROR).set(lastError);
        } finally {
            transaction.close();
        }
    }
}

From source file:com.torodb.mongowp.mongoserver.api.toro.ToroRequestProcessor.java

License:Open Source License

@Override
public void update(UpdateMessage updateMessage, MessageReplier messageReplier) throws Exception {
    AttributeMap attributeMap = messageReplier.getAttributeMap();
    ToroConnection connection = attributeMap.attr(CONNECTION).get();

    String collection = updateMessage.getCollection();
    WriteFailMode writeFailMode = WriteFailMode.ORDERED;
    BSONDocument selector = updateMessage.getSelector();
    for (String key : selector.getKeys()) {
        if (QueryModifier.getByKey(key) != null || QuerySortOrder.getByKey(key) != null) {
            throw new Exception("Modifier " + key + " not supported");
        }/*  www  .ja  v  a2s .c  om*/
    }
    BSONObject query = ((MongoBSONDocument) selector).getBSONObject();
    for (String key : query.keySet()) {
        if (QueryEncapsulation.getByKey(key) != null) {
            Object queryObject = query.get(key);
            if (queryObject != null && queryObject instanceof BSONObject) {
                query = (BSONObject) queryObject;
                break;
            }
        }
    }
    QueryCriteria queryCriteria = queryCriteriaTranslator.translate(query);
    List<UpdateOperation> updates = new ArrayList<UpdateOperation>();
    boolean upsert = updateMessage.isFlagSet(UpdateMessage.Flag.UPSERT);
    boolean justOne = !updateMessage.isFlagSet(UpdateMessage.Flag.MULTI_UPDATE);

    UpdateAction updateAction = UpdateActionTranslator
            .translate(((MongoBSONDocument) updateMessage.getupdate()).getBSONObject());

    updates.add(new UpdateOperation(queryCriteria, updateAction, upsert, justOne));

    ToroTransaction transaction = connection.createTransaction();

    try {
        Future<UpdateResponse> futureUpdateResponse = transaction.update(collection, updates, writeFailMode);

        Future<?> futureCommitResponse = transaction.commit();

        LastError lastError = new ToroLastError(RequestOpCode.OP_UPDATE, null, futureUpdateResponse,
                futureCommitResponse, false, null);
        attributeMap.attr(ToroRequestProcessor.LAST_ERROR).set(lastError);
    } finally {
        transaction.close();
    }
}

From source file:com.torodb.mongowp.mongoserver.api.toro.ToroRequestProcessor.java

License:Open Source License

@Override
public void delete(DeleteMessage deleteMessage, MessageReplier messageReplier) throws Exception {
    AttributeMap attributeMap = messageReplier.getAttributeMap();
    ToroConnection connection = attributeMap.attr(CONNECTION).get();

    String collection = deleteMessage.getCollection();
    WriteFailMode writeFailMode = WriteFailMode.ORDERED;
    BSONDocument document = deleteMessage.getDocument();
    for (String key : document.getKeys()) {
        if (QueryModifier.getByKey(key) != null || QuerySortOrder.getByKey(key) != null) {
            throw new Exception("Modifier " + key + " not supported");
        }/*from  w  w  w.  j av a 2 s .  co m*/
    }
    BSONObject query = ((MongoBSONDocument) document).getBSONObject();
    for (String key : query.keySet()) {
        if (QueryEncapsulation.getByKey(key) != null) {
            Object queryObject = query.get(key);
            if (queryObject != null && queryObject instanceof BSONObject) {
                query = (BSONObject) queryObject;
                break;
            }
        }
    }
    QueryCriteria queryCriteria = queryCriteriaTranslator.translate(query);
    List<DeleteOperation> deletes = new ArrayList<DeleteOperation>();
    boolean singleRemove = deleteMessage.isFlagSet(DeleteMessage.Flag.SINGLE_REMOVE);

    deletes.add(new DeleteOperation(queryCriteria, singleRemove));

    ToroTransaction transaction = connection.createTransaction();

    try {
        Future<DeleteResponse> futureDeleteResponse = transaction.delete(collection, deletes, writeFailMode);

        Future<?> futureCommitResponse = transaction.commit();

        LastError lastError = new ToroLastError(RequestOpCode.OP_DELETE, null, futureDeleteResponse,
                futureCommitResponse, false, null);
        attributeMap.attr(ToroRequestProcessor.LAST_ERROR).set(lastError);
    } finally {
        transaction.close();
    }
}

From source file:com.torodb.mongowp.mongoserver.api.toro.ToroRequestProcessor.java

License:Open Source License

@Override
public boolean handleError(RequestOpCode requestOpCode, MessageReplier messageReplier, Throwable throwable)
        throws Exception {
    if (super.handleError(requestOpCode, messageReplier, throwable)) {
        return true;
    }//from  ww  w  .j  a  va 2s. com

    //TODO: Map real mongo error codes      
    AttributeMap attributeMap = messageReplier.getAttributeMap();
    MongoWP.ErrorCode errorCode = MongoWP.ErrorCode.INTERNAL_ERROR;
    LastError lastError = new ToroLastError(requestOpCode, null, null, null, true, errorCode);
    attributeMap.attr(ToroRequestProcessor.LAST_ERROR).set(lastError);
    switch (requestOpCode) {
    case OP_QUERY:
        messageReplier.replyQueryFailure(errorCode, throwable.getMessage());
        break;
    default:
        break;
    }

    return true;
}

From source file:io.grpc.netty.ProtocolNegotiators.java

License:Apache License

private static ChannelLogger negotiationLogger(AttributeMap attributeMap) {
    Attribute<ChannelLogger> attr = attributeMap.attr(NettyClientTransport.LOGGER_KEY);
    final ChannelLogger channelLogger = attr.get();
    if (channelLogger != null) {
        return channelLogger;
    }// w  ww. j a  v a  2 s .  co m
    // This is only for tests where there may not be a valid logger.
    final class NoopChannelLogger extends ChannelLogger {

        @Override
        public void log(ChannelLogLevel level, String message) {
        }

        @Override
        public void log(ChannelLogLevel level, String messageFormat, Object... args) {
        }
    }

    return new NoopChannelLogger();
}

From source file:io.reactivex.netty.contexts.http.HttpRequestIdProvider.java

License:Apache License

private static void addRequestId(AttributeMap channelAttributeMap, String requestId) {
    ConcurrentLinkedQueue<String> requestIdsQueue = channelAttributeMap.attr(REQUEST_IDS_KEY).get();
    if (null == requestIdsQueue) {
        requestIdsQueue = new ConcurrentLinkedQueue<String>();
        ConcurrentLinkedQueue<String> existingQueue = channelAttributeMap.attr(REQUEST_IDS_KEY)
                .setIfAbsent(requestIdsQueue);
        if (null != existingQueue) {
            requestIdsQueue = existingQueue;
        }//from   ww  w.  j a  v  a2  s  .  co m
    }
    if (null != requestIdsQueue) {
        requestIdsQueue.offer(requestId); // We can even use add() as this is a lock-free queue. Just using offer() to not confuse folks.
    }
}

From source file:io.reactivex.netty.contexts.http.HttpRequestIdProvider.java

License:Apache License

private static String getRequestIdFromQueue(AttributeMap channelAttributeMap) {
    ConcurrentLinkedQueue<String> requestIdsQueue = channelAttributeMap.attr(REQUEST_IDS_KEY).get();
    if (null != requestIdsQueue) {
        return requestIdsQueue.poll(); // Responses should be sent in the same order as the requests were received (HTTP pipelining)
    }/*  w  w  w  .  j a va 2s  . co  m*/
    return null;
}

From source file:io.reactivex.netty.contexts.http.HttpRequestIdProviderTest.java

License:Apache License

@Test
public void testNewRequestId() throws Exception {
    RequestIdProvider provider = new HttpRequestIdProvider("request_id", CORRELATOR);
    ContextKeySupplier keySupplier = new MapBackedKeySupplier(new HashMap<String, String>());
    AttributeMap attributeMap = new DefaultAttributeMap();
    String requestId = provider.newRequestId(keySupplier, attributeMap);
    ConcurrentLinkedQueue<String> ids = attributeMap.attr(HttpRequestIdProvider.REQUEST_IDS_KEY).get();
    Assert.assertNotNull("Request Id not added to context.", ids);
    Assert.assertNotNull("Request Id not added to context.", ids.peek());
    Assert.assertSame("Unexpected request Id in the context.", requestId, ids.poll());
}

From source file:io.reactivex.netty.contexts.ThreadLocalRequestCorrelator.java

License:Apache License

public void dumpThreadState() {
    if (logger.isDebugEnabled()) {
        ThreadStateHolder threadStateHolder = state.get();
        logger.debug("******************** Thread Attributes ********************");
        int count = 0;
        for (AttributeMap threadAttribute : threadStateHolder.threadAttributes) {
            logger.debug("Stack level==> " + ++count);
            logger.debug("Request Id: " + threadAttribute.attr(ThreadStateHolder.requestIdKey));
            logger.debug("Context container: " + threadAttribute.attr(ThreadStateHolder.containerKey));
        }/*w  w  w  .ja va2  s  .  c om*/
        logger.debug("***********************************************************");
    }
}

From source file:io.reactivex.netty.contexts.ThreadLocalRequestCorrelator.java

License:Apache License

public void dumpThreadState(PrintStream outputStream) {
    ThreadStateHolder threadStateHolder = state.get();
    outputStream.println("******************** Thread Attributes ********************");
    int count = 0;
    for (AttributeMap threadAttribute : threadStateHolder.threadAttributes) {
        outputStream.println("Stack level==> " + ++count);
        outputStream.println("Request Id: " + threadAttribute.attr(ThreadStateHolder.requestIdKey));
        outputStream.println("Context container: " + threadAttribute.attr(ThreadStateHolder.containerKey));
    }/*from  ww w .j a va2  s . c o m*/
    outputStream.println("***********************************************************");
}