org.jboss.netty.util.CharsetUtil Java Examples

The following examples show how to use org.jboss.netty.util.CharsetUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HBaseValueDecoder.java    From qmq with Apache License 2.0 6 votes vote down vote up
public static BackupMessageMeta getMessageMeta(byte[] value) {
    try {
        if (value != null && value.length > 0) {
            long sequence = Bytes.getLong(value, 0);
            long createTime = Bytes.getLong(value, 8);
            int brokerGroupLength = Bytes.getInt(value, 16);
            if (brokerGroupLength > 200) {
                return null;
            }
            byte[] brokerGroupBytes = new byte[brokerGroupLength];
            System.arraycopy(value, 20, brokerGroupBytes, 0, brokerGroupLength);
            int messageIdLength = value.length - 20 - brokerGroupLength;
            byte[] messageIdBytes = new byte[messageIdLength];
            System.arraycopy(value, 20 + brokerGroupLength, messageIdBytes, 0, messageIdLength);
            BackupMessageMeta meta = new BackupMessageMeta(sequence, new String(brokerGroupBytes, CharsetUtil.UTF_8), new String(messageIdBytes, CharsetUtil.UTF_8));
            meta.setCreateTime(createTime);
            return meta;
        }
    } catch (Exception ignored) {
    }
    return null;
}
 
Example #2
Source File: WebSocketServerIndexPage.java    From usergrid with Apache License 2.0 6 votes vote down vote up
public static ChannelBuffer getContent( String webSocketLocation ) {
    return ChannelBuffers.copiedBuffer(
            "<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>" + NEWLINE
                    + "<script type=\"text/javascript\">" + NEWLINE + "var socket;" + NEWLINE
                    + "if (window.WebSocket) {" + NEWLINE + "  socket = new WebSocket(\"" + webSocketLocation
                    + "/00000000-0000-0000-0000-000000000001/users/00000000-0000-0000-0000-000000000002?a=1\");"
                    + NEWLINE + "  socket.onmessage = function(event) { alert(event.data); };" + NEWLINE
                    + "  socket.onopen = function(event) { alert(\"Web Socket opened!\"); };" + NEWLINE
                    + "  socket.onclose = function(event) { alert(\"Web Socket closed.\"); };" + NEWLINE
                    + "} else {" + NEWLINE + "  alert(\"Your browser does not support Web Socket.\");" + NEWLINE
                    + "}" + NEWLINE + "" + NEWLINE + "function send(message) {" + NEWLINE
                    + "  if (!window.WebSocket) { return; }" + NEWLINE + "  if (socket.readyState == 1) {" + NEWLINE
                    + "    socket.send(message);" + NEWLINE + "  } else {" + NEWLINE
                    + "    alert(\"The socket is not open.\");" + NEWLINE + "  }" + NEWLINE + "}" + NEWLINE
                    + "</script>" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE
                    + "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>"
                    + "<input type=\"button\" value=\"Send Web Socket Data\" onclick=\"send(this.form.message" +
                    ".value)\" />" + NEWLINE + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE,
            CharsetUtil.US_ASCII );
}
 
Example #3
Source File: ChannelBuffers.java    From android-netty with Apache License 2.0 6 votes vote down vote up
static String decodeString(ByteBuffer src, Charset charset) {
    final CharsetDecoder decoder = CharsetUtil.getDecoder(charset);
    final CharBuffer dst = CharBuffer.allocate(
            (int) ((double) src.remaining() * decoder.maxCharsPerByte()));
    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = decoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    return dst.flip().toString();
}
 
