Example usage for javax.servlet ServletInputStream read

List of usage examples for javax.servlet ServletInputStream read

Introduction

In this page you can find the example usage for javax.servlet ServletInputStream read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads some number of bytes from the input stream and stores them into the buffer array b.

Usage

From source file:org.iita.struts.interceptor.GearsFileUploadInterceptor.java

/**
 * @param request//from  ww  w  .ja v  a2 s  .  co m
 * @param validation
 * @param ac
 * 
 */
@SuppressWarnings("unchecked")
private File doGearsUpload(HttpServletRequest request, ValidationAware validation, ActionContext ac) {
    // this is our extension for Gears uploads
    String fileName = request.getHeader("gears-filename");
    if (fileName != null) {
        String contentType = request.getHeader("gears-contentType");
        if (contentType == null)
            contentType = "application/x-binary";
        String inputName = request.getHeader("gears-inputName");
        if (inputName == null)
            inputName = "uploads";

        log.info("Gears filename: " + fileName);
        log.info("Gears contentType: " + contentType);
        log.info("Content-length: " + request.getContentLength());
        try {
            ServletInputStream uploadStream = request.getInputStream();
            File tempFile = File.createTempFile("gears.", ".upload");
            tempFile.deleteOnExit();
            FileOutputStream tempStream = new FileOutputStream(tempFile);
            byte[] b = new byte[2048];
            int len = 0, total = 0;
            do {
                len = uploadStream.read(b);
                if (len > 0) {
                    tempStream.write(b, 0, len);
                    total += len;
                }
            } while (len > 0);
            uploadStream.close();
            tempStream.flush();
            tempStream.close();
            log.debug("File uploaded from stream.");

            if (request.getContentLength() != total) {
                log.warn("Upload not complete? " + total + " received of " + request.getContentLength());
                tempFile.delete();
                tempFile = null;
                return null;
            }
            if (acceptFile(tempFile, contentType, inputName, validation, ac.getLocale())) {
                Map parameters = ac.getParameters();

                parameters.put(inputName, new File[] { tempFile });
                parameters.put(inputName + "ContentType", contentType);
                parameters.put(inputName + "FileName", fileName);
                return tempFile;

            }
        } catch (IOException e) {
            log.error(e);
        }
    }
    return null;
}

From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServletUtils.java

protected File serialize(DragDropContext ctx, ServletInputStream instream, int fileUploadSpeed)
        throws IOException {

    byte[] buff = new byte[1024];
    int bytesread = 0;
    int totalBytes = 0;
    int totalBytes2 = 0;
    //ByteArrayOutputStream bout=new ByteArrayOutputStream();
    File f = new File(folder, ctx.getUser() + "." + ctx.getDropID() + ".upload.mime");
    FileOutputStream fout = new FileOutputStream(f);
    while ((bytesread = instream.read(buff)) > 0) {
        totalBytes += bytesread;//w ww. j  av a  2 s  . c  o  m
        totalBytes2 += bytesread;
        fout.write(buff, 0, bytesread);

        //approximite timing ,assume stream reading/writing takes no time, just wait 1 second when limit per/sec is reached
        if (fileUploadSpeed > 0) {
            if (totalBytes2 > fileUploadSpeed) {
                try {
                    System.out.println("Sleeping...");
                    Thread.currentThread().sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
                totalBytes2 = 0;
            }
        }
    }

    return f;

}

From source file:org.ejbca.extra.ra.ScepRAServlet.java

/**
 * Handles HTTP post//ww  w .j a  va2  s  . c o  m
 *
 * @param request java standard arg
 * @param response java standard arg
 *
 * @throws IOException input/output error
 * @throws ServletException if the post could not be handled
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug(">doPost()");
    /* 
     If the remote CA supports it, any of the PKCS#7-encoded SCEP messages
     may be sent via HTTP POST instead of HTTP GET.   This is allowed for
     any SCEP message except GetCACert, GetCACertChain, GetNextCACert,
     or GetCACaps.  In this form of the message, Base 64 encoding is not
     used.
             
     POST /cgi-bin/pkiclient.exe?operation=PKIOperation
     <binary PKCS7 data>
     */
    String operation = "PKIOperation";
    ServletInputStream sin = request.getInputStream();
    // This small code snippet is inspired/copied by apache IO utils to Tomas Gustavsson...
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int n = 0;
    while (-1 != (n = sin.read(buf))) {
        output.write(buf, 0, n);
    }
    String message = new String(Base64.encode(output.toByteArray()));
    service(operation, message, request.getRemoteAddr(), response);
    log.debug("<doPost()");
}

