Example usage for io.netty.buffer Unpooled buffer

List of usage examples for io.netty.buffer Unpooled buffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled buffer.

Prototype

public static ByteBuf buffer() 

Source Link

Document

Creates a new big-endian Java heap buffer with reasonably small initial capacity, which expands its capacity boundlessly on demand.

Usage

From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

NettyHttpServerHandler(FugaApp app) {
    this.app = app;
    this.contentBuffer = Unpooled.buffer();

    this.serverVersion = app.getConfiguration().get("fuga.version");
    this.forwarded = app.getConfiguration().get("fuga.http.forwarded").equals("rfc7239") ? 1 : 0;
}

From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

private void reset() {
    this.httprequest = null;
    this.requestBuilder = null;
    this.decoder = false;
    this.contentBuffer = Unpooled.buffer();
}

From source file:com.chiorichan.factory.EvalFactory.java

License:Mozilla Public License

public EvalFactoryResult eval(String code, EvalMetaData meta, Site site) throws EvalFactoryException {
    EvalFactoryResult result = new EvalFactoryResult(meta, site);

    if (code == null || code.isEmpty())
        return result.setReason("Code Block was null or empty!");

    if (meta.contentType == null)
        if (meta.fileName == null)
            meta.contentType = meta.shell;
        else/*w w w . ja v a 2 s. c o m*/
            meta.contentType = ContentTypes.getContentType(meta.fileName);

    meta.source = code;
    meta.site = site;

    try {
        if (site != null)
            code = runParsers(code, site);
    } catch (Exception e) {
        result.addException(new IgnorableEvalException("Exception caught while running parsers", e));
    }

    for (PreProcessor p : preProcessors) {
        Set<String> handledTypes = new HashSet<String>(Arrays.asList(p.getHandledTypes()));

        for (String t : handledTypes)
            if (t.equalsIgnoreCase(meta.shell) || meta.contentType.toLowerCase().contains(t.toLowerCase())
                    || t.equalsIgnoreCase("all")) {
                try {
                    String evaled = p.process(meta, code);
                    if (evaled != null) {
                        code = evaled;
                        break;
                    }
                } catch (Exception e) {
                    result.addException(
                            new IgnorableEvalException("Exception caught while running PreProcessor `"
                                    + p.getClass().getSimpleName() + "`", e));
                }
            }
    }

    GroovyShellTracker tracker = getUnusedShellTracker();
    GroovyShell shell = tracker.getShell();

    shell.setVariable("__FILE__", meta.fileName);

    ByteBuf output = Unpooled.buffer();
    boolean success = false;

    Loader.getLogger().fine("Locking GroovyShell '" + shell.toString() + "' for execution of '" + meta.fileName
            + "', length '" + code.length() + "'");
    tracker.setInUse(true);

    byte[] saved = bs.toByteArray();
    bs.reset();

    for (Interpreter s : interpreters) {
        Set<String> handledTypes = new HashSet<String>(Arrays.asList(s.getHandledTypes()));

        for (String she : handledTypes) {
            if (she.equalsIgnoreCase(meta.shell) || she.equalsIgnoreCase("all")) {
                try {
                    result.obj = s.eval(meta, code, shellFactory.setShell(shell), bs);
                } catch (EvalFactoryException e) {
                    throw e;
                } catch (CompilationFailedException e) // This is usually a parsing exception
                {
                    throw new EvalFactoryException(e, shellFactory, meta);
                } catch (SecurityException e) {
                    throw new EvalFactoryException(e, shellFactory, meta);
                } catch (GroovyRuntimeException e) {
                    throw new EvalFactoryException(e, shellFactory);
                } catch (Exception e) {
                    throw new EvalFactoryException(e, shellFactory);
                }

                success = true;
                break;
            }
        }
    }

    try {
        output.writeBytes((success) ? bs.toByteArray() : code.getBytes(encoding));

        bs.reset();
        bs.write(saved);
    } catch (IOException e) {
        e.printStackTrace();
    }

    Loader.getLogger().fine("Unlocking GroovyShell '" + shell.toString() + "' for execution of '"
            + meta.fileName + "', length '" + code.length() + "'");
    tracker.setInUse(false);

    for (PostProcessor p : postProcessors) {
        Set<String> handledTypes = new HashSet<String>(Arrays.asList(p.getHandledTypes()));

        for (String t : handledTypes)
            if (t.equalsIgnoreCase(meta.shell) || meta.contentType.toLowerCase().contains(t.toLowerCase())
                    || t.equalsIgnoreCase("all")) {
                try {
                    ByteBuf finished = p.process(meta, output);
                    if (finished != null) {
                        output = finished;
                        break;
                    }
                } catch (Exception e) {
                    result.addException(
                            new IgnorableEvalException("Exception caught while running PostProcessor `"
                                    + p.getClass().getSimpleName() + "`", e));
                }
            }
    }

    return result.setResult(output, true);
}

