List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:com.addthis.hydra.query.web.GoogleDriveAuthentication.java
License:Apache License
/** * Send an HTML formatted error message. *///from w ww .j a v a 2 s . co m private static void sendErrorMessage(ChannelHandlerContext ctx, String message) throws IOException { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(CONTENT_TYPE, "text/html; charset=utf-8"); StringBuilderWriter writer = new StringBuilderWriter(50); writer.append("<html><head><title>Hydra Query Master</title></head><body>"); writer.append("<h3>"); writer.append(message); writer.append("</h3></body></html>"); ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()), CharsetUtil.UTF_8); HttpContent content = new DefaultHttpContent(textResponse); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes()); ctx.write(response); ctx.write(content); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); lastContentFuture.addListener(ChannelFutureListener.CLOSE); }
From source file:com.addthis.hydra.query.web.HttpQueryHandler.java
License:Apache License
private void fastHandle(ChannelHandlerContext ctx, FullHttpRequest request, String target, KVPairs kv) throws Exception { StringBuilderWriter writer = new StringBuilderWriter(50); HttpResponse response = HttpUtils.startResponse(writer); response.headers().add("Access-Control-Allow-Origin", "*"); switch (target) { case "/metrics": fakeMetricsServlet.writeMetrics(writer, kv); break;/*from ww w .j a v a 2 s . co m*/ case "/query/list": writer.write("[\n"); for (QueryEntryInfo stat : tracker.getRunning()) { writer.write(CodecJSON.encodeString(stat).concat(",\n")); } writer.write("]"); break; case "/completed/list": writer.write("[\n"); for (QueryEntryInfo stat : tracker.getCompleted()) { writer.write(CodecJSON.encodeString(stat).concat(",\n")); } writer.write("]"); break; case "/v2/host/list": case "/host/list": String queryStatusUuid = kv.getValue("uuid"); QueryEntry queryEntry = tracker.getQueryEntry(queryStatusUuid); if (queryEntry != null) { DetailedStatusHandler hostDetailsHandler = new DetailedStatusHandler(writer, response, ctx, request, queryEntry); hostDetailsHandler.handle(); return; } else { QueryEntryInfo queryEntryInfo = tracker.getCompletedQueryInfo(queryStatusUuid); if (queryEntryInfo != null) { JSONObject entryJSON = CodecJSON.encodeJSON(queryEntryInfo); writer.write(entryJSON.toString()); } else { throw new RuntimeException("could not find query"); } break; } case "/query/cancel": if (tracker.cancelRunning(kv.getValue("uuid"))) { writer.write("canceled " + kv.getValue("uuid")); } else { writer.write("canceled failed for " + kv.getValue("uuid")); response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); } break; case "/query/encode": { Query q = new Query(null, kv.getValue("query", kv.getValue("path", "")), null); JSONArray path = CodecJSON.encodeJSON(q).getJSONArray("path"); writer.write(path.toString()); break; } case "/query/decode": { String qo = "{path:" + kv.getValue("query", kv.getValue("path", "")) + "}"; Query q = CodecJSON.decodeString(new Query(), qo); writer.write(q.getPaths()[0]); break; } case "/v2/queries/finished.list": { JSONArray runningEntries = new JSONArray(); for (QueryEntryInfo entryInfo : tracker.getCompleted()) { JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo); //TODO: replace this with some high level summary entryJSON.put("hostInfoSet", ""); runningEntries.put(entryJSON); } writer.write(runningEntries.toString()); break; } case "/v2/queries/running.list": { JSONArray runningEntries = new JSONArray(); for (QueryEntryInfo entryInfo : tracker.getRunning()) { JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo); //TODO: replace this with some high level summary entryJSON.put("hostInfoSet", ""); runningEntries.put(entryJSON); } writer.write(runningEntries.toString()); break; } case "/v2/queries/workers": { JSONObject jsonObject = new JSONObject(); for (WorkerData workerData : meshQueryMaster.worky().values()) { jsonObject.put(workerData.hostName, workerData.queryLeases.availablePermits()); } writer.write(jsonObject.toString()); break; } case "/v2/queries/list": JSONArray queries = new JSONArray(); for (QueryEntryInfo entryInfo : tracker.getCompleted()) { JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo); entryJSON.put("state", 0); queries.put(entryJSON); } for (QueryEntryInfo entryInfo : tracker.getRunning()) { JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo); entryJSON.put("state", 3); queries.put(entryJSON); } writer.write(queries.toString()); break; case "/v2/job/list": { StringWriter swriter = new StringWriter(); final JsonGenerator json = QueryServer.factory.createJsonGenerator(swriter); json.writeStartArray(); for (IJob job : meshQueryMaster.keepy().getJobs()) { if (job.getQueryConfig() != null && job.getQueryConfig().getCanQuery()) { List<JobTask> tasks = job.getCopyOfTasks(); String uuid = job.getId(); json.writeStartObject(); json.writeStringField("id", uuid); json.writeStringField("description", Optional.fromNullable(job.getDescription()).or("")); json.writeNumberField("state", job.getState().ordinal()); json.writeStringField("creator", job.getCreator()); json.writeNumberField("submitTime", Optional.fromNullable(job.getSubmitTime()).or(-1L)); json.writeNumberField("startTime", Optional.fromNullable(job.getStartTime()).or(-1L)); json.writeNumberField("endTime", Optional.fromNullable(job.getStartTime()).or(-1L)); json.writeNumberField("replicas", Optional.fromNullable(job.getReplicas()).or(0)); json.writeNumberField("backups", Optional.fromNullable(job.getBackups()).or(0)); json.writeNumberField("nodes", tasks.size()); json.writeEndObject(); } } json.writeEndArray(); json.close(); writer.write(swriter.toString()); break; } case "/v2/settings/git.properties": { StringWriter swriter = new StringWriter(); final JsonGenerator json = QueryServer.factory.createJsonGenerator(swriter); Properties gitProperties = new Properties(); json.writeStartObject(); try { InputStream in = queryServer.getClass().getResourceAsStream("/git.properties"); gitProperties.load(in); in.close(); json.writeStringField("commitIdAbbrev", gitProperties.getProperty("git.commit.id.abbrev")); json.writeStringField("commitUserEmail", gitProperties.getProperty("git.commit.user.email")); json.writeStringField("commitMessageFull", gitProperties.getProperty("git.commit.message.full")); json.writeStringField("commitId", gitProperties.getProperty("git.commit.id")); json.writeStringField("commitUserName", gitProperties.getProperty("git.commit.user.name")); json.writeStringField("buildUserName", gitProperties.getProperty("git.build.user.name")); json.writeStringField("commitIdDescribe", gitProperties.getProperty("git.commit.id.describe")); json.writeStringField("buildUserEmail", gitProperties.getProperty("git.build.user.email")); json.writeStringField("branch", gitProperties.getProperty("git.branch")); json.writeStringField("commitTime", gitProperties.getProperty("git.commit.time")); json.writeStringField("buildTime", gitProperties.getProperty("git.build.time")); } catch (Exception ex) { log.warn("Error loading git.properties, possibly jar was not compiled with maven."); } json.writeEndObject(); json.close(); writer.write(swriter.toString()); break; } default: // forward to static file server ctx.pipeline().addLast(staticFileHandler); request.retain(); ctx.fireChannelRead(request); return; // don't do text response clean up } log.trace("response being sent {}", writer); ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()), CharsetUtil.UTF_8); HttpContent content = new DefaultHttpContent(textResponse); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes()); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } ctx.write(response); ctx.write(content); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); log.trace("response pending"); if (!HttpHeaders.isKeepAlive(request)) { log.trace("Setting close listener"); lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.addthis.hydra.query.web.LegacyHandler.java
License:Apache License
public static Query handleQuery(Query query, KVPairs kv, HttpRequest request, ChannelHandlerContext ctx) throws IOException, QueryException { String async = kv.getValue("async"); if (async == null) { return query; } else if (async.equals("new")) { StringBuilderWriter writer = new StringBuilderWriter(50); HttpResponse response = HttpUtils.startResponse(writer); String asyncUuid = genAsyncUuid(); asyncCache.put(asyncUuid, query); if (query.isTraced()) { Query.emitTrace("async create " + asyncUuid + " from " + query); }/*w w w.java 2 s .c o m*/ writer.write("{\"id\":\"" + asyncUuid + "\"}"); ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()), CharsetUtil.UTF_8); HttpContent content = new DefaultHttpContent(textResponse); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes()); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } ctx.write(response); ctx.write(content); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!HttpHeaders.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } return null; } else { Query asyncQuery = asyncCache.getIfPresent(async); asyncCache.invalidate(async); if (query.isTraced()) { Query.emitTrace("async restore " + async + " as " + asyncQuery); } if (asyncQuery != null) { return asyncQuery; } else { throw new QueryException("Missing Async Id"); } } }
From source file:com.addthis.meshy.ChannelState.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { buffer = ctx.alloc().buffer(16384); meshy.updateLastEventTime();//from w w w . ja va 2 s.c o m channelConnected(); meshy.channelConnected(ctx.channel(), this); }
From source file:com.antsdb.saltedfish.server.mysql.Helper.java
License:Open Source License
static void writeResonpse(ChannelHandlerContext ctx, MysqlServerHandler handler, Object result, boolean text) { ByteBuf bufferArray = ctx.alloc().buffer(); if (result == null) { PacketEncoder.writePacket(bufferArray, (byte) 1, () -> handler.packetEncoder.writeOKBody(bufferArray, 0, handler.session.getLastInsertId(), null, handler.session)); } else if (result instanceof Cursor) { Helper.writeCursor(bufferArray, handler, (Cursor) result, text); } else if (result instanceof Integer) { Integer count = (Integer) result; PacketEncoder.writePacket(bufferArray, handler.getNextPacketSequence(), () -> handler.packetEncoder .writeOKBody(bufferArray, count, handler.session.getLastInsertId(), null, handler.session)); } else {/*from w w w. j av a2 s . com*/ bufferArray.writeBytes(PacketEncoder.OK_PACKET); } // write preparedOk packet ctx.writeAndFlush(bufferArray); }
From source file:com.antsdb.saltedfish.server.mysql.MysqlClientHandler.java
License:Open Source License
public void state(ChannelHandlerContext ctx, StateIndicator msg) { ByteBuf buf = ctx.alloc().buffer(); if (msg.eventType == StateIndicator.INITIAL_STATE) { PacketEncoder.writePacket(buf, (byte) 1, () -> packetEncoder.writeHandshakeResponse(buf, MysqlServerHandler.getServerCapabilities(), masterUser, masterPassword)); ctx.writeAndFlush(buf);// w ww . ja v a 2s .co m } else if (msg.eventType == StateIndicator.HANDSHAKEN_STATE) { PacketEncoder.writePacket(buf, (byte) 0, () -> packetEncoder.writeRegisterSlave(buf, getConfig().getSlaveServerId())); ctx.writeAndFlush(buf); _log.info("Replication handshaken"); } else if (msg.eventType == StateIndicator.REGISTERED_STATE) { this.session = this.fish.getOrca().createSession(masterUser); PacketEncoder.writePacket(buf, (byte) 0, () -> packetEncoder.writeBinlogDump(buf, masterLogPos, getConfig().getSlaveServerId(), masterBinlog)); ctx.writeAndFlush(buf); _log.info("Slave registered"); } else if (msg.eventType == StateIndicator.HANDSHAKE_FAIL_STATE || msg.eventType == StateIndicator.REGISTER_FAIL_STATE) { _log.error("Replication failed to start"); close(ctx); } }
From source file:com.antsdb.saltedfish.server.mysql.MysqlServerHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { int packLength = 40; ByteBuf buf = ctx.alloc().buffer(packLength); threadId++;//from w w w . jav a2 s . co m // status is set to SERVER_STATUS_AUTOCOMMIT 0x0002 int status = 0x0002; PacketEncoder.writePacket(buf, (byte) 0, () -> PacketEncoder.writeHandshakeBody(buf, SERVER_VERSION, PROTOCOL_VERSION, threadId, getServerCapabilities(), CHAR_SET_INDEX, status)); ctx.writeAndFlush(buf); }
From source file:com.antsdb.saltedfish.server.mysql.MysqlServerHandler.java
License:Open Source License
private void auth(ChannelHandlerContext ctx, AuthPacket request) { // logging in this.session = this.fish.getOrca().createSession(request.user); this.session.setCurrentNamespace(request.dbname); if (_log.isTraceEnabled()) { _log.debug("Connection user:" + request.user); _log.debug("Connection default schema:" + request.dbname); }/* ww w . java 2s.c om*/ preparedStmtHandler = new PreparedStmtHandler(this); queryHandler = new QueryHandler(this); // if client send client_secure_connection, send back auth ok to client if ((request.clientParam & CLIENT_SECURE_CONNECTION) != 0) { ByteBuf buf = ctx.alloc().buffer(); buf.writeBytes(PacketEncoder.AUTH_OK_PACKET); ctx.writeAndFlush(buf); } }
From source file:com.antsdb.saltedfish.server.mysql.MysqlServerHandler.java
License:Open Source License
private void init(ChannelHandlerContext ctx, InitPacket request) { VdmContext vdm = new VdmContext(session, 0); new Use(request.database).run(vdm, null); ByteBuf bufferArray = ctx.alloc().buffer(); bufferArray.writeBytes(PacketEncoder.OK_PACKET); ctx.writeAndFlush(bufferArray);// w w w. ja v a 2 s.com }
From source file:com.antsdb.saltedfish.server.mysql.MysqlServerHandler.java
License:Open Source License
private void ping(ChannelHandlerContext ctx) { ByteBuf bufferArray = ctx.alloc().buffer(); bufferArray.writeBytes(PacketEncoder.OK_PACKET); ctx.writeAndFlush(bufferArray);//from ww w . j av a 2 s. co m }