Java 类org.springframework.web.bind.ServletRequestUtils 实例源码

项目:oneops    文件:PerfController.java   
/**
 * Sets the chart.
 *
 * @param request  the request
 * @param response the response
 * @throws Exception the exception
 */
@RequestMapping("/setChart")
public void setChart(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String chartSetJson = ServletRequestUtils.getStringParameter(request, "chartSet");
    Chart[] reqs = gson.fromJson(chartSetJson, Chart[].class);

    long startTime = System.currentTimeMillis();
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < reqs.length; i++) {
        Chart chart = reqs[i];
        if (i > 0) {
            stringBuilder.append(",");
        }
        stringBuilder.append("\"ok\"");
        perfDao.setChart(chart);
    }
    stringBuilder.append("]");

    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    logger.debug(request.getRemoteAddr() + " took " + duration + " ms");

    response.getOutputStream().print(stringBuilder.toString());
    response.setStatus(200);
}
项目:airsonic    文件:SubsonicRESTController.java   
@RequestMapping(path = "/getAlbumInfo")
public void getAlbumInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request = wrapRequest(request);

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");

    MediaFile mediaFile = this.mediaFileService.getMediaFile(id);
    if (mediaFile == null) {
        error(request, response, SubsonicRESTController.ErrorCode.NOT_FOUND, "Media file not found.");
        return;
    }
    AlbumNotes albumNotes = this.lastFmService.getAlbumNotes(mediaFile);

    AlbumInfo result = getAlbumInfoInternal(albumNotes);
    Response res = createResponse();
    res.setAlbumInfo(result);
    this.jaxbWriter.writeResponse(request, response, res);
}
项目:airsonic    文件:SubsonicRESTController.java   
@RequestMapping(path = "/getAlbumInfo2")
public void getAlbumInfo2(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request = wrapRequest(request);

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");

    Album album = this.albumDao.getAlbum(id);
    if (album == null) {
        error(request, response, SubsonicRESTController.ErrorCode.NOT_FOUND, "Album not found.");
        return;
    }
    AlbumNotes albumNotes = this.lastFmService.getAlbumNotes(album);

    AlbumInfo result = getAlbumInfoInternal(albumNotes);
    Response res = createResponse();
    res.setAlbumInfo(result);
    this.jaxbWriter.writeResponse(request, response, res);
}
项目:airsonic    文件:PlaylistController.java   
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<>();

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    User user = securityService.getCurrentUser(request);
    String username = user.getUsername();
    UserSettings userSettings = settingsService.getUserSettings(username);
    Player player = playerService.getPlayer(request, response);
    Playlist playlist = playlistService.getPlaylist(id);
    if (playlist == null) {
        return new ModelAndView(new RedirectView("notFound"));
    }

    map.put("playlist", playlist);
    map.put("user", user);
    map.put("player", player);
    map.put("editAllowed", username.equals(playlist.getUsername()) || securityService.isAdmin(username));
    map.put("partyMode", userSettings.isPartyModeEnabled());

    return new ModelAndView("playlist","model",map);
}
项目:airsonic    文件:AvatarController.java   
private Avatar getAvatar(HttpServletRequest request) {
    String id = request.getParameter("id");
    boolean forceCustom = ServletRequestUtils.getBooleanParameter(request, "forceCustom", false);

    if (id != null) {
        return settingsService.getSystemAvatar(Integer.parseInt(id));
    }

    String username = request.getParameter("username");
    if (username == null) {
        return null;
    }

    UserSettings userSettings = settingsService.getUserSettings(username);
    if (userSettings.getAvatarScheme() == AvatarScheme.CUSTOM || forceCustom) {
        return settingsService.getCustomAvatar(username);
    }
    if(userSettings.getAvatarScheme() == AvatarScheme.NONE) {
        return null;
    }
    return settingsService.getSystemAvatar(userSettings.getSystemAvatarId());
}
项目:airsonic    文件:ExportPlayListController.java   
@RequestMapping(method = { RequestMethod.GET })
public ModelAndView exportPlaylist(HttpServletRequest request, HttpServletResponse response) throws Exception {

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    Playlist playlist = playlistService.getPlaylist(id);
    if (!playlistService.isReadAllowed(playlist, securityService.getCurrentUsername(request))) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;

    }
    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + StringUtil.fileSystemSafe(playlist.getName()) + ".m3u8\"");

    playlistService.exportPlaylist(id, response.getOutputStream());
    return null;
}
项目:airsonic    文件:ChangeCoverArtController.java   
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    String artist = request.getParameter("artist");
    String album = request.getParameter("album");
    MediaFile dir = mediaFileService.getMediaFile(id);

    if (StringUtils.isBlank(artist)) {
        artist = dir.getArtist();
    }
    if (StringUtils.isBlank(album)) {
        album = dir.getAlbumName();
    }

    Map<String, Object> map = new HashMap<>();
    map.put("id", id);
    map.put("artist", artist);
    map.put("album", album);


    return new ModelAndView("changeCoverArt","model",map);
}
项目:airsonic    文件:EditTagsController.java   
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    MediaFile dir = mediaFileService.getMediaFile(id);
    List<MediaFile> files = mediaFileService.getChildrenOf(dir, true, false, true, false);

    Map<String, Object> map = new HashMap<String, Object>();
    if (!files.isEmpty()) {
        map.put("defaultArtist", files.get(0).getArtist());
        map.put("defaultAlbum", files.get(0).getAlbumName());
        map.put("defaultYear", files.get(0).getYear());
        map.put("defaultGenre", files.get(0).getGenre());
    }
    map.put("allGenres", JaudiotaggerParser.getID3V1Genres());

    List<Song> songs = new ArrayList<Song>();
    for (int i = 0; i < files.size(); i++) {
        songs.add(createSong(files.get(i), i));
    }
    map.put("id", id);
    map.put("songs", songs);

    return new ModelAndView("editTags","model",map);
}
项目:airsonic    文件:VideoPlayerController.java   
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    User user = securityService.getCurrentUser(request);
    Map<String, Object> map = new HashMap<String, Object>();
    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    MediaFile file = mediaFileService.getMediaFile(id);
    mediaFileService.populateStarredDate(file, user.getUsername());

    Integer duration = file.getDurationSeconds();
    String playerId = playerService.getPlayer(request, response).getId();
    String url = NetworkService.getBaseUrl(request);
    String streamUrl = url + "stream?id=" + file.getId() + "&player=" + playerId + "&format=mp4";
    String coverArtUrl = url + "coverArt.view?id=" + file.getId();

    map.put("video", file);
    map.put("streamUrl", streamUrl);
    map.put("remoteStreamUrl", streamUrl);
    map.put("remoteCoverArtUrl", coverArtUrl);
    map.put("duration", duration);
    map.put("bitRates", BIT_RATES);
    map.put("defaultBitRate", DEFAULT_BIT_RATE);
    map.put("user", user);

    return new ModelAndView("videoPlayer", "model", map);
}
项目:airsonic    文件:StreamController.java   
private VideoTranscodingSettings createVideoTranscodingSettings(MediaFile file, HttpServletRequest request) throws ServletRequestBindingException {
    Integer existingWidth = file.getWidth();
    Integer existingHeight = file.getHeight();
    Integer maxBitRate = ServletRequestUtils.getIntParameter(request, "maxBitRate");
    int timeOffset = ServletRequestUtils.getIntParameter(request, "timeOffset", 0);
    int defaultDuration = file.getDurationSeconds() == null ? Integer.MAX_VALUE : file.getDurationSeconds() - timeOffset;
    int duration = ServletRequestUtils.getIntParameter(request, "duration", defaultDuration);
    boolean hls = ServletRequestUtils.getBooleanParameter(request, "hls", false);

    Dimension dim = getRequestedVideoSize(request.getParameter("size"));
    if (dim == null) {
        dim = getSuitableVideoSize(existingWidth, existingHeight, maxBitRate);
    }

    return new VideoTranscodingSettings(dim.width, dim.height, timeOffset, duration, hls);
}
项目:oneops    文件:PerfController.java   
/**
 * Gets the perf data.
 *
 * @param request  the request, contains json array of {@link PerfDataRequest}
 * @param response the response, contains json array of tabled results.
 * @return the perf data
 * @throws Exception the exception
 */
