Search in sources :

Example 1 with HttpException

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

the class HttpApiServerHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) {
    HttpRequest httpRequest = (HttpRequest) event.getMessage();
    logger.debug("Request: {}", httpRequest);
    QueryStringDecoder qs = new QueryStringDecoder(httpRequest.getUri());
    final Request request = new Request(ctx, httpRequest, qs);
    final Response response = new Response(ctx, httpRequest);
    try {
        execBeforeFilters(request, response);
        execHttpMethod(request, response);
        execAfterFilters(request, response);
    } catch (HttpException e) {
        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, e.getStatus());
        ctx.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE);
    } catch (Exception e) {
        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (logger.isDebugEnabled()) {
            ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer();
            PrintWriter printWriter = new PrintWriter(new ChannelBufferOutputStream(channelBuffer));
            e.printStackTrace(printWriter);
            printWriter.close();
            httpResponse.setContent(channelBuffer);
        }
        logger.error("web server error: ", e);
        ctx.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE);
    }
}
Also used : ChannelBufferOutputStream(org.jboss.netty.buffer.ChannelBufferOutputStream) HttpException(com.nabalive.framework.web.exception.HttpException) HttpException(com.nabalive.framework.web.exception.HttpException) ClosedChannelException(java.nio.channels.ClosedChannelException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) PrintWriter(java.io.PrintWriter)

Example 2 with HttpException

use of com.nabalive.framework.web.exception.HttpException 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 3 with HttpException

use of com.nabalive.framework.web.exception.HttpException 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");
        }
    });
}
Also used : Query(com.google.code.morphia.query.Query) Token(com.nabalive.server.web.Token) HttpException(com.nabalive.framework.web.exception.HttpException) TypeReference(org.codehaus.jackson.type.TypeReference) Route(com.nabalive.framework.web.Route) MongoException(com.mongodb.MongoException) SleepPacket(com.nabalive.server.jabber.packet.SleepPacket) ObjectId(org.bson.types.ObjectId) Request(com.nabalive.framework.web.Request) ParseException(java.text.ParseException) HttpException(com.nabalive.framework.web.exception.HttpException) MongoException(com.mongodb.MongoException) ImmutableMap(com.google.common.collect.ImmutableMap) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Response(com.nabalive.framework.web.Response) UpdateOperations(com.google.code.morphia.query.UpdateOperations) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) ImmutableMap(com.google.common.collect.ImmutableMap) PostConstruct(javax.annotation.PostConstruct)

Example 4 with HttpException

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

the class UserController method init.

@PostConstruct
void init() {
    restHandler.post(new Route("/user/login") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            String email = checkNotNull(request.getParam("email")).toLowerCase();
            String password = checkNotNull(request.getParam("password"));
            User user = checkNotNull(userDAO.findOne("email", email));
            user.checkPassword(password);
            Token token = new Token();
            token.setUserId(user.getId());
            // Map result = new HashMap();
            // result.put("token", TokenUtil.encode(token));
            response.writeJSON(TokenUtil.encode(token));
        }
    }).post(new Route("/user/register") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            String firstname = checkNotNull(request.getParam("firstname"));
            String lastname = checkNotNull(request.getParam("lastname"));
            String email = checkNotNull(request.getParam("email")).toLowerCase();
            String password = checkNotNull(request.getParam("password"));
            User user = new User();
            user.setFirstname(firstname);
            user.setLastname(lastname);
            user.setEmail(email);
            user.setPassword(password);
            userDAO.save(user);
            logger.info("new user: {}", user.getId());
            Token token = new Token();
            token.setUserId(user.getId());
            response.writeJSON(TokenUtil.encode(token));
        }
    }).post(new Route("/user/reset") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            String email = checkNotNull(request.getParam("email")).toLowerCase();
            String uuid = checkNotNull(request.getParam("uuid"));
            String password = checkNotNull(request.getParam("password"));
            User user = checkNotNull(userDAO.findOne("email", email));
            if (uuid.length() > 0 && uuid.equalsIgnoreCase(user.getResetId())) {
                Query<User> query = userDAO.createQuery().filter("_id", user.getId());
                user.setPassword(password);
                userDAO.update(query, userDAO.createUpdateOperations().set("password", user.getPassword()).unset("resetId"));
                response.writeJSON("ok");
            }
            throw new HttpException(HttpResponseStatus.INTERNAL_SERVER_ERROR, "bab reset ID");
        }
    }).get(new Route("/user/reset/mail") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            String email = checkNotNull(request.getParam("email")).toLowerCase();
            User user = checkNotNull(userDAO.findOne("email", email));
            Query<User> query = userDAO.createQuery().filter("_id", user.getId());
            String uuid = UUID.randomUUID().toString();
            userDAO.update(query, userDAO.createUpdateOperations().set("resetId", uuid));
            SendMail.postMail(new String[] { email }, "Reset de mot de passe Nabalive", "http://www.nabalive.com/#reset/" + uuid + "/" + user.getEmail(), "no_reply@nabalive.com");
            response.writeJSON("ok");
        }
    }).get(new Route("/user/info") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            String tokenString = checkNotNull(request.getParamOrHeader("token"));
            Token token = TokenUtil.decode(tokenString, Token.class);
            User user = checkNotNull(userDAO.get(token.getUserId()));
            response.writeJSON(user);
        }
    }).get(new Route("/user/test") {

        @Override
        public void handle(Request request, Response response, Map<String, String> map) throws Exception {
            response.write("ok");
        }
    });
}
Also used : User(com.nabalive.data.core.model.User) Query(com.google.code.morphia.query.Query) Request(com.nabalive.framework.web.Request) Token(com.nabalive.server.web.Token) HttpException(com.nabalive.framework.web.exception.HttpException) Response(com.nabalive.framework.web.Response) HttpException(com.nabalive.framework.web.exception.HttpException) Map(java.util.Map) Route(com.nabalive.framework.web.Route) PostConstruct(javax.annotation.PostConstruct)

Aggregations

HttpException (com.nabalive.framework.web.exception.HttpException)4 Request (com.nabalive.framework.web.Request)3 Response (com.nabalive.framework.web.Response)3 Route (com.nabalive.framework.web.Route)3 PostConstruct (javax.annotation.PostConstruct)3 Query (com.google.code.morphia.query.Query)2 Token (com.nabalive.server.web.Token)2 Map (java.util.Map)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 Nabaztag (com.nabalive.data.core.model.Nabaztag)1 TmpData (com.nabalive.data.core.model.TmpData)1 User (com.nabalive.data.core.model.User)1 SleepPacket (com.nabalive.server.jabber.packet.SleepPacket)1 PrintWriter (java.io.PrintWriter)1 ClosedChannelException (java.nio.channels.ClosedChannelException)1 ParseException (java.text.ParseException)1