Example usage for javax.servlet.http HttpServletResponse setCharacterEncoding

List of usage examples for javax.servlet.http HttpServletResponse setCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setCharacterEncoding.

Prototype

public void setCharacterEncoding(String charset);

Source Link

Document

Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.

Usage

From source file:com.mengka.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=upload", method = RequestMethod.POST)
public String upload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) {
    response.setCharacterEncoding("utf-8");

    boolean checkSuccess = true;
    String errorMessage = "?";
    if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
        checkSuccess = false;/*from w ww.  j  av  a2s.  c  om*/
        errorMessage = "DataId";
    }
    if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) {
        checkSuccess = false;
        errorMessage = "";
    }
    String content = getContentFromFile(contentFile);
    if (StringUtils.isBlank(content)) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (!checkSuccess) {
        modelMap.addAttribute("message", errorMessage);
        return "/admin/config/upload";
    }

    this.configService.addConfigInfo(dataId, group, content);
    modelMap.addAttribute("message", "???!");
    return listConfig(request, response, dataId, group, 1, 20, modelMap);
}

From source file:cn.leancloud.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=reupload", method = RequestMethod.POST)
public String reupload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) {
    response.setCharacterEncoding("UTF-8");

    boolean checkSuccess = true;
    String errorMessage = "?";
    String content = getContentFromFile(contentFile);
    ConfigInfo configInfo = new ConfigInfo(dataId, group, content);
    if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
        checkSuccess = false;//w  w  w  .jav  a  2 s  . com
        errorMessage = "DataId";
    }
    if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (StringUtils.isBlank(content)) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (!checkSuccess) {
        modelMap.addAttribute("message", errorMessage);
        modelMap.addAttribute("configInfo", configInfo);
        return "/admin/config/edit";
    }

    this.configService.updateConfigInfo(dataId, group, content);

    modelMap.addAttribute("message", "?!");
    return listConfig(request, response, dataId, group, 1, 20, modelMap);
}

From source file:com.taobao.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=reupload", method = RequestMethod.POST)
public String reupload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) {
    response.setCharacterEncoding("GBK");

    boolean checkSuccess = true;
    String errorMessage = "";
    String content = getContentFromFile(contentFile);
    ConfigInfo configInfo = new ConfigInfo(dataId, group, content);
    if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
        checkSuccess = false;//  w  w w.j  a  v  a 2 s .  co m
        errorMessage = "DataId";
    }
    if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (StringUtils.isBlank(content)) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (!checkSuccess) {
        modelMap.addAttribute("message", errorMessage);
        modelMap.addAttribute("configInfo", configInfo);
        return "/admin/config/edit";
    }

    this.configService.updateConfigInfo(dataId, group, content);

    modelMap.addAttribute("message", "!");
    return listConfig(request, response, dataId, group, 1, 20, modelMap);
}

From source file:com.mengka.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=reupload", method = RequestMethod.POST)
public String reupload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("dataId") String dataId, @RequestParam("group") String group,
        @RequestParam("contentFile") MultipartFile contentFile, ModelMap modelMap) {
    response.setCharacterEncoding("utf-8");

    boolean checkSuccess = true;
    String errorMessage = "?";
    String content = getContentFromFile(contentFile);
    ConfigInfo configInfo = new ConfigInfo(dataId, group, content);
    if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId.trim())) {
        checkSuccess = false;//from   w w  w.j a v  a2  s  . c om
        errorMessage = "DataId";
    }
    if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group.trim())) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (StringUtils.isBlank(content)) {
        checkSuccess = false;
        errorMessage = "";
    }
    if (!checkSuccess) {
        modelMap.addAttribute("message", errorMessage);
        modelMap.addAttribute("configInfo", configInfo);
        return "/admin/config/edit";
    }

    this.configService.updateConfigInfo(dataId, group, content);

    modelMap.addAttribute("message", "?!");
    return listConfig(request, response, dataId, group, 1, 20, modelMap);
}

From source file:com.esri.gpt.sdisuite.IntegrationLinkServlet.java

/**
 * Writes characters to the response stream.
 * @param response the servlet response//  w  w  w  .j  a  v  a2 s.c o  m
 * @param content the content to write
 * @param charset the response character encoding 
 * @param contentType the response content type
 * @throws IOException if an IO exception occurs
 */