From source file:com.chiorichan.factory.FileInterpreter.java

License:Mozilla Public License

public final void interpretParamsFromFile(File file) throws IOException {
    if (file == null)
        throw new FileNotFoundException("File path was null");

    FileInputStream is = null;/*from  w w  w  . j av a  2s  . c o m*/
    try {
        cachedFile = file;

        annotations.put("file", file.getAbsolutePath());

        if (file.isDirectory())
            annotations.put("shell", "embedded");
        else {
            if (!annotations.containsKey("shell") || annotations.get("shell") == null) {
                String shell = determineShellFromName(file.getName());
                if (shell != null && !shell.isEmpty())
                    annotations.put("shell", shell);
            }

            is = new FileInputStream(file);

            ByteBuf buf = Unpooled.wrappedBuffer(IOUtils.toByteArray(is));
            boolean beginContent = false;
            int lastInx;
            int lineCnt = 0;

            data = Unpooled.buffer();

            do {
                lastInx = buf.readerIndex();
                String l = readLine(buf);
                if (l == null)
                    break;

                if (l.trim().startsWith("@"))
                    try {
                        lineCnt++;

                        /* Only solution I could think of for CSS files since they use @annotations too, so we share them. */
                        if (ContentTypes.getContentType(file).equalsIgnoreCase("text/css"))
                            data.writeBytes((l + "\n").getBytes());
                        /* Only solution I could think of for CSS files since they use @annotations too, so we share them. */

                        String key;
                        String val = "";

                        if (l.contains(" ")) {
                            key = l.trim().substring(1, l.trim().indexOf(" "));
                            val = l.trim().substring(l.trim().indexOf(" ") + 1);
                        } else
                            key = l;

                        if (val.endsWith(";"))
                            val = val.substring(0, val.length() - 1);

                        if (val.startsWith("'") && val.endsWith("'"))
                            val = val.substring(1, val.length() - 1);

                        annotations.put(key.toLowerCase(), val);
                        Log.get().finer("Setting param '" + key + "' to '" + val + "'");

                        if (key.equals("encoding"))
                            if (Charset.isSupported(val))
                                setEncoding(Charsets.toCharset(val));
                            else
                                Log.get()
                                        .severe("The file '" + file.getAbsolutePath() + "' requested encoding '"
                                                + val + "' but it's not supported by the JVM!");
                    } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {

                    }
                else if (l.trim().isEmpty())
                    lineCnt++;
                // Continue reading, this line is empty.
                else {
                    // We encountered the beginning of the file content.
                    beginContent = true;
                    buf.readerIndex(lastInx); // This rewinds the buffer to the last reader index
                }
            } while (!beginContent);

            data.writeBytes(Strings.repeat('\n', lineCnt).getBytes());

            data.writeBytes(buf);
        }
    } finally {
        if (is != null)
            is.close();
    }
}

From source file:com.chiorichan.factory.postprocessors.ImagePostProcessor.java

License:Mozilla Public License