@RequestMapping(value = "/getPerfData", method = {GET, POST})
public void getPerfData(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String reqSet = ServletRequestUtils.getStringParameter(request, "reqSet");
    PerfDataRequest[] reqs = gson.fromJson(reqSet, PerfDataRequest[].class);

    long startTime = System.currentTimeMillis();
    StringBuilder bu = new StringBuilder("[ ");
    for (int i = 0; i < reqs.length; i++) {
        PerfDataRequest req = reqs[i];
        if (i > 0) {
            bu.append(",");
        }
        bu.append(perfDataAccessor.getPerfDataSeries(req));
    }
    bu.append("\n]");

    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    logger.debug(request.getRemoteAddr() + " took " + duration + " ms");

    response.getOutputStream().print(bu.toString());
    response.setStatus(200);
}
项目:oneops    文件:PerfController.java   
/**
 * Gets the chart data.
 *
 * @param request  the request
 * @param response the response
 * @return the chart
 * @throws Exception the exception
 */
@RequestMapping("/getChart")
public void getChart(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String chartSetJson = ServletRequestUtils.getStringParameter(request, "chartSet");
    Chart[] reqs = gson.fromJson(chartSetJson, Chart[].class);

    long startTime = System.currentTimeMillis();
    StringBuilder der = new StringBuilder("[");
    for (int i = 0; i < reqs.length; i++) {
        Chart chart = reqs[i];
        if (i > 0) {
            der.append("[");
        }
        chart = perfDao.getChart(chart.getKey());
        der.append(gson.toJson(chart));
    }
    der.append("]");

    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    logger.debug(request.getRemoteAddr() + " took " + duration + " ms");

    response.getOutputStream().print(der.toString());
    response.setStatus(200);
}
项目:mblog    文件:AuthorContentsDirective.java   
@Override
public boolean render(RenderHandler handler) throws RuntimeException, IOException {
    ServletRequest request = handler.getRequest();

    // request 获取参数
       int pn = ServletRequestUtils.getIntParameter(request, "pn", 1);

       // 标签中获取参数
       long uid = handler.getIntParameter(0);
       String alias = handler.getStringParameter(1);

       Paging paging = wrapPaing(pn);
    Paging result = postPlanet.pagingByAuthorId(paging, uid, EnumPrivacy.OPEN);

    handler.put(alias, result);
    handler.doRender();

    postRender(handler.getContext());
    return true;
}
项目:mblog    文件:ContentsDirective.java   
@Override
public boolean render(RenderHandler handler) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException {
    ServletRequest request = handler.getRequest();

    // request 获取参数
       String ord = ServletRequestUtils.getStringParameter(request, "ord", Consts.order.NEWEST);
       int pn = ServletRequestUtils.getIntParameter(request, "pn", 1);

       // 标签中获取参数
       int groupId = handler.getIntParameter(0);
       String alias = handler.getStringParameter(1);

       Paging paging = wrapPaing(pn);
    Paging result = postPlanet.paging(paging, groupId, ord);

    handler.put(alias, result);
    handler.doRender();

    postRender(handler.getContext());
    return true;
}
项目:androidpn-server    文件:NotificationApiController.java   
public void send(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String broadcast = ServletRequestUtils.getStringParameter(request,
                "broadcast", "Y");
        String username = ServletRequestUtils.getStringParameter(request,
                "username");
        String title = ServletRequestUtils.getStringParameter(request, "title");
        String message = ServletRequestUtils.getStringParameter(request,
                "message");
        String uri = ServletRequestUtils.getStringParameter(request, "uri");

        String apiKey = Config.getString("apiKey", "");
        logger.debug("apiKey=" + apiKey);

//      if (broadcast.equalsIgnoreCase("Y")) {
//          notificationManager.sendBroadcast(apiKey, title, message, uri);
//      } else {
//          notificationManager.sendNotifcationToUser(apiKey, username, title,
//                  message, uri, true);
//      }

        response.getWriter().print("{\"result\":\"0\",\"description\":\"success\"}");
//      ModelAndView mav = new ModelAndView();
//      mav.setViewName("redirect:notification.do");
//      return mav;
    }
