Example usage for io.netty.handler.codec.http.multipart FileUpload getFilename

List of usage examples for io.netty.handler.codec.http.multipart FileUpload getFilename

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.multipart FileUpload getFilename.

Prototype

String getFilename();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:com.chiorichan.http.UploadedFile.java

License:Mozilla Public License

public UploadedFile(FileUpload fileUpload) throws IOException {
    cachedFileUpload = fileUpload;/*w w w .  ja  v  a 2  s.c  om*/

    origFileName = fileUpload.getFilename();
    size = fileUpload.length();
    message = "File upload was successful!";

    if (!fileUpload.isInMemory())
        file = fileUpload.getFile();
}

From source file:com.netty.file.HttpUploadServerHandler.java

License:Apache License

private void writeHttpData(InterfaceHttpData data) {
    if (data.getHttpDataType() == HttpDataType.Attribute) {
        Attribute attribute = (Attribute) data;
        String value;//from   w  w w . j  av a2s.  c  o  m
        try {
            value = attribute.getValue();
        } catch (IOException e1) {
            // Error while reading data from File, only print name and error
            e1.printStackTrace();
            responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": "
                    + attribute.getName() + " Error while reading value: " + e1.getMessage() + "\r\n");
            return;
        }
        if (value.length() > 100) {
            responseContent.append("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": "
                    + attribute.getName() + " data too long\r\n");
        } else {
            responseContent.append(
                    "\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": " + attribute + "\r\n");
        }
    } else {
        responseContent.append(
                "\r\nBODY FileUpload: " + data.getHttpDataType().name() + ": ghjklkjhkljl" + data + "\r\n");
        if (data.getHttpDataType() == HttpDataType.FileUpload) {
            FileUpload fileUpload = (FileUpload) data;
            System.out.println(fileUpload.getFilename());
            try {
                FileUtils.writeByteArrayToFile(
                        new File("C:\\Users\\abhay.jain\\Desktop\\Abhay1\\" + fileUpload.getFilename()),
                        fileUpload.content().array());
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (fileUpload.isCompleted()) {
                responseContent.append("\tContent of file\r\n");
                try {
                    responseContent.append(fileUpload.getString(fileUpload.getCharset()));
                } catch (IOException e1) {
                    // do nothing for the example
                    e1.printStackTrace();
                }
                responseContent.append("\r\n");
                // fileUpload.isInMemory();// tells if the file is in Memory
                // or on File
                // fileUpload.renameTo(dest); // enable to move into another
                // File dest
                // decoder.removeFileUploadFromClean(fileUpload); //remove
                // the File of to delete file
            } else {
                responseContent.append("\tFile to be continued but should not!\r\n");
            }
        }
    }
}

From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java

License:Apache License

private String writeHttpData(InterfaceHttpData data, String globalId, boolean isChunked) throws IOException {

    logger.info("HTTP DATA name - " + data.getHttpDataType().name());

    String fileUploadResultInfo = "";

    if (data.getHttpDataType() == HttpDataType.Attribute) {
        Attribute attribute = (Attribute) data;
        String name = attribute.getName();
        String value = attribute.getValue();
        logger.info("name - " + name + ", value - " + value);
        fileUploadResultInfo = "\"name - \" + name + \", value - \" + value";

    } else if (data.getHttpDataType() == HttpDataType.FileUpload) {
        FileUpload fileUpload = (FileUpload) data;
        if (fileUpload.isCompleted()) {

            // print file info
            logger.info("data - " + data);
            logger.info("File name: " + fileUpload.getFilename() + ", length - " + fileUpload.length());
            logger.info("File isInMemory - " + fileUpload.isInMemory());

            //isChuned ??
            if (isChunked) {
                logger.info("File meqaUpload to localDisk as tempFile...");

                MeqaUpload record = fileRecordManager.findMeqaInfoById(globalId);

                if (record.getCurrentShard() < record.getShardSize()) {
                    boolean fileWriteStatus = false;
                    try (FileInputStream uploadFileStream = new FileInputStream(fileUpload.getFile());
                            FileOutputStream diskTempFileStream = new FileOutputStream(
                                    new File("/" + fileUpload.getFilename()));
                            FileChannel uploadFileChannel = uploadFileStream.getChannel();
                            FileChannel diskTempFileChannel = diskTempFileStream.getChannel()) {
                        uploadFileChannel.transferTo(0, uploadFileChannel.size(), diskTempFileChannel);
                        fileWriteStatus = true;
                    } catch (IOException e) {
                        logger.error(e);
                    } finally {
                        decoder.removeHttpDataFromClean(fileUpload);
                    }// w  w w  .j a v  a2  s  .  co  m

                    if (fileWriteStatus) {
                        int updateCount = fileRecordManager.incrementCurrentSize(globalId);

                        if (record.getCurrentShard() + 1 < record.getShardSize())
                            fileUploadResultInfo = "203";

                        else if (record.getCurrentShard() + 1 == record.getShardSize()) {

                            FileUtil fileUtil = new FileUtil();

                            String fileName = record.getFileName().split("\\.")[0];
                            // ??
                            byte[] fileByte = fileUtil.mergePartFiles(fileName, record.getPartFileSize(),
                                    record.getFileName());

                            fileUploadResultInfo = "200  meqa Files combine completed!";

                            Response<FileRecord> result = getFileRecordResponse(fileByte, record.getFileName(),
                                    globalId);

                            fileUploadResultInfo += JsonFormat.convertJson(result.getData()).get();
                        }
                    }
                } else
                    fileUploadResultInfo = "500  Duplicate Files";
            } else {
                Response<FileRecord> result = getFileRecordResponse(fileUpload.get(), fileUpload.getFilename(),
                        globalId);

                decoder.removeHttpDataFromClean(fileUpload);

                fileUploadResultInfo = JsonFormat.convertJson(result.getData()).get();
            }
        } else {
            logger.info("File to be continued!");
            fileUploadResultInfo = "File to be continued!";
        }
    }
    return fileUploadResultInfo;
}

From source file:dpfmanager.shell.modules.server.post.HttpPostHandler.java

License:Open Source License

private void parseFileUploadData(FileUpload fileUpload) throws IOException {
    if (fileUpload.isCompleted()) {
        destFolder = createNewDirectory(uuid);
        if (fileUpload.getName().equals("config")) {
            // Save config file
            File dest = new File(destFolder.getAbsolutePath() + "/config.dpf");
            configpath = dest.getAbsolutePath();
            fileUpload.renameTo(dest);//from   w  w w  . jav  a2 s.  co  m
        } else {
            // Save file to check
            File dest = new File(destFolder.getAbsolutePath() + "/" + fileUpload.getFilename());
            if (filepath == null) {
                filepath = dest.getAbsolutePath();
            } else {
                filepath = filepath + ";" + dest.getAbsolutePath();
            }
            fileUpload.renameTo(dest);
        }
    }
}

From source file:firebats.http.server.exts.form.Form.java

License:Apache License

private static Form decodeWithContent(Context context, ByteBuf content) {
    //new DefaultHttpDataFactory(/*useDisk*/true)decoder?
    //Mix?16K???/*from www .  j av a2 s.c  o  m*/
    //       final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(/*useDisk*/true),toNettyHttpRequest(context.request));
    HttpServerRequest<ByteBuf> rxRequest = context.getRequest();
    HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, rxRequest.getHttpMethod(),
            rxRequest.getUri());
    for (Map.Entry<String, String> header : rxRequest.getHeaders().entries()) {
        nettyRequest.headers().add(header.getKey(), header.getValue());
    }
    final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(nettyRequest);
    HttpContent httpContent = new DefaultHttpContent(content);
    decoder.offer(httpContent);
    decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT);

    Map<String, String> formParams = new LinkedHashMap<>();
    Map<String, UploadedFile> files = new LinkedHashMap<>();
    try {
        while (decoder.hasNext()) {
            InterfaceHttpData data = decoder.next();
            if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.Attribute)) {
                try {
                    Attribute attr = (Attribute) data;
                    if (!formParams.containsKey(data.getName())) {
                        formParams.put(attr.getName(), attr.getValue());
                    }
                } catch (IOException e) {
                    Throwables.propagate(e);
                } finally {
                    //?
                    data.release();
                }
            } else if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.FileUpload)) {
                try {
                    if (!files.containsKey(data.getName())) {
                        final FileUpload nettyFileUpload = (FileUpload) data;
                        final ByteBuf byteBuf = nettyFileUpload.content();
                        byteBuf.retain();
                        context.onComplete(new Action0() {
                            @Override
                            public void call() {
                                if (log.isDebugEnabled()) {
                                    log.debug("form upload file release[" + data.getName() + ":"
                                            + nettyFileUpload.getFilename() + "]");
                                }
                                byteBuf.release();
                            }
                        });
                        UploadedFile fileUpload = new UploadedFile(nettyFileUpload.getFilename(),
                                nettyFileUpload.getContentType(), byteBuf);
                        files.put(data.getName(), fileUpload);
                    }
                } finally {
                    data.release();
                }
            }
        }
    } catch (HttpPostRequestDecoder.EndOfDataDecoderException ignore) {
        // ignore
    } finally {
        decoder.destroy();
    }
    Map<String, String> query = Form.toFlatQueryParams(context.getRequest().getQueryParameters());
    return fromAll(query, formParams, files);
}

