Java Code Examples for javax.servlet.http.HttpServletResponse#setStatus()

The following examples show how to use javax.servlet.http.HttpServletResponse#setStatus() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: batch-scheduler   File: SysConfigController.java    License: MIT License 6 votes vote down vote up
@ApiOperation(value = "更新系统参数", notes = "更新结果只对当前操作的域有效")
@ApiImplicitParams({
        @ApiImplicitParam(required = true, name = "domain_id", value = "域编码"),
        @ApiImplicitParam(required = true, name = "config_id", value = "参数编码"),
        @ApiImplicitParam(required = true, name = "config_value", value = "参数值"),
})
@RequestMapping(value = "/v1/dispatch/config/user", method = RequestMethod.POST)
public String updateConfigValue(HttpServletResponse response, HttpServletRequest request) {
    String domainId = request.getParameter("domain_id");
    String configId = request.getParameter("config_id");
    String configValue = request.getParameter("config_value");

    int size = sysConfigService.setValue(domainId, configId, configValue);
    if (size != 1) {
        response.setStatus(421);
        return Hret.error(421, "更新ETL调度系统核心参数失败", null);
    }
    return Hret.success(200, "success", null);
}
 
Example 2
Source Project: scoold   File: ProfileController.java    License: Apache License 2.0 6 votes vote down vote up
@PostMapping("/{id}/make-mod")
public String makeMod(@PathVariable String id, HttpServletRequest req, HttpServletResponse res) {
	Profile authUser = utils.getAuthUser(req);
	if (!isMyid(authUser, Profile.id(id))) {
		Profile showUser = utils.getParaClient().read(Profile.id(id));
		if (showUser != null) {
			if (utils.isAdmin(authUser) && !utils.isAdmin(showUser)) {
				showUser.setGroups(utils.isMod(showUser) ? USERS.toString() : MODS.toString());
				showUser.update();
			}
		}
	}
	if (utils.isAjaxRequest(req)) {
		res.setStatus(200);
		return "base";
	} else {
		return "redirect:" + PROFILELINK + "/" + id;
	}
}
 
Example 3
Source Project: onedev   File: AttachmentUploadServlet.java    License: MIT License 6 votes vote down vote up
@Sessional
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	String fileName = URLDecoder.decode(request.getHeader("File-Name"), StandardCharsets.UTF_8.name());
	AttachmentSupport attachmentSuppport = (AttachmentSupport) SerializationUtils
			.deserialize(Base64.decodeBase64(request.getHeader("Attachment-Support")));
	try {
		String attachmentName = attachmentSuppport.saveAttachment(fileName, request.getInputStream());
		response.getWriter().print(URLEncoder.encode(attachmentName, StandardCharsets.UTF_8.name()));
		response.setStatus(HttpServletResponse.SC_OK);
	} catch (Exception e) {
		logger.error("Error uploading attachment.", e);
		if (e.getMessage() != null)
			response.getWriter().print(e.getMessage());
		else
			response.getWriter().print("Internal server error");
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
	}
}
 
Example 4
Source Project: oneops   File: PerfController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source Project: batch-scheduler   File: BatchDefineController.java    License: MIT License 6 votes vote down vote up
/**
 * 删除批次
 */
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "删除批次信息")
public String delete(HttpServletResponse response, HttpServletRequest request) {

    String json = request.getParameter("JSON");
    List<BatchDefineEntity> args = new GsonBuilder().create().fromJson(json, new TypeToken<List<BatchDefineEntity>>() {
    }.getType());
    for (BatchDefineEntity m : args) {
        if (BatchStatus.BATCH_STATUS_RUNNING == batchDefineService.getStatus(m.getBatchId())) {
            response.setStatus(421);
            return Hret.error(421, "批次正在运行中,无法被删除", null);
        }
    }

    RetMsg msg = batchDefineService.deleteBatch(args);
    if (msg.checkCode()) {
        return Hret.success(msg);
    }

    response.setStatus(421);
    return Hret.error(msg);
}
 
