Java Code Examples for javax.servlet.ServletOutputStream

The following examples show how to use javax.servlet.ServletOutputStream. 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 want to check out the right sidebar which shows the related API usage.
Example 1
public void createAppDefinitionBar(HttpServletResponse response, Model appModel, AppDefinitionRepresentation appDefinition) {

        try {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + appDefinition.getName() + ".bar\"; filename*=utf-8''" + UriUtils.encode(appDefinition.getName() + ".bar", "utf-8"));

            byte[] deployZipArtifact = createDeployableZipArtifact(appModel, appDefinition.getDefinition());

            ServletOutputStream servletOutputStream = response.getOutputStream();
            response.setContentType("application/zip");
            servletOutputStream.write(deployZipArtifact);

            // Flush and close stream
            servletOutputStream.flush();
            servletOutputStream.close();

        } catch (Exception e) {
            LOGGER.error("Could not generate app definition bar archive", e);
            throw new InternalServerErrorException("Could not generate app definition bar archive");
        }
    }
 
Example 2
private void exportToXls(String filename) throws IOException {
    this.getResponse().setContentType("application/vnd.ms-excel");
    this.getResponse().setHeader("Content-disposition", "attachment; filename=" + filename + ".xls");
    ServletOutputStream outputStream = this.getResponse().getOutputStream();

    String spreadSheetName = BundleUtil.getString(Bundle.APPLICATION, "title.enrolments");
    List<Object> headers = getStudentsEnroledListHeaders();
    Spreadsheet spreadsheet = new Spreadsheet(spreadSheetName, headers);

    reportInfo(spreadsheet);

    spreadsheet.exportToXLSSheet(outputStream);
    outputStream.flush();
    this.getResponse().flushBuffer();
    FacesContext.getCurrentInstance().responseComplete();
}
 
Example 3
Source Project: app-engine   Source File: ResponseWrapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ServletOutputStream getOutputStream() throws IOException {
    return new ServletOutputStream() {
        private TeeOutputStream tee = new TeeOutputStream(ResponseWrapper.super.getOutputStream(), bos);

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            tee.write(b);
        }
    };
}
 
Example 4
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 5
Source Project: flowable-engine   Source File: IdmProfileResource.java    License: Apache License 2.0 6 votes vote down vote up
@GetMapping(value = "/profile-picture")
public void getProfilePicture(HttpServletResponse response) {
    try {
        Pair<String, InputStream> picture = profileService.getProfilePicture();
        if (picture == null) {
            throw new NotFoundException();
        }
        response.setContentType(picture.getLeft());
        ServletOutputStream servletOutputStream = response.getOutputStream();

        byte[] buffer = new byte[32384];
        while (true) {
            int count = picture.getRight().read(buffer);
            if (count == -1)
                break;
            servletOutputStream.write(buffer, 0, count);
        }

        // Flush and close stream
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (Exception e) {
        throw new InternalServerErrorException("Could not get profile picture", e);
    }
}
 
Example 6
Source Project: taoshop   Source File: CodeController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping("/generate")
	public void generate(HttpServletRequest request, HttpServletResponse response){
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = drawImg(output);

//		Subject currentUser = SecurityUtils.getSubject();
//		Session session = currentUser.getSession();
		HttpSession session = request.getSession();
		session.setAttribute(SESSION_SECURITY_CODE, code);

		try {
			ServletOutputStream out = response.getOutputStream();
			output.writeTo(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
Example 7
Source Project: eladmin   Source File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 导出excel
 */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
    String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
    File file = new File(tempPath);
    BigExcelWriter writer = ExcelUtil.getBigWriter(file);
    // 一次性写出内容,使用默认样式,强制输出标题
    writer.write(list, true);
    //response为HttpServletResponse对象
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
    response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
    ServletOutputStream out = response.getOutputStream();
    // 终止后删除临时文件
    file.deleteOnExit();
    writer.flush(out, true);
    //此处记得关闭输出Servlet流
    IoUtil.close(out);
}
 
Example 8
public ActionForward downloadInconsistencies(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) {
    final ExecutionSemester executionSemester = getDomainObject(request, "executionSemesterOid");
    final CourseLoadOverviewBean bean = new CourseLoadOverviewBean(executionSemester);
    final StyledExcelSpreadsheet spreadsheet = bean.getInconsistencySpreadsheet();

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition",
            "attachment; filename=" + BundleUtil.getString(Bundle.ACADEMIC, "label.course.load.inconsistency.filename")
                    + ".xls");

    try {
        final ServletOutputStream writer = response.getOutputStream();
        spreadsheet.getWorkbook().write(writer);
        writer.close();
    } catch (final IOException e) {
        throw new Error(e);
    }

    return null;
}
 
Example 9
Source Project: olat   Source File: DefaultServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an
 * exception).
 * 
 * @param istream
 *            The input stream to read from
 * @param ostream
 *            The output stream to write to
 * @return Exception which occurred during processing
 */
private IOException copyRange(InputStream istream, ServletOutputStream ostream) {

    // Copy the input stream to the output stream
    IOException exception = null;
    byte buffer[] = new byte[input];
    int len = buffer.length;
    while (true) {
        try {
            len = istream.read(buffer);
            if (len == -1)
                break;
            ostream.write(buffer, 0, len);
        } catch (IOException e) {
            exception = e;
            len = -1;
            break;
        }
    }
    return exception;

}
 
Example 10
Source Project: vraptor4   Source File: InputStreamDownloadTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	MockitoAnnotations.initMocks(this);
	
	bytes = new byte[] { (byte) 0x0 };
	inputStream = new ByteArrayInputStream(bytes);
	outputStream = new ByteArrayOutputStream();

	socketStream = new ServletOutputStream() {
		@Override
		public void write(int b) throws IOException {
			outputStream.write(b);
		}

		@Override
		public boolean isReady() {
			return false;
		}

		@Override
		public void setWriteListener(WriteListener writeListener) {
		}
	};

	when(response.getOutputStream()).thenReturn(socketStream);
}
 