From source file:holon.internal.http.netty.NettyServerHandler.java

License:Open Source License

private void storeFormData(InterfaceHttpData data) {
    try {// ww  w.  j  ava  2s .co m
        if (data.getHttpDataType() == HttpDataType.Attribute) {
            Attribute attribute = (Attribute) data;
            formParams.put(attribute.getName(), attribute.getValue());
        } else {
            if (data.getHttpDataType() == HttpDataType.FileUpload) {
                FileUpload fileUpload = (FileUpload) data;
                if (fileUpload.isCompleted()) {
                    File tempFile = File.createTempFile("holon", "upload");
                    fileUpload.renameTo(tempFile);
                    formParams.put(fileUpload.getName(), new UploadedFile() {
                        @Override
                        public String fileName() {
                            return fileUpload.getFilename();
                        }

                        @Override
                        public String contentType() {
                            return fileUpload.getContentType();
                        }

                        @Override
                        public File file() {
                            return tempFile;
                        }
                    });
                } else {
                    System.out.println("File upload should have been completed here!");
                }
            }
        }
    } catch (IOException e1) {
        // Error while reading data from File, only print name and error
        e1.printStackTrace();
        return;
    }
}

From source file:io.syncframework.netty.RequestHandler.java

License:Apache License

/**
 * Example of reading request by chunk and getting values from chunk to chunk
 *//* ww  w.  j  a va 2  s.c  om*/
