Search in sources :

Example 6 with MimeType

use of lucee.commons.lang.mimetype.MimeType in project Lucee by lucee.

the class Props method callWDDX.

private void callWDDX(PageContext pc, Component component, Collection.Key methodName, boolean suppressContent) throws PageException {
    try {
        // Struct url = StructUtil.duplicate(pc.urlFormScope(),true);
        Struct url = StructUtil.merge(new Struct[] { pc.formScope(), pc.urlScope() });
        // define args
        url.removeEL(KeyConstants._fieldnames);
        url.removeEL(KeyConstants._method);
        Object args = url.get(KeyConstants._argumentCollection, null);
        String strArgCollFormat = Caster.toString(url.get("argumentCollectionFormat", null), null);
        // url.returnFormat
        int urlReturnFormat = -1;
        Object oReturnFormatFromURL = url.get(KeyConstants._returnFormat, null);
        if (oReturnFormatFromURL != null)
            urlReturnFormat = UDFUtil.toReturnFormat(Caster.toString(oReturnFormatFromURL, null), -1);
        // request header "accept"
        List<MimeType> accept = ReqRspUtil.getAccept(pc);
        int headerReturnFormat = MimeType.toFormat(accept, UDF.RETURN_FORMAT_XML, -1);
        Object queryFormat = url.get(KeyConstants._queryFormat, null);
        if (args == null) {
            args = pc.getHttpServletRequest().getAttribute("argumentCollection");
        }
        if (StringUtil.isEmpty(strArgCollFormat)) {
            strArgCollFormat = Caster.toString(pc.getHttpServletRequest().getAttribute("argumentCollectionFormat"), null);
        }
        // content-type
        Charset cs = getCharset(pc);
        Object o = component.get(pc, methodName, null);
        // onMissingMethod
        if (o == null)
            o = component.get(pc, KeyConstants._onmissingmethod, null);
        Props props = getProps(pc, o, urlReturnFormat, headerReturnFormat);
        // if(!props.output)
        setFormat(pc.getHttpServletResponse(), props.format, cs);
        Object rtn = null;
        try {
            if (suppressContent)
                pc.setSilent();
            if (args == null) {
                url = translate(component, methodName.getString(), url);
                rtn = component.callWithNamedValues(pc, methodName, url);
            } else if (args instanceof String) {
                String str = (String) args;
                int format = UDFUtil.toReturnFormat(strArgCollFormat, -1);
                // CFML
                if (UDF.RETURN_FORMAT_SERIALIZE == format) {
                    // do not catch exception when format is defined
                    args = new CFMLExpressionInterpreter().interpret(pc, str);
                }
                // JSON
                if (UDF.RETURN_FORMAT_JSON == format) {
                    // do not catch exception when format is defined
                    args = new JSONExpressionInterpreter(false).interpret(pc, str);
                } else // default
                {
                    // catch exception when format is not defined, then in this case the string can also be a simple argument
                    try {
                        args = new JSONExpressionInterpreter(false).interpret(pc, str);
                    } catch (PageException pe) {
                        try {
                            args = new CFMLExpressionInterpreter().interpret(pc, str);
                        } catch (PageException _pe) {
                        }
                    }
                }
            }
            // call
            if (args != null) {
                if (Decision.isCastableToStruct(args)) {
                    rtn = component.callWithNamedValues(pc, methodName, Caster.toStruct(args, false));
                } else if (Decision.isCastableToArray(args)) {
                    rtn = component.call(pc, methodName, Caster.toNativeArray(args));
                } else {
                    Object[] ac = new Object[1];
                    ac[0] = args;
                    rtn = component.call(pc, methodName, ac);
                }
            }
        } finally {
            if (suppressContent)
                pc.unsetSilent();
        }
        // convert result
        if (rtn != null) {
            if (pc.getHttpServletRequest().getHeader("AMF-Forward") != null) {
                pc.variablesScope().setEL("AMF-Forward", rtn);
            } else {
                _writeOut(pc, props, queryFormat, rtn, cs, false);
            }
        }
    } catch (Throwable t) {
        PageException pe = Caster.toPageException(t);
        pe.setExposeMessage(true);
        throw pe;
    }
}
Also used : PageException(lucee.runtime.exp.PageException) JSONExpressionInterpreter(lucee.runtime.interpreter.JSONExpressionInterpreter) Charset(java.nio.charset.Charset) CFMLExpressionInterpreter(lucee.runtime.interpreter.CFMLExpressionInterpreter) MimeType(lucee.commons.lang.mimetype.MimeType) StaticStruct(lucee.runtime.component.StaticStruct) Struct(lucee.runtime.type.Struct)