Example 11
Source Project: Tomcat8-Source-Read   Source File: TestCoyoteOutputStream.java    License: MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    ServletOutputStream sos = resp.getOutputStream();


    AsyncContext asyncCtxt = req.startAsync();
    asyncCtxt.setTimeout(5);
    Runnable task = new AsyncTask(asyncCtxt, sos);
    if (useContainerThreadToSetListener) {
        asyncCtxt.start(task);
    } else {
        Thread t = new Thread(task);
        t.start();
    }
}
 
Example 12
@Override
public void requestHandler(String videoId) throws Exception {
    MediaProxyTask mediaProxyTask = MediaProxyManager.getExecutedProxyTaskMap().get(videoId);
    if (mediaProxyTask instanceof TwitcastingMediaProxyTask) {
        TwitcastingMediaProxyTask twcProxyTask = (TwitcastingMediaProxyTask) mediaProxyTask;
        BlockingQueue<byte[]> bufferedQueue = new ArrayBlockingQueue<>(20);
        twcProxyTask.addBufferedQueue(bufferedQueue);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            boolean headerWrote = false;
            while (!twcProxyTask.getTerminated()) {
                byte[] bytes = bufferedQueue.poll(1000, TimeUnit.MILLISECONDS);
                if (bytes == null) {
                    continue;
                }
                if (!headerWrote) {
                    outputStream.write(twcProxyTask.getM4sHeader());
                    headerWrote = true;
                }
                outputStream.write(bytes);
            }
        } finally {
            twcProxyTask.removeBufferedQueue(bufferedQueue);
        }
    }
}
 
Example 13
Source Project: tutorials   Source File: AsyncServlet.java    License: MIT License 6 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ByteBuffer content = ByteBuffer.wrap(HEAVY_RESOURCE.getBytes(StandardCharsets.UTF_8));

    AsyncContext async = request.startAsync();
    ServletOutputStream out = response.getOutputStream();
    out.setWriteListener(new WriteListener() {
        @Override
        public void onWritePossible() throws IOException {
            while (out.isReady()) {
                if (!content.hasRemaining()) {
                    response.setStatus(200);
                    async.complete();
                    return;
                }
                out.write(content.get());
            }
        }

        @Override
        public void onError(Throwable t) {
            getServletContext().log("Async Error", t);
            async.complete();
        }
    });
}
 