Example #4
Source File: ChannelBuffers.java    From android-netty with Apache License 2.0 6 votes vote down vote up
static ByteBuffer encodeString(CharBuffer src, Charset charset) {
    final CharsetEncoder encoder = CharsetUtil.getEncoder(charset);
    final ByteBuffer dst = ByteBuffer.allocate(
            (int) ((double) src.remaining() * encoder.maxBytesPerChar()));
    try {
        CoderResult cr = encoder.encode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = encoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    dst.flip();
    return dst;
}
 
Example #5
Source File: HttpSearchAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected SearchResponse createResponse(HttpInvocationContext<SearchRequest,SearchResponse> httpInvocationContext) throws IOException {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    logger.info("{}", httpResponse.getContent().toString(CharsetUtil.UTF_8));
    BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
    Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();

    logger.info("{}", map);

    InternalSearchResponse internalSearchResponse = parseInternalSearchResponse(map);
    String scrollId = (String)map.get(SCROLL_ID);
    int totalShards = 0;
    int successfulShards = 0;
    if (map.containsKey(SHARDS)) {
        Map<String,?> shards = (Map<String,?>)map.get(SHARDS);
        totalShards =  shards.containsKey(TOTAL) ? (Integer)shards.get(TOTAL) : -1;
        successfulShards =  shards.containsKey(SUCCESSFUL) ? (Integer)shards.get(SUCCESSFUL) : -1;
    }
    int tookInMillis = map.containsKey(TOOK) ? (Integer)map.get(TOOK) : -1;
    ShardSearchFailure[] shardFailures = parseShardFailures(map);
    return new SearchResponse(internalSearchResponse, scrollId, totalShards, successfulShards, tookInMillis, shardFailures);
}
 
Example #6
Source File: WelcomeHandler.java    From feeyo-hlsserver with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ChannelHandlerContext ctx, MessageEvent e) {

	VelocityBuilder velocityBuilder = new VelocityBuilder();
	String htmlText = velocityBuilder.generate("index.vm", "UTF8", null);	
	
	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, htmlText.length());
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
	
	ChannelBuffer buffer = ChannelBuffers.copiedBuffer(htmlText, CharsetUtil.UTF_8);
	response.setContent(buffer);

	ChannelFuture channelFuture = ctx.getChannel().write(response);
	if (channelFuture.isSuccess()) {
		channelFuture.getChannel().close();
	}
}
 
Example #7
Source File: ChannelBuffers.java    From simple-netty-source with Apache License 2.0 6 votes vote down vote up
static String decodeString(ByteBuffer src, Charset charset) {
    final CharsetDecoder decoder = CharsetUtil.getDecoder(charset);
    final CharBuffer dst = CharBuffer.allocate(
            (int) ((double) src.remaining() * decoder.maxCharsPerByte()));
    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = decoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    return dst.flip().toString();
}
 
Example #8
Source File: FileServerHandler.java    From netty-file-parent with Apache License 2.0 6 votes vote down vote up
private void writeResponse(Channel channel) {
	ChannelBuffer buf = ChannelBuffers.copiedBuffer(
			this.responseContent.toString(), CharsetUtil.UTF_8);
	this.responseContent.setLength(0);

	boolean close = ("close".equalsIgnoreCase(this.request
			.getHeader("Connection")))
			|| ((this.request.getProtocolVersion()
					.equals(HttpVersion.HTTP_1_0)) && (!"keep-alive"
					.equalsIgnoreCase(this.request.getHeader("Connection"))));

	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
			HttpResponseStatus.OK);
	response.setContent(buf);
	response.setHeader("Content-Type", "text/plain; charset=UTF-8");
	if (!close) {
		response.setHeader("Content-Length",
				String.valueOf(buf.readableBytes()));
	}
	ChannelFuture future = channel.write(response);
	if (close)
		future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #9
