Search in sources :

Example 66 with Resource

use of lucee.commons.io.res.Resource 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 67 with Resource

use of lucee.commons.io.res.Resource in project Lucee by lucee.

the class CustomTagUtil method loadInitFile.

public static InitFile loadInitFile(PageContext pc, String name) throws PageException {
    InitFile initFile = loadInitFile(pc, name, null);
    if (initFile != null) {
        return initFile;
    }
    // EXCEPTION
    ConfigWeb config = pc.getConfig();
    // message
    StringBuilder msg = new StringBuilder("Custom tag \"").append(getDisplayName(config, name)).append("\" was not found.");
    List<String> dirs = new ArrayList();
    if (config.doLocalCustomTag()) {
        dirs.add(ResourceUtil.getResource(pc, pc.getCurrentPageSource()).getParent());
    }
    Mapping[] actms = pc.getApplicationContext().getCustomTagMappings();
    Mapping[] cctms = config.getCustomTagMappings();
    Resource r;
    if (actms != null) {
        for (Mapping m : actms) {
            r = m.getPhysical();
            if (r != null)
                dirs.add(r.toString());
        }
    }
    if (cctms != null) {
        for (Mapping m : cctms) {
            r = m.getPhysical();
            if (r != null)
                dirs.add(r.toString());
        }
    }
    if (!dirs.isEmpty()) {
        msg.append(" Directories searched: ");
        Iterator<String> it = dirs.iterator();
        while (it.hasNext()) {
            msg.append('"').append(it.next()).append('"');
            if (it.hasNext())
                msg.append(", ");
        }
    }
    throw new ExpressionException(msg.toString());
}
Also used : ArrayList(java.util.ArrayList) Resource(lucee.commons.io.res.Resource) Mapping(lucee.runtime.Mapping) ConfigWeb(lucee.runtime.config.ConfigWeb) ExpressionException(lucee.runtime.exp.ExpressionException)

Example 68 with Resource

use of lucee.commons.io.res.Resource in project Lucee by lucee.

the class PageSourceImpl method createComponentName.

private void createComponentName() {
    Resource res = this.getPhyscalFile();
    String str = null;
    final String relPath = this.relPath;
    if (res != null) {
        str = res.getAbsolutePath();
        int begin = str.length() - relPath.length();
        if (begin < 0) {
            // TODO patch, analyze the complete functinality and improve
            str = ListUtil.last(str, "\\/");
        } else {
            str = str.substring(begin);
            if (!str.equalsIgnoreCase(relPath)) {
                str = relPath;
            }
        }
    } else
        str = relPath;
    StringBuilder compName = new StringBuilder();
    String[] arr;
    // virtual part
    if (!mapping.ignoreVirtual()) {
        arr = ListUtil.toStringArrayEL(ListUtil.listToArrayRemoveEmpty(mapping.getVirtual(), "\\/"));
        for (int i = 0; i < arr.length; i++) {
            if (compName.length() > 0)
                compName.append('.');
            compName.append(arr[i]);
        }
    }
    // physical part
    arr = ListUtil.toStringArrayEL(ListUtil.listToArrayRemoveEmpty(str, '/'));
    for (int i = 0; i < arr.length; i++) {
        if (compName.length() > 0)
            compName.append('.');
        if (i == (arr.length - 1)) {
            compName.append(ResourceUtil.removeExtension(arr[i], arr[i]));
        } else
            compName.append(arr[i]);
    }
    this.compName = compName.toString();
}
Also used : Resource(lucee.commons.io.res.Resource)

Example 69 with Resource

use of lucee.commons.io.res.Resource in project Lucee by lucee.

the class PageSourceImpl method getPhyscalFile.

/**
 * return file object, based on physical path and realpath
 * @return file Object
 */
@Override
public Resource getPhyscalFile() {
    if (physcalSource == null) {
        if (!mapping.hasPhysical()) {
            return null;
        }
        Resource tmp = mapping.getPhysical().getRealResource(relPath);
        physcalSource = ResourceUtil.toExactResource(tmp);
        // fix if the case not match
        if (!tmp.getAbsolutePath().equals(physcalSource.getAbsolutePath())) {
            String relpath = physcalSource.getAbsolutePath().substring(mapping.getPhysical().getAbsolutePath().length());
            // just a security!
            if (relPath.equalsIgnoreCase(relpath)) {
                this.relPath = relpath;
                createClassAndPackage();
            } else {
            // MUST remove this
            /*aprint.e(
							tmp+":"+physcalSource+":"+
							mapping.getPhysical().getAbsolutePath()+":"+
							relpath+":"+relPath);*/
            }
        }
    }
    return physcalSource;
}
Also used : Resource(lucee.commons.io.res.Resource)

Example 70 with Resource

use of lucee.commons.io.res.Resource in project Lucee by lucee.

the class MetaData method getInstance.

public static MetaData getInstance(Resource directory) {
    MetaData instance = instances.get(directory.getAbsolutePath());
    if (instance == null) {
        Resource file = directory.getRealResource("meta");
        if (file.exists()) {
            try {
                instance = new MetaData(file, (HashMap) JavaConverter.deserialize(file));
            } catch (Throwable t) {
                ExceptionUtil.rethrowIfNecessary(t);
            }
        }
        if (instance == null)
            instance = new MetaData(file);
        instances.put(directory.getAbsolutePath(), instance);
    }
    return instance;
}
Also used : HashMap(java.util.HashMap) Resource(lucee.commons.io.res.Resource)

Aggregations

Resource (lucee.commons.io.res.Resource)309 IOException (java.io.IOException)100 ApplicationException (lucee.runtime.exp.ApplicationException)54 PageException (lucee.runtime.exp.PageException)40 ArrayList (java.util.ArrayList)31 Struct (lucee.runtime.type.Struct)28 ByteArrayInputStream (java.io.ByteArrayInputStream)21 InputStream (java.io.InputStream)21 ExpressionException (lucee.runtime.exp.ExpressionException)19 StructImpl (lucee.runtime.type.StructImpl)18 MalformedURLException (java.net.MalformedURLException)17 PageContextImpl (lucee.runtime.PageContextImpl)17 PageSource (lucee.runtime.PageSource)16 FileResource (lucee.commons.io.res.type.file.FileResource)15 SecurityException (lucee.runtime.exp.SecurityException)15 BundleException (org.osgi.framework.BundleException)15 ZipEntry (java.util.zip.ZipEntry)13 ExtensionResourceFilter (lucee.commons.io.res.filter.ExtensionResourceFilter)13 Array (lucee.runtime.type.Array)13 File (java.io.File)12