Example 14
Source Project: Tomcat8-Source-Read   Source File: TestUpgrade.java    License: MIT License 6 votes vote down vote up
@Override
public void init(WebConnection connection) {
    ServletInputStream sis;
    ServletOutputStream sos;

    try {
        sis = connection.getInputStream();
        sos = connection.getOutputStream();
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }

    EchoListener echoListener = new EchoListener(sis, sos);
    sis.setReadListener(echoListener);
    sos.setWriteListener(echoListener);
}
 
Example 15
Source Project: easypoi   Source File: JeecgMapExcelView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
    String codedFileName = "临时文件";
    Workbook workbook = ExcelExportUtil.exportExcel(
        (ExportParams) model.get(MapExcelConstants.PARAMS),
        (List<ExcelExportEntity>) model.get(MapExcelConstants.ENTITY_LIST),
        (Collection<? extends Map<?, ?>>) model.get(MapExcelConstants.MAP_LIST));
    if (model.containsKey(MapExcelConstants.FILE_NAME)) {
        codedFileName = (String) model.get(MapExcelConstants.FILE_NAME);
    }
    if (workbook instanceof HSSFWorkbook) {
        codedFileName += HSSF;
    } else {
        codedFileName += XSSF;
    }
    if (isIE(request)) {
        codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8");
    } else {
        codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
    }
    response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
    ServletOutputStream out = response.getOutputStream();
    workbook.write(out);
    out.flush();
}
 
Example 16
Source Project: ProxyPool   Source File: CommonController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/launchjob")
@ResponseBody
public void startJob(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

    log.info("manual startJob");
    try {
        httpServletResponse.setContentType("text/plain; charset=utf-8");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        if(scheduleJobs.getJobStatus() == ScheduleJobs.JOB_STATUS_RUNNING) {
            responseOutputStream.write("Job正在运行。。。".getBytes("utf-8"));
            responseOutputStream.flush();
            responseOutputStream.close();
        } else {
            log.info("scheduleJobs.cronJob() start by controller...");
            scheduleJobs.cronJob();
        }
    } catch (Exception e) {
        log.info("startJob exception e="+e.getMessage());
    }
}
 
Example 17
public ActionForward printDocument(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException, FenixServiceException {
    final IDocumentRequest documentRequest = getPhdAcademicServiceRequest(request);
    try {
        byte[] data = documentRequest.generateDocument();

        response.setContentLength(data.length);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + documentRequest.getReportFileName() + ".pdf");

        final ServletOutputStream writer = response.getOutputStream();
        writer.write(data);
        writer.flush();
        writer.close();

        response.flushBuffer();
        return null;
    } catch (DomainException e) {
        throw e;
    }
}
 
Example 18
Source Project: hbase   Source File: TestGZIPResponseWrapper.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testResetBuffer() throws IOException {
  when(response.isCommitted()).thenReturn(false);
  ServletOutputStream out = mock(ServletOutputStream.class);
  when(response.getOutputStream()).thenReturn(out);

  ServletOutputStream servletOutput = wrapper.getOutputStream();
  assertEquals(GZIPResponseStream.class, servletOutput.getClass());
  wrapper.resetBuffer();
  verify(response).setHeader("Content-Encoding", null);

  when(response.isCommitted()).thenReturn(true);
  servletOutput = wrapper.getOutputStream();
  assertEquals(out.getClass(), servletOutput.getClass());
  assertNotNull(wrapper.getWriter());
}
 
Example 19
Source Project: easypoi   Source File: JeecgTemplateWordView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
    String codedFileName = "临时文件.docx";
    if (model.containsKey(TemplateWordConstants.FILE_NAME)) {
        codedFileName = (String) model.get(TemplateWordConstants.FILE_NAME) + ".docx";
    }
    if (isIE(request)) {
        codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8");
    } else {
        codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
    }
    response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
    XWPFDocument document = WordExportUtil.exportWord07(
        (String) model.get(TemplateWordConstants.URL),
        (Map<String, Object>) model.get(TemplateWordConstants.MAP_DATA));
    ServletOutputStream out = response.getOutputStream();
    document.write(out);
    out.flush();
}
 