private void writeCharacterResponse(HttpServletResponse response, String content, String charset,
        String contentType) throws IOException {
    PrintWriter writer = null;
    try {
        if (content.length() > 0) {
            response.setCharacterEncoding(charset);
            response.setContentType(contentType);
            writer = response.getWriter();
            writer.write(content);
            writer.flush();
        }
    } finally {
        try {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        } catch (Exception ef) {
            LOGGER.log(Level.SEVERE, "Error closing PrintWriter.", ef);
        }
    }
}

From source file:it.greenvulcano.gvesb.adapter.http.mapping.RESTHttpServletMapping.java

/**
 * Sets content type and charset header fields of the servlet response.
 * //w  ww  .  ja  v  a2 s.  c om
 * @param resp
 *        An HttpServletResponse object
 * @param contentType
 *        A string containing the declared response's content type
 * @param charset
 *        A string containing the declared response's charset
 */
private void setRespContentTypeAndCharset(HttpServletResponse resp, String contentType, String charset) {
    resp.setContentType(contentType);
    resp.setCharacterEncoding(charset);
}

From source file:com.taobao.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=batchAddOrUpdate", method = RequestMethod.POST)
public String batchAddOrUpdate(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("allDataIdAndContent") String allDataIdAndContent, @RequestParam("group") String group,
        ModelMap modelMap) {// w  w  w  .  java2s  .  c o  m

    response.setCharacterEncoding("GBK");

    // , 500, sdk, sdk500
    if (StringUtils.isBlank(allDataIdAndContent)) {
        throw new IllegalArgumentException(", allDataIdAndContent");
    }
    // group, for
    if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group)) {
        throw new IllegalArgumentException(", group");
    }

    String[] dataIdAndContentArray = allDataIdAndContent.split(Constants.LINE_SEPARATOR);
    group = group.trim();

    List<ConfigInfoEx> configInfoExList = new ArrayList<ConfigInfoEx>();
    for (String dataIdAndContent : dataIdAndContentArray) {
        String dataId = dataIdAndContent.substring(0, dataIdAndContent.indexOf(Constants.WORD_SEPARATOR));
        String content = dataIdAndContent.substring(dataIdAndContent.indexOf(Constants.WORD_SEPARATOR) + 1);
        ConfigInfoEx configInfoEx = new ConfigInfoEx();
        configInfoEx.setDataId(dataId);
        configInfoEx.setGroup(group);
        configInfoEx.setContent(content);

        try {
            // dataId
            if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId)) {
                // , catch, , dataIddataId
                throw new IllegalArgumentException(", dataId");
            }
            // 
            if (StringUtils.isBlank(content)) {
                throw new IllegalArgumentException(", ");
            }

            // 
            ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
            if (configInfo == null) {
                // , 
                this.configService.addConfigInfo(dataId, group, content);
                // , 
                configInfoEx.setStatus(Constants.BATCH_ADD_SUCCESS);
                configInfoEx.setMessage("add success");
            } else {
                // , 
                this.configService.updateConfigInfo(dataId, group, content);
                // , 
                configInfoEx.setStatus(Constants.BATCH_UPDATE_SUCCESS);
                configInfoEx.setMessage("update success");
            }
        } catch (Exception e) {
            log.error(", dataId=" + dataId + ",group=" + group + ",content=" + content, e);
            // , 
            configInfoEx.setStatus(Constants.BATCH_OP_ERROR);
            configInfoEx.setMessage("batch write error: " + e.getMessage());
        }
        configInfoExList.add(configInfoEx);
    }

    String json = null;
    try {
        json = JSONUtils.serializeObject(configInfoExList);
    } catch (Exception e) {
        log.error(", , json=" + json, e);
    }
    modelMap.addAttribute("json", json);

    return "/admin/config/batch_result";
}

