Example usage for javax.servlet ServletInputStream close

List of usage examples for javax.servlet ServletInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:es.tid.cep.esperanza.Events.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  ww w .ja v a  2 s  .com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("events doPost");
    PrintWriter out = response.getWriter();
    try {
        response.setContentType("application/json;charset=UTF-8");
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        sis.close();
        String eventText = new String(b);
        logger.debug("event as text:" + eventText);
        org.json.JSONObject jo = new JSONObject(eventText);
        logger.debug("event as JSONObject: " + jo);
        Map<String, Object> otro = Utils.JSONObject2Map(jo);
        logger.debug("event as map: " + otro);
        epService.getEPRuntime().sendEvent(otro, "iotEvent");
        logger.debug("event was sent: " + otro);
    } catch (JSONException je) {
        logger.debug("error: " + je.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":\"%s\"}\n", je.getMessage());

    } finally {
        out.close();
    }
}

From source file:com.bstek.dorado.idesupport.resolver.RobotResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    DoradoContext context = DoradoContext.getCurrent();
    Document document = null;//from  w w  w .j a va2  s. c  o m
    List<Element> resultElements = null;
    Exception error = null;

    String robotName = getRobotName(request);
    Assert.notEmpty(robotName, "\"robotName\" undefined.");

    Robot robot = robotRegistry.getRobot(robotName);
    if (robot == null) {
        throw new IllegalArgumentException("Unknown robotName \"" + robotName + "\".");
    }

    ServletInputStream in = request.getInputStream();
    try {
        String charset = request.getCharacterEncoding();
        document = getXmlDocumentBuilder(context)
                .loadDocument(new InputStreamResource(in, request.getRequestURI()), charset);
    } catch (Exception e) {
        logger.error(e, e);
        error = e;
    } finally {
        in.close();
    }

    Element documentElement = document.getDocumentElement();

    Element contentElement = DomUtils.getChildByTagName(documentElement, "Content");
    List<Element> elements = DomUtils.getChildElements(contentElement);

    Properties properties = null;
    Element propertiesElement = DomUtils.getChildByTagName(documentElement, "Properties");
    if (propertiesElement != null) {
        List<Element> propertieElements = DomUtils.getChildElements(propertiesElement);
        if (!propertieElements.isEmpty()) {
            properties = new Properties();
            for (Element propertyElement : propertieElements) {
                properties.setProperty(propertyElement.getAttribute("name"),
                        DomUtils.getTextContent(propertyElement));
            }
        }
    }

    resultElements = new ArrayList<Element>();
    for (Element element : elements) {
        resultElements.add((Element) robot.execute(element, properties));
    }

    // Output
    document = getXmlDocumentBuilder(context).newDocument();
    Element responseElement = document.createElement("Response");
    document.appendChild(responseElement);
    if (error == null) {
        assembleContent(document, responseElement, resultElements);
    } else {
        responseElement.setAttribute("failed", "true");
        assembleError(document, responseElement, error);
    }

    PrintWriter writer = null;
    TransformerFactory transFactory = TransformerFactory.newInstance();
    try {
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty("encoding", Constants.DEFAULT_CHARSET);
        transformer.setOutputProperty("indent", "yes");

        DOMSource source = new DOMSource(document);
        writer = getWriter(request, response);
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }
}

From source file:kms.prolog.comms.TransportServlet.java

