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

The following examples show how to use javax.servlet.http.HttpServletResponse#addHeader() . 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
private ActionForward printMarkSheet(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {
    DynaActionForm form = (DynaActionForm) actionForm;
    String markSheetString = form.getString("markSheet");
    MarkSheet markSheet = getDomainObject(form, "markSheet");
    ActionMessages actionMessages = new ActionMessages();

    try (ServletOutputStream writer = response.getOutputStream()) {
        MarkSheetDocument document = new MarkSheetDocument(markSheet);
        byte[] data = ReportsUtils.generateReport(document).getData();
        response.setContentLength(data.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", String.format("attachment; filename=%s.pdf", document.getReportFileName()));
        writer.write(data);
        markAsPrinted(markSheet);
        return null;
    } catch (Exception e) {
        request.setAttribute("markSheet", markSheetString);
        addMessage(request, actionMessages, e.getMessage());
        return choosePrinterMarkSheetsWeb(mapping, actionForm, request, response);
    }
}
 
Example 2
Source Project: flair-engine   File: UserJWTController.java    License: Apache License 2.0 6 votes vote down vote up
@PostMapping("/authenticate")
@Timed
public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());

    try {
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return ResponseEntity.ok(new JWTToken(jwt));
    } catch (AuthenticationException ae) {
        log.info("Authentication exception", ae);
        return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",
            ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
    }
}
 
Example 3
private void writeHeader( HttpServletResponse response )
{
    try
    {
        response.setHeader( "Expires", "Sat, 6 May 1995 12:00:00 GMT" );
        response.setHeader( "Cache-Control", "no-store, no-cache, must-revalidate" );
        response.addHeader( "Cache-Control", "post-check=0, pre-check=0" );
        response.setHeader( "Pragma", "no-cache" );
        response.setHeader( "Content-Type", "application/javascript" );
        response.setHeader( "Connection", "close" );
    }
    catch ( Exception e )
    {
        Log.error( "OFMeetConfig writeHeader Error", e );
    }
}
 
Example 4
@RequestMapping(method = RequestMethod.GET, value = "/publisher-earnings/{id}/invoice")
public  @ResponseBody Object licenceInvoice(@PathVariable("id") long id, HttpServletResponse response) throws Exception {
    Map<String, Object> result = new HashMap<>();
	User user = AuthenticationService.currentActingUser();
	PublisherEarning publisherEarning = PublisherEarning.findByIdAndCompanyId(id, user.getCompany().getId());
	if (publisherEarning != null) {
		response.setContentType("application/pdf");
		response.addHeader("content-disposition", "attachment; filename=invoice_" + publisherEarning.getLicence().getId() + ".pdf");
		licenceInvoiceService.generateOutletInvoice(publisherEarning.getLicence(), response.getOutputStream());
		response.flushBuffer();
		publisherEarning.setInvoiceState(InvoiceState.DOWNLOADED);
		publisherEarning.merge();
		result.put("result", true);
		result.put("message", "");
	}
	return result;
}
 
Example 5
Source Project: smart-framework   File: WebUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 下载文件
 */
public static void downloadFile(HttpServletResponse response, String filePath) {
    try {
        String originalFileName = FilenameUtils.getName(filePath);
        String downloadedFileName = new String(originalFileName.getBytes("GBK"), "ISO8859_1"); // 防止中文乱码

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename=\"" + downloadedFileName + "\"");

        InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        StreamUtil.copyStream(inputStream, outputStream);
    } catch (Exception e) {
        logger.error("下载文件出错!", e);
        throw new RuntimeException(e);
    }
}
 
