Search in sources :

Example 1 with Request

use of com.nabalive.framework.web.Request in project NabAlive by jcheype.

the class ChorController method init.

@PostConstruct
void init() {
    restHandler.get(new Route("/api/chor") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            String chor = checkNotNull(request.getParam("data"));
            int loop = Integer.parseInt(firstNonNull(request.getParam("loop"), "1"));
            ChorBuilder chorBuilder = new ChorBuilder(chor, loop);
            response.write(chorBuilder.build());
        }
    }).get(new Route("/api/chor/ears") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            ChorBuilder chorBuilder = new ChorBuilder();
            String left = request.getParam("left");
            String right = request.getParam("right");
            if (left != null) {
                int val = Integer.parseInt(left);
                chorBuilder.setEar((byte) 0, (byte) (val > 0 ? 0 : 1), (byte) Math.abs(val));
            }
            if (right != null) {
                int val = Integer.parseInt(right);
                chorBuilder.setEar((byte) 1, (byte) (val > 0 ? 0 : 1), (byte) Math.abs(val));
            }
            response.write(chorBuilder.build());
        }
    }).get(new Route("/api/chor/led/:led/:color") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            ChorBuilder chorBuilder = new ChorBuilder();
            String color = checkNotNull(map.get("color"));
            int led = Integer.parseInt(checkNotNull(map.get("led")));
            chorBuilder.setLed((byte) led, color);
            response.write(chorBuilder.build());
        }
    }).get(new Route("/api/chor/rand/:time") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            int time = Integer.parseInt(map.get("time"));
            Random rand = new Random();
            ChorBuilder chorBuilder = new ChorBuilder();
            for (int t = 0; t < time; t++) {
                for (int led = 0; led < 5; led++) if (rand.nextBoolean()) {
                    chorBuilder.setLed((byte) led, (byte) rand.nextInt(), (byte) rand.nextInt(), (byte) rand.nextInt());
                }
                if (t % 10 == 0) {
                    if (rand.nextBoolean()) {
                        chorBuilder.setEar((byte) 0, (byte) (rand.nextBoolean() ? 0 : 1), (byte) rand.nextInt(0x4));
                    }
                    if (rand.nextBoolean()) {
                        chorBuilder.setEar((byte) 1, (byte) (rand.nextBoolean() ? 0 : 1), (byte) rand.nextInt(0x4));
                    }
                }
                chorBuilder.waitChor(1);
            }
            chorBuilder.setEar((byte) 1, (byte) 0, (byte) 0);
            chorBuilder.setEar((byte) 0, (byte) 0, (byte) 0);
            response.write(chorBuilder.build());
        }
    });
}
Also used : Response(com.nabalive.framework.web.Response) Random(java.util.Random) Request(com.nabalive.framework.web.Request) ChorBuilder(com.nabalive.server.web.ChorBuilder) Map(java.util.Map) Route(com.nabalive.framework.web.Route) PostConstruct(javax.annotation.PostConstruct)

Example 2 with Request

use of com.nabalive.framework.web.Request in project NabAlive by jcheype.

the class LocateController method init.

//private final Pattern domainPattern = Pattern.compile("([^:]+)");
@PostConstruct
void init() {
    restHandler.get(new Route(".*/locate.jsp") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            StringBuilder sb = new StringBuilder();
            sb.append("ping " + HOST + "\n");
            sb.append("broad " + HOST + "\n");
            if (XMPP_PORT != null)
                sb.append("xmpp_domain " + HOST + ":" + XMPP_PORT + "\n");
            else
                sb.append("xmpp_domain " + HOST + "\n");
            response.write(sb.toString());
        }
    }).get(new Route(".*/bc.jsp") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            InputStream resourceAsStream = getClass().getResourceAsStream("/bc.jsp");
            response.write(ByteStreams.toByteArray(resourceAsStream));
        }
    });
}
Also used : DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Response(com.nabalive.framework.web.Response) InputStream(java.io.InputStream) Request(com.nabalive.framework.web.Request) Map(java.util.Map) Route(com.nabalive.framework.web.Route) PostConstruct(javax.annotation.PostConstruct)