/** 
 * Prolog typically deals with HTTP POST for RESTful communication
 * Therefore we use the doPost to implement a RESTful web service
 * for contacting the chosen web service to receive the chosen data
 * Prolog sends JSON { transport: "moduleId", queryPayload="relevant parameters" }
 * This method://w  w w  .j ava2 s.  c om
 * 1. Looks up module id in RDBMS in order to find external web service location
 *    to retrieve data from
 * 2. Acts as a SOAP client to retrieve data from this service
 * --> For first web service 
 *     a.Create and generate web service WSDL
 *     b.Use wsimport to generate necessary stubs
 *     c.Import stubs to project
 *     d.Use WSDL as generic wsdl for people to implement other web services
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //       logger.log(Level.INFO, "Inside the transport servlet");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder requestStringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            requestStringBuilder.append(line + "\n");
        }
        inputStream.close();
        PrologRESTClient restClient = new PrologRESTClient();
        JSONParser jsonParser = new JSONParser();
        ContainerFactory jsonContainerFactory = getJsonContainerFactory();
        try {
            //              out.print(requestStringBuilder.toString());
            Map<String, Object> jsonMap = (Map<String, Object>) jsonParser
                    .parse(requestStringBuilder.toString(), jsonContainerFactory);
            String transportId = (String) jsonMap.get(TRANSPORT_PARAMETER_ID);
            Object queryObject = (Object) jsonMap.get(TRANSPORT_PARAMETER_QUERY);
            String query = null;
            if (queryObject instanceof String) {
                query = (String) queryObject;
            } else if (queryObject instanceof Map) {
                query = JSONValue.toJSONString(queryObject);
            }
            if (transportId != null) {
                TransportServiceImpl transportService = getTransportModuleWebService(transportId);
                if (transportService != null) {
                    String result = (String) transportService.transport(query);
                    out.print(result);
                } else {
                    throw new TransportException(
                            "Transport Servlet could not locate transport web service with transportId: "
                                    + transportId);
                }
            } else {
                throw new TransportException("Transport Servlet not supplied with transportId");
            }
        } catch (ParseException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
        } catch (ServiceException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
        } catch (IOException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
            throw (e);
        } catch (TransportException e) {
            logger.log(Level.SEVERE, "", e);
        }
    } finally {
        out.close();
    }
    processRequest(request, response);
}

From source file:com.dreamwork.web.FrontJsonController.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestID = request.getHeader("RequestID");
    response.addHeader("RequestID", requestID);
    response.setContentType("text/json; charset=UTF-8");
    ServletInputStream in = request.getInputStream();
    ServletOutputStream out = response.getOutputStream();
    String req = "";
    try {/*from w  ww . j a va2s  .c  om*/
        req = new String(read(in), "UTF-8");

        JSONObject jsonObject = new JSONObject(req);
        JSONObject requestJson = jsonObject.getJSONObject("request");
        String to = requestJson.getString("to");
        String date = requestJson.getString("date");
        String message = requestJson.getString("message");
        ServiceHolder.getService().receiveMessage(to, df.parse(date), message);

    } catch (JSONException e) {

    } catch (IOException e) {

    } catch (RuntimeException e) {

    } catch (Exception e) {

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

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

/**
 * @param request// w  w w.  j a v a 2s  .  c  om
 * @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:org.ireland.jnetty.http.HttpServletRequestImpl.java

@Override
// ok/*from w  w w  . j a  va  2 s. co  m*/
public BufferedReader getReader() throws IOException {
    if (usingInputStream) {
        throw new IllegalStateException("using InputStream already");
    }

    usingReader = true;

    String encoding = getCharacterEncoding();

    if (encoding == null)
        encoding = "ISO-8859-1";

    if (_reader == null || !encoding.equalsIgnoreCase(_readerEncoding)) {
        final ServletInputStream in = getInputStream();
        _readerEncoding = encoding;
        _reader = new BufferedReader(new InputStreamReader(in, encoding)) {
            @Override
            public void close() throws IOException {
                in.close();
            }
        };
    }

    return _reader;
}

From source file:org.sakaiproject.tool.assessment.ui.servlet.delivery.UploadAudioMediaServlet.java

private boolean writeToFile(HttpServletRequest req, String mediaLocation) {
    // default status message, if things go wrong
    boolean mediaIsValid = false;
    String status = "Upload failure: empty media location.";
    ServletInputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    BufferedInputStream bufInputStream = null;
    BufferedOutputStream bufOutputStream = null;
    int count = 0;

    try {//www.  ja v  a2s. co m
        inputStream = req.getInputStream();
        fileOutputStream = getFileOutputStream(mediaLocation);

        // buffered input for servlet
        bufInputStream = new BufferedInputStream(inputStream);
        // buffered output to file
        bufOutputStream = new BufferedOutputStream(fileOutputStream);

        // write the binary data
        int i = 0;
        count = 0;
        if (bufInputStream != null) {
            while ((i = bufInputStream.read()) != -1) {
                bufOutputStream.write(i);
                count++;
            }
        }
        bufOutputStream.flush();

        /* Move following clean up code to finally block
        // clean up
        bufOutputStream.close();
        bufInputStream.close();
        if (inputStream != null){
          inputStream.close();
        }
        fileOutputStream.close();
        */
        status = "Acknowleged: " + mediaLocation + "-> " + count + " bytes.";
        if (count > 0)
            mediaIsValid = true;
    } catch (Exception ex) {
        log.info(ex.getMessage());
        status = "Upload failure: " + mediaLocation;
    } finally {
        if (bufOutputStream != null) {
            try {
                bufOutputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (bufInputStream != null) {
            try {
                bufInputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }
    log.info(status);
    return mediaIsValid;
}

From source file:com.bstek.dorado.view.resolver.ViewServiceResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    XmlEscapeWriter writer = new XmlEscapeWriter(getWriter(request, response));

    JsonBuilder jsonBuilder = new JsonBuilder(writer);
    ServletInputStream in = request.getInputStream();
    DoradoContext context = DoradoContext.getCurrent();
    try {//from   www.j  a v  a 2s .  c  o  m
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains(JAVASCRIPT_TOKEN)) {
            Reader reader = new InputStreamReader(in, Constants.DEFAULT_CHARSET);
            StringBuffer buf = new StringBuffer();
            char[] cs = new char[BUFFER_SIZE];
            for (int n; (n = reader.read(cs)) > 0;) {
                buf.append(new String(cs, 0, n));
            }

            ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(buf.toString());

            processTask(writer, objectNode, context);
        } else if (contentType != null && contentType.contains(XML_TOKEN)) {
            Document document = getXmlDocumentBuilder(context)
                    .loadDocument(new InputStreamResource(in, request.getRequestURI()));

            writer.append("<?xml version=\"1.0\" encoding=\"" + Constants.DEFAULT_CHARSET + "\"?>\n");
            writer.append("<result>\n");

            Writer escapeWriter = new XmlEscapeWriter(writer);
            for (Element element : DomUtils.getChildElements(document.getDocumentElement())) {
                writer.append("<request>\n");
                writer.append("<response type=\"json\"><![CDATA[\n");
                writer.setEscapeEnabled(true);

                String textContent = DomUtils.getTextContent(element);

                ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(textContent);
                try {
                    processTask(escapeWriter, objectNode, context);
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                } catch (Exception e) {
                    Throwable t = e;
                    while (t.getCause() != null) {
                        t = t.getCause();
                    }
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                    if (t instanceof ClientRunnableException) {
                        writer.append("<exception type=\"runnable\"><![CDATA[");
                        writer.setEscapeEnabled(true);
                        writer.append("(function(){").append(((ClientRunnableException) t).getScript())
                                .append("})");
                    } else {
                        writer.append("<exception><![CDATA[\n");
                        writer.setEscapeEnabled(true);
                        outputException(jsonBuilder, e);
                    }
                    writer.setEscapeEnabled(false);
                    writer.append("\n]]></exception>\n");
                    logger.error(e, e);
                }
                writer.append("</request>\n");
            }

            writer.append("</result>");
        }
    } catch (Exception e) {
        in.close();

        Throwable t = e;
        while (t.getCause() != null) {
            t = t.getCause();
        }

        if (t instanceof ClientRunnableException) {
            response.setContentType("text/runnable");
            writer.append("(function(){").append(((ClientRunnableException) t).getScript()).append("})");
        } else {
            response.setContentType("text/dorado-exception");
            outputException(jsonBuilder, e);
        }

        logger.error(e, e);
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
 * All actions come here to process the request body. We check if it is JSON.
 * DELETE is a special case because the content could be JSON or just the @id string and it only has to specify a content type if passing a JSONy object.  
 * and pretty format it. Returns pretty stringified JSON or fail to null.
 * Methods that call this should handle requestBody==null as unexpected.
 * @param http_request Incoming request to check.
 * @param supportStringID The request may be allowed to pass the @id as the body.
 * @return String of anticipated JSON format.
 * @throws java.io.IOException/*from  ww w  .jav a2s .c o m*/
 * @throws javax.servlet.ServletException
 * @throws java.lang.Exception
 */
public String processRequestBody(HttpServletRequest http_request, boolean supportStringID)
        throws IOException, ServletException, Exception {
    String cType = http_request.getContentType();
    http_request.setCharacterEncoding("UTF-8");
    String requestBody;
    JSONObject complianceInfo = new JSONObject();
    /* UTF-8 special character support for requests */
    //http://biercoff.com/malformedinputexception-input-length-1-exception-solution-for-scala-and-java/
    ServletInputStream input = http_request.getInputStream();
    //CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
    //decoder.onMalformedInput(CodingErrorAction.REPLACE);
    InputStreamReader reader = new InputStreamReader(input, "utf-8");
    //bodyReader = new BufferedReader( reader );
    //System.out.println("Process req body...");
    bodyReader = new BufferedReader(reader);
    //System.out.println("...got reader");
    bodyString = new StringBuilder();
    String line;
    JSONObject test;
    JSONArray test2;
    if (null != cType && (cType.contains("application/json") || cType.contains("application/ld+json"))) {
        //System.out.println("Processing because it was jsony");
        //Note special characters cause this to break right here. 
        try {
            while ((line = bodyReader.readLine()) != null) {
                bodyString.append(line);
            }
        } catch (Exception e) {
            System.out.println("Couldn't access body to read");
            System.out.println(e);
        }

        //System.out.println("built body string");
        requestBody = bodyString.toString();
        //System.out.println("here is the bodyString");
        //System.out.println(requestBody);
        try {
            //JSONObject test
            test = JSONObject.fromObject(requestBody);
        } catch (Exception ex) {
            System.out.println("not a json object for processing");
            if (supportStringID) {
                //We do not allow arrays of ID's for DELETE, so if it failed JSONObject parsing then this is a hard fail for DELETE.
                //They attempted to provide a JSON object for DELETE but it was not valid JSON
                writeErrorResponse("The data passed was not valid JSON.  Could not get @id: " + requestBody,
                        HttpServletResponse.SC_BAD_REQUEST);
                requestBody = null;
            } else {
                //Maybe it was an action on a JSONArray, check that before failing JSON parse test.
                try {
                    //JSONArray test
                    test2 = JSONArray.fromObject(requestBody);
                } catch (Exception ex2) {
                    // not a JSONObject or a JSONArray. 
                    writeErrorResponse("The data passed was not valid JSON:\n" + requestBody,
                            HttpServletResponse.SC_BAD_REQUEST);
                    requestBody = null;
                }
            }
        }
        // no-catch: Is either JSONObject or JSON Array
    } else {
        if (supportStringID) { //Content type is not JSONy, looking for @id string as body
            while ((line = bodyReader.readLine()) != null) {
                bodyString.append(line);
            }
            requestBody = bodyString.toString();
            try {
                test = JSONObject.fromObject(requestBody);
                if (test.containsKey("@id")) {
                    requestBody = test.getString("@id");
                    if ("".equals(requestBody)) {
                        //No ID provided
                        writeErrorResponse(
                                "Must provide an id or a JSON object containing @id of object to perform this action.",
                                HttpServletResponse.SC_BAD_REQUEST);
                        requestBody = null;
                    } else {
                        // This string could be ANYTHING.  ANY string is valid at this point.  Create a wrapper JSONObject for elegant handling in deleteObject().  
                        // We will check against the string for existing objects in deleteObject(), processing the body is completed as far as this method is concerned.
                        JSONObject modifiedDeleteRequest = new JSONObject();
                        modifiedDeleteRequest.element("@id", requestBody);
                        requestBody = modifiedDeleteRequest.toString();
                    }
                }
            } catch (Exception e) {
                //This is good, they should not be using a JSONObject
                if ("".equals(requestBody)) {
                    //No ID provided
                    writeErrorResponse(
                            "Must provide an id or a JSON object containing @id of object to delete.",
                            HttpServletResponse.SC_BAD_REQUEST);
                    requestBody = null;
                } else {
                    // This string could be ANYTHING.  ANY string is valid at this point.  Create a wrapper JSONObject for elegant handling in deleteObject().  
                    // We will check against the string for existing objects in deleteObject(), processing the body is completed as far as this method is concerned.
                    JSONObject modifiedDeleteRequest = new JSONObject();
                    modifiedDeleteRequest.element("@id", requestBody);
                    requestBody = modifiedDeleteRequest.toString();
                }
            }
        } else { //This is an error, actions must use the correct content type
            writeErrorResponse("Invalid Content-Type. Please use 'application/json' or 'application/ld+json'",
                    HttpServletResponse.SC_BAD_REQUEST);
            requestBody = null;
        }
    }
    //@cubap @theHabes TODO IIIF compliance handling on action objects
    /*
    if(null != requestBody){
    complianceInfo = checkIIIFCompliance(requestBody, "2.1");
    if(complianceInfo.getInt("okay") < 1){
        writeErrorResponse(complianceInfo.toString(), HttpServletResponse.SC_CONFLICT);
        requestBody = null;
    }
    }
    */
    reader.close();
    input.close();
    content = requestBody;
    response.setContentType("application/json; charset=utf-8"); // We create JSON objects for the return body in most cases.  
    response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    response.addHeader("Access-Control-Allow-Methods", "GET,OPTIONS,HEAD,PUT,PATCH,DELETE,POST"); // Must have OPTIONS for @webanno 
    return requestBody;
}

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");
    }// w w w.j av a2  s .c o  m
    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");
}