private void readHttpDataChunkByChunk() throws Exception {
    try {
        while (decoder.hasNext()) {
            InterfaceHttpData data = decoder.next();
            if (data != null) {
                try {
                    if (log.isTraceEnabled())
                        log.trace("data[{}]", data);
                    // new value
                    if (data.getHttpDataType() == HttpDataType.Attribute) {
                        Attribute attribute = (Attribute) data;
                        String value = attribute.getValue();
                        Map<String, List<String>> parameters = requestWrapper.getParameters();
                        List<String> values = parameters.get(attribute.getName());
                        if (values == null)
                            values = new LinkedList<String>();
                        values.add(value);
                        parameters.put(attribute.getName(), values);
                    } else if (data.getHttpDataType() == HttpDataType.FileUpload) {
                        FileUpload fileUpload = (FileUpload) data;

                        if (fileUpload.getFilename() == null || fileUpload.getFilename().equals("")) {
                            if (log.isTraceEnabled())
                                log.trace("fileupload filename is null or empty; returning");
                            decoder.removeHttpDataFromClean(fileUpload);
                            return;
                        }

                        if (fileUpload.isCompleted()) {

                            // in this case we shall place the file to the <application>/tmp directory

                            String domain = this.request.headers().getAsString(HttpHeaderNames.HOST);
                            if (log.isTraceEnabled())
                                log.trace("request host: {}", domain);
                            int p = domain.indexOf(':');
                            if (p != -1)
                                domain = domain.substring(0, p);
                            Application application = ApplicationManager.getApplication(domain);
                            if (application == null) {
                                throw new RuntimeException(
                                        "no application found responsible for domain " + domain);
                            }

                            String applicationHome = (String) application.getContext()
                                    .get(ApplicationContext.HOME);
                            String tmpDirectoryPath = applicationHome + File.separator + "tmp";
                            File tmpfile = new File(tmpDirectoryPath, fileUpload.getFilename());

                            if (fileUpload.isInMemory()) {
                                if (!fileUpload.renameTo(tmpfile)) {
                                    throw new RuntimeException(
                                            "failed to place the upload file under the directory: "
                                                    + tmpDirectoryPath);
                                }
                            } else {
                                if (!fileUpload.getFile().renameTo(tmpfile)) {
                                    decoder.removeHttpDataFromClean(fileUpload);
                                    throw new RuntimeException(
                                            "failed to place the upload file under the directory: "
                                                    + tmpDirectoryPath);
                                }
                            }

                            io.syncframework.api.FileUpload fu = new io.syncframework.api.FileUpload();
                            fu.setName(fileUpload.getFilename());
                            fu.setType(fileUpload.getContentType());
                            fu.setFile(new File(tmpDirectoryPath, fileUpload.getFilename()));
                            requestWrapper.getFiles().put(fileUpload.getName(), fu);
                        } else {
                            log.error("file yet to be completed but should not");
                        }
                    } else {
                        log.warn("why is falling into this category ?");
                    }
                } finally {
                    data.release();
                }
            }
        }
    } catch (EndOfDataDecoderException ignore) {
        // just ignore
    }
}