From source file:org.ejbca.ui.web.protocol.ScepServlet.java

/**
 * Handles HTTP post//  w w w.  j av  a2s . com
 *
 * @param request java standard arg
 * @param response java standard arg
 *
 * @throws IOException input/output error
 * @throws ServletException if the post could not be handled
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.trace(">SCEP doPost()");
    /* 
     If the remote CA supports it, any of the PKCS#7-encoded SCEP messages
     may be sent via HTTP POST instead of HTTP GET.   This is allowed for
     any SCEP message except GetCACert, GetCACertChain, GetNextCACert,
     or GetCACaps.  In this form of the message, Base 64 encoding is not
     used.
             
     POST /cgi-bin/pkiclient.exe?operation=PKIOperation
     <binary PKCS7 data>
     */
    String operation = "PKIOperation";
    ServletInputStream sin = request.getInputStream();
    // This small code snippet is inspired/copied by apache IO utils to Tomas Gustavsson...
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int n = 0;
    while (-1 != (n = sin.read(buf))) {
        output.write(buf, 0, n);
    }
    String message = new String(Base64.encode(output.toByteArray()));
    service(operation, message, request.getRemoteAddr(), response, request.getPathInfo());
    log.trace("<SCEP doPost()");
}

From source file:com.gamewin.weixin.web.api.ApiListController.java