Example 6
/**
 * Handles If-None-Match header precondition
 *
 * @param request The HTTP request object
 * @param response The servlet response object
 * @param etag The file's ETag
 * @return {@code true} if the If-None-Match header precondition failed (matches the file's ETag), {@code false} otherwise
 */
protected boolean handleIfNoneMatchHeader(HttpServletRequest request, HttpServletResponse response, String etag) {
	String ifNoneMatchHeader = request.getHeader(ProtocolConstants.HEADER_IF_NONE_MATCH);
	if (ifNoneMatchHeader != null && ifNoneMatchHeader.equals(etag)) {
		switch (getMethod(request)) {
			case HEAD :
				// fall through
			case GET :
				response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
				break;
			case DELETE : //see Bug 450014
				return false;
			default :
				response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
				break;
		}
		response.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
		response.setHeader(ProtocolConstants.KEY_ETAG, etag);
		return true;
	}
	return false;
}
 
Example 7
Source Project: fw-cloud-framework   File: ValidateCodeFilter.java    License: MIT License 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {
	if (isValidate
			&& (StringUtils.contains(request.getRequestURI(), SecurityConstant.OAUTH_TOKEN_URL) || StringUtils
					.contains(request.getRequestURI(), SecurityConstant.MOBILE_TOKEN_URL))) {
		PrintWriter printWriter = null;
		try {
			checkCode(request, response, filterChain);
		} catch (ValidateCodeException e) {
			response.setCharacterEncoding(CommonConstant.UTF8);
			response.setContentType(CommonConstant.CONTENT_TYPE);
			R<String> result = new R<String>().failure(e);
			response.setStatus(478);
			printWriter = response.getWriter();
			printWriter.append(objectMapper.writeValueAsString(result));
		} finally {
			IOUtils.closeQuietly(printWriter);
		}
	} else {
		filterChain.doFilter(request, response);
	}
}
 
Example 8
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (!initialized.get()) {
        init(request.getServletContext());
        initialized.set(true);
    }
    String result = validateFormService.refresh(request);
    CrosUtil.setCrosHeader(response);
    response.setContentType("application/json;charset=utf-8");
    response.setStatus(200);
    response.getWriter().write(result);
    response.getWriter().close();
    return;
}
 
Example 9
Source Project: soabase   File: IndexServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String requestURI = ((request.getRequestURI() != null) && (request.getRequestURI().length() > 0)) ? request.getRequestURI() : "/";
    if ( requestURI.startsWith(FORCE) )
    {
        rebuild();
        requestURI = (requestURI.length() > FORCE.length()) ? requestURI.substring(FORCE.length()) : "/";
    }
    else
    {
        int componentManagerVersion = componentManager.getVersion();
        int localBuiltFromVersion = builtFromVersion.get();
        if ( localBuiltFromVersion != componentManagerVersion )
        {
            if ( builtFromVersion.compareAndSet(localBuiltFromVersion, componentManagerVersion) )
            {
                rebuild();
            }
        }
    }

    Entry entry = files.get().get(requestURI);
    if ( entry == null )
    {
        response.setStatus(404);
        return;
    }

    response.setStatus(200);
    response.setContentType("text/html");
    response.setContentLength(entry.content.length());
    response.setCharacterEncoding("UTF-8");
    response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified.get());
    response.setHeader(HttpHeaders.ETAG, entry.eTag);
    response.getWriter().print(entry.content);
}
 
Example 10
@Override
	public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
		httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
//		httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		// 如果这里状态改为HttpServletResponse.SC_UNAUTHORIZED 会导致feign之间调用异常 see https://xujin.org/sc/sc-feign-4xx/
		httpServletResponse.setStatus(HttpServletResponse.SC_OK);
		LogBack.error("用户没有登录时返回给前端的数据");
		JsonData jsonData =  new JsonData(StatusEnum.LOGIN_EXPIRED);
		httpServletResponse.getWriter().write(JsonUtil.toJsonString(jsonData));
	}
 