From source file:io.werval.server.netty.NettyHttpFactories.java

License:Apache License

static Request requestOf(Charset defaultCharset, HttpBuildersSPI builders,
        String remoteSocketAddress, String identity, FullHttpRequest request)
        throws HttpRequestParsingException {
    ensureNotEmpty("Request Identity", identity);
    ensureNotNull("Netty FullHttpRequest", request);

    try {/* w  ww  . java  2 s. co  m*/
        RequestBuilder builder = builders.newRequestBuilder().identifiedBy(identity)
                .remoteSocketAddress(remoteSocketAddress)
                .version(ProtocolVersion.valueOf(request.getProtocolVersion().text()))
                .method(request.getMethod().name()).uri(request.getUri())
                .headers(headersToMap(request.headers()));

        if (request.content().readableBytes() > 0 && (POST.equals(request.getMethod())
                || PUT.equals(request.getMethod()) || PATCH.equals(request.getMethod()))) {
            Optional<String> contentType = Headers.extractContentMimeType(request.headers().get(CONTENT_TYPE));
            if (contentType.isPresent()) {
                switch (contentType.get()) {
                case APPLICATION_X_WWW_FORM_URLENCODED:
                case MULTIPART_FORM_DATA:
                    try {
                        Map<String, List<String>> attributes = new LinkedHashMap<>();
                        Map<String, List<Upload>> uploads = new LinkedHashMap<>();
                        HttpPostRequestDecoder postDecoder = new HttpPostRequestDecoder(request);
                        for (InterfaceHttpData data : postDecoder.getBodyHttpDatas()) {
                            switch (data.getHttpDataType()) {
                            case Attribute:
                                Attribute attribute = (Attribute) data;
                                if (!attributes.containsKey(attribute.getName())) {
                                    attributes.put(attribute.getName(), new ArrayList<>());
                                }
                                attributes.get(attribute.getName()).add(attribute.getValue());
                                break;
                            case FileUpload:
                                FileUpload fileUpload = (FileUpload) data;
                                if (!uploads.containsKey(fileUpload.getName())) {
                                    uploads.put(fileUpload.getName(), new ArrayList<>());
                                }
                                Upload upload;
                                if (fileUpload.isInMemory()) {
                                    upload = new UploadInstance(fileUpload.getContentType(),
                                            fileUpload.getCharset(), fileUpload.getFilename(),
                                            new ByteBufByteSource(fileUpload.getByteBuf()).asBytes(),
                                            defaultCharset);
                                } else {
                                    upload = new UploadInstance(fileUpload.getContentType(),
                                            fileUpload.getCharset(), fileUpload.getFilename(),
                                            fileUpload.getFile(), defaultCharset);
                                }
                                uploads.get(fileUpload.getName()).add(upload);
                                break;
                            default:
                                break;
                            }
                        }
                        builder = builder.bodyForm(attributes, uploads);
                        break;
                    } catch (ErrorDataDecoderException | IncompatibleDataDecoderException
                            | NotEnoughDataDecoderException | IOException ex) {
                        throw new WervalException("Form or multipart parsing error", ex);
                    }
                default:
                    builder = builder.bodyBytes(new ByteBufByteSource(request.content()));
                    break;
                }
            } else {
                builder = builder.bodyBytes(new ByteBufByteSource(request.content()));
            }
        }
        return builder.build();
    } catch (Exception ex) {
        throw new HttpRequestParsingException(ex);
    }
}