@Override
public ByteBuf process(EvalMetaData meta, ByteBuf buf) throws Exception {
    float x = 0;// www .j av a 2 s.  c o m
    float y = 0;

    if (meta.params != null) {
        if (meta.params.get("serverSideOptions") != null) {
            String[] params = meta.params.get("serverSideOptions").trim().split("_");

            for (String p : params) {
                if (p.toLowerCase().startsWith("width") && p.length() > 1)
                    x = Integer.parseInt(p.substring(5));
                else if ((p.toLowerCase().startsWith("x") || p.toLowerCase().startsWith("w")) && p.length() > 1)
                    x = Integer.parseInt(p.substring(1));
                else if (p.toLowerCase().startsWith("height") && p.length() > 1)
                    y = Integer.parseInt(p.substring(6));
                else if ((p.toLowerCase().startsWith("y") || p.toLowerCase().startsWith("h")) && p.length() > 1)
                    y = Integer.parseInt(p.substring(1));
                else if (p.toLowerCase().equals("thumb")) {
                    x = 150;
                    y = 0;
                    break;
                }
            }
        }

        if (meta.params.get("width") != null)
            x = Integer.parseInt(meta.params.get("width"));

        if (meta.params.get("height") != null)
            y = Integer.parseInt(meta.params.get("height"));

        if (meta.params.get("w") != null)
            x = Integer.parseInt(meta.params.get("w"));

        if (meta.params.get("h") != null)
            y = Integer.parseInt(meta.params.get("h"));

        if (meta.params.get("thumb") != null) {
            x = 150;
            y = 0;
        }
    }

    // Tests if our Post Processor can process the current image.
    List<String> readerFormats = Arrays.asList(ImageIO.getReaderFormatNames());
    List<String> writerFormats = Arrays.asList(ImageIO.getWriterFormatNames());
    if (meta.contentType != null && !readerFormats.contains(meta.contentType.split("/")[1].toLowerCase()))
        return null;

    try {
        int inx = buf.readerIndex();
        BufferedImage img = ImageIO.read(new ByteBufInputStream(buf));
        buf.readerIndex(inx);

        if (img != null) {
            float w = img.getWidth();
            float h = img.getHeight();
            float w1 = w;
            float h1 = h;

            if (x < 1 && y < 1) {
                x = w;
                y = h;
            } else if (x > 0 && y < 1) {
                w1 = x;
                h1 = x * (h / w);
            } else if (y > 0 && x < 1) {
                w1 = y * (w / h);
                h1 = y;
            } else if (x > 0 && y > 0) {
                w1 = x;
                h1 = y;
            }

            if (w1 < 1 || h1 < 1 || (w1 == w && h1 == h))
                return null;

            Image image = img.getScaledInstance(Math.round(w1), Math.round(h1),
                    Loader.getConfig().getBoolean("advanced.processors.useFastGraphics", true)
                            ? Image.SCALE_FAST
                            : Image.SCALE_SMOOTH);

            BufferedImage rtn = new BufferedImage(Math.round(w1), Math.round(h1), img.getType());
            Graphics2D graphics = rtn.createGraphics();
            graphics.drawImage(image, 0, 0, null);
            graphics.dispose();

            Loader.getLogger().info(ConsoleColor.GRAY + "Resized image from " + Math.round(w) + "px by "
                    + Math.round(h) + "px to " + Math.round(w1) + "px by " + Math.round(h1) + "px");

            if (rtn != null) {
                ByteArrayOutputStream bs = new ByteArrayOutputStream();

                if (meta.contentType != null
                        && writerFormats.contains(meta.contentType.split("/")[1].toLowerCase()))
                    ImageIO.write(rtn, meta.contentType.split("/")[1].toLowerCase(), bs);
                else
                    ImageIO.write(rtn, "png", bs);

                return Unpooled.buffer().writeBytes(bs.toByteArray());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.chiorichan.factory.postprocessors.JSMinPostProcessor.java

License:Mozilla Public License

@Override
public ByteBuf process(EvalMetaData meta, ByteBuf buf) throws Exception {
    // A simple way to ignore JS files that might already be minimized
    if (meta.fileName != null && meta.fileName.toLowerCase().endsWith(".min.js"))
        return buf;

    String code = buf.toString(Charset.defaultCharset());
    List<SourceFile> externs = Lists.newArrayList();
    List<SourceFile> inputs = Arrays.asList(SourceFile.fromCode(
            (meta.fileName == null || meta.fileName.isEmpty()) ? "fakefile.js" : meta.fileName, code));

    Compiler compiler = new Compiler();

    CompilerOptions options = new CompilerOptions();

    CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

    compiler.compile(externs, inputs, options);

    return Unpooled.buffer().writeBytes(StringUtils.trimToNull(compiler.toSource()).getBytes());
}

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

License:Mozilla Public License

/**
 * Handles the HTTP request. Each HTTP subsystem will be explicitly activated until a resolve is determined.
 *
 * @throws IOException// w  ww  . j a  v a2 s.  c  o m
 *              Universal exception for all Input/Output errors
 * @throws HttpError
 *              for HTTP Errors
 * @throws PermissionException
 *              for permission problems, like access denied
 * @throws MultipleException
 *              for multiple Scripting Factory Evaluation Exceptions
 * @throws ScriptingException
 *              for Scripting Factory Evaluation Exception
 * @throws SessionException
 *              for problems initializing a new or used session
 */
private void handleHttp() throws Exception // IOException, HttpError, SiteException, PermissionException, MultipleException, ScriptingException, SessionException
{
    log.log(Level.INFO, request.methodString() + " " + request.getFullUrl());

    Session sess = request.startSession();

    log.log(Level.FINE, "Session {id=%s,timeout=%s,new=%s}", sess.getSessId(), sess.getTimeout(), sess.isNew());

    if (response.getStage() == HttpResponseStage.CLOSED)
        throw new IOException("Connection reset by peer"); // This is not the only place 'Connection reset by peer' is thrown

    RequestEvent requestEvent = new RequestEvent(request);

    try {
        EventBus.instance().callEventWithException(requestEvent);
    } catch (EventException ex) {
        throw new IOException(
                "Exception encountered during request event call, most likely the fault of a plugin.", ex);
    }

    response.setStatus(requestEvent.getStatus());

    if (requestEvent.isCancelled()) {
        int status = requestEvent.getStatus();
        String reason = requestEvent.getReason();

        if (status == 200) {
            status = 502;
            reason = "Navigation Cancelled by Plugin Event";
        }

        NetworkManager.getLogger().warning("Navigation was cancelled by a Plugin Event");

        throw new HttpError(status, reason);
    }

    if (response.isCommitted())
        return;

    // Throws IOException and HttpError
    fi = new WebInterpreter(request);
    response.annotations.putAll(fi.getAnnotations());

    currentSite = request.getLocation();
    sess.setSite(currentSite);

    if (request.getSubdomain().length() > 0
            && !currentSite.getSubdomain(request.getSubdomain()).isMaped(request.getDomain())) {
        if ("www".equalsIgnoreCase(request.getSubdomain())
                || AppConfig.get().getBoolean("sites.redirectMissingSubDomains")) {
            log.log(Level.SEVERE, "Redirecting non-existent subdomain '%s' to root domain '%s'",
                    request.getSubdomain(), request.getFullUrl(""));
            response.sendRedirect(request.getFullUrl(""));
        } else {
            log.log(Level.SEVERE, "The requested subdomain '%s' is non-existent.", request.getSubdomain(),
                    request.getFullDomain(""));
            response.sendError(HttpResponseStatus.NOT_FOUND, "Subdomain not found");
        }
        return;
    }

    File docRoot = currentSite.getSubdomain(request.getSubdomain()).directory();

    Validate.notNull(docRoot);

    if (sess.isLoginPresent())
        log.log(Level.FINE, "Account {id=%s,displayName=%s}", sess.getId(), sess.getDisplayName());

    /*
     * Start: SSL enforcer
     *
     * Acts on the value of annotation 'SSL'.
     * REQUIRED means a forbidden error will be thrown is it can not be accomplished
     *
     * Options include:
     * Preferred: If SSL is available, we preferred to be switched to it
     * PostOnly: SSL is REQUIRED is this is a POST request
     * GetOnly: SSL is REQUIRED if this is a GET request
     * Required: SSL is REQUIRED, no exceptions!
     * Deny: SSL is DENIED, no exceptions!
     * Ignore: We don't care one way or other, do nothing! DEFAULT
     */
    SslLevel sslLevel = SslLevel.parse(fi.get("ssl"));
    boolean required = false;

    switch (sslLevel) {
    case Preferred:
        if (NetworkManager.isHttpsRunning())
            required = true;
        break;
    case PostOnly:
        if (request.method() == HttpMethod.POST)
            required = true;
        break;
    case GetOnly:
        if (request.method() == HttpMethod.GET)
            required = true;
        break;
    case Required:
        required = true;
        break;
    case Deny:
        if (ssl) {
            if (!response.switchToUnsecure())
                response.sendError(HttpCode.HTTP_FORBIDDEN, "This page requires an unsecure connection.");
            return;
        }
        break;
    case Ignore:
        break;
    }

    if (required && !ssl) {
        if (!response.switchToSecure())
            response.sendError(HttpCode.HTTP_FORBIDDEN, "This page requires a secure connection.");
        return;
    }
    /*
     * End: SSL enforcer
     */

    if (fi.getStatus() != HttpResponseStatus.OK)
        throw new HttpError(fi.getStatus());

    /*
     * Start: Apache Configuration Section
     *
     * Loads a Apache configuration and .htaccess files into a common handler, then parsed for directives like access restrictions and basic auth
     * TODO Load server-wide Apache Configuration then merge with Site Configuration
     */
    ApacheHandler htaccess = new ApacheHandler();
    response.setApacheParser(htaccess);

    try {
        boolean result = htaccess.handleDirectives(currentSite.getApacheConfig(), this);

        if (htaccess.overrideNone() || htaccess.overrideListNone()) // Ignore .htaccess files
        {
            if (fi.hasFile())
                if (!htaccess.handleDirectives(new ApacheConfiguration(fi.getFile().getParentFile()), this))
                    result = false;

            if (!htaccess.handleDirectives(new ApacheConfiguration(docRoot), this))
                result = false;
        }

        if (!result) {
            if (!response.isCommitted())
                response.sendError(500,
                        "Your request was blocked by an internal configuration directive, exact details are unknown.");
            return;
        }
    } catch (ApacheDirectiveException e) {
        log.log(Level.SEVERE, "Caught Apache directive exception: " + e.getMessage());

        // TODO Throw 500 unless told not to
    }
    /*
     * End: Apache Configuration Section
     */

    if (!fi.hasFile() && !fi.hasHTML())
        response.setStatus(HttpResponseStatus.NO_CONTENT);

    sess.setGlobal("__FILE__", fi.getFile());

    request.putRewriteParams(fi.getRewriteParams());
    response.setContentType(fi.getContentType());
    response.setEncoding(fi.getEncoding());

    request.getServer().put(ServerVars.DOCUMENT_ROOT, docRoot);

    request.setGlobal("_SERVER", request.getServer());
    request.setGlobal("_POST", request.getPostMap());
    request.setGlobal("_GET", request.getGetMap());
    request.setGlobal("_REWRITE", request.getRewriteMap());
    request.setGlobal("_FILES", request.getUploadedFiles());

    // TODO Implement NONCE requirement for login page
    NonceLevel level = NonceLevel.parse(fi.get("nonce"));
    boolean nonceProvided = sess.nonce() == null ? false
            : request.getRequestMap().get(sess.nonce().key()) != null;
    boolean processNonce = false;

    switch (level) {
    case Required:
        processNonce = true;
        break;
    case GetOnly:
        processNonce = request.method() == HttpMethod.GET || nonceProvided;
        break;
    case PostOnly:
        processNonce = request.method() == HttpMethod.POST || nonceProvided;
        break;
    case Flexible:
        processNonce = nonceProvided;
        break;
    case Disabled:
    default:
        // Do Nothing
    }

    Map<String, String> nonceMap = Maps.newHashMap();

    if (processNonce) {
        if (!nonceProvided) {
            log.log(Level.SEVERE,
                    "The request has failed NONCE validation, because the nonce key was not present!");
            response.sendError(HttpResponseStatus.FORBIDDEN, "Your request has failed NONCE validation!");
            return;
        }

        Nonce nonce = sess.nonce();

        if (level == NonceLevel.Required)
            // Required NonceLevels are of the highest protected state
            sess.destroyNonce();

        try {
            if (!(request.getRequestMap().get(nonce.key()) instanceof String))
                throw new NonceException("Nonce token is not a string");
            nonce.validateWithException((String) request.getRequestMap().get(nonce.key()));
        } catch (NonceException e) {
            log.log(Level.SEVERE,
                    "The request has failed NONCE validation, because " + e.getMessage().toLowerCase() + "!");
            response.sendError(HttpResponseStatus.FORBIDDEN, "Your request has failed NONCE validation!");
            sess.destroyNonce();
            return;
        } finally {
            log.log(Level.INFO, "The request has passed the NONCE validation!");
            request.nonceProcessed(true);
            nonceMap = nonce.mapValues();
        }
    }

    if (request.validateLogins())
        return;

    if (level != NonceLevel.Disabled)
        request.setGlobal("_NONCE", nonceMap);

    try {
        if (request.getUploadedFiles().size() > 0)
            log.log(Level.INFO,
                    "Uploads {"
                            + StringFunc.limitLength(
                                    Joiner.on(",").skipNulls().join(request.getUploadedFiles().values()), 255)
                            + "}");

        if (request.getGetMap().size() > 0)
            log.log(Level.INFO, "Params GET {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getGetMap()), 255)
                    + "}");

        if (request.getPostMap().size() > 0)
            log.log(Level.INFO, "Params POST {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getPostMap()),
                    255) + "}");

        if (request.getRewriteMap().size() > 0)
            log.log(Level.INFO, "Params REWRITE {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getRewriteMap()),
                    255) + "}");

        if (fi.getAnnotations().size() > 0)
            log.log(Level.INFO, "Params ANNOTATIONS {" + StringFunc.limitLength(
                    Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(fi.getAnnotations()), 255)
                    + "}");
    } catch (Throwable t) {
        t.printStackTrace();
    }

    if (AppConfig.get().getBoolean("advanced.security.requestMapEnabled", true))
        request.setGlobal("_REQUEST", request.getRequestMap());

    ByteBuf rendered = Unpooled.buffer();

    ScriptingFactory factory = request.getEvalFactory();
    factory.setEncoding(fi.getEncoding());

    NetworkSecurity.isForbidden(htaccess, currentSite, fi);

    String req = fi.get("reqperm");

    if (req == null)
        req = "-1";

    sess.requirePermission(req, currentSite.getId());

    // Enhancement: Allow HTML to be ran under different shells. Default is embedded.
    if (fi.hasHTML()) {
        ScriptingResult result = factory.eval(
                ScriptingContext.fromSource(fi.getHTML(), "<embedded>").request(request).site(currentSite));

        if (result.hasExceptions())
            // TODO Print notices to output like PHP does
            for (ScriptingException e : result.getExceptions()) {
                ExceptionReport.throwExceptions(e);
                log.exceptions(e);
                if (e.reportingLevel().isEnabled())
                    rendered.writeBytes(e.getMessage().getBytes());
            }

        if (result.isSuccessful()) {
            rendered.writeBytes(result.content());
            if (result.getObject() != null && !(result.getObject() instanceof NullObject))
                try {
                    rendered.writeBytes(ObjectFunc.castToStringWithException(result.getObject()).getBytes());
                } catch (Exception e) {
                    log.log(Level.SEVERE, "Exception Excountered: %s", e.getMessage());
                    if (Versioning.isDevelopment())
                        log.log(Level.SEVERE, e.getStackTrace()[0].toString());
                }
        }

        log.log(Level.INFO, "EvalHtml {timing=%sms,success=%s}", Timings.mark(this), result.isSuccessful());
    }

    if (fi.hasFile()) {
        if (fi.isDirectoryRequest()) {
            processDirectoryListing();
            return;
        }

        ScriptingResult result = factory.eval(ScriptingContext.fromFile(fi).request(request).site(currentSite));

        if (result.hasExceptions())
            // TODO Print notices to output like PHP does
            for (ScriptingException e : result.getExceptions()) {
                ExceptionReport.throwExceptions(e);
                log.exceptions(e);
                if (e.reportingLevel().isEnabled() && e.getMessage() != null)
                    rendered.writeBytes(e.getMessage().getBytes());
            }

        if (result.isSuccessful()) {
            rendered.writeBytes(result.content());
            if (result.getObject() != null && !(result.getObject() instanceof NullObject))
                try {
                    rendered.writeBytes(ObjectFunc.castToStringWithException(result.getObject()).getBytes());
                } catch (Exception e) {
                    rendered.writeBytes(result.getObject().toString().getBytes());
                    log.log(Level.SEVERE, "Exception encountered while writing returned object to output. %s",
                            e.getMessage());
                    if (Versioning.isDevelopment())
                        log.log(Level.SEVERE, e.getStackTrace()[0].toString());
                }
        }

        log.log(Level.INFO, "EvalFile {file=%s,timing=%sms,success=%s}", fi.getFilePath(), Timings.mark(this),
                result.isSuccessful());
    }

    // if the connection was in a MultiPart mode, wait for the mode to change then return gracefully.
    if (response.stage == HttpResponseStage.MULTIPART) {
        while (response.stage == HttpResponseStage.MULTIPART)
            // I wonder if there is a better way to handle multipart responses.
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new HttpError(500, "Internal Server Error encountered during multipart execution.");
            }

        return;
    }
    // If the connection was closed from page redirect, return gracefully.
    else if (response.stage == HttpResponseStage.CLOSED || response.stage == HttpResponseStage.WRITTEN)
        return;

    // Allows scripts to directly override interpreter values. For example: Themes, Views, Titles
    for (Entry<String, String> kv : response.annotations.entrySet())
        fi.put(kv.getKey(), kv.getValue());

    RenderEvent renderEvent = new RenderEvent(this, rendered, fi.getEncoding(), fi.getAnnotations());

    try {
        EventBus.instance().callEventWithException(renderEvent);
        if (renderEvent.getSource() != null)
            rendered = renderEvent.getSource();
    } catch (EventException ex) {
        throw new ScriptingException(ReportingLevel.E_ERROR,
                "Caught EventException while trying to fire the RenderEvent", ex.getCause());
    }

    log.log(Level.INFO, "Written {bytes=%s,total_timing=%sms}", rendered.readableBytes(), Timings.finish(this));

    try {
        response.write(rendered);
    } catch (IllegalReferenceCountException e) {
        log.log(Level.SEVERE, "Exception encountered while writting script object to output, %s",
                e.getMessage());
    }
}

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

License:Mozilla Public License

public void resetBuffer() {
    output = Unpooled.buffer();
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtilTest.java

License:Apache License

@Test
public void writeNullTerminatedString() throws Exception {
    ByteBuf buffer0 = Unpooled.buffer().capacity(10);

    // handle null case
    buffer0.clear();// w w  w  . j av a  2s .co m
    ChannelBufferUtil.writeNullTerminatedString(buffer0, null);
    Assert.assertArrayEquals(HexUtil.toByteArray("00"), BufferHelper.createByteArray(buffer0));

    buffer0.clear();
    ChannelBufferUtil.writeNullTerminatedString(buffer0, "");
    Assert.assertArrayEquals(HexUtil.toByteArray("00"), BufferHelper.createByteArray(buffer0));

    buffer0.clear();
    ChannelBufferUtil.writeNullTerminatedString(buffer0, "A");
    Assert.assertArrayEquals(HexUtil.toByteArray("4100"), BufferHelper.createByteArray(buffer0));
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtilTest.java

License:Apache License

@Test
public void writeTlv() throws Exception {
    Tlv tlv0 = null;/*from   w ww .j a va  2 s.  c om*/
    ByteBuf buffer0 = null;

    buffer0 = Unpooled.buffer().capacity(10);

    // handle null case
    buffer0.clear();
    ChannelBufferUtil.writeTlv(buffer0, tlv0);
    Assert.assertArrayEquals(HexUtil.toByteArray(""), BufferHelper.createByteArray(buffer0));

    buffer0.clear();
    tlv0 = new Tlv((short) 0xFFFF, new byte[] { 0x41, 0x42 });
    ChannelBufferUtil.writeTlv(buffer0, tlv0);
    Assert.assertArrayEquals(HexUtil.toByteArray("FFFF00024142"), BufferHelper.createByteArray(buffer0));
}