Example 11
Source Project: SI   File: ClientServlet.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void processDeviceResponse(HttpServletRequest req, HttpServletResponse resp, LwM2mResponse cResponse)
        throws IOException {
    String response = null;
    if (cResponse == null) {
        LOG.warn(String.format("Request %s%s timed out.", req.getServletPath(), req.getPathInfo()));
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().append("Request timeout").flush();
    } else {
        response = this.gson.toJson(cResponse);
        resp.setContentType("application/json");
        resp.getOutputStream().write(response.getBytes());
        resp.setStatus(HttpServletResponse.SC_OK);
    }
}
 
Example 12
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  try {
    String result = contentProvider.getContent();
    resp.setContentType("application/json");
    resp.getWriter().write(result);
  } catch (IOException e) {
    resp.setStatus(500);
    resp.setContentType("application/json");
    resp.getWriter().write("{\"error\":\"" + e.getMessage() + "\"}");
  }
}
 
Example 13
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String requestURI = httpRequest.getRequestURI();

    // Exclude the urls which needn't auth
    if (authFilterExcludeUrls.contains(requestURI)) {
        chain.doFilter(request, response);
        return;
    }

    // Exclude the urls with suffixes which needn't auth
    for (String authFilterExcludeUrlSuffix : authFilterExcludeUrlSuffixes) {
        if (StringUtils.isBlank(authFilterExcludeUrlSuffix)) {
            continue;
        }

        // Add . for url suffix so that we needn't add . in property file
        if (!authFilterExcludeUrlSuffix.startsWith(URL_SUFFIX_DOT)) {
            authFilterExcludeUrlSuffix = URL_SUFFIX_DOT + authFilterExcludeUrlSuffix;
        }

        if (requestURI.endsWith(authFilterExcludeUrlSuffix)) {
            chain.doFilter(request, response);
            return;
        }
    }

    AuthService.AuthUser authUser = authService.getAuthUser(httpRequest);

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    if (authUser == null) {
        // If auth fail, set response status code to 401
        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 14
@Override
public void handle(
    String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
  response.setContentType("text/html;charset=utf-8");
  response.setStatus(HttpServletResponse.SC_OK);
  baseRequest.setHandled(true);
  response.getWriter().println("<h1>Hello World. default handler.</h1>");
}
 
Example 15
Source Project: batch-scheduler   File: JwtService.java    License: MIT License 5 votes vote down vote up
public static void addAuthentication(HttpServletResponse response, String username) throws IOException {
    UserDetailsEntity userDetailsEntity = jwtService.userDetailsService.findById(username);

    if (userDetailsEntity == null) {
        logger.info("用户{}不存在:", username);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // 生成JWT
    String JWT = Jwts.builder().signWith(SignatureAlgorithm.HS256, SECRET)
            .setHeaderParam("alg", "HS256")
            .setHeaderParam("typ", "JWT")
            // 有效期设置
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
            // 用户名写入标题
            .setIssuer("hzwy23")
            .claim("UserId", userDetailsEntity.getUserId())
            .claim("DomainId", userDetailsEntity.getDomainId())
            .claim("OrgUnitId", userDetailsEntity.getOrgUnitId())
            // 保存权限(角色)
            .claim("authorities", JWT_ROLES)
            // 签名设置
            .compact();
    responseJWT(response, JWT);

}
 
Example 16
private void neverReturnAnyResults(Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
    String sessionId = getSessionId(request);
    setHeaders(response, sessionId);
    response.setStatus(responseCode);
    baseRequest.setHandled(true);
    PrintWriter responseWriter = response.getWriter();
    BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    while (reader.readLine() != null) {
        //consume input, not really needed?
    }
    reader.close();
    closeChannel(responseWriter);
}
 
Example 17
@Override
public void onAuthenticationFailure(final HttpServletRequest request,
                                    final HttpServletResponse response,
                                    final AuthenticationException exception) throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("UsernamePasswordAuthenticationFailureHandler:" + exception.getMessage());
    }
    final Response resp = Response.failure(exception.getMessage());
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    response.getWriter().write(objectMapper.writeValueAsString(resp));
}
 
