本文整理匯總了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);
}