Search in sources :

Example 11 with Sysprop

use of com.erudika.para.core.Sysprop in project scoold by Erudika.

the class ScooldUtils method sendWelcomeEmail.

public void sendWelcomeEmail(User user, boolean verifyEmail, HttpServletRequest req) {
    // send welcome email notification
    if (user != null) {
        Map<String, Object> model = new HashMap<String, Object>();
        Map<String, String> lang = getLang(req);
        String subject = Utils.formatMessage(lang.get("signin.welcome"), Config.APP_NAME);
        String body1 = Utils.formatMessage(Config.getConfigParam("emails.welcome_text1", lang.get("signin.welcome.body1") + "<br><br>"), Config.APP_NAME);
        String body2 = Config.getConfigParam("emails.welcome_text2", lang.get("signin.welcome.body2") + "<br><br>");
        String body3 = getDefaultEmailSignature(Config.getConfigParam("emails.welcome_text3", lang.get("notification.signature") + "<br><br>"));
        if (verifyEmail && !user.getActive() && !StringUtils.isBlank(user.getIdentifier())) {
            Sysprop s = pc.read(user.getIdentifier());
            if (s != null) {
                String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes());
                s.addProperty(Config._EMAIL_TOKEN, token);
                pc.update(s);
                token = getServerURL() + CONTEXT_PATH + SIGNINLINK + "/register?id=" + user.getId() + "&token=" + token;
                body3 = "<b><a href=\"" + token + "\">" + lang.get("signin.welcome.verify") + "</a></b><br><br>" + body3;
            }
        }
        model.put("subject", escapeHtml(subject));
        model.put("logourl", getSmallLogoUrl());
        model.put("heading", Utils.formatMessage(lang.get("signin.welcome.title"), escapeHtml(user.getName())));
        model.put("body", body1 + body2 + body3);
        emailer.sendEmail(Arrays.asList(user.getEmail()), subject, compileEmailTemplate(model));
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Sysprop(com.erudika.para.core.Sysprop) ParaObject(com.erudika.para.core.ParaObject) ConfigObject(com.typesafe.config.ConfigObject)

Example 12 with Sysprop

use of com.erudika.para.core.Sysprop in project scoold by Erudika.

the class LanguageUtils method readLanguage.

/**
 * Reads localized strings from a file first, then the DB if a file is not found.
 * Returns a map of all translations for a given language.
 * Defaults to the default language which must be set.
 * @param langCode the 2-letter language code
 * @return the language map
 */
public Map<String, String> readLanguage(String langCode) {
    if (StringUtils.isBlank(langCode) || langCode.equals(getDefaultLanguageCode())) {
        return getDefaultLanguage();
    } else if (langCode.length() > 2 && !ALL_LOCALES.containsKey(langCode)) {
        return readLanguage(langCode.substring(0, 2));
    } else if (LANG_CACHE.containsKey(langCode)) {
        return LANG_CACHE.get(langCode);
    }
    // load language map from file
    Map<String, String> lang = readLanguageFromFileAndUpdateProgress(langCode);
    if (lang == null || lang.isEmpty()) {
        // or try to load from DB
        lang = new TreeMap<String, String>(getDefaultLanguage());
        Sysprop s = pc.read(keyPrefix.concat(langCode));
        if (s != null && !s.getProperties().isEmpty()) {
            Map<String, Object> loaded = s.getProperties();
            for (Map.Entry<String, String> entry : lang.entrySet()) {
                if (loaded.containsKey(entry.getKey())) {
                    lang.put(entry.getKey(), String.valueOf(loaded.get(entry.getKey())));
                } else {
                    lang.put(entry.getKey(), entry.getValue());
                }
            }
        }
    }
    LANG_CACHE.put(langCode, lang);
    return Collections.unmodifiableMap(lang);
}
Also used : Sysprop(com.erudika.para.core.Sysprop) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 13 with Sysprop

use of com.erudika.para.core.Sysprop in project scoold by Erudika.

the class ScooldUtils method verifyExistingSpace.

public String verifyExistingSpace(Profile authUser, String space) {
    if (!isDefaultSpace(space) && !isAllSpaces(space)) {
        Sysprop s = pc.read(getSpaceId(space));
        if (s == null) {
            if (authUser != null) {
                authUser.removeSpace(space);
                pc.update(authUser);
            }
            return DEFAULT_SPACE;
        } else {
            // updates current space name in case it was renamed
            return s.getId() + Config.SEPARATOR + s.getName();
        }
    }
    return space;
}
Also used : Sysprop(com.erudika.para.core.Sysprop)

Example 14 with Sysprop

use of com.erudika.para.core.Sysprop in project scoold by Erudika.

the class AdminController method renameSpace.

@PostMapping("/rename-space")
public String renameSpace(@RequestParam String space, @RequestParam String newspace, HttpServletRequest req, HttpServletResponse res) {
    Profile authUser = utils.getAuthUser(req);
    Sysprop s = pc.read(utils.getSpaceId(space));
    if (s != null && utils.isAdmin(authUser)) {
        String origSpace = s.getId() + Config.SEPARATOR + s.getName();
        int index = utils.getAllSpaces().indexOf(s);
        s.setName(newspace);
        pc.update(s);
        if (index >= 0) {
            utils.getAllSpaces().get(index).setName(newspace);
        }
        Pager pager = new Pager(1, "_docid", false, Config.MAX_ITEMS_PER_PAGE);
        LinkedList<Map<String, Object>> toUpdate = new LinkedList<>();
        List<Profile> profiles;
        do {
            String query = "properties.spaces:(\"" + origSpace + "\")";
            profiles = pc.findQuery(Utils.type(Profile.class), query, pager);
            profiles.stream().forEach(p -> {
                p.getSpaces().remove(origSpace);
                p.getSpaces().add(s.getId() + Config.SEPARATOR + s.getName());
                Map<String, Object> profile = new HashMap<>();
                profile.put(Config._ID, p.getId());
                profile.put("spaces", p.getSpaces());
                toUpdate.add(profile);
            });
            if (!toUpdate.isEmpty()) {
                pc.invokePatch("_batch", toUpdate, Map.class);
            }
        } while (!profiles.isEmpty());
    }
    if (utils.isAjaxRequest(req)) {
        res.setStatus(200);
        return "space";
    } else {
        return "redirect:" + ADMINLINK;
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Pager(com.erudika.para.core.utils.Pager) Sysprop(com.erudika.para.core.Sysprop) ParaObject(com.erudika.para.core.ParaObject) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 15 with Sysprop

use of com.erudika.para.core.Sysprop in project scoold by Erudika.

the class AdminController method restore.

@PostMapping("/import")
public String restore(@RequestParam("file") MultipartFile file, @RequestParam(required = false, defaultValue = "false") Boolean isso, HttpServletRequest req, HttpServletResponse res) {
    Profile authUser = utils.getAuthUser(req);
    if (!utils.isAdmin(authUser)) {
        res.setStatus(403);
        return null;
    }
    ObjectReader reader = ParaObjectUtils.getJsonMapper().readerFor(new TypeReference<List<Map<String, Object>>>() {
    });
    Map<String, String> comments2authors = new LinkedHashMap<>();
    int count = 0;
    int importBatchSize = Config.getConfigInt("import_batch_size", 100);
    String filename = file.getOriginalFilename();
    Sysprop s = new Sysprop();
    s.setType("scooldimport");
    try (InputStream inputStream = file.getInputStream()) {
        if (StringUtils.endsWithIgnoreCase(filename, ".zip")) {
            try (ZipInputStream zipIn = new ZipInputStream(inputStream)) {
                ZipEntry zipEntry;
                List<ParaObject> toCreate = new LinkedList<ParaObject>();
                while ((zipEntry = zipIn.getNextEntry()) != null) {
                    if (isso) {
                        count += importFromSOArchive(zipIn, zipEntry, reader, comments2authors).size();
                    } else if (zipEntry.getName().endsWith(".json")) {
                        List<Map<String, Object>> objects = reader.readValue(new FilterInputStream(zipIn) {

                            public void close() throws IOException {
                                zipIn.closeEntry();
                            }
                        });
                        objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
                        if (toCreate.size() >= importBatchSize) {
                            pc.createAll(toCreate);
                            toCreate.clear();
                        }
                        count += objects.size();
                    } else {
                        logger.error("Expected JSON but found unknown file type to import: {}", zipEntry.getName());
                    }
                }
                if (!toCreate.isEmpty()) {
                    pc.createAll(toCreate);
                }
                if (isso) {
                    updateSOCommentAuthors(comments2authors);
                }
            }
        } else if (StringUtils.endsWithIgnoreCase(filename, ".json")) {
            List<Map<String, Object>> objects = reader.readValue(inputStream);
            List<ParaObject> toCreate = new LinkedList<ParaObject>();
            objects.forEach(o -> toCreate.add(ParaObjectUtils.setAnnotatedFields(o)));
            count = objects.size();
            pc.createAll(toCreate);
        }
        s.setCreatorid(authUser.getCreatorid());
        s.setName(authUser.getName());
        s.addProperty("count", count);
        s.addProperty("file", filename);
        logger.info("Imported {} objects to {}. Executed by {}", count, Config.getConfigParam("access_key", "scoold"), authUser.getCreatorid() + " " + authUser.getName());
        if (count > 0) {
            pc.create(s);
        }
    } catch (Exception e) {
        logger.error("Failed to import " + filename, e);
        return "redirect:" + ADMINLINK + "?error=true&imported=" + count;
    }
    return "redirect:" + ADMINLINK + "?success=true&imported=" + count;
}
Also used : SIGNINLINK(com.erudika.scoold.ScooldServer.SIGNINLINK) Question(com.erudika.scoold.core.Question) RequestParam(org.springframework.web.bind.annotation.RequestParam) Arrays(java.util.Arrays) Webhook(com.erudika.para.core.Webhook) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) ParaClient(com.erudika.para.client.ParaClient) StringUtils(org.apache.commons.lang3.StringUtils) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) Model(org.springframework.ui.Model) Locale(java.util.Locale) Map(java.util.Map) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ParseException(java.text.ParseException) Config(com.erudika.para.core.utils.Config) ZipEntry(java.util.zip.ZipEntry) ScooldUtils(com.erudika.scoold.utils.ScooldUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) ParaObject(com.erudika.para.core.ParaObject) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) ConfigValue(com.typesafe.config.ConfigValue) MediaType(org.springframework.http.MediaType) Set(java.util.Set) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) UUID(java.util.UUID) JsonMapper(com.fasterxml.jackson.databind.json.JsonMapper) SignedJWT(com.nimbusds.jwt.SignedJWT) Collectors(java.util.stream.Collectors) Comment(com.erudika.scoold.core.Comment) List(java.util.List) Tag(com.erudika.para.core.Tag) Optional(java.util.Optional) ADMINLINK(com.erudika.scoold.ScooldServer.ADMINLINK) App(com.erudika.para.core.App) Sysprop(com.erudika.para.core.Sysprop) ZipOutputStream(java.util.zip.ZipOutputStream) ParaObjectUtils(com.erudika.para.core.utils.ParaObjectUtils) ZipInputStream(java.util.zip.ZipInputStream) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) Pager(com.erudika.para.core.utils.Pager) Controller(org.springframework.stereotype.Controller) ArrayList(java.util.ArrayList) HOMEPAGE(com.erudika.scoold.ScooldServer.HOMEPAGE) Inject(javax.inject.Inject) LinkedHashMap(java.util.LinkedHashMap) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterInputStream(java.io.FilterInputStream) GetMapping(org.springframework.web.bind.annotation.GetMapping) LinkedList(java.util.LinkedList) Logger(org.slf4j.Logger) Post(com.erudika.scoold.core.Post) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) User(com.erudika.para.core.User) Utils(com.erudika.para.core.utils.Utils) DateUtils(org.apache.commons.lang3.time.DateUtils) TimeUnit(java.util.concurrent.TimeUnit) HttpStatus(org.springframework.http.HttpStatus) Reply(com.erudika.scoold.core.Reply) MultipartFile(org.springframework.web.multipart.MultipartFile) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) Profile(com.erudika.scoold.core.Profile) InputStream(java.io.InputStream) FilterInputStream(java.io.FilterInputStream) ZipInputStream(java.util.zip.ZipInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) Profile(com.erudika.scoold.core.Profile) LinkedList(java.util.LinkedList) ParseException(java.text.ParseException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) ZipInputStream(java.util.zip.ZipInputStream) ParaObject(com.erudika.para.core.ParaObject) Sysprop(com.erudika.para.core.Sysprop) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ParaObject(com.erudika.para.core.ParaObject) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

Sysprop (com.erudika.para.core.Sysprop)32 HashMap (java.util.HashMap)8 PostMapping (org.springframework.web.bind.annotation.PostMapping)8 Map (java.util.Map)6 ParaObject (com.erudika.para.core.ParaObject)5 Profile (com.erudika.scoold.core.Profile)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 LinkedHashMap (java.util.LinkedHashMap)4 Pager (com.erudika.para.core.utils.Pager)3 TreeMap (java.util.TreeMap)3 User (com.erudika.para.core.User)2 ConfigValue (com.typesafe.config.ConfigValue)2 IOException (java.io.IOException)2 LinkedList (java.util.LinkedList)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 ParaClient (com.erudika.para.client.ParaClient)1 App (com.erudika.para.core.App)1 Tag (com.erudika.para.core.Tag)1 Webhook (com.erudika.para.core.Webhook)1 Config (com.erudika.para.core.utils.Config)1