Example 20
@Test
public void testInterceptionServlet_noKarafEtc_defaultFound() throws Exception {

	// Mocks
	HttpServletResponse resp = Mockito.mock( HttpServletResponse.class );
	Mockito.when( resp.getOutputStream()).thenReturn( Mockito.mock( ServletOutputStream.class ));

	HttpServletRequest req = Mockito.mock( HttpServletRequest.class );
	Mockito.when( req.getServletPath()).thenReturn( CSS_STYLESHEET );

	ServletConfig sc = Mockito.mock( ServletConfig.class );
	ServletContext ctx = Mockito.mock( ServletContext.class );
	Mockito.when( ctx.getResourceAsStream( Mockito.anyString())).thenReturn( new ByteArrayInputStream( new byte[ 0 ]));
	Mockito.when( sc.getServletContext()).thenReturn( ctx );

	// Initialization
	WebAdminInterceptionServlet servlet = new WebAdminInterceptionServlet();
	servlet.init( sc );

	// Execution
	servlet.doGet( req, resp );

	// Assertions
	Mockito.verify( req, Mockito.atLeast( 1 )).getServletPath();
	Mockito.verify( resp, Mockito.only()).getOutputStream();
}
 
Example 21
Source Project: logbook   Source File: LocalResponseTest.java    License: MIT License 6 votes vote down vote up
@BeforeEach
void setUp() throws IOException {
    mock = mock(HttpServletResponse.class);
    when(mock.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(final WriteListener listener) {
            // nothing to do here
        }

        @Override
        public void write(final int b) {
            // serves as a null or no-op output stream
        }
    });
    unit = new LocalResponse(mock, "1");
}
 
Example 22
Source Project: sakai   Source File: DownloadEventBean.java    License: Educational Community License v2.0 6 votes vote down vote up
private void downloadCsvSpreadsheet(List<SignupMeetingWrapper> smWrappers, String fileName) {

		FacesContext fc = FacesContext.getCurrentInstance();
		ServletOutputStream out = null;
		try {
			HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
			responseSettings(fileName, CSV_MIME_TYPE, response);
			out = response.getOutputStream();

			csvSpreadsheet(out, smWrappers);

			out.flush();
		} catch (IOException ex) {
			log.warn("Error generating CSV spreadsheet for download event:" + ex.getMessage());
		} finally {
			if (out != null)
				closeStream(out);
		}
		fc.responseComplete();
	}
 
Example 23
Source Project: sakai   Source File: DownloadEventBean.java    License: Educational Community License v2.0 5 votes vote down vote up
private void closeStream(ServletOutputStream out) {
	try {
		out.close();
	} catch (IOException e) {
		log.warn("Error closing the output stream: " +e.getMessage());
	}
}
 
Example 24
Source Project: roboconf-platform   Source File: IconServletTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGet() throws Exception {

	// Prepare the servlet
	File configurationDirectory = this.folder.newFolder();

	this.manager = new Manager();
	this.manager.configurationMngr().setWorkingDirectory( configurationDirectory );

	File appDir = ConfigurationUtils.findApplicationDirectory( "app", configurationDirectory );
	File descDir = new File( appDir, Constants.PROJECT_DIR_DESC );
	Assert.assertTrue( descDir.mkdirs());

	IconServlet servlet = new IconServlet( this.manager );

	// Add a fake file
	File trickFile = new File( descDir, "directory.jpg" );
	Assert.assertTrue( trickFile.mkdirs());

	// Prepare our mocks
	HttpServletRequest req = Mockito.mock( HttpServletRequest.class );
	HttpServletResponse resp = Mockito.mock( HttpServletResponse.class );

	Mockito.when( req.getPathInfo()).thenReturn( "/app/whatever.jpg" );
	servlet.doGet( req, resp );
	Mockito.verify( resp ).setStatus( HttpServletResponse.SC_NOT_FOUND );

	// Now, add a real icon and make sure it is returned
	// (it is returned if a MIME type was set).
	File singleJpgFile = new File( descDir, "whatever.jpg" );
	Assert.assertTrue( singleJpgFile.createNewFile());

	ServletOutputStream out = Mockito.mock( ServletOutputStream.class );
	Mockito.when( resp.getOutputStream()).thenReturn( out );
	servlet.doGet( req, resp );
	Mockito.verify( resp ).setContentType( IconUtils.MIME_JPG );
}
 