private void acceptMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // ??/*from  ww  w.  j  av a 2s .  c  o  m*/
    ServletInputStream in = request.getInputStream();
    // POST??XStream
    XStream xs = SerializeXmlUtil.createXstream();
    xs.processAnnotations(InputMessage.class);
    xs.processAnnotations(OutputMessage.class);
    // xml?
    xs.alias("xml", InputMessage.class);
    // ??
    StringBuilder xmlMsg = new StringBuilder();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        xmlMsg.append(new String(b, 0, n, "UTF-8"));
    }
    // xml?InputMessage
    InputMessage inputMsg = (InputMessage) xs.fromXML(xmlMsg.toString());

    String servername = inputMsg.getToUserName();// ?
    String custermname = inputMsg.getFromUserName();// 
    long createTime = inputMsg.getCreateTime();// 
    Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;//
    // 

    // ??
    String msgType = inputMsg.getMsgType();

    // ?
    System.out.println("??" + inputMsg.getToUserName());
    System.out.println("????" + inputMsg.getFromUserName());
    System.out.println("?" + inputMsg.getCreateTime() + new Date(createTime * 1000l));
    System.out.println("?Event" + inputMsg.getEvent());
    System.out.println("?EventKey" + inputMsg.getEventKey());
    System.out.println("" + inputMsg.getContent());
    StringBuffer str = new StringBuffer();
    // ????
    if ("event".equals(msgType)) {

        if ("subscribe".equals(inputMsg.getEvent())) {

            if (!StringUtils.isEmpty(inputMsg.getEventKey())) {
                Long qrCodeId = null;
                try {
                    qrCodeId = Long
                            .parseLong(inputMsg.getEventKey().replaceAll("qrscene_", "").trim().toString());
                } catch (Exception e) {
                    System.out.println("" + inputMsg.getEventKey() + "------?");
                    e.printStackTrace();
                }

                ManageQRcode manageQRcode = manageQRcodeService.getManageQRcode(qrCodeId);

                Integer count = manageQRcodeService.selectHistoryWeixinBytaskId(manageQRcode.getTask().getId(),
                        inputMsg.getFromUserName());

                HistoryWeixin wxUser = new HistoryWeixin();
                wxUser.setCreateDate(new Date());
                wxUser.setToUserName(inputMsg.getToUserName());
                wxUser.setFromUserName(inputMsg.getFromUserName());
                wxUser.setMsgType(msgType);
                wxUser.setEvent(inputMsg.getEvent());
                wxUser.setEventKey(inputMsg.getEventKey());
                wxUser.setCreateTime(inputMsg.getCreateTime().toString());
                wxUser.setQrcodeId(qrCodeId);
                wxUser.setTaskId(manageQRcode.getTask().getId());

                if (count == 0) {
                    if ("Y".equals(manageQRcode.getQrState())) {
                        manageQRcode.setQrSubscribeCount(manageQRcode.getQrSubscribeCount() + 1);
                        manageQRcode.setQrSubscribeAdminCount(manageQRcode.getQrSubscribeAdminCount() + 1);
                        manageQRcodeService.saveManageQRcode(manageQRcode);
                        wxUser.setStatus("Y");
                    } else {
                        manageQRcode.setQrSubscribeAdminCount(manageQRcode.getQrSubscribeAdminCount() + 1);
                        manageQRcodeService.saveManageQRcode(manageQRcode);
                        wxUser.setStatus("N");
                    }
                }

                manageQRcodeService.saveHistoryWeixin(wxUser);

            }
            String content = "HI???????????? \n ";

            List<Game> gameList = gameService.getEffectiveGamelist();
            if (gameList != null && gameList.size() > 0) {
                for (int i = 0; i < gameList.size(); i++) {
                    Game game = gameList.get(i);
                    content += "[" + game.getXuhao() + "] " + game.getGameName() + "\n";
                }
            } else {
                content += "???";
            }

            str.append("<xml>                                              ");
            str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
            str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
            str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
            str.append("<MsgType><![CDATA[text]]></MsgType>                ");
            str.append("<Content><![CDATA[" + content + "]]></Content>                     ");
            str.append("</xml>                                             ");
            System.out.println(str.toString());
            response.getWriter().write(str.toString());
        }

    } else if ("text".equals(msgType)) {

        String redurl = URLEncoder.encode(MobileContants.YM + "/weixinUser/bindUserOpenId", "utf-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + MobileContants.appID
                + "&redirect_uri=" + redurl + "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";

        String xxxx = inputMsg.getContent().toString();
        String content = "";
        if (xxxx.indexOf("") != -1) {

            str.append("<xml>                                              ");
            str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
            str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
            str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
            str.append("<MsgType><![CDATA[news]]></MsgType>                ");
            str.append("<ArticleCount>1</ArticleCount>                     ");
            str.append("<Articles>                                         ");
            str.append("<item>                                             ");
            str.append("<Title><![CDATA[??]]></Title>                   ");
            str.append(
                    "<Description><![CDATA[??,,]]></Description> ");
            str.append("<PicUrl><![CDATA[]]></PicUrl>                ");
            str.append("<Url><![CDATA[" + url + "]]></Url>                         ");
            str.append("</item>                                            ");
            str.append("</Articles>                                        ");
            str.append("</xml>                                             ");

            System.out.println(str.toString());
            response.getWriter().write(str.toString());
        } else {
            if ("?".equals(xxxx) || "".equals(xxxx) || "".equals(xxxx) || "".equals(xxxx)) {
                List<Game> gameList = gameService.getEffectiveGamelist();
                if (gameList != null && gameList.size() > 0) {
                    for (int i = 0; i < gameList.size(); i++) {
                        Game game = gameList.get(i);
                        content += "[" + game.getXuhao() + "] " + game.getGameName() + "\n";
                    }
                    content += "??????";
                } else {
                    content = "???";
                }
            } else {
                Game game = gameService.findGameByNameOrXuhao(xxxx);
                if (game != null) {
                    Long count = gameService.getMyGameCodeCount(game.getId(), custermname);
                    System.out.println(count);
                    System.out.println(game.getMaximum());
                    if (count < game.getMaximum()) {
                        //?
                        GameCode code = gameService.getMyGameCode(game.getId());
                        gameService.updateMyGameCode(code.getId(), custermname);
                        content = "???" + code.getCode() + " \n  "
                                + game.getGameMessage() + "";

                    } else {
                        content = "????????\n ?'?'?????????";
                    }

                } else {
                    content = " ????\n ?'?'?????????";
                }

            }
            str.append("<xml>                                              ");
            str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>        ");
            str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>  ");
            str.append("<CreateTime>" + returnTime + "</CreateTime>                  ");
            str.append("<MsgType><![CDATA[text]]></MsgType>                ");
            str.append("<Content><![CDATA[" + content + "]]></Content>                     ");
            str.append("</xml>                                             ");
            System.out.println(str.toString());
            response.getWriter().write(str.toString());
        }

    }

}

