Search in sources :

Example 1 with MimeType

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

the class HTTPClient method getMetaData.

private Struct getMetaData(PageContext pc) {
    if (meta == null) {
        pc = ThreadLocalPageContext.get(pc);
        InputStream is = null;
        HTTPResponse rsp = null;
        try {
            rsp = HTTPEngine.get(metaURL, username, password, -1, false, "UTF-8", createUserAgent(pc), proxyData, null);
            MimeType mt = getMimeType(rsp, null);
            int format = MimeType.toFormat(mt, -1);
            if (format == -1)
                throw new ApplicationException("cannot convert response with mime type [" + mt + "] to a CFML Object");
            is = rsp.getContentAsStream();
            Struct data = Caster.toStruct(ReqRspUtil.toObject(pc, IOUtil.toBytes(is, false), format, mt.getCharset(), null));
            Object oUDF = data.get(KeyConstants._functions, null);
            Object oAACF = data.get(ComponentPageImpl.ACCEPT_ARG_COLL_FORMATS, null);
            if (oUDF != null && oAACF != null) {
                meta = Caster.toStruct(oUDF);
                String[] strFormats = ListUtil.listToStringArray(Caster.toString(oAACF), ',');
                argumentsCollectionFormat = UDFUtil.toReturnFormat(strFormats, UDF.RETURN_FORMAT_JSON);
            } else {
                meta = data;
            }
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
            throw new PageRuntimeException(Caster.toPageException(t));
        } finally {
            IOUtil.closeEL(is);
            HTTPEngine.closeEL(rsp);
        }
    }
    return meta;
}
Also used : ApplicationException(lucee.runtime.exp.ApplicationException) InputStream(java.io.InputStream) HTTPResponse(lucee.commons.net.http.HTTPResponse) PageRuntimeException(lucee.runtime.exp.PageRuntimeException) MimeType(lucee.commons.lang.mimetype.MimeType) Struct(lucee.runtime.type.Struct)

Example 2 with MimeType

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

the class HTTPClient method _callWithNamedValues.

private Object _callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException {
    // prepare request
    Map<String, String> formfields = new HashMap<String, String>();
    formfields.put("method", methodName.getString());
    formfields.put("returnformat", "cfml");
    String str;
    try {
        if (UDF.RETURN_FORMAT_JSON == argumentsCollectionFormat) {
            Charset cs = pc.getWebCharset();
            str = new JSONConverter(true, cs).serialize(pc, args, false);
            formfields.put("argumentCollectionFormat", "json");
        } else if (UDF.RETURN_FORMAT_SERIALIZE == argumentsCollectionFormat) {
            str = new ScriptConverter().serialize(args);
            formfields.put("argumentCollectionFormat", "cfml");
        } else {
            // Json interpreter also accepts cfscript
            str = new ScriptConverter().serialize(args);
        }
    } catch (ConverterException e) {
        throw Caster.toPageException(e);
    }
    // add aparams to request
    formfields.put("argumentCollection", str);
    /*
		Iterator<Entry<Key, Object>> it = args.entryIterator();
		Entry<Key, Object> e;
		while(it.hasNext()){
			e = it.next();
			formfields.put(e.getKey().getString(), Caster.toString(e.getValue()));
		}*/
    Map<String, String> headers = new HashMap<String, String>();
    // application/java disabled for the moment, it is not working when we have different lucee versions
    headers.put("accept", "application/cfml,application/json");
    HTTPResponse rsp = null;
    InputStream is = null;
    try {
        // call remote cfc
        rsp = HTTPEngine.post(url, username, password, -1, false, "UTF-8", createUserAgent(pc), proxyData, headers, formfields);
        // read result
        Header[] rspHeaders = rsp.getAllHeaders();
        MimeType mt = getMimeType(rspHeaders, null);
        int format = MimeType.toFormat(mt, -1);
        if (format == -1) {
            if (rsp.getStatusCode() != 200) {
                boolean hasMsg = false;
                String msg = rsp.getStatusText();
                for (int i = 0; i < rspHeaders.length; i++) {
                    if (rspHeaders[i].getName().equalsIgnoreCase("exception-message")) {
                        msg = rspHeaders[i].getValue();
                        hasMsg = true;
                    }
                }
                is = rsp.getContentAsStream();
                ApplicationException ae = new ApplicationException("remote component throws the following error:" + msg);
                if (!hasMsg)
                    ae.setAdditional(KeyImpl.init("respone-body"), IOUtil.toString(is, mt.getCharset()));
                throw ae;
            }
            throw new ApplicationException("cannot convert response with mime type [" + mt + "] to a CFML Object");
        }
        is = rsp.getContentAsStream();
        return ReqRspUtil.toObject(pc, IOUtil.toBytes(is, false), format, mt.getCharset(), null);
    } catch (IOException ioe) {
        throw Caster.toPageException(ioe);
    } finally {
        IOUtil.closeEL(is);
        HTTPEngine.closeEL(rsp);
    }
}
Also used : ConverterException(lucee.runtime.converter.ConverterException) HashMap(java.util.HashMap) InputStream(java.io.InputStream) HTTPResponse(lucee.commons.net.http.HTTPResponse) Charset(java.nio.charset.Charset) IOException(java.io.IOException) MimeType(lucee.commons.lang.mimetype.MimeType) ApplicationException(lucee.runtime.exp.ApplicationException) Header(lucee.commons.net.http.Header) ScriptConverter(lucee.runtime.converter.ScriptConverter) JSONConverter(lucee.runtime.converter.JSONConverter)

