本文整理汇总了Java中org.jboss.netty.util.CharsetUtil类的典型用法代码示例。如果您正苦于以下问题:Java CharsetUtil类的具体用法?Java CharsetUtil怎么用?Java CharsetUtil使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CharsetUtil类属于org.jboss.netty.util包,在下文中一共展示了CharsetUtil类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createResponse
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
protected SearchResponse createResponse(HttpContext<SearchRequest, SearchResponse> httpContext) throws IOException {
if (httpContext == null) {
throw new IllegalStateException("no http context");
}
HttpResponse httpResponse = httpContext.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 = null;
return new SearchResponse(internalSearchResponse, scrollId, totalShards, successfulShards, tookInMillis, shardFailures);
}
示例2: readString
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
private static String readString(ChannelBuffer cb, int length)
{
try
{
String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8);
cb.readerIndex(cb.readerIndex() + length);
return str;
}
catch (IllegalStateException e)
{
// That's the way netty encapsulate a CCE
if (e.getCause() instanceof CharacterCodingException)
throw new ProtocolException("Cannot decode string as UTF8");
else
throw e;
}
}
示例3: sendHttpResponse
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
private static 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);
}
}
示例4: encodeString
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
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;
}
示例5: decodeString
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
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();
}
示例6: writeResponse
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
private void writeResponse(MessageEvent e) {
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");
ChannelBuffer content = ChannelBuffers.dynamicBuffer();
Writer writer = new OutputStreamWriter(new ChannelBufferOutputStream(content), CharsetUtil.UTF_8);
reportAdapter.toJson(report.get(), writer);
try {
writer.close();
} catch (IOException e1) {
LOG.error("error writing resource report", e1);
}
response.setContent(content);
ChannelFuture future = e.getChannel().write(response);
future.addListener(ChannelFutureListener.CLOSE);
}
示例7: sendStatus
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
private static void sendStatus(HttpResponse response, @Nullable HttpRequest request, Channel channel, @Nullable String description) {
response.setHeader(CONTENT_TYPE, "text/html");
if (request == null || request.getMethod() != HttpMethod.HEAD) {
String message = response.getStatus().toString();
StringBuilder builder = new StringBuilder();
builder.append("<!doctype html><title>").append(message).append("</title>").append("<h1 style=\"text-align: center\">").append(message).append("</h1>");
if (description != null) {
builder.append("<p>").append(description).append("</p>");
}
builder.append("<hr/><p style=\"text-align: center\">").append(StringUtil.notNullize(getServerHeaderValue(), "")).append("</p>");
response.setContent(ChannelBuffers.copiedBuffer(builder, CharsetUtil.UTF_8));
}
send(response, channel, request);
}
示例8: createResponse
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
@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);
}
示例9: decode
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
public static ByePacket decode(ChannelBuffer buffer, boolean hasPadding, byte innerBlocks, int length) {
ByePacket packet = new ByePacket();
int read = 0;
for (int i = 0; i < innerBlocks; i++) {
packet.addSsrc(buffer.readUnsignedInt());
read += 4;
}
// Length is written in 32bit words, not octet count.
int lengthInOctets = (length * 4);
if (read < lengthInOctets) {
byte[] reasonBytes = new byte[buffer.readUnsignedByte()];
buffer.readBytes(reasonBytes);
packet.reasonForLeaving = new String(reasonBytes, CharsetUtil.UTF_8);
read += (1 + reasonBytes.length);
if (read < lengthInOctets) {
// Skip remaining bytes (used for padding). This takes care of both the null termination bytes (padding
// of the 'reason for leaving' string and the packet padding bytes.
buffer.skipBytes(lengthInOctets - read);
}
}
return packet;
}
示例10: sendMessage
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
public void sendMessage(SipRequest request) throws Exception {
// initial line
StringBuffer buf = new StringBuffer(String.format("%s %s %s", request.getMethod().name(),
request.getUri(), request.getVersion().toString()));
buf.append(StringUtil.NEWLINE);
// headers
for (Map.Entry<String, List<String>> header : request.getHeaders().entrySet()) {
buf.append(header.getKey());
buf.append(": ");
buf.append(StringUtils.arrayToDelimitedString(header.getValue().toArray(), "\n"));
buf.append(StringUtil.NEWLINE);
}
buf.append(StringUtil.NEWLINE);
// content
ChannelBuffer content = request.getContent();
if (content.readable()) {
buf.append(content.toString(CharsetUtil.UTF_8)).append(StringUtil.NEWLINE);
}
sendMessage(null, buf.toString());
}
示例11: getContent
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
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 );
}
示例12: start
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
public void start() {
ExecutorService bossPool = Executors.newCachedThreadPool();
log.info("Creating worker thread pool with " + workers + " threads.");
ExecutorService workerPool = Executors.newFixedThreadPool(workers);
bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(bossPool, workerPool));
jmxRequestHandler = new JmxRequestHandler();
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
new DelimiterBasedFrameDecoder(1024 * 1024, ChannelBuffers
.copiedBuffer("\n", CharsetUtil.UTF_8)), new StringDecoder(), new StringEncoder(),
jmxRequestHandler);
};
});
bootstrap.bind(listenAddress);
log.info("Starting listening to {}", listenAddress);
}
示例13: simpleResponse
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
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);
}
示例14: sendError
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
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);
}
示例15: writeResponse
import org.jboss.netty.util.CharsetUtil; //导入依赖的package包/类
private void writeResponse(MessageEvent e)
{
// Build the response object.
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
// Write the response.
ChannelFuture future = e.getChannel().write(response);
// Close the non-keep-alive connection after the write operation is done.
future.addListener(ChannelFutureListener.CLOSE);
}