Example 3 with Request

use of com.nabalive.framework.web.Request in project NabAlive by jcheype.

the class RecordController method init.

@PostConstruct
void init() {
    restHandler.post(new Route("/vl/record.jsp") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            String mac = checkNotNull(request.getParam("sn")).toLowerCase();
            if (!connectionManager.containsKey(mac))
                throw new HttpException(HttpResponseStatus.NOT_FOUND, "sn is not connected");
            Nabaztag nabaztag = checkNotNull(nabaztagDAO.findOne("macAddress", mac));
            ChannelBuffer content = request.request.getContent();
            logger.debug("record orig size: {}", content.readableBytes());
            ChannelBufferInputStream inputStream = new ChannelBufferInputStream(content);
            TmpData sound = new TmpData();
            sound.setData(ByteStreams.toByteArray(inputStream));
            tmpDataDAO.save(sound, WriteConcern.SAFE);
            String host = request.request.getHeader("Host");
            String url = "http://" + host + "/record/" + sound.getId().toString();
            logger.debug("sound url: {}", url);
            final String command = "ST " + url + "\nMW\n";
            Query<Nabaztag> query = nabaztagDAO.createQuery();
            query.filter("subscribe.objectId", nabaztag.getId().toString());
            List<Nabaztag> nabaztags = nabaztagDAO.find(query).asList();
            logger.debug("sending to {} subscribers", nabaztags.size());
            for (Nabaztag nab : nabaztags) {
                if (connectionManager.containsKey(nab.getMacAddress())) {
                    final Nabaztag nabTmp = nab;
                    Runnable runnable = new Runnable() {

                        @Override
                        public void run() {
                            logger.debug("sending to {}", nabTmp.getMacAddress());
                            logger.debug("command {}", command);
                            messageService.sendMessage(nabTmp.getMacAddress(), command);
                        }
                    };
                    ses.schedule(runnable, 500, TimeUnit.MILLISECONDS);
                }
            }
            response.write("ok");
        }
    }).get(new Route("/record/:recordId") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            ObjectId recordId = new ObjectId(checkNotNull(map.get("recordId")));
            TmpData sound = checkNotNull(tmpDataDAO.get(recordId));
            response.write(sound.getData());
        }
    });
}
Also used : ObjectId(org.bson.types.ObjectId) Request(com.nabalive.framework.web.Request) HttpException(com.nabalive.framework.web.exception.HttpException) ExecutionException(java.util.concurrent.ExecutionException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) Response(com.nabalive.framework.web.Response) Nabaztag(com.nabalive.data.core.model.Nabaztag) TmpData(com.nabalive.data.core.model.TmpData) HttpException(com.nabalive.framework.web.exception.HttpException) ChannelBufferInputStream(org.jboss.netty.buffer.ChannelBufferInputStream) Map(java.util.Map) Route(com.nabalive.framework.web.Route) PostConstruct(javax.annotation.PostConstruct)

Example 4 with Request

use of com.nabalive.framework.web.Request in project NabAlive by jcheype.

the class TtsController method init.