Example 7 with MimeType

use of lucee.commons.lang.mimetype.MimeType in project Lucee by lucee.

the class HTTPClient method getMimeType.

private MimeType getMimeType(Header[] headers, MimeType defaultValue) {
    String returnFormat = null, contentType = null;
    for (int i = 0; i < headers.length; i++) {
        if (headers[i].getName().equalsIgnoreCase("Return-Format"))
            returnFormat = headers[i].getValue();
        else if (headers[i].getName().equalsIgnoreCase("Content-Type"))
            contentType = headers[i].getValue();
    }
    MimeType rf = null, ct = null;
    // return format
    if (!StringUtil.isEmpty(returnFormat)) {
        int format = UDFUtil.toReturnFormat(returnFormat, -1);
        rf = MimeType.toMimetype(format, null);
    }
    // ContentType
    if (!StringUtil.isEmpty(contentType)) {
        ct = MimeType.getInstance(contentType);
    }
    if (rf != null && ct != null) {
        // because this has perhaps a charset definition
        if (rf.same(ct))
            return ct;
        return rf;
    }
    if (rf != null)
        return rf;
    if (ct != null)
        return ct;
    return defaultValue;
}
Also used : MimeType(lucee.commons.lang.mimetype.MimeType)

Example 8 with MimeType

use of lucee.commons.lang.mimetype.MimeType in project Lucee by lucee.

the class ReqRspUtil method getRequestBody.

/**
 * returns the body of the request
 *
 * @param pc
 * @param deserialized
 *            if true lucee tries to deserialize the body based on the content-type, for example when the content type is "application/json"
 * @param defaultValue
 *            value returned if there is no body
 * @return
 */