Example 25
private void writeReportForExternalDegrees(final DegreeChangeCandidacyProcess process, final ServletOutputStream outputStream)
        throws IOException {
    final StyledExcelSpreadsheet excelSpreadsheet = new StyledExcelSpreadsheet();
    for (final Entry<Degree, SortedSet<DegreeChangeIndividualCandidacyProcess>> entry : process
            .getValidExternalIndividualCandidacyProcessesByDegree().entrySet()) {
        createSpreadsheet(excelSpreadsheet, entry.getKey(), entry.getValue());
    }
    excelSpreadsheet.getWorkbook().write(outputStream);
}
 
Example 26
public ServletOutputStream getOutputStream() throws IOException {

      if (outputStreamWrapper == null) {

         final ServletOutputStream outputStream = super.getOutputStream();
         final int bufferSize = getBufferSize();
         outputStreamWrapper = outputWrapperFactory.createServletOutputStream(outputStream, bufferSize);
      }

      return outputStreamWrapper;
   }
 
Example 27
Source Project: WeEvent   Source File: CommonService.java    License: Apache License 2.0 5 votes vote down vote up
public void writeResponse(CloseableHttpResponse closeResponse, HttpServletResponse res) throws IOException {
    String mes = EntityUtils.toString(closeResponse.getEntity());
    log.info("response: " + mes);
    Header encode = closeResponse.getFirstHeader(CONTENT_TYPE);
    res.setHeader(encode.getName(), encode.getValue());
    ServletOutputStream out = res.getOutputStream();
    out.write(mes.getBytes());
}
 
Example 28
Source Project: mycore   Source File: MCRCompressServlet.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void render(MCRServletJob job, Exception ex) throws Exception {
    if (ex != null) {
        //we cannot handle it ourself
        throw ex;
    }
    if (job.getResponse().isCommitted()) {
        return;
    }
    MCRObjectID id = (MCRObjectID) job.getRequest().getAttribute(KEY_OBJECT_ID);
    String path = (String) job.getRequest().getAttribute(KEY_PATH);
    try (ServletOutputStream sout = job.getResponse().getOutputStream()) {
        StringBuffer requestURL = job.getRequest().getRequestURL();
        if (job.getRequest().getQueryString() != null) {
            requestURL.append('?').append(job.getRequest().getQueryString());
        }
        MCRISO8601Date mcriso8601Date = new MCRISO8601Date();
        mcriso8601Date.setDate(new Date());
        String comment = "Created by " + requestURL + " at " + mcriso8601Date.getISOString();
        try (T container = createContainer(sout, comment)) {
            job.getResponse().setContentType(getMimeType());
            String filename = getFileName(id, path);
            job.getResponse().addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            if (id.getTypeId().equals("derivate")) {
                sendDerivate(id, path, container);
            } else {
                sendObject(id, job, container);
            }
            disposeContainer(container);
        }
    }
}
 
Example 29
public ActionForward prepareExecutePrintCandidacies(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=" + getReportFilename());

    final ServletOutputStream writer = response.getOutputStream();
    writeReport(getProcess(request), writer);
    writer.flush();
    response.flushBuffer();
    return null;
}
 
Example 30
Source Project: spring-microservice-exam   Source File: ExaminationController.java    License: MIT License 5 votes vote down vote up
/**
 * 根据考试ID生成二维码
 * @param examinationId examinationId
 * @param response response
 * @author tangyi
 * @date 2020/3/15 1:16 下午
 */
@ApiOperation(value = "生成二维码", notes = "生成二维码")
@ApiImplicitParams({
        @ApiImplicitParam(name = "examinationId", value = "考试ID", required = true, dataType = "Long", paramType = "path")
})
@GetMapping("anonymousUser/generateQrCode/{examinationId}")
public void produceCode(@PathVariable Long examinationId, HttpServletResponse response) throws Exception {
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setContentType("image/jpeg");
    try (ByteArrayInputStream inputStream = new ByteArrayInputStream(examinationService.produceCode(examinationId)); ServletOutputStream out = response.getOutputStream()) {
        BufferedImage image = ImageIO.read(inputStream);
        ImageIO.write(image, "PNG", out);
    }
}