Example 6
Source Project: openapi-generator   File: ApiUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void setExampleResponse(NativeWebRequest req, String contentType, String example) {
    try {
        HttpServletResponse res = req.getNativeResponse(HttpServletResponse.class);
        res.setCharacterEncoding("UTF-8");
        res.addHeader("Content-Type", contentType);
        res.getWriter().print(example);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
/**
 * exports a sample dataset items a comma delimited file
 * @param dataSetId
 * @param principal
 * @param response
 */

@RequestMapping(value="/example", produces = "text/html")
public void getExampleCsvFile(Principal principal,
							  HttpServletResponse response) {
	try {
		StringBuilder stringBuilder  = new StringBuilder();
		stringBuilder.append(messageSource.getMessage(VALUE_FIELD_NAME_MESSAGE, null, LocaleContextHolder.getLocale()).replace(",", ""));
		stringBuilder.append(",");
		stringBuilder.append(messageSource.getMessage(TEXT_FIELD_NAME_MESSAGE, null, LocaleContextHolder.getLocale()).replace(",", ""));
		stringBuilder.append("\n");
		stringBuilder.append("B,Boston\n");
		stringBuilder.append("N,New York\n");
		//response.setContentType("text/html; charset=utf-8");
		response.setContentType("application/octet-stream");
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Content-Disposition", "inline;filename=datasetExample.csv");
		ServletOutputStream servletOutputStream = response.getOutputStream();
		servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
		servletOutputStream.flush();

	} 

	catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}	

}
 
Example 8
Source Project: DAFramework   File: FileController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(value = "/download/{id}")
	public void downloadFile(@PathVariable Long id,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try{
        	if(id != 0){
        		EFile fileInfo = fileDao.fetch(id);
        		if(fileInfo!= null){
        			String path = fileInfo.getPath();
//        			String suffix = path.split("\\.")[1];
					File file = new File(rootPath+path);
//                    String filename = fileInfo.getName()+"."+suffix;
                    InputStream fis = new BufferedInputStream(new FileInputStream(file));
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    fis.close();
                    response.reset();
                    response.addHeader("Content-Disposition","attachment;filename="
                            + new String(java.net.URLEncoder.encode(fileInfo.getName(), "UTF-8")));
                    response.addHeader("Content-Length","" + file.length());
                    response.setContentType("application/octet-stream");
                    OutputStream toClient = new BufferedOutputStream(
                            response.getOutputStream());
                    toClient.write(buffer);
                    toClient.flush();
                    toClient.close();
        		}
        	}
        }catch(Exception e){
			LOG.error("下载失败,原因:"+e.getMessage());
		}
	}
 
Example 9
protected void respond(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);
    response.setCharacterEncoding(UTF_8.name());
    response.setContentType("text/event-stream");
    // By adding this header, and not closing the connection,
    // we disable HTTP chunking, and we can use write()+flush()
    // to send data in the text/event-stream protocol
    response.addHeader("Connection", "close");
    response.flushBuffer();
}
 
Example 10
@Override
public void commence(final HttpServletRequest request, 
        final HttpServletResponse response, 
        final AuthenticationException authException) throws IOException, ServletException {
    //Authentication failed, send error response.
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
     
    PrintWriter writer = response.getWriter();
    writer.println("HTTP Status 401 : " + authException.getMessage());
}
 
Example 11
/**
 * Creates the Hadoop authentication HTTP cookie.
 *
 * @param token authentication token for the cookie.
 * @param expires UNIX timestamp that indicates the expire date of the
 *                cookie. It has no effect if its value &lt; 0.
 *
 * XXX the following code duplicate some logic in Jetty / Servlet API,
 * because of the fact that Hadoop is stuck at servlet 2.5 and jetty 6
 * right now.
 */
private static void createAuthCookie(HttpServletResponse resp, String token,
                                    String domain, String path, long expires,
                                    boolean isSecure) {
  StringBuilder sb = new StringBuilder(AuthenticatedURL.AUTH_COOKIE)
                         .append("=");
  if (token != null && token.length() > 0) {
    sb.append("\"").append(token).append("\"");
  }

  if (path != null) {
    sb.append("; Path=").append(path);
  }

  if (domain != null) {
    sb.append("; Domain=").append(domain);
  }

  if (expires >= 0) {
    Date date = new Date(expires);
    SimpleDateFormat df = new SimpleDateFormat("EEE, " +
            "dd-MMM-yyyy HH:mm:ss zzz");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    sb.append("; Expires=").append(df.format(date));
  }

  if (isSecure) {
    sb.append("; Secure");
  }

  sb.append("; HttpOnly");
  resp.addHeader("Set-Cookie", sb.toString());
}
 