@PostConstruct
void init() {
    restHandler.get(new Route("/tts/:apikey/:voice") {

        @Override
        public void handle(Request request, final Response response, Map<String, String> map) throws Exception {
            String text = StringEscapeUtils.escapeXml(checkNotNull(request.getParam("text")));
            String voice = checkNotNull(map.get("voice"));
            if (!text.startsWith("<s>")) {
                text = "<s>" + text + "</s>";
            }
            final String key = text + "|" + voice;
            byte[] bytes = ttsCache.asMap().get(key);
            if (bytes != null) {
                response.write(ChannelBuffers.copiedBuffer(bytes));
                return;
            }
            asyncHttpClient.preparePost(frenchTtsUrl).setBody(text).execute(new AsyncCompletionHandler<com.ning.http.client.Response>() {

                @Override
                public com.ning.http.client.Response onCompleted(com.ning.http.client.Response asyncResponse) throws Exception {
                    InputStream inputStream = asyncResponse.getResponseBodyAsStream();
                    byte[] bytes = ByteStreams.toByteArray(inputStream);
                    ttsCache.asMap().put(key, bytes);
                    response.write(bytes);
                    return asyncResponse;
                }

                @Override
                public void onThrowable(Throwable t) {
                    logger.error("TTS error", t);
                    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    response.write(httpResponse);
                }
            });
        }
    }).get(new Route("/tts/:voice") {

        @Override
        public void handle(Request request, final Response response, Map<String, String> map) throws Exception {
            String text = StringEscapeUtils.escapeXml(checkNotNull(request.getParam("text")));
            String voice = checkNotNull(map.get("voice"));
            if (!text.startsWith("<s>")) {
                text = "<s>" + text + "</s>";
            }
            final String key = text + "|" + voice;
            byte[] bytes = ttsCache.asMap().get(key);
            if (bytes != null) {
                response.write(ChannelBuffers.copiedBuffer(bytes));
                return;
            }
            asyncHttpClient.preparePost(frenchTtsUrl).setBody(text).execute(new AsyncCompletionHandler<com.ning.http.client.Response>() {

                @Override
                public com.ning.http.client.Response onCompleted(com.ning.http.client.Response asyncResponse) throws Exception {
                    InputStream inputStream = asyncResponse.getResponseBodyAsStream();
                    byte[] bytes = ByteStreams.toByteArray(inputStream);
                    ttsCache.asMap().put(key, bytes);
                    response.write(bytes);
                    return asyncResponse;
                }

                @Override
                public void onThrowable(Throwable t) {
                    logger.error("TTS error", t);
                    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    response.write(httpResponse);
                }
            });
        }
    });
}
Also used : InputStream(java.io.InputStream) Request(com.nabalive.framework.web.Request) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Response(com.nabalive.framework.web.Response) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) AsyncCompletionHandler(com.ning.http.client.AsyncCompletionHandler) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Map(java.util.Map) Route(com.nabalive.framework.web.Route) PostConstruct(javax.annotation.PostConstruct)

Example 5 with Request

use of com.nabalive.framework.web.Request 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);
//                    }
//                })
}
Also used : Request(com.nabalive.framework.web.Request) ApplicationLogo(com.nabalive.data.core.model.ApplicationLogo) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Response(com.nabalive.framework.web.Response) ApplicationStore(com.nabalive.data.core.model.ApplicationStore) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Map(java.util.Map) Route(com.nabalive.framework.web.Route) PostConstruct(javax.annotation.PostConstruct)

Aggregations

Request (com.nabalive.framework.web.Request)7 Response (com.nabalive.framework.web.Response)7 Route (com.nabalive.framework.web.Route)7 PostConstruct (javax.annotation.PostConstruct)7 Map (java.util.Map)6 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)4 HttpException (com.nabalive.framework.web.exception.HttpException)3 Query (com.google.code.morphia.query.Query)2 Token (com.nabalive.server.web.Token)2 InputStream (java.io.InputStream)2 ObjectId (org.bson.types.ObjectId)2 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)2 UpdateOperations (com.google.code.morphia.query.UpdateOperations)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 MongoException (com.mongodb.MongoException)1 ApplicationLogo (com.nabalive.data.core.model.ApplicationLogo)1 ApplicationStore (com.nabalive.data.core.model.ApplicationStore)1 Nabaztag (com.nabalive.data.core.model.Nabaztag)1 TmpData (com.nabalive.data.core.model.TmpData)1 User (com.nabalive.data.core.model.User)1