From source file:TwitterRetrieval.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out;//from w w  w . jav  a  2 s. c om
    try {

        // img stuff not req'd for source code html showing
        // all links relative
        // XXX
        // making these absolute till we work out the
        // addition of a PathInfo issue

        ConfigurationBuilder cb = new ConfigurationBuilder();
        System.setProperty("twitter4j.http.httpClient", "twitter4j.internal.http.HttpClientImpl");
        cb.setOAuthConsumerKey("56NAE9lQHSOZIGXRktd5Qw")
                .setOAuthConsumerSecret("zJjJrUUs1ubwKjtPOyYzrwBJzpwq7ud8Aryq1VhYH2E")
                .setOAuthAccessTokenURL("https://api.twitter.com/oauth/access_token")
                .setOAuthRequestTokenURL("https://api.twitter.com/oauth/request_token")
                .setOAuthAuthorizationURL("https://api.twitter.com/oauth/authorize")
                .setOAuthAccessToken("234742739-I1l0VGTTjRUbZrfH1jvKnTVFU9ZEvkxxUDpvsAJ2")
                .setOAuthAccessTokenSecret("jLe3imI3JiPgmHCatt6SqYgRAcX5q8s6z38oUrqMc");

        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        Query query = new Query(request.getParameter("q"));

        String tags = request.getParameter("tags");

        String zone = request.getParameter("zone");

        String users = request.getParameter("users");

        Map<String, LatLon> latslongs = new HashMap();

        String[] tagsArray = null;
        if (tags != null) {
            tagsArray = tags.split(",");
        }

        String[] userArray = null;

        if (users != null) {
            userArray = users.split(",");
            int count = userArray.length;
            usuarios = new String[count];
            latitud = new String[count];
            longitud = new String[count];
            for (int i = 0; i < userArray.length; i++) {
                temp = userArray[i];
                if (temp != null) {
                    int hit1 = temp.indexOf("[");
                    int hit2 = temp.indexOf(";");
                    int hit3 = temp.indexOf("]");
                    latslongs.put(temp.substring(0, hit1),
                            new LatLon(temp.substring(hit1 + 1, hit2), temp.substring(hit2 + 1, hit3)));
                    /*
                     * usuarios[i] = temp.substring(0, hit1); latitud[i] =
                     * temp.substring(hit1 + 1, hit2); longitud[i] =
                     * temp.substring(hit2 + 1, hit3);
                     */
                }
            }
        }

        QueryResult result;

        result = twitter.search(query);

        List<Post> postList = new ArrayList();
        List<PostType> postsList = new ArrayList();

        Post solrPost;
        PostType post;
        //List<LinkType> links = new ArrayList();
        List<ActionType> actions;
        ArrayList<User> toUsers = new ArrayList();

        ArrayList<LinkType> links;
        int d;

        InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/servlet.properties");
        Properties props = null;
        if (props == null) {
            props = new Properties();
            props.load(stream);
        }
        ZoneDao zoneDao = new ZoneDao(props.getProperty("db_host"),
                Integer.valueOf(props.getProperty("db_port")), props.getProperty("db_name"));
        PlaceDao placeDao = new PlaceDao(props.getProperty("db_host"),
                Integer.valueOf(props.getProperty("db_port")), props.getProperty("db_name"));
        Place place = null;
        org.zonales.tagsAndZones.objects.Zone zoneObj = zoneDao
                .retrieveByExtendedString(Utils.normalizeZone(zone));

        for (Tweet tweet : (List<Tweet>) result.getTweets()) {
            d = MAX_TITLE_LENGTH;
            actions = new ArrayList();
            try {
                actions.add(new ActionType("retweets", twitter.getRetweets(tweet.getId()).size()));
                actions.add(new ActionType("replies",
                        twitter.getRelatedResults(tweet.getId()).getTweetsWithReply().size()));
            } catch (TwitterException ex) {
                Logger.getLogger(TwitterRetrieval.class.getName()).log(Level.SEVERE,
                        "Error intentando obtener retweets o replies: {0}", new Object[] { ex });
            }

            solrPost = new Post();
            solrPost.setZone(new Zone(String.valueOf(zoneObj.getId()), zoneObj.getName(),
                    zoneObj.getType().getName(), zoneObj.getExtendedString()));
            solrPost.setSource("Twitter");

            solrPost.setId(String.valueOf(tweet.getId()));

            if (request.getParameter(tweet.getFromUser() + "Place") != null) {
                place = placeDao.retrieveByExtendedString(request.getParameter(tweet.getFromUser() + "Place"));
            } else {
                place = null;
            }
            User usersolr = new User(String.valueOf(tweet.getFromUserId()), tweet.getFromUser(),
                    "http://twitter.com/#!/" + tweet.getFromUser(), tweet.getSource(),
                    place != null
                            ? new org.zonales.entities.Place(String.valueOf(place.getId()), place.getName(),
                                    place.getType().getName())
                            : null);

            if (users != null) {
                /*
                 * for (int i = 0; i < usuarios.length; i++) { if
                 * (tweet.getFromUser().equals(usuarios[i])) {
                 * usersolr.setLatitude(Double.parseDouble(latitud[i]));
                 * usersolr.setLongitude(Double.parseDouble(longitud[i])); }
                }
                 */
                //usersolr.setLatitude(Double.parseDouble(latslongs.get(tweet.getFromUser()).latitud));
                //usersolr.setLongitude(Double.parseDouble(latslongs.get(tweet.getFromUser()).longitud));
            }

            solrPost.setFromUser(usersolr);
            if (tweet.getToUser() != null) {
                toUsers.add(new User(String.valueOf(tweet.getToUserId()), tweet.getToUser(), null,
                        tweet.getSource(), null));
                solrPost.setToUsers(toUsers);
            }
            if (tweet.getText().length() > d) {
                while (d > 0 && tweet.getText().charAt(d - 1) != ' ') {
                    d--;
                }
            } else {
                d = tweet.getText().length() - 1;
            }
            solrPost.setTitle(tweet.getText().substring(0, d)
                    + (tweet.getText().length() > MAX_TITLE_LENGTH ? "..." : ""));
            solrPost.setText(tweet.getText());
            //post.setLinks(new LinksType(links));
            solrPost.setActions((ArrayList<ActionType>) actions);
            solrPost.setCreated(tweet.getCreatedAt().getTime());
            solrPost.setModified(tweet.getCreatedAt().getTime());
            solrPost.setRelevance(
                    actions.size() == 2 ? actions.get(0).getCant() * 3 + actions.get(1).getCant() : 0);
            solrPost.setPostLatitude(
                    tweet.getGeoLocation() != null ? tweet.getGeoLocation().getLatitude() : null);
            solrPost.setPostLongitude(
                    tweet.getGeoLocation() != null ? tweet.getGeoLocation().getLongitude() : null);

            links = new ArrayList<LinkType>();
            links.add(new LinkType("avatar", tweet.getProfileImageUrl()));
            if (tweet.getText() != null && getLinks(tweet.getText()) != null) {
                links.addAll(getLinks(tweet.getText()));
            }

            if (solrPost.getLinks() == null) {
                solrPost.setLinks(new ArrayList<LinkType>());
            }
            solrPost.setLinks(links);

            if (tagsArray != null && tagsArray.length > 0) {
                solrPost.setTags(new ArrayList<String>(Arrays.asList(tagsArray)));
            }

            solrPost.setExtendedString(WordUtils.capitalize((solrPost.getFromUser().getPlace() != null
                    ? solrPost.getFromUser().getPlace().getName() + ", "
                    : "") + solrPost.getZone().getExtendedString().replace("_", " ")));
            postList.add(solrPost);

            post = new PostType();
            post.setZone(new Zone(String.valueOf(zoneObj.getId()), zoneObj.getName(),
                    zoneObj.getType().getName(), zoneObj.getExtendedString()));
            post.setSource("Twitter");

            post.setId(String.valueOf(tweet.getId()));
            User user = new User(String.valueOf(tweet.getFromUserId()), tweet.getFromUser(),
                    "http://twitter.com/#!/" + tweet.getFromUser(), tweet.getSource(),
                    place != null
                            ? new org.zonales.entities.Place(String.valueOf(place.getId()), place.getName(),
                                    place.getType().getName())
                            : null);

            if (users != null) {
                /*
                 * for (int i = 0; i < usuarios.length; i++) { if
                 * (tweet.getFromUser().equals(usuarios[i])) {
                 * user.setLatitude(Double.parseDouble(latitud[i]));
                 * user.setLongitude(Double.parseDouble(longitud[i])); }
                }
                 */
                //user.setLatitude(Double.parseDouble(latslongs.get(tweet.getFromUser()).latitud));
                //user.setLongitude(Double.parseDouble(latslongs.get(tweet.getFromUser()).longitud));
            }

            post.setFromUser(user);

            if (tweet.getToUser() != null) {
                toUsers.add(new User(String.valueOf(tweet.getToUserId()), tweet.getToUser(), null,
                        tweet.getSource(), null));
                post.setToUsers(new ToUsersType(toUsers));
            }

            post.setTitle(tweet.getText().substring(0, d)
                    + (tweet.getText().length() > MAX_TITLE_LENGTH ? "..." : ""));
            post.setText(tweet.getText());
            //post.setLinks(new LinksType(links));
            post.setActions(new ActionsType(actions));
            post.setCreated(String.valueOf(tweet.getCreatedAt().getTime()));
            post.setModified(String.valueOf(tweet.getCreatedAt().getTime()));
            post.setRelevance(
                    actions.size() == 2 ? actions.get(0).getCant() * 3 + actions.get(1).getCant() : 0);
            post.setPostLatitude(tweet.getGeoLocation() != null ? tweet.getGeoLocation().getLatitude() : null);
            post.setPostLongitude(
                    tweet.getGeoLocation() != null ? tweet.getGeoLocation().getLongitude() : null);

            links = new ArrayList<LinkType>();
            links.add(new LinkType("avatar", tweet.getProfileImageUrl()));

            post.setLinks(new LinksType(getLinks(tweet.getText())));

            if (tagsArray != null && tagsArray.length > 0) {
                post.setTags(new TagsType(Arrays.asList(tagsArray)));
            }

            postsList.add(post);

        }
        PostsType posts = new PostsType(postsList);
        Gson gson = new Gson();
        if ("xml".equalsIgnoreCase(request.getParameter("format"))) {
            response.setContentType("application/xml");
            out = response.getWriter();
            try {
                for (PostType postIt : posts.getPost()) {
                    postIt.setVerbatim(gson.toJson(postIt));
                }
                Twitter2XML(posts, out);
            } catch (Exception ex) {
                Logger.getLogger(TwitterRetrieval.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            response.setContentType("text/javascript");
            out = response.getWriter();
            out.println("{post: " + gson.toJson(postList) + "}");
        }

    } catch (TwitterException ex) {
        Logger.getLogger(TwitterRetrieval.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:cn.leancloud.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=batchAddOrUpdate", method = RequestMethod.POST)
public String batchAddOrUpdate(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("allDataIdAndContent") String allDataIdAndContent, @RequestParam("group") String group,
        ModelMap modelMap) {/*from   w  w  w  .  j a va2  s.c  om*/

    response.setCharacterEncoding("UTF-8");

    // , 500, sdk, sdk500
    if (StringUtils.isBlank(allDataIdAndContent)) {
        throw new IllegalArgumentException("?, allDataIdAndContent?");
    }
    // group??????, ??for?
    if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group)) {
        throw new IllegalArgumentException("?, group???");
    }

    String[] dataIdAndContentArray = allDataIdAndContent.split(Constants.LINE_SEPARATOR);
    group = group.trim();

    List<ConfigInfoEx> configInfoExList = new ArrayList<ConfigInfoEx>();
    for (String dataIdAndContent : dataIdAndContentArray) {
        String dataId = dataIdAndContent.substring(0, dataIdAndContent.indexOf(Constants.WORD_SEPARATOR));
        String content = dataIdAndContent.substring(dataIdAndContent.indexOf(Constants.WORD_SEPARATOR) + 1);
        ConfigInfoEx configInfoEx = new ConfigInfoEx();
        configInfoEx.setDataId(dataId);
        configInfoEx.setGroup(group);
        configInfoEx.setContent(content);

        try {
            // dataId???
            if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId)) {
                // , ?catch, ??, ??dataId??dataId
                throw new IllegalArgumentException("?, dataId???");
            }
            // ?
            if (StringUtils.isBlank(content)) {
                throw new IllegalArgumentException("?, ?");
            }

            // ?
            ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
            if (configInfo == null) {
                // ??, 
                this.configService.addConfigInfo(dataId, group, content);
                // ?, ??
                configInfoEx.setStatus(Constants.BATCH_ADD_SUCCESS);
                configInfoEx.setMessage("add success");
            } else {
                // ?, 
                this.configService.updateConfigInfo(dataId, group, content);
                // ?, ??
                configInfoEx.setStatus(Constants.BATCH_UPDATE_SUCCESS);
                configInfoEx.setMessage("update success");
            }
        } catch (Exception e) {
            log.error("???, dataId=" + dataId + ",group=" + group + ",content="
                    + content, e);
            // , ??
            configInfoEx.setStatus(Constants.BATCH_OP_ERROR);
            configInfoEx.setMessage("batch write error: " + e.getMessage());
        }
        configInfoExList.add(configInfoEx);
    }

    String json = null;
    try {
        json = JSONUtils.serializeObject(configInfoExList);
    } catch (Exception e) {
        log.error("?, ?, json=" + json, e);
    }
    modelMap.addAttribute("json", json);

    return "/admin/config/batch_result";
}