Example 12
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    HttpServletResponse res = (HttpServletResponse) response;
    res.addHeader("Access-Control-Allow-Origin", "*");
    res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    res.addHeader("Access-Control-Allow-Headers", "Content-Type");
    chain.doFilter(request, response);
}
 
Example 13
Source Project: aem-solr-search   File: ProxyServlet.java    License: Apache License 2.0 5 votes vote down vote up
/** Copy proxied response headers back to the servlet client. */
protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletResponse servletResponse) {
    for (Header header : proxyResponse.getAllHeaders()) {
        if (hopByHopHeaders.containsHeader(header.getName()))
            continue;
        servletResponse.addHeader(header.getName(), header.getValue());
    }
}
 
Example 14
/**
 * Populates the headers in the {@code HttpServletResponse} with the
 * headers supplied by the user.
 */
private void populateHeaders(HttpServletResponse response) {
	// Apply the headers to the response.
	for (Enumeration<?> en = this.headers.propertyNames(); en.hasMoreElements();) {
		String key = (String) en.nextElement();
		response.addHeader(key, this.headers.getProperty(key));
	}
}
 
Example 15
Source Project: javamelody   File: PdfController.java    License: Apache License 2.0 5 votes vote down vote up
void addPdfContentTypeAndDisposition(HttpServletRequest httpRequest,
		HttpServletResponse httpResponse) {
	httpResponse.setContentType("application/pdf");
	final String contentDisposition = encodeFileNameToContentDisposition(httpRequest,
			PdfReport.getFileName(getApplication()));
	// encoding des CRLF pour http://en.wikipedia.org/wiki/HTTP_response_splitting
	httpResponse.addHeader("Content-Disposition",
			contentDisposition.replace('\n', '_').replace('\r', '_'));
}
 
Example 16
protected void handleAccessIcalCommon(HttpServletRequest req, HttpServletResponse res, Reference ref, String calRef)
		throws EntityPermissionException, PermissionException, IOException {

	// Ok so we need to check to see if we've handled this reference before.
	// This is to prevent loops when including calendars
	// that currently includes other calendars we only do the check in here.
	if (getUserAgent().equals(req.getHeader("User-Agent"))) {
		res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		log.warn("Reject internal request for: "+ calRef);
		return;
	}

	// Extract the alias name to use for the filename.
	List<Alias> alias =  m_aliasService.getAliases(calRef);
	String aliasName = "schedule.ics";
	if ( ! alias.isEmpty() )
		aliasName =  alias.get(0).getId();
	
	List<String> referenceList = getCalendarReferences(ref.getContext());
	Time modDate = m_timeService.newTime(0);

	// update date/time reference
	for (String curCalRef: referenceList)
	{
		Calendar curCal = findCalendar(curCalRef);
		/*
		 * TODO: This null check is required to handle the references 
		 * pertaining to external calendar subscriptions as they are 
		 * currently broken in (at least) the 2 following ways:
		 * 
		 * (i) findCalendar will return null rather than a calendar object.
		 * (ii) getCalendar(String) will return a calendar object that is 
		 * not null, but the corresponding getModified() method returns a
		 * date than can not be parsed.  
		 *  
		 * Clearly such references to need to be improved to make them 
		 * consistent with other types as at the moment they have to be
		 * excluded as part of this process to find the most recent modified
		 * date. 
		 */
		if (curCal == null)
		{	
			continue;
		}
		Time curModDate = curCal.getModified();
		if ( curModDate != null && curModDate.after(modDate))
		{
			modDate = curModDate;
		}
	}
	res.addHeader("Content-Disposition", "inline; filename=\"" + aliasName + "\"");
	res.setContentType(ICAL_MIME_TYPE);
	res.setDateHeader("Last-Modified", modDate.getTime() );
	String calendarName = "";
	try {
		calendarName = m_siteService.getSite(ref.getContext()).getTitle();
		boolean isMyDashboard = m_siteService.isUserSite(ref.getContext());
		if (isMyDashboard){
			calendarName = m_serverConfigurationService.getString(UI_SERVICE, SAKAI);
		}
	} catch (IdUnusedException e) {
	}
	printICalSchedule(calendarName, referenceList, res.getOutputStream());
}
 