From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java

/**
 * <p> This is an example how the NIO Parser can be used in a plain Servlet 3.1 fashion.
 *
 * @param request The {@code HttpServletRequest}
 * @throws IOException if an IO exception happens
 *///  w  ww . j ava2s .com
@RequestMapping(value = "/nio/multipart", method = RequestMethod.POST)
public @ResponseBody void nioMultipart(final HttpServletRequest request) throws IOException {

    assertRequestIsMultipart(request);

    final VerificationItems verificationItems = new VerificationItems();
    final AsyncContext asyncContext = switchRequestToAsyncIfNeeded(request);
    final ServletInputStream inputStream = request.getInputStream();
    final AtomicInteger synchronizer = new AtomicInteger(0);

    final NioMultipartParserListener listener = new NioMultipartParserListener() {

        Metadata metadata;

        @Override
        public void onPartFinished(final StreamStorage partBodyStreamStorage,
                final Map<String, List<String>> headersFromPart) {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onPartFinished");
            final String fieldName = MultipartUtils.getFieldName(headersFromPart);
            final ChecksumStreamStorage checksumPartStreams = getChecksumStreamStorageOrThrow(
                    partBodyStreamStorage);
            if (METADATA_FIELD_NAME.equals(fieldName)) {
                metadata = unmarshalMetadataOrThrow(checksumPartStreams);
            } else {
                VerificationItem verificationItem = buildVerificationItem(checksumPartStreams, fieldName);
                verificationItems.getVerificationItems().add(verificationItem);
            }
        }

        @Override
        public void onNestedPartStarted(final Map<String, List<String>> headersFromParentPart) {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onNestedPartStarted");
        }

        @Override
        public void onNestedPartFinished() {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onNestedPartFinished");
        }

        @Override
        public void onFormFieldPartFinished(String fieldName, String fieldValue,
                Map<String, List<String>> headersFromPart) {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onFormFieldPartFinished");
            if (METADATA_FIELD_NAME.equals(fieldName)) {
                metadata = unmarshalMetadataOrThrow(fieldValue);
            }
        }

        @Override
        public void onAllPartsFinished() {
            if (log.isInfoEnabled())
                log.info("PARSER LISTENER - onAllPartsFinished");
            processVerificationItems(verificationItems, metadata, true);
            sendResponseOrSkip(synchronizer, asyncContext, verificationItems);
        }

        @Override
        public void onError(String message, Throwable cause) {
            // Probably invalid data...
            throw new IllegalStateException("Encountered an error during the parsing: " + message, cause);
        }

        synchronized Metadata unmarshalMetadataOrThrow(final String json) {
            if (metadata != null) {
                throw new IllegalStateException("Found two metadata fields");
            }
            return unmarshalMetadata(json);
        }

        synchronized Metadata unmarshalMetadataOrThrow(final ChecksumStreamStorage checksumPartStreams) {
            if (metadata != null) {
                throw new IllegalStateException("Found more than one metadata fields");
            }
            return unmarshalMetadata(checksumPartStreams.getInputStream());
        }

    };

    final MultipartContext ctx = getMultipartContext(request);
    final NioMultipartParser parser = multipart(ctx)
            .usePartBodyStreamStorageFactory(partBodyStreamStorageFactory).forNIO(listener);

    // Add a listener to ensure the parser is closed.
    asyncContext.addListener(new AsyncListener() {
        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onError(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onStartAsync(AsyncEvent event) throws IOException {
            // Nothing to do.
        }
    });

    inputStream.setReadListener(new ReadListener() {

        @Override
        public void onDataAvailable() throws IOException {
            if (log.isInfoEnabled())
                log.info("NIO READ LISTENER - onDataAvailable");
            int bytesRead;
            byte bytes[] = new byte[2048];
            while (inputStream.isReady() && (bytesRead = inputStream.read(bytes)) != -1) {
                parser.write(bytes, 0, bytesRead);
            }
            if (log.isInfoEnabled())
                log.info("Epilogue bytes...");
        }

        @Override
        public void onAllDataRead() throws IOException {
            if (log.isInfoEnabled())
                log.info("NIO READ LISTENER - onAllDataRead");
            sendResponseOrSkip(synchronizer, asyncContext, verificationItems);
        }

        @Override
        public void onError(Throwable throwable) {
            log.error("onError", throwable);
            IOUtils.closeQuietly(parser);
            sendErrorOrSkip(synchronizer, asyncContext, "Unknown error");
        }
    });

}

From source file:com.tmwsoft.sns.web.action.MainAction.java

public ActionForward cp_videophoto(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> sGlobal = (Map<String, Object>) request.getAttribute("sGlobal");
    Map<String, Object> sConfig = (Map<String, Object>) request.getAttribute("sConfig");
    Map<String, Object> space = (Map<String, Object>) request.getAttribute("space");
    if (Common.empty(sConfig.get("videophoto"))) {
        return showMessage(request, response, "no_open_videophoto");
    }//  ww  w.j  a v a2  s .c om
    String videoPic = (String) space.get("videopic");
    int videoStatus = (Integer) space.get("videostatus");
    String oldVideoPhoto = null;
    if (!Common.empty(videoPic)) {
        oldVideoPhoto = mainService.getVideoPicDir(videoPic);
        request.setAttribute("videophoto", mainService.getVideoPicUrl(videoPic));
    }
    try {
        if (submitCheck(request, "uploadsubmit")) {
            ServletInputStream sis = null;
            FileOutputStream fos = null;
            PrintWriter out = null;
            try {
                response.setHeader("Expires", "0");
                response.setHeader("Cache-Control", "no-store, private, post-check=0, pre-check=0, max-age=0");
                response.setHeader("Pragma", "no-cache");
                response.setContentType("text/html");
                out = response.getWriter();
                if (!Common.empty(videoStatus) && Common.empty(sConfig.get("videophotochange"))) {
                    out.write("-1");
                    return null;
                }
                if (videoStatus == 0 && !Common.empty(videoPic)) {
                    out.write("-2");
                    return null;
                }
                int uid = (Integer) sGlobal.get("supe_uid");
                int timestamp = (Integer) sGlobal.get("timestamp");
                String newFileName = Common.md5(String.valueOf(timestamp).substring(0, 7) + uid);
                String snsRoot = SysConstants.snsRoot + "/";
                String attachDir = SysConstants.snsConfig.get("attachDir");
                File file = new File(snsRoot + attachDir + "video/" + newFileName.substring(0, 1) + "/"
                        + newFileName.substring(1, 2));
                if (!file.exists() && !file.isDirectory() && !file.mkdirs()) {
                    out.write("Can not write to the attachment/video folder!");
                    return null;
                }
                if (oldVideoPhoto != null) {
                    file = new File(snsRoot + oldVideoPhoto);
                    if (file.exists())
                        file.delete();
                }
                sis = request.getInputStream();
                fos = new FileOutputStream(snsRoot + mainService.getVideoPicDir(newFileName));
                byte[] buffer = new byte[256];
                int count = 0;
                while ((count = sis.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                boolean videoPhotoCheck = Common.empty(sConfig.get("videophotocheck"));
                videoStatus = videoPhotoCheck ? 1 : 0;
                dataBaseService.executeUpdate(
                        "UPDATE sns_spacefield SET videopic='" + newFileName + "' WHERE uid='" + uid + "'");
                dataBaseService.executeUpdate(
                        "UPDATE sns_space SET videostatus='" + videoStatus + "' WHERE uid='" + uid + "'");
                List<String> sets = new ArrayList<String>();
                Map<String, Integer> reward = Common.getReward("videophoto", false, 0, "", true, request,
                        response);
                int credit = reward.get("credit");
                int experience = reward.get("experience");
                if (credit != 0) {
                    sets.add("credit=credit+" + credit);
                }
                if (experience != 0) {
                    sets.add("experience=experience+" + experience);
                }
                sets.add("updatetime=" + timestamp);
                if (sets.size() > 0) {
                    dataBaseService.executeUpdate(
                            "UPDATE sns_space SET " + Common.implode(sets, ",") + " WHERE uid='" + uid + "'");
                }
                if (videoPhotoCheck) {
                    out.write("2");
                } else {
                    out.write("1");
                }
                return null;
            } catch (Exception e) {
                out.write("??");
                return null;
            } finally {
                try {
                    if (fos != null) {
                        fos.flush();
                        fos.close();
                        fos = null;
                    }
                    if (sis != null) {
                        sis.close();
                        sis = null;
                    }
                    if (out != null) {
                        out.flush();
                        out.close();
                        out = null;
                    }
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
        return showMessage(request, response, e.getMessage());
    }
    String op = request.getParameter("op");
    if ("check".equals(op)) {
        if ((videoStatus > 0 && Common.empty(sConfig.get("videophotochange")))
                || (videoStatus == 0 && !Common.empty(videoPic))) {
            request.getParameterMap().remove("op");
        } else {
            String flashSrc = "image/videophoto.swf?post_url="
                    + Common.urlEncode(Common.getSiteUrl(request) + "main.action") + "&agrs="
                    + Common.urlEncode("ac=videophoto&uid=" + sGlobal.get("supe_uid")
                            + "&uploadsubmit=true&formhash=" + formHash(request));
            String videoFlash = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"560\" height=\"390\" id=\"videoCheck\" align=\"middle\">"
                    + "<param name=\"allowScriptAccess\" value=\"always\" />"
                    + "<param name=\"scale\" value=\"exactfit\" />"
                    + "<param name=\"wmode\" value=\"transparent\" />"
                    + "<param name=\"quality\" value=\"high\" />"
                    + "<param name=\"bgcolor\" value=\"#ffffff\" />" + "<param name=\"movie\" value=\""
                    + flashSrc + "\" />" + "<param name=\"menu\" value=\"false\" />" + "<embed src=\""
                    + flashSrc
                    + "\" quality=\"high\" bgcolor=\"#ffffff\" width=\"560\" height=\"390\" name=\"videoCheck\" align=\"middle\" allowScriptAccess=\"always\" allowFullScreen=\"false\" scale=\"exactfit\"  wmode=\"transparent\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />"
                    + "</object>";
            request.setAttribute("videoFlash", videoFlash);
        }
    }
    return include(request, response, sConfig, sGlobal, "cp_videophoto.jsp");
}

From source file:cn.jcenterhome.web.action.CpAction.java

public ActionForward cp_videophoto(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> sGlobal = (Map<String, Object>) request.getAttribute("sGlobal");
    Map<String, Object> sConfig = (Map<String, Object>) request.getAttribute("sConfig");
    Map<String, Object> space = (Map<String, Object>) request.getAttribute("space");
    if (Common.empty(sConfig.get("videophoto"))) {
        return showMessage(request, response, "no_open_videophoto");
    }//from  ww w .j a  va2 s . c  om
    String videoPic = (String) space.get("videopic");
    int videoStatus = (Integer) space.get("videostatus");
    String oldVideoPhoto = null;
    if (!Common.empty(videoPic)) {
        oldVideoPhoto = cpService.getVideoPic(videoPic);
        request.setAttribute("videophoto", oldVideoPhoto);
    }
    try {
        if (submitCheck(request, "uploadsubmit")) {
            ServletInputStream sis = null;
            FileOutputStream fos = null;
            PrintWriter out = null;
            try {
                response.setHeader("Expires", "0");
                response.setHeader("Cache-Control", "no-store, private, post-check=0, pre-check=0, max-age=0");
                response.setHeader("Pragma", "no-cache");
                response.setContentType("text/html");
                out = response.getWriter();
                if (!Common.empty(videoStatus) && Common.empty(sConfig.get("videophotochange"))) {
                    out.write("-1");
                    return null;
                }
                if (videoStatus == 0 && !Common.empty(videoPic)) {
                    out.write("-2");
                    return null;
                }
                int uid = (Integer) sGlobal.get("supe_uid");
                int timestamp = (Integer) sGlobal.get("timestamp");
                String newFileName = Common.md5(String.valueOf(timestamp).substring(0, 7) + uid);
                String jchRoot = JavaCenterHome.jchRoot + "/";
                File file = new File(jchRoot + "data/video/" + newFileName.substring(0, 1) + "/"
                        + newFileName.substring(1, 2));
                if (!file.exists() && !file.isDirectory() && !file.mkdirs()) {
                    out.write("Can not write to the data/video folder!");
                    return null;
                }
                if (oldVideoPhoto != null) {
                    file = new File(jchRoot + oldVideoPhoto);
                    if (file.exists())
                        file.delete();
                }
                sis = request.getInputStream();
                fos = new FileOutputStream(jchRoot + cpService.getVideoPic(newFileName));
                byte[] buffer = new byte[256];
                int count = 0;
                while ((count = sis.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                boolean videoPhotoCheck = Common.empty(sConfig.get("videophotocheck"));
                videoStatus = videoPhotoCheck ? 1 : 0;
                dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("spacefield")
                        + " SET videopic='" + newFileName + "' WHERE uid='" + uid + "'");
                dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space")
                        + " SET videostatus='" + videoStatus + "' WHERE uid='" + uid + "'");
                List<String> sets = new ArrayList<String>();
                Map<String, Integer> reward = Common.getReward("videophoto", false, 0, "", true, request,
                        response);
                int credit = reward.get("credit");
                int experience = reward.get("experience");
                if (credit != 0) {
                    sets.add("credit=credit+" + credit);
                }
                if (experience != 0) {
                    sets.add("experience=experience+" + experience);
                }
                sets.add("updatetime=" + timestamp);
                if (sets.size() > 0) {
                    dataBaseService.executeUpdate("UPDATE " + JavaCenterHome.getTableName("space") + " SET "
                            + Common.implode(sets, ",") + " WHERE uid='" + uid + "'");
                }
                if (videoPhotoCheck) {
                    out.write("2");
                } else {
                    out.write("1");
                }
                return null;
            } catch (Exception e) {
                out.write("Upload an exception occurred during the");
                return null;
            } finally {
                try {
                    if (fos != null) {
                        fos.flush();
                        fos.close();
                        fos = null;
                    }
                    if (sis != null) {
                        sis.close();
                        sis = null;
                    }
                    if (out != null) {
                        out.flush();
                        out.close();
                        out = null;
                    }
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
        return showMessage(request, response, e.getMessage());
    }
    String op = request.getParameter("op");
    if ("check".equals(op)) {
        if ((videoStatus > 0 && Common.empty(sConfig.get("videophotochange")))
                || (videoStatus == 0 && !Common.empty(videoPic))) {
            request.getParameterMap().remove("op");
        } else {
            String flashSrc = "image/videophoto.swf?post_url="
                    + Common.urlEncode(Common.getSiteUrl(request) + "cp.jsp") + "&agrs="
                    + Common.urlEncode("ac=videophoto&uid=" + sGlobal.get("supe_uid")
                            + "&uploadsubmit=true&formhash=" + formHash(request));
            String videoFlash = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"560\" height=\"390\" id=\"videoCheck\" align=\"middle\">"
                    + "<param name=\"allowScriptAccess\" value=\"always\" />"
                    + "<param name=\"scale\" value=\"exactfit\" />"
                    + "<param name=\"wmode\" value=\"transparent\" />"
                    + "<param name=\"quality\" value=\"high\" />"
                    + "<param name=\"bgcolor\" value=\"#ffffff\" />" + "<param name=\"movie\" value=\""
                    + flashSrc + "\" />" + "<param name=\"menu\" value=\"false\" />" + "<embed src=\""
                    + flashSrc
                    + "\" quality=\"high\" bgcolor=\"#ffffff\" width=\"560\" height=\"390\" name=\"videoCheck\" align=\"middle\" allowScriptAccess=\"always\" allowFullScreen=\"false\" scale=\"exactfit\"  wmode=\"transparent\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />"
                    + "</object>";
            request.setAttribute("videoFlash", videoFlash);
        }
    }
    return include(request, response, sConfig, sGlobal, "cp_videophoto.jsp");
}