Example 3 with MimeType

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

the class Props method callRest.

private void callRest(PageContext pc, Component component, String path, Result result, boolean suppressContent) throws IOException, ConverterException {
    String method = pc.getHttpServletRequest().getMethod();
    String[] subPath = result.getPath();
    Struct cMeta;
    try {
        cMeta = component.getMetaData(pc);
    } catch (PageException pe) {
        throw ExceptionUtil.toIOException(pe);
    }
    // Consumes
    MimeType[] cConsumes = null;
    String strMimeType = Caster.toString(cMeta.get(KeyConstants._consumes, null), null);
    if (!StringUtil.isEmpty(strMimeType, true)) {
        cConsumes = MimeType.getInstances(strMimeType, ',');
    }
    // Produces
    MimeType[] cProduces = null;
    strMimeType = Caster.toString(cMeta.get(KeyConstants._produces, null), null);
    if (!StringUtil.isEmpty(strMimeType, true)) {
        cProduces = MimeType.getInstances(strMimeType, ',');
    }
    Iterator<Entry<Key, Object>> it = component.entryIterator();
    Entry<Key, Object> e;
    Object value;
    UDF udf;
    Struct meta;
    int status = 404;
    MimeType bestP, bestC;
    while (it.hasNext()) {
        e = it.next();
        value = e.getValue();
        if (value instanceof UDF) {
            udf = (UDF) value;
            try {
                meta = udf.getMetaData(pc);
                // check if http method match
                String httpMethod = Caster.toString(meta.get(KeyConstants._httpmethod, null), null);
                if (StringUtil.isEmpty(httpMethod) || !httpMethod.equalsIgnoreCase(method))
                    continue;
                // get consumes mimetype
                MimeType[] consumes;
                strMimeType = Caster.toString(meta.get(KeyConstants._consumes, null), null);
                if (!StringUtil.isEmpty(strMimeType, true)) {
                    consumes = MimeType.getInstances(strMimeType, ',');
                } else
                    consumes = cConsumes;
                // get produces mimetype
                MimeType[] produces;
                strMimeType = Caster.toString(meta.get(KeyConstants._produces, null), null);
                if (!StringUtil.isEmpty(strMimeType, true)) {
                    produces = MimeType.getInstances(strMimeType, ',');
                } else
                    produces = cProduces;
                String restPath = Caster.toString(meta.get(KeyConstants._restPath, null), null);
                // no rest path
                if (StringUtil.isEmpty(restPath)) {
                    if (ArrayUtil.isEmpty(subPath)) {
                        bestC = best(consumes, result.getContentType());
                        bestP = best(produces, result.getAccept());
                        if (bestC == null)
                            status = 405;
                        else if (bestP == null)
                            status = 406;
                        else {
                            status = 200;
                            _callRest(pc, component, udf, path, result.getVariables(), result, bestP, produces, suppressContent, e.getKey());
                            break;
                        }
                    }
                } else {
                    Struct var = result.getVariables();
                    int index = RestUtil.matchPath(var, Path.init(restPath), /*TODO cache this*/
                    result.getPath());
                    if (index >= 0 && index + 1 == result.getPath().length) {
                        bestC = best(consumes, result.getContentType());
                        bestP = best(produces, result.getAccept());
                        if (bestC == null)
                            status = 405;
                        else if (bestP == null)
                            status = 406;
                        else {
                            status = 200;
                            _callRest(pc, component, udf, path, var, result, bestP, produces, suppressContent, e.getKey());
                            break;
                        }
                    }
                }
            } catch (PageException pe) {
                pc.getConfig().getLog("rest").error("REST", pe);
            }
        }
    }
    if (status == 404) {
        RestUtil.setStatus(pc, 404, "no rest service for [" + path + "] found");
        pc.getConfig().getLog("rest").error("REST", "404; no rest service for [" + path + "] found");
    } else if (status == 405) {
        RestUtil.setStatus(pc, 405, "Unsupported Media Type");
        pc.getConfig().getLog("rest").error("REST", "405; Unsupported Media Type");
    } else if (status == 406) {
        RestUtil.setStatus(pc, 406, "Not Acceptable");
        pc.getConfig().getLog("rest").error("REST", "406; Not Acceptable");
    }
}
Also used : PageException(lucee.runtime.exp.PageException) MimeType(lucee.commons.lang.mimetype.MimeType) StaticStruct(lucee.runtime.component.StaticStruct) Struct(lucee.runtime.type.Struct) Entry(java.util.Map.Entry) UDF(lucee.runtime.type.UDF) Key(lucee.runtime.type.Collection.Key)