项目:subsonic    文件:ProxyController.java   
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String url = ServletRequestUtils.getRequiredStringParameter(request, "url");

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
    HttpGet method = new HttpGet(url);

    InputStream in = null;
    try {
        HttpResponse resp = client.execute(method);
        int statusCode = resp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            response.sendError(statusCode);
        } else {
            in = resp.getEntity().getContent();
            IOUtils.copy(in, response.getOutputStream());
        }
    } finally {
        IOUtils.closeQuietly(in);
        client.getConnectionManager().shutdown();
    }
    return null;
}
项目:subsonic    文件:PlaylistController.java   
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    User user = securityService.getCurrentUser(request);
    String username = user.getUsername();
    UserSettings userSettings = settingsService.getUserSettings(username);
    Player player = playerService.getPlayer(request, response);
    Playlist playlist = playlistService.getPlaylist(id);
    if (playlist == null) {
        return new ModelAndView(new RedirectView("notFound.view"));
    }

    map.put("playlist", playlist);
    map.put("user", user);
    map.put("player", player);
    map.put("editAllowed", username.equals(playlist.getUsername()) || securityService.isAdmin(username));
    map.put("partyMode", userSettings.isPartyModeEnabled());

    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}
项目:subsonic    文件:AvatarController.java   
private Avatar getAvatar(HttpServletRequest request) {
    String id = request.getParameter("id");
    boolean forceCustom = ServletRequestUtils.getBooleanParameter(request, "forceCustom", false);

    if (id != null) {
        return settingsService.getSystemAvatar(Integer.parseInt(id));
    }

    String username = request.getParameter("username");
    if (username == null) {
        return null;
    }

    UserSettings userSettings = settingsService.getUserSettings(username);
    if (userSettings.getAvatarScheme() == AvatarScheme.CUSTOM || forceCustom) {
        return settingsService.getCustomAvatar(username);
    }
    return settingsService.getSystemAvatar(userSettings.getSystemAvatarId());
}
项目:subsonic    文件:ChangeCoverArtController.java   
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

    int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
    String artist = request.getParameter("artist");
    String album = request.getParameter("album");
    MediaFile dir = mediaFileService.getMediaFile(id);

    if (artist == null) {
        artist = dir.getArtist();
    }
    if (album == null) {
        album = dir.getAlbumName();
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("id", id);
    map.put("artist", artist);
    map.put("album", album);

    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);

    return result;
}
项目:subsonic    文件:EditTagsController.java   
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

        int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
        MediaFile dir = mediaFileService.getMediaFile(id);
        List<MediaFile> files = mediaFileService.getChildrenOf(dir, true, false, true, false);

        Map<String, Object> map = new HashMap<String, Object>();
        if (!files.isEmpty()) {
            map.put("defaultArtist", files.get(0).getArtist());
            map.put("defaultAlbum", files.get(0).getAlbumName());
            map.put("defaultYear", files.get(0).getYear());
            map.put("defaultGenre", files.get(0).getGenre());
        }
        map.put("allGenres", JaudiotaggerParser.getID3V1Genres());

        List<Song> songs = new ArrayList<Song>();
        for (int i = 0; i < files.size(); i++) {
            songs.add(createSong(files.get(i), i));
        }
        map.put("id", id);
        map.put("songs", songs);

        ModelAndView result = super.handleRequestInternal(request, response);
        result.addObject("model", map);
        return result;
    }