Example 17
Source Project: nimrod   File: SystemRestController.java    License: MIT License 4 votes vote down vote up
/**
 * 获取验证码
 *
 * @param httpServletResponse HttpServletResponse
 * @param httpServletRequest  HttpServletRequest
 * @throws BaseResponseException BaseResponseException
 */

@OperationLog(value = "获取验证码", type = OperationLogType.API)
@GetMapping(value = "/verify_code")
public void verifyCode(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) throws BaseResponseException {
    long expiration = Long.parseLong((String) dictionaryService.get("VERIFY_CODE", "EXPIRATION"));
    boolean yawp = Boolean.parseBoolean((String) dictionaryService.get("VERIFY_CODE", "YAWP"));
    int stringLength = Integer.parseInt((String) dictionaryService.get("VERIFY_CODE", "STRING_LENGTH"));
    int interLine = Integer.parseInt((String) dictionaryService.get("VERIFY_CODE", "INTER_LINE"));
    String hexBackgroundColor = String.valueOf(dictionaryService.get("VERIFY_CODE", "HEX_BACKGROUND_COLOR"));
    String fontColor = String.valueOf(dictionaryService.get("VERIFY_CODE", "FONT_COLOR"));
    String fontPath = String.valueOf(dictionaryService.get("VERIFY_CODE", "FONT_PATH"));
    stringLength = (stringLength >= 3 && stringLength <= 8) ? stringLength : 4;
    interLine = (interLine >= 1 && interLine <= 8) ? interLine : 0;
    expiration = (expiration >= 20) ? expiration : 60;
    hexBackgroundColor = hexBackgroundColor.length() == 7 ? hexBackgroundColor : "#0064c8";
    fontColor = fontColor.length() == 7 ? fontColor : "#FFFFFF";
    ImageUtil.VerifyCodeImage verifyCodeImage;
    try {

        if (fontPath.toLowerCase().contains(ResourceLoader.CLASSPATH_URL_PREFIX)) {
            Resource fontResource = resourceLoader.getResource(fontPath);
            if (!fontResource.getFile().exists()) {
                throw new BaseResponseException(failureEntity.i18n("system.verify_code_create_fail_font_not_exists"));
            }
            InputStream fontInputStream = fontResource.getInputStream();
            verifyCodeImage = ImageUtil.createVerifyCodeImage(114, 40, ColorUtil.getRGBColorByHexString(hexBackgroundColor), RandomUtil.randomString(stringLength, RandomUtil.NUMBER_LETTER), ColorUtil.getRGBColorByHexString(fontColor), fontInputStream, yawp, interLine, expiration);

        } else {
            URL url = ResourceUtil.getResource(fontPath);
            File fontFile = new File(URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8.name()));
            if (!fontFile.exists()) {
                throw new BaseResponseException(failureEntity.i18n("system.verify_code_create_fail_font_not_exists"));
            }
            verifyCodeImage = ImageUtil.createVerifyCodeImage(114, 40, ColorUtil.getRGBColorByHexString(hexBackgroundColor), RandomUtil.randomString(stringLength, RandomUtil.NUMBER_LETTER), ColorUtil.getRGBColorByHexString(fontColor), fontFile, yawp, interLine, expiration);
        }

        httpServletResponse.addHeader("Pragma", "no-cache");
        httpServletResponse.addHeader("Cache-Control", "no-cache");
        httpServletResponse.addHeader("Expires", "0");
        // 生成验证码,写入用户session
        httpServletRequest.getSession().setAttribute(VERIFY_CODE_NAME, verifyCodeImage);
        // 输出验证码给客户端
        httpServletResponse.setContentType(MediaType.IMAGE_JPEG_VALUE);
        ImageIO.write(verifyCodeImage.getBufferedImage(), "jpg", httpServletResponse.getOutputStream());
    } catch (FontFormatException | IOException e) {
        e.printStackTrace();
        throw new BaseResponseException(failureEntity.i18n("system.verify_code_create_fail"));
    }
}
 