Example 4 with MimeType

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

the class PageContextImpl method executeRest.

@Override
public void executeRest(String realPath, boolean throwExcpetion) throws PageException {
    initallog();
    // config.get ApplicationListener();
    ApplicationListener listener = null;
    try {
        String pathInfo = req.getPathInfo();
        // charset
        try {
            String charset = HTTPUtil.splitMimeTypeAndCharset(req.getContentType(), new String[] { "", "" })[1];
            if (StringUtil.isEmpty(charset))
                charset = getWebCharset().name();
            java.net.URL reqURL = new java.net.URL(req.getRequestURL().toString());
            String path = ReqRspUtil.decode(reqURL.getPath(), charset, true);
            String srvPath = req.getServletPath();
            if (path.startsWith(srvPath)) {
                pathInfo = path.substring(srvPath.length());
            }
        } catch (Exception e) {
        }
        // Service mapping
        if (StringUtil.isEmpty(pathInfo) || pathInfo.equals("/")) {
            // list available services (if enabled in admin)
            if (config.getRestList()) {
                try {
                    HttpServletRequest _req = getHttpServletRequest();
                    write("Available sevice mappings are:<ul>");
                    lucee.runtime.rest.Mapping[] mappings = config.getRestMappings();
                    lucee.runtime.rest.Mapping _mapping;
                    String path;
                    for (int i = 0; i < mappings.length; i++) {
                        _mapping = mappings[i];
                        Resource p = _mapping.getPhysical();
                        path = _req.getContextPath() + ReqRspUtil.getScriptName(this, _req) + _mapping.getVirtual();
                        write("<li " + (p == null || !p.isDirectory() ? " style=\"color:red\"" : "") + ">" + path + "</li>");
                    }
                    write("</ul>");
                } catch (IOException e) {
                    throw Caster.toPageException(e);
                }
            } else
                RestUtil.setStatus(this, 404, null);
            return;
        }
        // check for matrix
        int index;
        String entry;
        Struct matrix = new StructImpl();
        while ((index = pathInfo.lastIndexOf(';')) != -1) {
            entry = pathInfo.substring(index + 1);
            pathInfo = pathInfo.substring(0, index);
            if (StringUtil.isEmpty(entry, true))
                continue;
            index = entry.indexOf('=');
            if (index != -1)
                matrix.setEL(KeyImpl.init(entry.substring(0, index).trim()), entry.substring(index + 1).trim());
            else
                matrix.setEL(KeyImpl.init(entry.trim()), "");
        }
        // get accept
        List<MimeType> accept = ReqRspUtil.getAccept(this);
        MimeType contentType = ReqRspUtil.getContentType(this);
        // check for format extension
        // int format = getApplicationContext().getRestSettings().getReturnFormat();
        int format;
        boolean hasFormatExtension = false;
        if (StringUtil.endsWithIgnoreCase(pathInfo, ".json")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 5);
            format = UDF.RETURN_FORMAT_JSON;
            accept.clear();
            accept.add(MimeType.APPLICATION_JSON);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".wddx")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 5);
            format = UDF.RETURN_FORMAT_WDDX;
            accept.clear();
            accept.add(MimeType.APPLICATION_WDDX);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".cfml")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 5);
            format = UDF.RETURN_FORMAT_SERIALIZE;
            accept.clear();
            accept.add(MimeType.APPLICATION_CFML);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".serialize")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 10);
            format = UDF.RETURN_FORMAT_SERIALIZE;
            accept.clear();
            accept.add(MimeType.APPLICATION_CFML);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".xml")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 4);
            format = UDF.RETURN_FORMAT_XML;
            accept.clear();
            accept.add(MimeType.APPLICATION_XML);
            hasFormatExtension = true;
        } else if (StringUtil.endsWithIgnoreCase(pathInfo, ".java")) {
            pathInfo = pathInfo.substring(0, pathInfo.length() - 5);
            format = UDFPlus.RETURN_FORMAT_JAVA;
            accept.clear();
            accept.add(MimeType.APPLICATION_JAVA);
            hasFormatExtension = true;
        } else {
            format = getApplicationContext() == null ? null : getApplicationContext().getRestSettings().getReturnFormat();
        // MimeType mt=MimeType.toMimetype(format);
        // if(mt!=null)accept.add(mt);
        }
        if (accept.size() == 0)
            accept.add(MimeType.ALL);
        // loop all mappings
        // lucee.runtime.rest.Result result = null;//config.getRestSource(pathInfo, null);
        RestRequestListener rl = null;
        lucee.runtime.rest.Mapping[] restMappings = config.getRestMappings();
        lucee.runtime.rest.Mapping m, mapping = null, defaultMapping = null;
        // String callerPath=null;
        if (restMappings != null)
            for (int i = 0; i < restMappings.length; i++) {
                m = restMappings[i];
                if (m.isDefault())
                    defaultMapping = m;
                if (pathInfo.startsWith(m.getVirtualWithSlash(), 0) && m.getPhysical() != null) {
                    mapping = m;
                    // result = m.getResult(this,callerPath=pathInfo.substring(m.getVirtual().length()),format,matrix,null);
                    rl = new RestRequestListener(m, pathInfo.substring(m.getVirtual().length()), matrix, format, hasFormatExtension, accept, contentType, null);
                    break;
                }
            }
        // default mapping
        if (mapping == null && defaultMapping != null && defaultMapping.getPhysical() != null) {
            mapping = defaultMapping;
            // result = mapping.getResult(this,callerPath=pathInfo,format,matrix,null);
            rl = new RestRequestListener(mapping, pathInfo, matrix, format, hasFormatExtension, accept, contentType, null);
        }
        if (mapping == null || mapping.getPhysical() == null) {
            RestUtil.setStatus(this, 404, "no rest service for [" + pathInfo + "] found");
            getConfig().getLog("rest").error("REST", "no rest service for [" + pathInfo + "] found");
        } else {
            base = config.toPageSource(null, mapping.getPhysical(), null);
            listener = ((MappingImpl) base.getMapping()).getApplicationListener();
            listener.onRequest(this, base, rl);
        }
    } catch (Throwable t) {
        ExceptionUtil.rethrowIfNecessary(t);
        PageException pe = Caster.toPageException(t);
        if (!Abort.isSilentAbort(pe)) {
            log(true);
            if (fdEnabled) {
                FDSignal.signal(pe, false);
            }
            if (listener == null) {
                if (base == null)
                    listener = config.getApplicationListener();
                else
                    listener = ((MappingImpl) base.getMapping()).getApplicationListener();
            }
            listener.onError(this, pe);
        } else
            log(false);
        if (throwExcpetion)
            throw pe;
    } finally {
        if (enablecfoutputonly > 0) {
            setCFOutputOnly((short) 0);
        }
        base = null;
    }
}
Also used : URL(lucee.runtime.type.scope.URL) MimeType(lucee.commons.lang.mimetype.MimeType) Struct(lucee.runtime.type.Struct) HttpServletRequest(javax.servlet.http.HttpServletRequest) PageException(lucee.runtime.exp.PageException) RestRequestListener(lucee.runtime.rest.RestRequestListener) Resource(lucee.commons.io.res.Resource) IOException(java.io.IOException) PageException(lucee.runtime.exp.PageException) CasterException(lucee.runtime.exp.CasterException) MissingIncludeException(lucee.runtime.exp.MissingIncludeException) JspException(javax.servlet.jsp.JspException) IOException(java.io.IOException) CacheException(lucee.commons.io.cache.exp.CacheException) DatabaseException(lucee.runtime.exp.DatabaseException) ServletException(javax.servlet.ServletException) ModernAppListenerException(lucee.runtime.listener.ModernAppListenerException) RequestTimeoutException(lucee.runtime.exp.RequestTimeoutException) ExpressionException(lucee.runtime.exp.ExpressionException) ApplicationException(lucee.runtime.exp.ApplicationException) StructImpl(lucee.runtime.type.StructImpl) ApplicationListener(lucee.runtime.listener.ApplicationListener)