项目:subsonic    文件:StreamController.java   
private VideoTranscodingSettings createVideoTranscodingSettings(MediaFile file, HttpServletRequest request) throws ServletRequestBindingException {
    Integer existingWidth = file.getWidth();
    Integer existingHeight = file.getHeight();
    Integer maxBitRate = ServletRequestUtils.getIntParameter(request, "maxBitRate");
    int timeOffset = ServletRequestUtils.getIntParameter(request, "timeOffset", 0);
    int defaultDuration = file.getDurationSeconds() == null ? Integer.MAX_VALUE : file.getDurationSeconds() - timeOffset;
    int duration = ServletRequestUtils.getIntParameter(request, "duration", defaultDuration);
    boolean hls = ServletRequestUtils.getBooleanParameter(request, "hls", false);

    Dimension dim = getRequestedVideoSize(request.getParameter("size"));
    if (dim == null) {
        dim = getSuitableVideoSize(existingWidth, existingHeight, maxBitRate);
    }

    return new VideoTranscodingSettings(dim.width, dim.height, timeOffset, duration, hls);
}
项目:subsonic    文件:SonosHelper.java   
public String getBaseUrl(HttpServletRequest request) {
    int port = settingsService.getPort();
    String contextPath = settingsService.getUrlRedirectContextPath();

    // Note that the server IP can be overridden by the "ip" parameter. Used when Subsonic and Sonos are
    // on different networks.
    String ip = settingsService.getLocalIpAddress();
    if (request != null) {
        ip = ServletRequestUtils.getStringParameter(request, "ip", ip);
    }

    // Note: Serving media and cover art with http (as opposed to https) works when using jetty and SubsonicDeployer.
    StringBuilder url = new StringBuilder("http://")
            .append(ip)
            .append(":")
            .append(port)
            .append("/");

    if (StringUtils.isNotEmpty(contextPath)) {
        url.append(contextPath).append("/");
    }
    return url.toString();
}
项目:communote-server    文件:RepositoryContentView.java   
/**
 * {@inheritDoc}
 */