From source file:com.mengka.diamond.server.controller.AdminController.java

@RequestMapping(params = "method=batchAddOrUpdate", method = RequestMethod.POST)
public String batchAddOrUpdate(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("allDataIdAndContent") String allDataIdAndContent, @RequestParam("group") String group,
        ModelMap modelMap) {//from  ww  w. j  ava  2 s  .c  om

    response.setCharacterEncoding("utf-8");

    // , 500, sdk, sdk500
    if (StringUtils.isBlank(allDataIdAndContent)) {
        throw new IllegalArgumentException("?, allDataIdAndContent?");
    }
    // group??????, ??for?
    if (StringUtils.isBlank(group) || DiamondUtils.hasInvalidChar(group)) {
        throw new IllegalArgumentException("?, group???");
    }

    String[] dataIdAndContentArray = allDataIdAndContent.split(Constants.LINE_SEPARATOR);
    group = group.trim();

    List<ConfigInfoEx> configInfoExList = new ArrayList<ConfigInfoEx>();
    for (String dataIdAndContent : dataIdAndContentArray) {
        String dataId = dataIdAndContent.substring(0, dataIdAndContent.indexOf(Constants.WORD_SEPARATOR));
        String content = dataIdAndContent.substring(dataIdAndContent.indexOf(Constants.WORD_SEPARATOR) + 1);
        ConfigInfoEx configInfoEx = new ConfigInfoEx();
        configInfoEx.setDataId(dataId);
        configInfoEx.setGroup(group);
        configInfoEx.setContent(content);

        try {
            // dataId???
            if (StringUtils.isBlank(dataId) || DiamondUtils.hasInvalidChar(dataId)) {
                // , ?catch, ??, ??dataId??dataId
                throw new IllegalArgumentException("?, dataId???");
            }
            // ?
            if (StringUtils.isBlank(content)) {
                throw new IllegalArgumentException("?, ?");
            }

            // ?
            ConfigInfo configInfo = this.configService.findConfigInfo(dataId, group);
            if (configInfo == null) {
                // ??, 
                this.configService.addConfigInfo(dataId, group, content);
                // ?, ??
                configInfoEx.setStatus(Constants.BATCH_ADD_SUCCESS);
                configInfoEx.setMessage("add success");
            } else {
                // ?, 
                this.configService.updateConfigInfo(dataId, group, content);
                // ?, ??
                configInfoEx.setStatus(Constants.BATCH_UPDATE_SUCCESS);
                configInfoEx.setMessage("update success");
            }
        } catch (Exception e) {
            log.error("???, dataId=" + dataId + ",group=" + group + ",content="
                    + content, e);
            // , ??
            configInfoEx.setStatus(Constants.BATCH_OP_ERROR);
            configInfoEx.setMessage("batch write error: " + e.getMessage());
        }
        configInfoExList.add(configInfoEx);
    }

    String json = null;
    try {
        json = JSONUtils.serializeObject(configInfoExList);
    } catch (Exception e) {
        log.error("?, ?, json=" + json, e);
    }
    modelMap.addAttribute("json", json);

    return "/admin/config/batch_result";
}