use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project camel by apache.
the class NettyHttpAccessHttpRequestAndResponseBeanTest method myTransformer.
/**
* We can use both a netty http request and response type for transformation
*/
public static HttpResponse myTransformer(HttpRequest request) {
String in = request.getContent().toString(Charset.forName("UTF-8"));
String reply = "Bye " + in;
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
response.setContent(ChannelBuffers.copiedBuffer(reply.getBytes()));
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, reply.length());
return response;
}
use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project cdap by caskdata.
the class HttpStatusRequestHandler method messageReceived.
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
Object msg = event.getMessage();
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
// be served by the router itself without it talking to any downstream services
if (request.getUri().equals(Constants.EndPoints.STATUS)) {
String statusString = Constants.Monitor.STATUS_OK;
ChannelBuffer responseContent = ChannelBuffers.wrappedBuffer(Charsets.UTF_8.encode(statusString));
HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
httpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, responseContent.readableBytes());
httpResponse.setContent(responseContent);
ChannelFuture writeFuture = Channels.future(event.getChannel());
Channels.write(ctx, writeFuture, httpResponse);
writeFuture.addListener(ChannelFutureListener.CLOSE);
return;
}
}
super.messageReceived(ctx, event);
}
use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project NabAlive by jcheype.
the class ApplicationController method init.
@PostConstruct
void init() {
restHandler.get(new Route("/applications") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
List<ApplicationStore> applicationStores = applicationStoreDAO.find().asList();
Iterables.filter(applicationStores, new Predicate<ApplicationStore>() {
@Override
public boolean apply(@Nullable ApplicationStore applicationStore) {
return applicationManager.getApplication(applicationStore.getApikey()) != null;
}
});
response.writeJSON(applicationStores);
}
}).get(new Route("/applications/:apikey/logo.png") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
ChannelBuffer buffer;
String apikey = checkNotNull(map.get("apikey"));
ApplicationLogo applicationLogo = applicationLogoDAO.get(apikey);
if (applicationLogo != null)
buffer = ChannelBuffers.copiedBuffer(applicationLogo.getData());
else {
byte[] bytes = ByteStreams.toByteArray(getClass().getResourceAsStream("/app/default.png"));
buffer = ChannelBuffers.copiedBuffer(bytes);
}
DefaultHttpResponse defaultHttpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
defaultHttpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "image/png");
defaultHttpResponse.setContent(buffer);
response.write(defaultHttpResponse);
}
});
// .post(new Route("/applications/:apikey/logo.png") {
// @Override
// public void handle(Request request, Response response, Map<String, String> map) throws Exception {
// String apikey = checkNotNull(map.get("apikey"));
// String contentType = request.getHeader("Content-Type");
// Matcher matcher = boundaryPattern.matcher(contentType);
// if (!matcher.matches())
// throw new HttpException(HttpResponseStatus.INTERNAL_SERVER_ERROR, "bad content type");
//
// String boundary = matcher.group(1);
//
// ChannelBuffer content = request.request.getContent();
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// MultipartStream multipartStream = new MultipartStream(new ChannelBufferInputStream(content), boundary.getBytes(CharsetUtil.UTF_8));
// String contentTypeLogo = null;
// boolean nextPart = multipartStream.skipPreamble();
// while (nextPart) {
// String header = multipartStream.readHeaders();
// if(header.contains("form-data; name=\"logo\"")){
// contentTypeLogo = "application/octet-stream"; // TODO parse contentType
// multipartStream.readBodyData(outputStream);
// nextPart=false;
// }
// else
// nextPart = multipartStream.readBoundary();
// }
// if(contentTypeLogo == null)
// throw new HttpException(HttpResponseStatus.INTERNAL_SERVER_ERROR, "cannot parse data");
//
// ApplicationLogo applicationLogo = new ApplicationLogo();
// applicationLogo.setApikey(apikey);
// applicationLogo.setContentType(contentTypeLogo);
// applicationLogo.setFilename("logo.png");
// applicationLogo.setData(outputStream.toByteArray());
//
// applicationLogoDAO.save(applicationLogo);
//
// response.writeJSON(applicationLogo);
// }
// })
}
use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project NabAlive by jcheype.
the class NabaztagController method init.
@PostConstruct
void init() {
restHandler.get(new Route("/nabaztags") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
Token token = TokenUtil.decode(checkNotNull(request.getParamOrHeader("token")), Token.class);
List<Nabaztag> nabaztagList = nabaztagDAO.find(nabaztagDAO.createQuery().filter("owner", token.getUserId())).asList();
for (Nabaztag nabaztag : nabaztagList) {
if (connectionManager.containsKey(nabaztag.getMacAddress())) {
nabaztag.setConnected(true);
}
}
response.writeJSON(nabaztagList);
}
}).post(new Route("/nabaztags", ".*json.*") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
Token token = TokenUtil.decode(checkNotNull(request.getParamOrHeader("token")), Token.class);
logger.debug("received json: {}", request.content);
Map<String, String> nabMap = mapper.readValue(request.content, Map.class);
String mac = CharMatcher.JAVA_LETTER_OR_DIGIT.retainFrom(checkNotNull(nabMap.get("mac")).toLowerCase());
if (!connectionManager.containsKey(mac)) {
throw new HttpException(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Nabaztag not Connected");
}
Nabaztag nabaztag = new Nabaztag();
nabaztag.setMacAddress(mac);
nabaztag.setName(nabMap.get("name"));
nabaztag.setApikey(UUID.randomUUID().toString());
nabaztag.setOwner(token.getUserId());
try {
nabaztagDAO.save(nabaztag);
} catch (MongoException.DuplicateKey e) {
ImmutableMap<String, String> error = (new ImmutableMap.Builder<String, String>()).put("error", "Adresse mac déjà enregistrée").build();
response.writeJSON(error);
return;
}
messageService.sendMessage(mac, "ST " + OPERATIONNEL_URL + "\nMW\n");
response.writeJSON(nabaztag);
}
}).post(new Route("/nabaztags") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
Token token = TokenUtil.decode(checkNotNull(request.getParamOrHeader("token")), Token.class);
String mac = CharMatcher.JAVA_LETTER_OR_DIGIT.retainFrom(checkNotNull(request.getParam("mac")).toLowerCase());
String name = request.getParam("name");
if (!connectionManager.containsKey(mac)) {
throw new HttpException(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Nabaztag not Connected");
}
Nabaztag nabaztag = new Nabaztag();
nabaztag.setMacAddress(mac);
nabaztag.setName(name);
nabaztag.setApikey(UUID.randomUUID().toString());
nabaztag.setOwner(token.getUserId());
try {
nabaztagDAO.save(nabaztag);
} catch (MongoException.DuplicateKey e) {
ImmutableMap<String, String> error = (new ImmutableMap.Builder<String, String>()).put("error", "Adresse mac déjà enregistrée").build();
response.writeJSON(error);
return;
}
messageService.sendMessage(mac, "ST " + OPERATIONNEL_URL + "\nMW\n");
response.writeJSON(nabaztag);
}
}).post(new Route("/nabaztags/:mac/addconfig") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
Token token = TokenUtil.decode(checkNotNull(request.getParamOrHeader("token")), Token.class);
List<String> tags = request.parameters.get("rfid");
String appApikey = checkNotNull(request.getParam("apikey"));
String name = checkNotNull(request.getParam("name"));
String appName = checkNotNull(request.getParam("appName"));
String uuid = request.getParam("uuid");
String mac = checkNotNull(map.get("mac"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("macAddress", mac));
if (!nabaztag.getOwner().equals(token.getUserId()))
throw new IllegalArgumentException();
Iterator<ApplicationConfig> iterator = nabaztag.getApplicationConfigList().iterator();
while (iterator.hasNext()) {
ApplicationConfig next = iterator.next();
if (tags != null)
next.getTags().removeAll(tags);
if (next.getUuid().equals(uuid))
iterator.remove();
}
ApplicationConfig config = new ApplicationConfig();
config.setApplicationStoreApikey(appApikey);
config.getTags().clear();
if (tags != null)
config.getTags().addAll(tags);
for (Map.Entry<String, List<String>> entry : request.parameters.entrySet()) {
if (entry.getKey().startsWith("parameter.")) {
String key = entry.getKey().substring("parameter.".length());
config.getParameters().put(key, entry.getValue());
}
}
config.setName(name);
config.setAppName(appName);
nabaztag.addApplicationConfig(config);
nabaztagDAO.save(nabaztag);
tts(nabaztag.getMacAddress(), request.request.getHeader("Host"), "fr", Format.get("app.install.success", appName));
response.writeJSON(nabaztag);
}
}).delete(new Route("/config/:uuid") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
Token token = TokenUtil.decode(checkNotNull(request.getParamOrHeader("token")), Token.class);
String uuid = checkNotNull(map.get("uuid"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("applicationConfigList.uuid", uuid));
if (!nabaztag.getOwner().equals(token.getUserId()))
throw new IllegalArgumentException();
Iterator<ApplicationConfig> iterator = nabaztag.getApplicationConfigList().iterator();
while (iterator.hasNext()) {
ApplicationConfig next = iterator.next();
if (next.getUuid().equals(uuid))
iterator.remove();
}
nabaztagDAO.save(nabaztag);
response.writeJSON(nabaztag);
}
}).get(new Route("/nabaztags/:mac") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
Token token = TokenUtil.decode(checkNotNull(request.getParamOrHeader("token")), Token.class);
String mac = checkNotNull(map.get("mac"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("macAddress", mac));
if (token.getUserId().equals(nabaztag.getOwner())) {
response.writeJSON(nabaztag);
} else {
response.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
}
}
}).delete(new Route("/nabaztags/:mac") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
Token token = TokenUtil.decode(checkNotNull(request.getParamOrHeader("token")), Token.class);
String mac = checkNotNull(map.get("mac"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("macAddress", mac));
if (token.getUserId().equals(nabaztag.getOwner())) {
nabaztagDAO.delete(nabaztag);
response.writeJSON("ok");
} else {
response.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
}
}
}).get(new Route("/nabaztags/:apikey/play") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
List<String> urlList = checkNotNull(request.qs.getParameters().get("url"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
List<String> urlListSanitized = Lists.transform(urlList, new Function<String, String>() {
@Override
public String apply(@Nullable String url) {
return CharMatcher.isNot('\n').retainFrom(url);
}
});
StringBuilder commands = new StringBuilder();
for (String url : urlListSanitized) {
commands.append("ST " + url + "\nMW\n");
}
logger.debug("COMMAND: {}", commands);
messageService.sendMessage(nabaztag.getMacAddress(), commands.toString());
response.writeJSON("ok");
}
}).get(new Route("/nabaztags/:apikey/tts/:voice") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
String text = checkNotNull(request.getParam("text"));
String voice = checkNotNull(map.get("voice"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
String host = request.request.getHeader("Host");
tts(nabaztag.getMacAddress(), host, voice, text);
response.writeJSON("ok");
}
}).get(new Route("/nabaztags/:apikey/exec") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
String command = checkNotNull(request.getParam("command"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
logger.debug("COMMAND: {}", command);
messageService.sendMessage(nabaztag.getMacAddress(), command);
response.writeJSON("ok");
}
}).post(new Route("/nabaztags/:apikey/tags", ".*json.*") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
List<Tag> tagList = mapper.readValue(request.content, new TypeReference<List<Tag>>() {
});
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
nabaztagDAO.update(nabaztagDAO.createQuery().filter("apikey", apikey), nabaztagDAO.createUpdateOperations().set("tags", tagList));
response.writeJSON("ok");
}
}).get(new Route("/nabaztags/:apikey/sleep") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
messageService.sendMessage(nabaztag.getMacAddress(), new SleepPacket(SleepPacket.Action.Sleep));
response.writeJSON("ok");
}
}).get(new Route("/nabaztags/:apikey/wakeup") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
messageService.sendMessage(nabaztag.getMacAddress(), new SleepPacket(SleepPacket.Action.WakeUp));
response.writeJSON("ok");
}
}).get(new Route("/nabaztags/:apikey/tz") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
String tz = checkNotNull(request.getParam("tz"));
Query<Nabaztag> query = nabaztagDAO.createQuery().filter("apikey", apikey);
UpdateOperations<Nabaztag> updateOperations = nabaztagDAO.createUpdateOperations();
updateOperations.set("timeZone", tz);
nabaztagDAO.update(query, updateOperations);
response.writeJSON("ok");
}
}).get(new Route("/nabaztags/:apikey/schedule") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
List<String> sleep = request.parameters.get("sleep[]");
List<String> wakeup = request.parameters.get("wakeup[]");
final Nabaztag nabaztag = nabaztagDAO.findOne("apikey", apikey);
Query<Nabaztag> query = nabaztagDAO.createQuery().filter("apikey", apikey);
UpdateOperations<Nabaztag> updateOperations = nabaztagDAO.createUpdateOperations();
if (!sleep.isEmpty()) {
nabaztag.setSleepLocal(sleep);
Set<String> nabaztagSleep = nabaztag.getSleep();
logger.debug("sleep {}", nabaztagSleep);
updateOperations.set("sleep", nabaztagSleep);
}
if (!wakeup.isEmpty()) {
nabaztag.setWakeupLocal(wakeup);
Set<String> nabaztagWakeup = nabaztag.getWakeup();
logger.debug("wakeup {}", nabaztagWakeup);
updateOperations.set("wakeup", nabaztagWakeup);
}
nabaztagDAO.update(query, updateOperations);
response.writeJSON("ok");
}
}).get(new Route("/nabaztags/:apikey/subscribe") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
String email = checkNotNull(request.getParam("email"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
Set<Subscription> subscriptionSet = nabaztag.getSubscribe();
User user = checkNotNull(userDAO.findOne("email", email));
Query<Nabaztag> query = nabaztagDAO.createQuery().filter("owner", user.getId());
for (Nabaztag nab : nabaztagDAO.find(query).asList()) {
Subscription subscription = new Subscription();
subscription.setName(nab.getName());
subscription.setOwnerFisrtName(user.getFirstname());
subscription.setOwnerLastName(user.getLastname());
subscription.setObjectId(nab.getId().toString());
subscriptionSet.add(subscription);
}
UpdateOperations<Nabaztag> updateOperations = nabaztagDAO.createUpdateOperations().set("subscribe", subscriptionSet);
nabaztagDAO.update(nabaztagDAO.createQuery().filter("_id", nabaztag.getId()), updateOperations);
response.writeJSON("ok");
}
}).delete(new Route("/nabaztags/:apikey/subscribe/:objectId") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
String objectId = checkNotNull(map.get("objectId"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
Set<Subscription> subscriptionSet = nabaztag.getSubscribe();
Iterator<Subscription> iterator = subscriptionSet.iterator();
while (iterator.hasNext()) {
Subscription next = iterator.next();
if (next.getObjectId().equals(objectId))
iterator.remove();
}
UpdateOperations<Nabaztag> updateOperations = nabaztagDAO.createUpdateOperations().set("subscribe", subscriptionSet);
nabaztagDAO.update(nabaztagDAO.createQuery().filter("_id", nabaztag.getId()), updateOperations);
response.writeJSON("ok");
}
}).get(new Route("/nab2nabs/:apikey/send") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
String url = checkNotNull(request.getParam("url"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
Set<Subscription> subscriptionSet = nabaztag.getSubscribe();
List<ObjectId> objectList = new ArrayList<ObjectId>();
for (Subscription subscription : subscriptionSet) {
objectList.add(new ObjectId(subscription.getObjectId()));
}
List<Nabaztag> nabaztagList = nabaztagDAO.find(nabaztagDAO.createQuery().field("_id").in(objectList)).asList();
String command = "ST " + url + "\nMW\n";
for (Nabaztag nab : nabaztagList) {
if (connectionManager.containsKey(nab.getMacAddress()))
messageService.sendMessage(nab.getMacAddress(), command);
}
response.writeJSON("ok");
}
}).get(new Route("/nab2nabs/:apikey/tts") {
@Override
public void handle(Request request, Response response, Map<String, String> map) throws Exception {
String apikey = checkNotNull(map.get("apikey"));
String text = checkNotNull(request.getParam("text"));
Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("apikey", apikey));
Set<Subscription> subscriptionSet = nabaztag.getSubscribe();
List<ObjectId> objectList = new ArrayList<ObjectId>();
for (Subscription subscription : subscriptionSet) {
objectList.add(new ObjectId(subscription.getObjectId()));
}
List<Nabaztag> nabaztagList = nabaztagDAO.find(nabaztagDAO.createQuery().field("_id").in(objectList)).asList();
for (Nabaztag nab : nabaztagList) {
if (connectionManager.containsKey(nab.getMacAddress())) {
String host = request.request.getHeader("Host");
tts(nab.getMacAddress(), host, "FR", text);
}
}
response.writeJSON("ok");
}
});
}
use of org.jboss.netty.handler.codec.http.DefaultHttpResponse in project NabAlive by jcheype.
the class Response method write.
public void write(ChannelBuffer buffer) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
response.setHeader(HttpHeaders.Names.SERVER, "nuvoos server");
setContentLength(response, buffer.readableBytes());
response.setContent(buffer);
if (isKeepAlive(request)) {
response.setHeader(HttpHeaders.Names.CONNECTION, "Keep-Alive");
}
final ChannelFuture future = ctx.getChannel().write(response);
if (!isKeepAlive(request)) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
Aggregations