public static Object getRequestBody(PageContext pc, boolean deserialized, Object defaultValue) {
    HttpServletRequest req = pc.getHttpServletRequest();
    MimeType contentType = getContentType(pc);
    String strContentType = contentType == MimeType.ALL ? null : contentType.toString();
    Charset cs = getCharacterEncoding(pc, req);
    boolean isBinary = !(strContentType == null || HTTPUtil.isTextMimeType(contentType) || strContentType.toLowerCase().startsWith("application/x-www-form-urlencoded"));
    if (req.getContentLength() > -1) {
        ServletInputStream is = null;
        try {
            // new byte[req.getContentLength()];
            byte[] data = IOUtil.toBytes(is = req.getInputStream());
            Object obj = NULL;
            if (deserialized) {
                int format = MimeType.toFormat(contentType, -1);
                obj = toObject(pc, data, format, cs, obj);
            }
            if (obj == NULL) {
                if (isBinary)
                    obj = data;
                else
                    obj = toString(data, cs);
            }
            return obj;
        } catch (Exception e) {
            pc.getConfig().getLog("application").error("request", e);
            return defaultValue;
        } finally {
            IOUtil.closeEL(is);
        }
    }
    return defaultValue;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletInputStream(javax.servlet.ServletInputStream) Charset(java.nio.charset.Charset) MimeType(lucee.commons.lang.mimetype.MimeType) PageException(lucee.runtime.exp.PageException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 9 with MimeType

use of lucee.commons.lang.mimetype.MimeType in project Lucee by lucee.

the class ReqRspUtil method getContentType.

public static MimeType getContentType(PageContext pc) {
    java.util.Iterator<String> it = ReqRspUtil.getHeadersIgnoreCase(pc, "content-type").iterator();
    String value;
    MimeType rtn = null;
    while (it.hasNext()) {
        value = it.next();
        MimeType[] mtes = MimeType.getInstances(value, ',');
        if (mtes != null)
            for (int i = 0; i < mtes.length; i++) {
                rtn = mtes[i];
            }
    }
    if (rtn == null)
        return MimeType.ALL;
    return rtn;
}
Also used : MimeType(lucee.commons.lang.mimetype.MimeType)

Example 10 with MimeType

use of lucee.commons.lang.mimetype.MimeType in project Lucee by lucee.

the class ModernAppListener method _onRequest.

protected void _onRequest(PageContext pc, PageSource requestedPage, PageSource appPS, RequestListener rl) throws PageException {
    PageContextImpl pci = (PageContextImpl) pc;
    pci.setAppListenerType(ApplicationListener.TYPE_MODERN);
    if (appPS != null) {
        String callPath = appPS.getComponentName();
        Component app = ComponentLoader.loadComponent(pci, appPS, callPath, false, false);
        // init
        ModernApplicationContext appContext = initApplicationContext(pci, app);
        apps.put(appContext.getName(), app);
        if (!pci.initApplicationContext(this))
            return;
        if (rl != null) {
            requestedPage = rl.execute(pc, requestedPage);
            if (requestedPage == null)
                return;
        }
        String targetPage = requestedPage.getRealpathWithVirtual();
        RefBoolean goon = new RefBooleanImpl(true);
        // onRequestStart
        if (app.contains(pc, ON_REQUEST_START)) {
            try {
                Object rtn = call(app, pci, ON_REQUEST_START, new Object[] { targetPage }, false);
                if (!Caster.toBooleanValue(rtn, true))
                    return;
            } catch (PageException pe) {
                pe = handlePageException(pci, app, pe, requestedPage, targetPage, goon);
                if (pe != null)
                    throw pe;
            }
        }
        // onRequest
        if (goon.toBooleanValue()) {
            boolean isComp = isComponent(pc, requestedPage);
            Object method;
            if (isComp && app.contains(pc, ON_CFCREQUEST) && (method = pc.urlFormScope().get(KeyConstants._method, null)) != null) {
                Struct url = (Struct) Duplicator.duplicate(pc.urlFormScope(), true);
                url.removeEL(KeyConstants._fieldnames);
                url.removeEL(KeyConstants._method);
                Object args = url.get(KeyConstants._argumentCollection, null);
                // url returnFormat
                Object oReturnFormat = url.removeEL(KeyConstants._returnFormat);
                int urlReturnFormat = -1;
                if (oReturnFormat != null)
                    urlReturnFormat = UDFUtil.toReturnFormat(Caster.toString(oReturnFormat, null), -1);
                // request header accept
                List<MimeType> accept = ReqRspUtil.getAccept(pc);
                int headerReturnFormat = MimeType.toFormat(accept, -1, -1);
                Object queryFormat = url.removeEL(KeyConstants._queryFormat);
                if (args == null) {
                    args = pc.getHttpServletRequest().getAttribute("argumentCollection");
                }
                if (args instanceof String) {
                    args = new JSONExpressionInterpreter().interpret(pc, (String) args);
                }
                if (args != null) {
                    if (Decision.isCastableToStruct(args)) {
                        Struct sct = Caster.toStruct(args, false);
                        // Key[] keys = url.keys();
                        Iterator<Entry<Key, Object>> it = url.entryIterator();
                        Entry<Key, Object> e;
                        while (it.hasNext()) {
                            e = it.next();
                            sct.setEL(e.getKey(), e.getValue());
                        }
                        args = sct;
                    } else if (Decision.isCastableToArray(args)) {
                        args = Caster.toArray(args);
                    } else {
                        Array arr = new ArrayImpl();
                        arr.appendEL(args);
                        args = arr;
                    }
                } else
                    args = url;
                Object rtn = call(app, pci, ON_CFCREQUEST, new Object[] { requestedPage.getComponentName(), method, args }, true);
                if (rtn != null) {
                    if (pc.getHttpServletRequest().getHeader("AMF-Forward") != null) {
                        pc.variablesScope().setEL("AMF-Forward", rtn);
                    // ThreadLocalWDDXResult.set(rtn);
                    } else {
                        try {
                            ComponentPageImpl.writeToResponseStream(pc, app, method.toString(), urlReturnFormat, headerReturnFormat, queryFormat, rtn);
                        } catch (Exception e) {
                            throw Caster.toPageException(e);
                        }
                    }
                }
            } else {
                // TODO impl die nicht so generisch ist
                try {
                    if (!isComp && app.contains(pc, ON_REQUEST))
                        call(app, pci, ON_REQUEST, new Object[] { targetPage }, false);
                    else
                        pci._doInclude(new PageSource[] { requestedPage }, false, null);
                } catch (PageException pe) {
                    pe = handlePageException(pci, app, pe, requestedPage, targetPage, goon);
                    if (pe != null)
                        throw pe;
                }
            }
        }
        // onRequestEnd
        if (goon.toBooleanValue() && app.contains(pc, ON_REQUEST_END)) {
            try {
                call(app, pci, ON_REQUEST_END, new Object[] { targetPage }, false);
            } catch (PageException pe) {
                pe = handlePageException(pci, app, pe, requestedPage, targetPage, goon);
                if (pe != null)
                    throw pe;
            }
        }
    } else {
        apps.put(pc.getApplicationContext().getName(), null);
        if (rl != null) {
            requestedPage = rl.execute(pc, requestedPage);
            if (requestedPage == null)
                return;
        }
        pci._doInclude(new PageSource[] { requestedPage }, false, null);
    }
}
Also used : PageException(lucee.runtime.exp.PageException) RefBoolean(lucee.commons.lang.types.RefBoolean) ArrayImpl(lucee.runtime.type.ArrayImpl) PageContextImpl(lucee.runtime.PageContextImpl) MimeType(lucee.commons.lang.mimetype.MimeType) PageException(lucee.runtime.exp.PageException) MissingIncludeException(lucee.runtime.exp.MissingIncludeException) IOException(java.io.IOException) Struct(lucee.runtime.type.Struct) PageSource(lucee.runtime.PageSource) Array(lucee.runtime.type.Array) Entry(java.util.Map.Entry) JSONExpressionInterpreter(lucee.runtime.interpreter.JSONExpressionInterpreter) Component(lucee.runtime.Component) RefBooleanImpl(lucee.commons.lang.types.RefBooleanImpl) Key(lucee.runtime.type.Collection.Key)

Aggregations

MimeType (lucee.commons.lang.mimetype.MimeType)10 PageException (lucee.runtime.exp.PageException)5 Struct (lucee.runtime.type.Struct)5 ApplicationException (lucee.runtime.exp.ApplicationException)4 IOException (java.io.IOException)3 Charset (java.nio.charset.Charset)3 InputStream (java.io.InputStream)2 Entry (java.util.Map.Entry)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HTTPResponse (lucee.commons.net.http.HTTPResponse)2 StaticStruct (lucee.runtime.component.StaticStruct)2 MissingIncludeException (lucee.runtime.exp.MissingIncludeException)2 JSONExpressionInterpreter (lucee.runtime.interpreter.JSONExpressionInterpreter)2 Array (lucee.runtime.type.Array)2 Key (lucee.runtime.type.Collection.Key)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HashMap (java.util.HashMap)1 ServletException (javax.servlet.ServletException)1 ServletInputStream (javax.servlet.ServletInputStream)1 JspException (javax.servlet.jsp.JspException)1