From source file:org.knoxcraft.netty.server.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    try {//from w  w  w . j  a  v a  2 s.co  m
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest fullRequest = (FullHttpRequest) msg;
            if (fullRequest.getUri().startsWith("/kctupload")) {

                if (fullRequest.getMethod().equals(HttpMethod.GET)) {
                    // HTTP Get request!
                    // Write the HTML page with the form
                    writeMenu(ctx);
                } else if (fullRequest.getMethod().equals(HttpMethod.POST)) {
                    /* 
                     * HTTP Post request! Handle the uploaded form
                     * HTTP parameters:
                            
                    /kctupload
                    username (should match player's Minecraft name)
                    language (java, python, etc)
                    jsonfile (a file upload, or empty)
                    sourcefile (a file upload, or empty)
                    jsontext (a JSON string, or empty)
                    sourcetext (code as a String, or empty)
                     */

                    String language = null;
                    String playerName = null;
                    String client = null;
                    String jsonText = null;
                    String sourceText = null;
                    Map<String, UploadedFile> files = new LinkedHashMap<String, UploadedFile>();

                    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(fullRequest);
                    try {
                        logger.trace("is multipart? " + decoder.isMultipart());
                        while (decoder.hasNext()) {
                            InterfaceHttpData data = decoder.next();
                            if (data == null)
                                continue;

                            try {
                                if (data.getHttpDataType() == HttpDataType.Attribute) {
                                    Attribute attribute = (Attribute) data;
                                    String name = attribute.getName();
                                    String value = attribute.getValue();
                                    logger.trace(String.format("http attribute: %s => %s", name, value));
                                    if (name.equals("language")) {
                                        language = value;
                                    } else if (name.equals("playerName")) {
                                        playerName = value;
                                    } else if (name.equals("client")) {
                                        client = value;
                                    } else if (name.equals("jsontext")) {
                                        jsonText = value;
                                    } else if (name.equals("sourcetext")) {
                                        sourceText = value;
                                    } else {
                                        logger.warn(String.format("Unknown kctupload attribute: %s => %s", name,
                                                value));
                                    }
                                } else if (data.getHttpDataType() == HttpDataType.FileUpload) {
                                    // Handle file upload
                                    // We may have json, source, or both
                                    FileUpload fileUpload = (FileUpload) data;
                                    logger.debug(String.format("http file upload name %s, filename: ",
                                            data.getName(), fileUpload.getFilename()));
                                    String filename = fileUpload.getFilename();
                                    ByteBuf buf = fileUpload.getByteBuf();
                                    String fileBody = new String(buf.array(), "UTF-8");
                                    files.put(data.getName(), new UploadedFile(filename, fileBody));
                                }
                            } finally {
                                data.release();
                            }
                        }
                    } finally {
                        if (decoder != null) {
                            // clean up resources
                            decoder.cleanFiles();
                            decoder.destroy();
                        }
                    }

                    /*
                     * Error checking here makes the most sense, since we can send back a reasonable error message
                     * to the uploading client at this point. Makes less sense to wait to compile.
                     * 
                     * Upload possibilities:
                     * 
                     * bluej: file1, file2, etc. All source code. Language should be set to Java.
                     * Convert to JSON, then to KCTScript. Signal an error if one happens.
                     * 
                     * web: jsontext and/or sourcetext. json-only is OK; source-only is OK if it's Java. 
                     * Cannot send source-only for non-Java languages, since we can't build them (yet).
                     * 
                     * anything else: convert to Json and hope for the best
                     */
                    try {
                        KCTUploadHook hook = new KCTUploadHook();
                        StringBuilder res = new StringBuilder();

                        if (playerName == null || playerName.equals("")) {
                            // XXX How do we know that the playerName is valid?
                            // TODO: authenticate against Mojang's server?
                            throw new TurtleException("You must specify your MineCraft player name!");
                        }

                        if (client == null) {
                            throw new TurtleException("Your uploading and submission system must specify "
                                    + "the type of client used for the upload (i.e. bluej, web, pykc, etc)");
                        }

                        hook.setPlayerName(playerName);
                        res.append(
                                String.format("Hello %s! Thanks for using KnoxCraft Turtles\n\n", playerName));

                        TurtleCompiler turtleCompiler = new TurtleCompiler(logger);
                        int success = 0;
                        int failure = 0;
                        if (client.equalsIgnoreCase("web") || client.equalsIgnoreCase("testclient")
                                || client.startsWith("pykc")) {
                            // WEB OR PYTHON UPLOAD
                            logger.trace("Upload from web");
                            // must have both Json and source, either in text area or as uploaded files
                            //XXX Conlfict of comments of the top and here??? What do we need both/ only JSon?
                            //Is there a want we want, thus forcing it
                            if (sourceText != null && jsonText != null) {
                                KCTScript script = turtleCompiler.parseFromJson(jsonText);
                                script.setLanguage(language);
                                script.setSourceCode(sourceText);
                                res.append(String.format(
                                        "Successfully uploaded KnoxCraft Turtle program "
                                                + "named %s, in programming language %s\n",
                                        script.getScriptName(), script.getLanguage()));
                                success++;
                                hook.addScript(script);
                            } else if (files.containsKey("jsonfile") && files.containsKey("sourcefile")) {
                                UploadedFile sourceUpload = files.get("sourcefile");
                                UploadedFile jsonUpload = files.get("jsonfile");
                                KCTScript script = turtleCompiler.parseFromJson(jsonUpload.body);
                                script.setLanguage(language);
                                script.setSourceCode(sourceUpload.body);
                                res.append(String.format(
                                        "Successfully uploaded KnoxCraft Turtle program "
                                                + "named %s, in programming language %s\n",
                                        script.getScriptName(), script.getLanguage()));
                                success++;
                                hook.addScript(script);
                            } else {
                                throw new TurtleException(
                                        "You must upload BOTH json and the corresponding source code "
                                                + " (either as files or pasted into the text areas)");
                            }
                        } else if ("bluej".equalsIgnoreCase(client)) {
                            // BLUEJ UPLOAD
                            logger.trace("Upload from bluej");
                            for (Entry<String, UploadedFile> entry : files.entrySet()) {
                                try {
                                    UploadedFile uploadedFile = entry.getValue();
                                    res.append(String.format("Trying to upload and compile file %s\n",
                                            uploadedFile.filename));
                                    logger.trace(String.format("Trying to upload and compile file %s\n",
                                            uploadedFile.filename));
                                    KCTScript script = turtleCompiler
                                            .compileJavaTurtleCode(uploadedFile.filename, uploadedFile.body);
                                    logger.trace("Returned KCTScript (it's JSON is): " + script.toJSONString());
                                    hook.addScript(script);
                                    res.append(String.format(
                                            "Successfully uploaded file %s and compiled KnoxCraft Turtle program "
                                                    + "named %s in programming language %s\n\n",
                                            uploadedFile.filename, script.getScriptName(),
                                            script.getLanguage()));
                                    success++;
                                } catch (TurtleCompilerException e) {
                                    logger.warn("Unable to compile Turtle code", e);
                                    res.append(String.format("%s\n\n", e.getMessage()));
                                    failure++;
                                } catch (TurtleException e) {
                                    logger.error("Error in compiling (possibly a server side error)", e);
                                    res.append(String.format("Unable to process Turtle code %s\n\n",
                                            e.getMessage()));
                                    failure++;
                                } catch (Exception e) {
                                    logger.error("Unexpected error compiling Turtle code to KCTScript", e);
                                    failure++;
                                    res.append(String.format("Failed to load script %s\n", entry.getKey()));
                                }
                            }
                        } else {
                            // UNKNOWN CLIENT UPLOAD
                            // TODO Unknown client; make a best effort to handle upload
                            res.append(String.format(
                                    "Unknown upload client: %s; making our best effort to handle the upload"));
                        }

                        res.append(String.format("\nSuccessfully uploaded %d KnoxCraft Turtles programs\n",
                                success));
                        if (failure > 0) {
                            res.append(String.format("\nFailed to upload %d KnoxCraft Turtles programs\n",
                                    failure));
                        }
                        Canary.hooks().callHook(hook);
                        writeResponse(ctx.channel(), fullRequest, res.toString(), client);
                    } catch (TurtleException e) {
                        // XXX can this still happen? Don't we catch all of these?
                        writeResponse(ctx.channel(), fullRequest, e.getMessage(), "error");
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error("Internal Server Error: Channel error", e);
        throw e;
    }
}

From source file:org.pidome.server.system.network.http.HttpRequestHandler.java

/**
 * Process the request made for http2/* w ww.  j  av  a 2 s  .  c o m*/
 *
 * @param chc The channel context.
 * @param request The url request.
 * @param writer The output writer of type HttpRequestWriterInterface.
 * @param streamId The stream Id in case of http2, when http1 leave null.
 */
protected static void processManagement(ChannelHandlerContext chc, FullHttpRequest request,
        HttpRequestWriterInterface writer, String streamId) {
    String plainIp = getPlainIp(chc.channel().remoteAddress());
    String localIp = getPlainIp(chc.channel().localAddress());
    int localPort = getPort(chc.channel().localAddress());
    try {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        String fileRequest = queryStringDecoder.path();

        if (fileRequest.equals("/")) {
            fileRequest = "/index.html";
        } else if (fileRequest.endsWith("/")) {
            fileRequest = fileRequest + "index.html";
        }

        String nakedfile = fileRequest.substring(1, fileRequest.lastIndexOf("."));
        String fileType = fileRequest.substring(fileRequest.lastIndexOf(".") + 1);

        String loginError = "";
        RemoteClientInterface client = null;
        RemoteClient remoteClient = null;

        WebRenderInterface renderClass = null;

        try {
            Set<Cookie> cookie = cookieParser(request);
            Map<RemoteClientInterface, RemoteClient> clientSet = getAuthorizedClient(request, plainIp,
                    (cookie.isEmpty() ? "" : ((Cookie) cookie.toArray()[0]).getValue()), fileRequest);
            client = clientSet.keySet().iterator().next();
            remoteClient = clientSet.get(client);
        } catch (Exception ex) {
            if (ex instanceof HttpClientNotAuthorizedException) {
                LOG.error("Not authorized at {}", plainIp, request.uri());
                loginError = "Not authorized or bad username/password";
            } else if (ex instanceof HttpClientLoggedInOnOtherLocationException) {
                LOG.error("Not authorized at {} (Logged in on other location: {}!)", plainIp, ex.getMessage());
                loginError = "Client seems to be already logged in on another location";
            } else {
                LOG.error("Not authorized at: {} (Cookie problem? ({}))", ex, ex.getMessage(), ex);
                loginError = "Problem getting authentication data, refer to log file";
            }
            if (!request.uri().equals("/jsonrpc.json")) {
                fileType = "xhtml";
                nakedfile = "login";
                fileRequest = "/login.xhtml";
            }
        }

        if (!fileType.isEmpty()) {
            switch (fileType) {
            case "xhtml":
            case "json":
            case "upload":
            case "xml":
            case "/":
                if (request.uri().startsWith("/jsonrpc.json")) {
                    renderClass = getJSONRPCRenderer(request);
                } else if (request.uri().startsWith("/xmlapi/")) {
                    /// This is a temp solution until the xml output has been transfered to the json rpc api.
                    Class classToLoad = Class.forName(
                            HttpServer.getXMLClassesRoot() + nakedfile.replace("xmlapi/", ".Webclient_"));
                    renderClass = (WebRenderInterface) classToLoad.getConstructor().newInstance();
                } else {
                    Class classToLoad = Class
                            .forName(HttpServer.getDocumentClassRoot() + nakedfile.replace("/", ".Webclient_"));
                    renderClass = (WebRenderInterface) classToLoad.getConstructor().newInstance();
                }
                renderClass.setHostData(localIp, localPort, plainIp);
                renderClass.setRequestData(queryStringDecoder.parameters());
                Map<String, String> postData = new HashMap<>();
                Map<String, byte[]> fileMap = new HashMap<>();
                if (request.method().equals(HttpMethod.POST)) {
                    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(
                            new DefaultHttpDataFactory(false), request);
                    decoder.setDiscardThreshold(0);
                    if (request instanceof HttpContent) {
                        HttpContent chunk = (HttpContent) request;
                        decoder.offer(chunk);
                        try {
                            while (decoder.hasNext()) {
                                InterfaceHttpData data = decoder.next();
                                if (data != null) {
                                    if (data.getHttpDataType()
                                            .equals(InterfaceHttpData.HttpDataType.Attribute)) {
                                        postData.put(data.getName(), ((HttpData) data).getString());
                                    } else if (data.getHttpDataType()
                                            .equals(InterfaceHttpData.HttpDataType.FileUpload)) {
                                        FileUpload fileUpload = (FileUpload) data;
                                        fileMap.put(fileUpload.getFilename(), fileUpload.get());
                                    }
                                }
                            }
                        } catch (HttpPostRequestDecoder.EndOfDataDecoderException e1) {

                        }
                        if (chunk instanceof LastHttpContent) {
                            decoder.destroy();
                            decoder = null;
                        }
                    }
                }
                renderClass.setPostData(postData);
                renderClass.setFileData(fileMap);
                renderClass.setLoginData(client, remoteClient, loginError);
                renderClass.collect();
                renderClass.setTemplate(fileRequest);

                ByteArrayOutputStream outputWriter = new ByteArrayOutputStream();
                renderClass.setOutputStream(outputWriter);

                String output = renderClass.render();
                outputWriter.close();
                writer.writeResponse(chc, HttpResponseStatus.OK, output.getBytes(), fileType, streamId, false);
                break;
            default:
                sendStaticFile(chc, writer, fileRequest, queryStringDecoder, streamId);
                break;
            }
        }
    } catch (ClassNotFoundException | Webservice404Exception ex) {
        LOG.warn("404 error: {} - {} (by {})", ex.getMessage(), ex, plainIp);
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) {
            ex.printStackTrace(pw);
            writer.writeResponse(chc, HttpResponseStatus.NOT_FOUND, return404Error().getBytes(), "html",
                    streamId, false);
        } catch (IOException exWriters) {
            LOG.error("Problem outputting 404 error: {}", exWriters.getMessage(), exWriters);
        }
    } catch (Exception ex) {
        LOG.error("500 error: {}", ex.getLocalizedMessage(), ex);
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) {
            ex.printStackTrace(pw);
            String errorOutput = sw.toString() + "\n\n" + getRandQuote();
            writer.writeResponse(chc, HttpResponseStatus.INTERNAL_SERVER_ERROR,
                    (errorOutput + "<br/><br/><p>" + getRandQuote() + "</p>").getBytes(), "", streamId, false);
        } catch (IOException exWriters) {
            LOG.error("Problem outputting 500 error: {}", exWriters.getMessage(), exWriters);
        }
    }
}