@Override
public void render(@SuppressWarnings("rawtypes") Map model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    AttachmentTO content = (AttachmentTO) model.get(MODEL_ATTRIBUTE_BINARY_CONTENT);

    if (content == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {

        content.sendInResponse(request, response, this.characterEncoding,
                ServletRequestUtils.getBooleanParameter(request,
                        DOWNLOAD_PARAMETER, false));
    }
}
项目:communote-server    文件:FollowApiController.java   
/**
 * {@inheritDoc}
 */
@Override
protected Object doPost(ApiResult apiResult, HttpServletRequest request,
        HttpServletResponse response) throws HttpRequestMethodNotSupportedException,
        ApiException {
    boolean isFollowAction = isFollowAction(request);
    Long blogId = ServletRequestUtils.getLongParameter(request, PARAM_BLOG_ID, -1);
    Long userId = ServletRequestUtils.getLongParameter(request, PARAM_USER_ID, -1);
    Long noteId = ServletRequestUtils.getLongParameter(request, PARAM_NOTE_ID, -1);
    Long discussionId = ServletRequestUtils.getLongParameter(request, PARAM_DISCUSSION_ID, -1);
    Long tag = ServletRequestUtils.getLongParameter(request, PARAM_TAG, -1);
    if (blogId == -1 && noteId == -1 && discussionId == -1 && tag == -1 && userId == -1) {
        throw new MissingRequestParameterException(new String[] { PARAM_BLOG_ID, PARAM_NOTE_ID,
                PARAM_DISCUSSION_ID, PARAM_TAG, PARAM_USER_ID }, null);
    }
    if (isFollowAction) {
        doFollow(apiResult, request, blogId, noteId, discussionId, tag, userId);
    } else {
        doUnfollow(apiResult, request, blogId, noteId, discussionId, tag, userId);
    }
    return null;
}
项目:communote-server    文件:UserManagementUserProfileController.java   
/**
 * {@inheritDoc}
 */
@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
    Long userId = ServletRequestUtils.getLongParameter(request, PARAM_USER_ID);
    User user = ServiceLocator.instance().getService(UserManagement.class)
            .findUserByUserId(userId, true);
    Collection<String> tags = new HashSet<String>();
    if (user.getTags() != null) {
        for (Tag tag : user.getTags()) {
            tags.add(tag.getName());
        }
    }
    UserProfileVO profile = ServiceLocator.instance().getService(UserProfileManagement.class)
            .findUserProfileVOByUserId(user.getId());
    Locale locale = SessionHandler.instance().getCurrentLocale(request);
    UserProfileForm userProfileForm = new UserProfileForm(profile, locale.getLanguage(),
            StringUtils.join(tags, ", "), new HashSet<String>());
    setFixedProfileFields(userId, userProfileForm);
    request.setAttribute("userId", user.getId());
    request.setAttribute("userStatus", user.getStatus());
    request.setAttribute("alias", user.getAlias());
    request.setAttribute("isClientManager", SecurityHelper.isClientManager());
    return userProfileForm;
}
项目:move2alf    文件:JobController.java   
@RequestMapping("/job/{jobId}/history")
public ModelAndView history(@PathVariable int jobId,
        HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView();
    int page = ServletRequestUtils.getIntParameter(request, "p", 0);
    int pageSize = 20;

    HistoryPage historyPage = getJobService().getHistory(jobId, page, pageSize);
    PagedListHolder pagedListHolder = new PageHolder(historyPage.getTotalNumberOfResults(), page, pageSize, 10);


    mav.addObject("job", getJobService().getJob(jobId));
    mav.addObject("history", historyPage.getHistoryInfos());
    mav.addObject("pagedListHolder", pagedListHolder);
    mav.addObject("page", page);
    mav.addObject("numberOfPages", historyPage.getNumberOfPages());
    mav.addObject("role", getRole());
    mav.setViewName("history");
    return mav;
}
项目:trivolous    文件:GameController.java   
@RequestMapping(value="/game/image", method=RequestMethod.GET, produces = "image/jpg" )
public void getImage(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    long id = ServletRequestUtils.getLongParameter(request, "id", -1);
    byte[] imageArray = null;

    if (id > 0) {
        imageArray = imageService.getImageById(id);
    }


    if (imageArray != null)
    {
        response.getOutputStream().write(imageArray);
    }
}
项目:openmrs-module-legacyui    文件:ProposeConceptFormController.java   
/**
 * This is called prior to displaying a form for the first time. It tells Spring the
 * form/command object to load into the request
 *
 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
 */