Source File: ChannelBuffers.java    From simple-netty-source with Apache License 2.0 6 votes vote down vote up
static ByteBuffer encodeString(CharBuffer src, Charset charset) {
    final CharsetEncoder encoder = CharsetUtil.getEncoder(charset);
    final ByteBuffer dst = ByteBuffer.allocate(
            (int) ((double) src.remaining() * encoder.maxBytesPerChar()));
    try {
        CoderResult cr = encoder.encode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = encoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    dst.flip();
    return dst;
}
 
Example #10
Source File: HttpDataServerHandler.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(ChannelBuffers.copiedBuffer(
      "Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #11
Source File: TajoPullServerService.java    From tajo with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  ChannelBuffer content = ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8);
  response.setContent(content);
  response.setHeader(Names.CONTENT_LENGTH, content.writerIndex());

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #12
Source File: TajoPullServerService.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #13
Source File: PullServerAuxService.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #14
Source File: HttpServerHandler.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void writeResponse(MessageEvent e) throws Exception {
    HttpResponse response =
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.setContent(ChannelBuffers.copiedBuffer("Hello world", CharsetUtil.UTF_8));
    addHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ChannelFuture future = e.getChannel().write(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #15
Source File: ShuffleHandler.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(
      ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #16
Source File: WebSocketChannelHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private void sendHttpResponse( ChannelHandlerContext ctx, HttpRequest req, HttpResponse res ) {
    // Generate an error page if response status code is not OK (200).
    if ( res.getStatus().getCode() != 200 ) {
        res.setContent( ChannelBuffers.copiedBuffer( res.getStatus().toString(), CharsetUtil.UTF_8 ) );
        setContentLength( res, res.getContent().readableBytes() );
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.getChannel().write( res );
    if ( !isKeepAlive( req ) || ( res.getStatus().getCode() != 200 ) ) {
        f.addListener( ChannelFutureListener.CLOSE );
    }
}
 
Example #17
Source File: ShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.headers().set(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.headers().set(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #18
Source File: ShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.headers().set(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.headers().set(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #19
Source File: HttpDataServerHandler.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(ChannelBuffers.copiedBuffer(
      "Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #20
Source File: KeyValueListImpl.java    From qmq with Apache License 2.0 5 votes vote down vote up
public KeyValueListImpl(List<KeyValue> keyValues) {
    if (keyValues != null && !keyValues.isEmpty()) {
        this.keyValues = keyValues;
        key = keyValues.get(0).key();
        for (KeyValue keyValue : keyValues) {
            data.put(new String(keyValue.qualifier(), CharsetUtil.UTF_8), keyValue);
        }
    }
}
 
Example #21
Source File: ShuffleHandler.java    From big-c with Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.setHeader(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.setHeader(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #22
Source File: ShuffleHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.setHeader(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.setHeader(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #23
Source File: FileClientHandler.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	if (!this.readingChunks) {
		HttpResponse response = (HttpResponse) e.getMessage();
		LOGGER.info("STATUS: " + response.getStatus());
		if ((response.getStatus().getCode() == 200)
				&& (response.isChunked())) {
			this.readingChunks = true;
		} else {
			ChannelBuffer content = response.getContent();
			if (content.readable())
				this.responseContent.append(content
						.toString(CharsetUtil.UTF_8));
		}
	} else {
		HttpChunk chunk = (HttpChunk) e.getMessage();
		if (chunk.isLast()) {
			this.readingChunks = false;
			this.responseContent.append(chunk.getContent().toString(
					CharsetUtil.UTF_8));

			String json = this.responseContent.toString();
			this.result = ((Result) JSONUtil.parseObject(json,Result.class));
		} else {
			this.responseContent.append(chunk.getContent().toString(
					CharsetUtil.UTF_8));
		}
	}
}
 
Example #24
Source File: HttpBlobHandler.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void simpleResponse(HttpResponseStatus status, String body) {
    if (body == null) {
        simpleResponse(status);
        return;
    }
    HttpResponse response = prepareResponse(status);
    if (!body.endsWith("\n")) {
        body += "\n";
    }
    HttpHeaders.setContentLength(response, body.length());
    response.setContent(ChannelBuffers.copiedBuffer(body, CharsetUtil.UTF_8));
    sendResponse(response);
}
 
Example #25
Source File: HBaseRecordStore.java    From qmq with Apache License 2.0 5 votes vote down vote up
private List<BackupMessageMeta> scanMessageMeta(String subject, String messageId) {
    final LocalDateTime now = LocalDateTime.now();
    final Date createTimeEnd = localDateTime2Date(now);
    final Date createTimeBegin = localDateTime2Date(now.minusDays(30));

    try {
        final String subjectId = dicService.name2Id(subject);
        final String keyRegexp = BackupMessageKeyRegexpBuilder.buildRetryRegexp(subjectId, messageId);
        final String startKey = BackupMessageKeyRangeBuilder.buildRetryRangeKey(subjectId, messageId, createTimeEnd);
        final String endKey = BackupMessageKeyRangeBuilder.buildRetryRangeKey(subjectId, messageId, createTimeBegin);
        final List<BackupMessageMeta> metas = scan(indexTable, keyRegexp, startKey, endKey, 1000, 0, B_FAMILY, B_MESSAGE_QUALIFIERS, kvs -> {
            KeyValueList<KeyValue> kvl = new KeyValueListImpl(kvs);
            byte[] value = kvl.getValue(CONTENT);
            byte[] rowKey = kvl.getKey();
            BackupMessageMeta meta = getMessageMeta(value);
            if (meta != null && rowKey.length > CONSUMER_GROUP_INDEX_IN_RETRY_MESSAGE) {
                byte[] consumerGroupId = new byte[CONSUMER_GROUP_LENGTH];
                System.arraycopy(rowKey, CONSUMER_GROUP_INDEX_IN_RETRY_MESSAGE, consumerGroupId, 0, CONSUMER_GROUP_LENGTH);
                meta.setConsumerGroupId(new String(consumerGroupId, CharsetUtil.UTF_8));
            }
            return meta;
        });
        return Lists.newArrayList(Sets.newHashSet(metas));
    } catch (Exception e) {
        LOG.error("Failed to scan messages meta.", e);
        return Lists.newArrayList();
    }
}
 
Example #26
Source File: HBaseStore.java    From qmq with Apache License 2.0 5 votes vote down vote up
private static String[] getStringArrays(final byte[][] bs) {
    if (bs != null) {
        String[] arr = new String[bs.length];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new String(bs[i], CharsetUtil.UTF_8);
        }
        return arr;
    }
    return null;
}
 
Example #27
Source File: HBaseStore.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> T get(byte[] table, byte[] key, byte[] family, byte[][] qualifiers, RowExtractor<T> rowExtractor) throws Exception {
    LOG.info("****************[get] table:{},key:{},family:{},qualifiers:{}", new String(table, CharsetUtil.UTF_8), new String(key, CharsetUtil.UTF_8), new String(family, CharsetUtil.UTF_8),
            Arrays.toString(getStringArrays(qualifiers)));
    GetRequest request = new GetRequest(table, key).family(family).qualifiers(qualifiers);
    ArrayList<KeyValue> row = client.get(request).join();
    return (row == null || row.isEmpty()) ? null : rowExtractor.extractData(row);
}
 
Example #28
Source File: AbstractHBaseMessageStore.java    From qmq with Apache License 2.0 5 votes vote down vote up
void getMessageFromHBase(final String subject, final byte[] table, final MessageQueryResult messageQueryResult, final String keyRegexp, final String startKey, final String endKey
        , final int maxResults) {
    List<BackupMessageMeta> metas;
    try {
        metas = scan(table, keyRegexp, startKey, endKey, maxResults + 1, 0, B_FAMILY, B_MESSAGE_QUALIFIERS, kvs -> {
            KeyValueList<KeyValue> kvl = new KeyValueListImpl(kvs);
            messageQueryResult.setNext(new String(kvl.getKey(), CharsetUtil.UTF_8));
            byte[] value = kvl.getValue(CONTENT);
            BackupMessageMeta meta = getMessageMeta(value);
            if (meta == null) {
                Metrics.counter("message.content.missing").inc();
                LOG.info("Message content missing");
            }
            return meta;
        });
    } catch (Exception e) {
        LOG.error("Failed to get messages from hbase.", e);
        messageQueryResult.setList(Collections.emptyList());
        return;
    }
    int size = metas.size();
    LOG.info("Found {} metas from HBase.", size);
    slim(metas, messageQueryResult, maxResults);

    List<MessageQueryResult.MessageMeta> messages = getMessagesWithMeta(subject, metas);
    messageQueryResult.setList(messages);
}
 
Example #29
Source File: ManageSieveServer.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
protected ChannelPipelineFactory createPipelineFactory(final ChannelGroup group) {

    return new ChannelPipelineFactory() {

        private final ChannelGroupHandler groupHandler = new ChannelGroupHandler(group);

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = pipeline();
            Encryption secure = getEncryption();
            if (secure != null && !secure.isStartTLS()) {
                // We need to set clientMode to false.
                // See https://issues.apache.org/jira/browse/JAMES-1025
                SSLEngine engine = secure.getContext().createSSLEngine();
                engine.setUseClientMode(false);
                pipeline.addFirst(SSL_HANDLER, new SslHandler(engine));

            }
            pipeline.addLast(GROUP_HANDLER, groupHandler);
            pipeline.addLast(CONNECTION_LIMIT_HANDLER, new ConnectionLimitUpstreamHandler(ManageSieveServer.this.connectionLimit));
            pipeline.addLast(CONNECTION_LIMIT_PER_IP_HANDLER, new ConnectionPerIpLimitUpstreamHandler(ManageSieveServer.this.connPerIP));
            // Add the text line decoder which limit the max line length,
            // don't strip the delimiter and use CRLF as delimiter
            // Use a SwitchableDelimiterBasedFrameDecoder, see JAMES-1436
            pipeline.addLast(FRAMER, getFrameHandlerFactory().create(pipeline));
            pipeline.addLast(CONNECTION_COUNT_HANDLER, getConnectionCountHandler());
            pipeline.addLast(CHUNK_WRITE_HANDLER, new ChunkedWriteHandler());

            ExecutionHandler ehandler = getExecutionHandler();
            if (ehandler  != null) {
                pipeline.addLast(EXECUTION_HANDLER, ehandler);

            }
            pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast(CORE_HANDLER, createCoreHandler());
            pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
            return pipeline;
        }

    };
}
 
Example #30
Source File: HttpAction.java    From elasticsearch-helper with Apache License 2.0 4 votes vote down vote up
protected HttpRequest newRequest(HttpMethod method, URL url, String path, CharSequence content) {
    return newRequest(method, url, path, content != null ? ChannelBuffers.copiedBuffer(content, CharsetUtil.UTF_8) : null);
}