/*
 * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.wso2.carbon.mss.examples.petstore.fileserver;

import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.mss.HttpResponder;
import org.wso2.carbon.mss.HttpStreamHandler;
import org.wso2.carbon.mss.HttpStreamer;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

/**
 * FileServer service class. This uses request streaming
 * to save the submitted files in the server.
 */
@Path("/")
public class FileServerService {

    private static final Logger log = LoggerFactory.getLogger(FileServerService.class);

    @POST
    @Path("/{fileName}")
    public void postFile(@Context HttpStreamer httpStreamer,
                         @PathParam("fileName") String fileName)
            throws IOException {
        httpStreamer.callback(new HttpStreamHandlerImpl(fileName));
    }

    @POST
    @Path("/{fileName}")
    public Response getFile(@PathParam("fileName") String fileName) {
        File file = Paths.get("fs", fileName).toFile();
        if (file.exists()) {
            return Response.ok(file).build();
        }
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    private static class HttpStreamHandlerImpl implements HttpStreamHandler {
        private BufferedOutputStream outputStream = null;

        public HttpStreamHandlerImpl(String fileName) throws FileNotFoundException {
            File file = Paths.get("fs", fileName).toFile();
            if (!file.exists() || file.exists() && file.delete()) {
                outputStream = new BufferedOutputStream(new FileOutputStream(file));
            }
        }

        @Override
        public void chunk(ByteBuf request, HttpResponder responder) throws IOException {
            if (outputStream == null) {
                throw new IOException("Unable to write file");
            }
            outputStream.write(request.array());
        }

        @Override
        public void finished(ByteBuf request, HttpResponder responder) throws IOException {
            if (outputStream == null) {
                throw new IOException("Unable to write file");
            }
            outputStream.write(request.array());
            outputStream.close();
        }

        @Override
        public void error(Throwable cause) {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                // Log if unable to close the output stream
                log.error("Unable to close file output stream", e);
            }
        }
    }
}

@@ -750,16 +750,71 @@
 yteBuf;%0A
+import io.netty.handler.codec.http.HttpResponseStatus;%0A
 import o
@@ -826,24 +826,24 @@
 f4j.Logger;%0A
-
 import org.s
@@ -1177,16 +1177,40 @@
 .Paths;%0A
+import javax.ws.rs.GET;%0A
 import j
@@ -1864,27 +1864,26 @@
     %7D%0A%0A    @
-POS
+GE
 T%0A    @Path(
@@ -2484,30 +2484,28 @@
 if (
-!
 file.
-exists() %7C%7C f
+getParentF
 ile
+()
 .exi
@@ -2514,22 +2514,38 @@
 s() 
-&&
+%7C%7C
  file.
-delete
+getParentFile().mkdirs
 ()) 
@@ -2884,32 +2884,50 @@
   %7D%0A            
+request.readBytes(
 outputStream.wri
@@ -2918,39 +2918,34 @@
 outputStream
-.write(
+, 
 request.
 array());%0A  
@@ -2924,36 +2924,39 @@
 Stream, request.
-arra
+capacit
 y());%0A        %7D%0A
@@ -3187,32 +3187,50 @@
   %7D%0A            
+request.readBytes(
 outputStream.wri
@@ -3229,23 +3229,18 @@
 ream
-.write(
+, 
 request.
 arra
@@ -3239,12 +3239,15 @@
 est.
-arra
+capacit
 y())
@@ -3274,32 +3274,95 @@
 Stream.close();%0A
+            responder.sendStatus(HttpResponseStatus.ACCEPTED);%0A
         %7D%0A%0A     

Fix file writing and send HTTP Accepted response