protected Object formBackingObject(HttpServletRequest request) throws ServletException {

    ConceptProposal cp = new ConceptProposal();

    if (Context.isAuthenticated()) {
        ConceptService cs = Context.getConceptService();
        EncounterService es = Context.getEncounterService();
        String id = ServletRequestUtils.getStringParameter(request, "encounterId");
        if (id != null) {
            cp.setEncounter(es.getEncounter(Integer.valueOf(id)));
        }

        id = ServletRequestUtils.getStringParameter(request, "obsConceptId");
        if (id != null) {
            cp.setObsConcept(cs.getConcept(Integer.valueOf(id)));
        }

    }

    return cp;
}
项目:openmrs-module-dataimporttool    文件:DataImportToolStartMigrationController.java   
/**
 * Displays the form to add a DataImportTool(Migration Settings)
 * 
 * @param request
 * @param model
 * @return new ModelAndView
 * @throws ServletRequestBindingException
 */
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm(HttpServletRequest request, ModelMap model) throws ServletRequestBindingException{

    DataImportTool dit;
    Integer Id = ServletRequestUtils.getIntParameter(request, "id");

    if (Id != null) {
        dit = Context.getService(DataImportToolService.class).getDataImportTool();
    } else {
        dit = new DataImportTool();
    }

    model.addAttribute("dit", dit);
    return new ModelAndView("/module/dataimporttool/addMigrationSettings", model);
}
项目:psi-probe    文件:AddQueryParamTag.java   
@Override
public int doStartTag() throws JspException {
  StringBuilder query = new StringBuilder();
  query.append(param).append("=").append(value);
  for (String name : Collections.list(pageContext.getRequest().getParameterNames())) {
    if (!param.equals(name)) {
      query.append("&").append(StringEscapeUtils.escapeHtml4(name)).append("=")
          .append(StringEscapeUtils.escapeHtml4(
              ServletRequestUtils.getStringParameter(pageContext.getRequest(), name, "")));
    }
  }
  try {
    pageContext.getOut().print(query);
  } catch (IOException e) {
    logger.debug("Exception printing query string to JspWriter", e);
    throw new JspException(e);
  }
  return EVAL_BODY_INCLUDE;
}
项目:psi-probe    文件:StandardSeriesProvider.java   
@Override
public void populate(DefaultTableXYDataset dataset, StatsCollection statsCollection,
    HttpServletRequest request) {

  String seriesParam = ServletRequestUtils.getStringParameter(request, "sp", null);
  for (int i = 0; i < statNames.size(); i++) {
    String statName = statNames.get(i);
    if (seriesParam != null) {
      statName = MessageFormat.format(statName, seriesParam);
    }
    List<XYDataItem> stats = statsCollection.getStats(statName);
    if (stats != null) {
      String series =
          ServletRequestUtils.getStringParameter(request, "s" + (i + 1) + "l", "series" + i);
      dataset.addSeries(toSeries(series, stats));
    }
  }
}
项目:psi-probe    文件:ConnectorSeriesProvider.java   
@Override
public void populate(DefaultTableXYDataset dataset, StatsCollection statsCollection,
    HttpServletRequest request) {

  // get Connector name from the request
  String connectorName = ServletRequestUtils.getStringParameter(request, "cn", null);

  // type of statistic to be displayed
  String statType = ServletRequestUtils.getStringParameter(request, "st", null);

  // Series legend
  String series1Legend = ServletRequestUtils.getStringParameter(request, "sl", "");

  if (connectorName != null && statType != null) {
    List<XYDataItem> stats =
        statsCollection.getStats("stat.connector." + connectorName + "." + statType);
    if (stats != null) {
      dataset.addSeries(toSeries(series1Legend, stats));
    }
  }
}
项目:psi-probe    文件:DownloadLogController.java   
@Override
protected ModelAndView handleLogFile(HttpServletRequest request, HttpServletResponse response,
    LogDestination logDest) throws Exception {

  boolean compressed =
      "true".equals(ServletRequestUtils.getStringParameter(request, "compressed"));

  File file = logDest.getFile();
  logger.info("Sending {}{} to {} ({})", file, compressed ? " compressed" : "",
      request.getRemoteAddr(), request.getRemoteUser());
  if (compressed) {
    Utils.sendCompressedFile(response, file);
  } else {
    Utils.sendFile(request, response, file);
  }
  return null;
}
项目:psi-probe    文件:DownloadServletController.java   
@Override
protected ModelAndView handleContext(String contextName, Context context,
    HttpServletRequest request, HttpServletResponse response) throws Exception {

  String jspName = ServletRequestUtils.getStringParameter(request, "source", null);

  if (jspName != null) {
    String servletName =
        getContainerWrapper().getTomcatContainer().getServletFileNameForJsp(context, jspName);
    if (servletName != null) {
      File servletFile = new File(servletName);
      if (servletFile.exists()) {
        Utils.sendFile(request, response, servletFile);
      }
    }
  }
  return null;
}
项目:psi-probe    文件:ViewServletSourceController.java   
@Override
protected ModelAndView handleContext(String contextName, Context context,
    HttpServletRequest request, HttpServletResponse response) throws Exception {

  String jspName = ServletRequestUtils.getStringParameter(request, "source", null);
  ServletContext sctx = context.getServletContext();
  ServletConfig scfg = (ServletConfig) context.findChild("jsp");
  Options opt = new EmbeddedServletOptions(scfg, sctx);
  String encoding = opt.getJavaEncoding();
  String content = null;

  if (jspName != null) {
    String servletName =
        getContainerWrapper().getTomcatContainer().getServletFileNameForJsp(context, jspName);

    if (servletName != null) {
      File servletFile = new File(servletName);
      if (servletFile.exists()) {
        try (FileInputStream fis = new FileInputStream(servletFile)) {
          content = Utils.highlightStream(jspName, fis, "java", encoding);
        }
      }
    }
  }
  return new ModelAndView(getViewName(), "content", content);
}
项目:psi-probe    文件:DisplayJspController.java   
@Override
protected ModelAndView handleContext(String contextName, Context context,
    HttpServletRequest request, HttpServletResponse response) throws Exception {
  boolean compile = ServletRequestUtils.getBooleanParameter(request, "compile", false);

  HttpSession session = request.getSession(false);
  Summary summary = (Summary) session.getAttribute(SUMMARY_ATTRIBUTE);
  if (summary == null || !contextName.equals(summary.getName())) {
    summary = new Summary();
    summary.setName(contextName);
  }
  getContainerWrapper().getTomcatContainer().listContextJsps(context, summary, compile);

  request.getSession(false).setAttribute(SUMMARY_ATTRIBUTE, summary);

  if (compile) {
    return new ModelAndView(new RedirectView(
        request.getRequestURI() + "?webapp=" + (contextName.length() == 0 ? "/" : contextName)));
  }
  return new ModelAndView(getViewName(), "summary", summary);
}
项目:psi-probe    文件:ListSessionAttributesController.java   
@Override
protected ModelAndView handleContext(String contextName, Context context,
    HttpServletRequest request, HttpServletResponse response) throws Exception {

  boolean privileged = SecurityUtils.hasAttributeValueRole(getServletContext(), request);
  boolean calcSize =
      ServletRequestUtils.getBooleanParameter(request, "size", false) && privileged;
  String sid = ServletRequestUtils.getStringParameter(request, "sid");

  ApplicationSession appSession = ApplicationUtils
      .getApplicationSession(context.getManager().findSession(sid), calcSize, true);

  if (appSession != null) {
    appSession.setAllowedToViewValues(privileged);
    return new ModelAndView(getViewName(), "session", appSession);
  }
  return new ModelAndView(getViewName());
}
项目:psi-probe    文件:RememberVisibilityController.java   
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
    HttpServletResponse response) throws Exception {

  String cookieName = ServletRequestUtils.getStringParameter(request, "cn");
  String state = ServletRequestUtils.getStringParameter(request, "state");
  if (cookieName != null && state != null) {
    cookieName = Functions.safeCookieName(cookieName);
    // expire the cookies at the current date + 10years (roughly, nevermind leap years)
    response.addHeader("Set-Cookie",
        cookieName + "=" + state + "; Expires="
            + sdf.format(new Date(System.currentTimeMillis() + 315360000000L))
            + "; Secure=true; HttpOnly=true");
  }
  return null;
}
项目:psi-probe    文件:BaseGetApplicationController.java   
@Override
protected ModelAndView handleContext(String contextName, Context context,
    HttpServletRequest request, HttpServletResponse response) throws Exception {

  boolean calcSize = ServletRequestUtils.getBooleanParameter(request, "size", false)
      && SecurityUtils.hasAttributeValueRole(getServletContext(), request);

  ResourceResolver resourceResolver = getContainerWrapper().getResourceResolver();
  Application app = ApplicationUtils.getApplication(context,
      isExtendedInfo() ? resourceResolver : null, calcSize, getContainerWrapper());

  if (isExtendedInfo() && getStatsCollection() != null) {
    String avgStatisticName = "app.avg_proc_time." + app.getName();
    app.setAvgTime(getStatsCollection().getLastValueForStat(avgStatisticName));
  }

  return new ModelAndView(getViewName()).addObject("app", app)
      .addObject("no_resources", !resourceResolver.supportsPrivateResources())
      .addObject("collectionPeriod", getCollectionPeriod());
}
项目:psi-probe    文件:KillThreadController.java   
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
    HttpServletResponse response) throws Exception {

  String threadName = ServletRequestUtils.getStringParameter(request, "thread", null);

  Thread thread = null;
  if (threadName != null) {
    thread = Utils.getThreadByName(threadName);
  }

  if (thread != null) {
    thread.stop();
  }

  String referer = request.getHeader("Referer");
  String redirectUrl;
  if (referer != null) {
    redirectUrl = referer.replaceAll(replacePattern, "");
  } else {
    redirectUrl = request.getContextPath() + getViewName();
  }
  return new ModelAndView(new RedirectView(redirectUrl));
}