Example 18
Source Project: cloud-service   File: ExceptionHandlerAdvice.java    License: MIT License 5 votes vote down vote up
/**
 * feignClient调用异常,将服务的异常和http状态码解析
 * 
 * @param exception
 * @param response
 * @return
 */
@ExceptionHandler({ FeignException.class })
public Map<String, Object> feignException(FeignException exception, HttpServletResponse response) {
	int httpStatus = exception.status();
	if (httpStatus >= 500) {
		log.error("feignClient调用异常", exception);
	}

	Map<String, Object> data = new HashMap<>();

	String msg = exception.getMessage();

	if (!StringUtils.isEmpty(msg)) {
		int index = msg.indexOf("\n");
		if (index > 0) {
			String string = msg.substring(index);
			if (!StringUtils.isEmpty(string)) {
				JSONObject json = JSONObject.parseObject(string.trim());
				data.putAll(json.getInnerMap());
			}
		}
	}
	if (data.isEmpty()) {
		data.put("message", msg);
	}

	data.put("code", httpStatus + "");

	response.setStatus(httpStatus);

	return data;
}
 
Example 19
@ApiOperation(value = "Create a new decision table deployment", nickname = "uploadDecisionTableDeployment", tags = {
        "Deployment" }, consumes = "multipart/form-data", produces = "application/json", notes = "The request body should contain data of type multipart/form-data. There should be exactly one file in the request, any additional files will be ignored. The deployment name is the name of the file-field passed in. If multiple resources need to be deployed in a single deployment, compress the resources in a zip and make sure the file-name ends with .bar or .zip.\n"
                + "\n"
                + "An additional parameter (form-field) can be passed in the request body with name tenantId. The value of this field will be used as the id of the tenant this deployment is done in.")
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "Indicates the deployment was created."),
        @ApiResponse(code = 400, message = "Indicates there was no content present in the request body or the content mime-type is not supported for deployment. The status-description contains additional information.")
})
@ApiImplicitParams({
    @ApiImplicitParam(name="file", paramType = "form", dataType = "java.io.File")
})
@PostMapping(value = "/dmn-repository/deployments", produces = "application/json", consumes = "multipart/form-data")
public DmnDeploymentResponse uploadDeployment(@ApiParam(name = "tenantId") @RequestParam(value = "tenantId", required = false) String tenantId, HttpServletRequest request, HttpServletResponse response) {

    if (!(request instanceof MultipartHttpServletRequest)) {
        throw new FlowableIllegalArgumentException("Multipart request is required");
    }
    
    if (restApiInterceptor != null) {
        restApiInterceptor.executeNewDeploymentForTenantId(tenantId);
    }

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    if (multipartRequest.getFileMap().size() == 0) {
        throw new FlowableIllegalArgumentException("Multipart request with file content is required");
    }

    MultipartFile file = multipartRequest.getFileMap().values().iterator().next();

    try {
        DmnDeploymentBuilder deploymentBuilder = dmnRepositoryService.createDeployment();
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName) || !DmnResourceUtil.isDmnResource(fileName)) {
            fileName = file.getName();
        }

        if (DmnResourceUtil.isDmnResource(fileName)) {
            deploymentBuilder.addInputStream(fileName, file.getInputStream());
        } else {
            throw new FlowableIllegalArgumentException("File must be of type .dmn");
        }
        deploymentBuilder.name(fileName);

        if (tenantId != null) {
            deploymentBuilder.tenantId(tenantId);
        }

        if (restApiInterceptor != null) {
            restApiInterceptor.enhanceDeployment(deploymentBuilder);
        }

        DmnDeployment deployment = deploymentBuilder.deploy();

        response.setStatus(HttpStatus.CREATED.value());

        return dmnRestResponseFactory.createDmnDeploymentResponse(deployment);

    } catch (Exception e) {
        if (e instanceof FlowableException) {
            throw (FlowableException) e;
        }
        throw new FlowableException(e.getMessage(), e);
    }
}
 
Example 20
private void setStatus(ResponseEntity<byte[]> responseEntity, HttpServletResponse response) {
    response.setStatus(responseEntity.getStatusCodeValue());
}