Example 18
Source Project: para   File: CORSFilter.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Handles a CORS request of type {@link CORSRequestType}.SIMPLE.
 *
 * @param request The {@link HttpServletRequest} object.
 * @param response The {@link HttpServletResponse} object.
 * @param filterChain The {@link FilterChain} object.
 * @throws IOException ex
 * @throws ServletException ex
 * @see <a href="http://www.w3.org/TR/cors/#resource-requests">Simple Cross-Origin Request, Actual Request, and
 * Redirects</a>
 */
public void handleSimpleCORS(final HttpServletRequest request,
		final HttpServletResponse response, final FilterChain filterChain)
		throws IOException, ServletException {
	CORSFilter.CORSRequestType requestType
			= checkRequestType(request);
	if (!(requestType == CORSFilter.CORSRequestType.SIMPLE
			|| requestType == CORSFilter.CORSRequestType.ACTUAL)) {
		String message
				= "Expects a HttpServletRequest object of type "
				+ CORSFilter.CORSRequestType.SIMPLE
				+ " or "
				+ CORSFilter.CORSRequestType.ACTUAL;
		throw new IllegalArgumentException(message);
	}

	final String origin
			= request.getHeader(CORSFilter.REQUEST_HEADER_ORIGIN);
	final String method = request.getMethod();

	// Section 6.1.2
	if (!isOriginAllowed(origin)) {
		handleInvalidCORS(request, response, filterChain);
		return;
	}

	if (!allowedHttpMethods.contains(method)) {
		handleInvalidCORS(request, response, filterChain);
		return;
	}

       // Section 6.1.3
	// Add a single Access-Control-Allow-Origin header.
	if (anyOriginAllowed && !supportsCredentials) {
           // If resource doesn't support credentials and if any origin is
		// allowed
		// to make CORS request, return header with '*'.
		response.addHeader(
				CORSFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, "*");
	} else {
           // If the resource supports credentials add a single
		// Access-Control-Allow-Origin header, with the value of the Origin
		// header as value.
		response.addHeader(
				CORSFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN,
				origin);
	}
       // Section 6.1.3
	// If the resource supports credentials, add a single
	// Access-Control-Allow-Credentials header with the case-sensitive
	// string "true" as value.
	if (supportsCredentials) {
		response.addHeader(
				CORSFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS,
				"true");
	}

       // Section 6.1.4
	// If the list of exposed headers is not empty add one or more
	// Access-Control-Expose-Headers headers, with as values the header
	// field names given in the list of exposed headers.
	if ((exposedHeaders != null) && (!exposedHeaders.isEmpty())) {
		String exposedHeadersString = join(exposedHeaders, ",");
		response.addHeader(
				CORSFilter.RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS,
				exposedHeadersString);
	}

	// Forward the request down the filter chain.
	filterChain.doFilter(request, response);
}
 
Example 19
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
    response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer error=\"Insufficient scope\"");
    super.handle(request, response, accessDeniedException);
}
 
Example 20
public void addMyHeader(HttpServletResponse res, String name, String value) {
  name = "X-" + this.getClass().getSimpleName() + "-" + name;
  res.addHeader(name, value);
}