Example 5 with MimeType

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

the class FileTag method checkContentType.

/**
 * check if the content ii ok
 * @param contentType
 * @throws PageException
 */
private static void checkContentType(String contentType, String accept, String ext, boolean strict) throws PageException {
    if (!StringUtil.isEmpty(ext, true)) {
        ext = ext.trim().toLowerCase();
        if (ext.startsWith("*."))
            ext = ext.substring(2);
        if (ext.startsWith("."))
            ext = ext.substring(1);
    } else
        ext = null;
    if (StringUtil.isEmpty(accept, true))
        return;
    MimeType mt = MimeType.getInstance(contentType), sub;
    Array whishedTypes = ListUtil.listToArrayRemoveEmpty(accept, ',');
    int len = whishedTypes.size();
    for (int i = 1; i <= len; i++) {
        String whishedType = Caster.toString(whishedTypes.getE(i)).trim().toLowerCase();
        if (whishedType.equals("*"))
            return;
        // check mimetype
        if (ListUtil.len(whishedType, "/", true) == 2) {
            sub = MimeType.getInstance(whishedType);
            if (mt.match(sub))
                return;
        }
        // check extension
        if (ext != null && !strict) {
            if (whishedType.startsWith("*."))
                whishedType = whishedType.substring(2);
            if (whishedType.startsWith("."))
                whishedType = whishedType.substring(1);
            if (ext.equals(whishedType))
                return;
        }
    }
    throw new ApplicationException("The MIME type of the uploaded file [" + contentType + "] was not accepted by the server.", "only this [" + accept + "] mime type are accepted");
}
Also used : Array(lucee.runtime.type.Array) ApplicationException(lucee.runtime.exp.ApplicationException) MimeType(lucee.commons.lang.mimetype.MimeType)

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