private PDFDocument toPDFDocument(Object source, String password, Resource directory) throws ExpressionException, IOException { if (source instanceof PDFDocument) return (PDFDocument) source; if (Decision.isBinary(source)) { return new PDFDocument(Caster.toBinary(source), password); } if (source instanceof Resource) { return new PDFDocument((Resource) source, password); } if (source instanceof String) { if (directory != null) { Resource res = directory.getRealResource((String) source); if (!res.isFile()) { Resource res2 = ResourceUtil.toResourceNotExisting(pageContext, (String) source); if (res2.isFile()) res = res2; else throw new ExpressionException("file or directory " + res + " not exist"); } return new PDFDocument(res, password); } return new PDFDocument( ResourceUtil.toResourceExisting(pageContext, (String) source), password); } throw new CasterException(source, PdfReader.class); }
private void checkSize(ConfigWeb config, Resource dir, long maxSize, ResourceFilter filter) { if (!dir.exists()) return; Resource res = null; int count = ArrayUtil.size(filter == null ? dir.list() : dir.list(filter)); long size = ResourceUtil.getRealSize(dir, filter); PrintWriter out = config.getOutWriter(); SystemOut.printDate(out, "check size of directory [" + dir + "]"); SystemOut.printDate(out, "- current size [" + size + "]"); SystemOut.printDate(out, "- max size [" + maxSize + "]"); int len = -1; while (count > 100000 || size > maxSize) { Resource[] files = filter == null ? dir.listResources() : dir.listResources(filter); if (len == files.length) break; // protect from inifinti loop len = files.length; for (int i = 0; i < files.length; i++) { if (res == null || res.lastModified() > files[i].lastModified()) { res = files[i]; } } if (res != null) { size -= res.length(); try { res.remove(true); count--; } catch (IOException e) { SystemOut.printDate(out, "cannot remove resource " + res.getAbsolutePath()); break; } } res = null; } }
private void checkOldClientFile(ConfigWeb config) { ExtensionResourceFilter filter = new ExtensionResourceFilter(".script", false); // move old structured file in new structure try { Resource dir = config.getClientScopeDir(), trgres; Resource[] children = dir.listResources(filter); String src, trg; int index; for (int i = 0; i < children.length; i++) { src = children[i].getName(); index = src.indexOf('-'); trg = ClientFile.getFolderName(src.substring(0, index), src.substring(index + 1), false); trgres = dir.getRealResource(trg); if (!trgres.exists()) { trgres.createFile(true); ResourceUtil.copy(children[i], trgres); } // children[i].moveTo(trgres); children[i].delete(); } } catch (Throwable t) { } }
public static void _getTagContext( PageContext pc, Array tagContext, Throwable t, Collection.Key lineNumberName) { // Throwable root = t.getRootCause(); Throwable cause = t.getCause(); if (cause != null) _getTagContext(pc, tagContext, cause, lineNumberName); StackTraceElement[] traces = t.getStackTrace(); UDF[] udfs = ((PageContextImpl) pc).getUDFs(); int line = 0; String template; Struct item; StackTraceElement trace = null; String functionName, methodName; int index = udfs.length - 1; for (int i = 0; i < traces.length; i++) { trace = traces[i]; template = trace.getFileName(); if (trace.getLineNumber() <= 0 || template == null || ResourceUtil.getExtension(template, "").equals("java")) continue; methodName = trace.getMethodName(); if (methodName != null && methodName.startsWith("udfCall") && index > -1) functionName = udfs[index--].getFunctionName(); else functionName = ""; item = new StructImpl(); line = trace.getLineNumber(); item.setEL(KeyConstants._function, functionName); item.setEL(KeyConstants._template, template); item.setEL(lineNumberName, new Double(line)); tagContext.appendEL(item); } }
protected void _init(PageContext pc, Map<String, String> arguments) { this.pc = pc; // header HttpServletRequest req = pc.getHttpServletRequest(); header = new StringBuffer(); createHeader(header, "context-path", req.getContextPath()); createHeader(header, "remote-user", req.getRemoteUser()); createHeader(header, "remote-addr", req.getRemoteAddr()); createHeader(header, "remote-host", req.getRemoteHost()); createHeader( header, "script-name", StringUtil.emptyIfNull(req.getContextPath()) + StringUtil.emptyIfNull(req.getServletPath())); createHeader(header, "server-name", req.getServerName()); createHeader(header, "protocol", req.getProtocol()); createHeader(header, "server-port", Caster.toString(req.getServerPort())); createHeader( header, "path-info", StringUtil.replace( StringUtil.emptyIfNull(req.getRequestURI()), StringUtil.emptyIfNull(req.getServletPath()), "", true)); // createHeader(header,"path-translated",pc.getBasePageSource().getDisplayPath()); createHeader(header, "query-string", req.getQueryString()); createHeader(header, "unit", unitShortToString(unit)); createHeader(header, "min-time-nano", min + ""); content = new StringBuffer(); // directory String strDirectory = arguments.get("directory"); if (dir == null) { if (StringUtil.isEmpty(strDirectory)) { dir = getTemp(pc); } else { try { dir = ResourceUtil.toResourceNotExisting(pc, strDirectory, false); if (!dir.exists()) { dir.createDirectory(true); } else if (dir.isFile()) { err( pc, "can not create directory [" + dir + "], there is already a file with same name."); } } catch (Throwable t) { err(pc, t); dir = getTemp(pc); } } } file = dir.getRealResource((pc.getId()) + "-" + CreateUUID.call(pc) + ".exl"); file.createNewFile(); start = System.currentTimeMillis(); }
@Override public OutputStream getOutputStream() throws IOException { ResourceUtil.checkGetOutputStreamOK(this); // Resource res = getRamResource(); // Resource p = res.getParentResource(); // if(p!=null && !p.exists())p.mkdirs(); return new CompressOutputStreamSynchronizer( getRamResource().getOutputStream(), zip, provider.async); }
public static String call( PageContext pc, String source, String destination, boolean recurse, Object filter) throws PageException { Resource src = ResourceUtil.toResourceNotExisting(pc, source); ResourceAndResourceNameFilter fi = filter == null ? null : UDFFilter.createResourceAndResourceNameFilter(filter); Directory.actionCopy(pc, src, destination, null, null, S3Constants.STORAGE_UNKNOW, fi, recurse); return null; }
private static boolean validExtension(String[] extensions, String file) { String ext = ResourceUtil.getExtension(file, ""); ext = railo.runtime.type.util.ListUtil.first(ext, "/", true); if (StringUtil.isEmpty(ext)) return true; for (int i = 0; i < extensions.length; i++) { if (ext.equalsIgnoreCase(extensions[i])) return true; } return false; }
public static InputSource toInputSource(PageContext pc, String xml, boolean canBePath) throws IOException, ExpressionException { // xml text xml = xml.trim(); if (!canBePath || xml.startsWith("<")) { return new InputSource(new StringReader(xml)); } // xml link pc = ThreadLocalPageContext.get(pc); Resource res = ResourceUtil.toResourceExisting(pc, xml); return toInputSource(pc, res); }
public void checkFileLocation(Config config, Resource res, String serverPassword) throws SecurityException { if (res == null || !(res.getResourceProvider() instanceof FileResourceProvider)) { return; } // All if (getAccess(TYPE_FILE) == VALUE_ALL) return; // Local if (getAccess(TYPE_FILE) == VALUE_LOCAL) { res = ResourceUtil.getCanonicalResourceEL(res); // local if (rootDirectory != null) if (ResourceUtil.isChildOf(res, rootDirectory)) return; // custom if (!ArrayUtil.isEmpty(customFileAccess)) { for (int i = 0; i < customFileAccess.length; i++) { if (ResourceUtil.isChildOf(res, customFileAccess[i])) return; } } if (isValid(config, serverPassword) || isAdminContext()) return; throw new SecurityException( createExceptionMessage(res, true), "access is prohibited by security manager"); } // None if (isValid(config, serverPassword)) return; // custom if (!ArrayUtil.isEmpty(customFileAccess)) { res = ResourceUtil.getCanonicalResourceEL(res); for (int i = 0; i < customFileAccess.length; i++) { if (ResourceUtil.isChildOf(res, customFileAccess[i])) return; } } if (isAdminContext()) return; throw new SecurityException( createExceptionMessage(res, false), "access is prohibited by security manager"); }
private PageContextImpl createPageContext( CFMLFactory factory, ComponentAccess app, String applicationName, String cfid, Collection.Key methodName) throws PageException { Resource root = factory.getConfig().getRootDirectory(); String path = app.getPageSource().getFullRealpath(); // Request HttpServletRequestDummy req = new HttpServletRequestDummy(root, "localhost", path, "", null, null, null, null, null); if (!StringUtil.isEmpty(cfid)) req.setCookies(new Cookie[] {new Cookie("cfid", cfid), new Cookie("cftoken", "0")}); // Response OutputStream os = DevNullOutputStream.DEV_NULL_OUTPUT_STREAM; try { Resource out = factory .getConfig() .getConfigDir() .getRealResource("output/" + methodName.getString() + ".out"); out.getParentResource().mkdirs(); os = out.getOutputStream(false); } catch (IOException e) { e.printStackTrace(); // TODO was passiert hier } HttpServletResponseDummy rsp = new HttpServletResponseDummy(os); // PageContext PageContextImpl pc = (PageContextImpl) factory.getRailoPageContext(factory.getServlet(), req, rsp, null, false, -1, false); // ApplicationContext ClassicApplicationContext ap = new ClassicApplicationContext( factory.getConfig(), applicationName, false, app == null ? null : ResourceUtil.getResource(pc, app.getPageSource(), null)); initApplicationContext(pc, app); ap.setName(applicationName); ap.setSetSessionManagement(true); // if(!ap.hasName())ap.setName("Controler") // Base pc.setBase(app.getPageSource()); return pc; }
private void doActionThumbnail() throws PageException, IOException, DocumentException { required("pdf", "thumbnail", "source", source); PDFDocument doc = toPDFDocument(source, password, null); PdfReader pr = doc.getPdfReader(); boolean isEnc = pr.isEncrypted(); pr.close(); if (isEnc) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); // PDFUtil.concat(new PDFDocument[]{doc}, baos, true, true, true, (char)0); PDFUtil.encrypt(doc, baos, null, null, 0, PDFUtil.ENCRYPT_NONE); baos.close(); doc = new PDFDocument(baos.toByteArray(), doc.getResource(), null); } doc.setPages(pages); // scale if (scale < 1) throw new ApplicationException( "value of attribute scale [" + scale + "] should be at least 1"); // destination if (destination == null) destination = ResourceUtil.toResourceNotExisting(pageContext, "thumbnails"); // imagePrefix if (imagePrefix == null) { Resource res = doc.getResource(); if (res != null) { String n = res.getName(); int index = n.lastIndexOf('.'); if (index != -1) imagePrefix = n.substring(0, index); else imagePrefix = n; } else imagePrefix = "memory"; } // MUST password PDFUtil.writeImages( doc.getRaw(), doc.getPages(), destination, imagePrefix, format, scale, overwrite, resolution == RESOLUTION_HIGH, transparent); }
/** * Constructor of the class * * @param provider * @param zip * @param path * @param caseSensitive */ CompressResource( CompressResourceProvider provider, Compress zip, String path, boolean caseSensitive) { if (StringUtil.isEmpty(path)) path = "/"; this.provider = provider; this.zip = zip; this.path = path; if ("/".equals(path)) { this.parent = null; this.name = ""; } else { String[] pn = ResourceUtil.translatePathName(path); this.parent = pn[0]; this.name = pn[1]; } this.caseSensitive = caseSensitive; }
public static InputSource toInputSource(PageContext pc, Object value) throws IOException, ExpressionException { if (value instanceof InputSource) { return (InputSource) value; } if (value instanceof String) { return toInputSource(pc, (String) value); } if (value instanceof StringBuffer) { return toInputSource(pc, value.toString()); } if (value instanceof Resource) { String str = IOUtil.toString(((Resource) value), null); return new InputSource(new StringReader(str)); } if (value instanceof File) { String str = IOUtil.toString(ResourceUtil.toResource(((File) value)), null); return new InputSource(new StringReader(str)); } if (value instanceof InputStream) { InputStream is = (InputStream) value; try { String str = IOUtil.toString(is, null); return new InputSource(new StringReader(str)); } finally { IOUtil.closeEL(is); } } if (value instanceof Reader) { Reader reader = (Reader) value; try { String str = IOUtil.toString(reader); return new InputSource(new StringReader(str)); } finally { IOUtil.closeEL(reader); } } if (value instanceof byte[]) { return new InputSource(new ByteArrayInputStream((byte[]) value)); } throw new ExpressionException( "cat cast object of type [" + Caster.toClassName(value) + "] to a Input for xml parser"); }
public static synchronized void log( Debugger debugger, int type, String category, String text, String varName, String varValue) { Throwable t = new Exception("Stack trace"); Throwable cause = t.getCause(); while (cause != null) { t = cause; cause = t.getCause(); } StackTraceElement[] traces = t.getStackTrace(); int line = 0; String template = null; StackTraceElement trace = null; for (int i = 0; i < traces.length; i++) { trace = traces[i]; template = trace.getFileName(); if (trace.getLineNumber() <= 0 || template == null || ResourceUtil.getExtension(template, "").equals("java") || template.endsWith("Dump.cfc") || template.endsWith("dump.cfm")) // MUST bad impl continue; line = trace.getLineNumber(); break; } // print.e(t); if (line == 0) return; /*String type=traces[2].getMethodName(); int row=qry.addRow(); qry.setAtEL(LABEL, row, label); qry.setAtEL(ACTION, row, type(type)); qry.setAtEL(PARAMS, row, addional); */ String action = type(traces[2].getMethodName()); if (debugger != null) debugger.addTrace(type, category, text, template, line, action, varName, varValue); }
private void doActionMerge() throws ApplicationException, PageException, IOException, DocumentException { if (source == null && params == null && directory == null) throw new ApplicationException( "at least one of the following constellation must be defined" + " attribute source, attribute directory or cfpdfparam child tags"); if (destination == null && StringUtil.isEmpty(name, true)) throw new ApplicationException( "at least one of the following attributes must be defined " + "[destination,name]"); if (destination != null && !overwrite) throw new ApplicationException("destination file [" + destination + "] already exists"); ArrayList docs = new ArrayList(); PDFDocument doc; boolean isListing = false; // source if (source != null) { if (Decision.isArray(source)) { Array arr = Caster.toArray(source); int len = arr.size(); for (int i = 1; i <= len; i++) { docs.add(doc = toPDFDocument(arr.getE(i), password, null)); doc.setPages(pages); } } else if (source instanceof String) { String[] sources = List.toStringArrayTrim(List.listToArrayRemoveEmpty((String) source, ',')); for (int i = 0; i < sources.length; i++) { docs.add(doc = toPDFDocument(sources[i], password, null)); doc.setPages(pages); } } else docs.add(toPDFDocument(source, password, null)); } boolean destIsSource = false; // params if (directory != null && !directory.isDirectory()) { if (!directory.exists()) throw new ApplicationException("defined attribute directory does not exist"); throw new ApplicationException("defined attribute directory is not a directory"); } if (params != null) { Iterator it = params.iterator(); PDFParamBean param; while (it.hasNext()) { param = (PDFParamBean) it.next(); docs.add(doc = toPDFDocument(param.getSource(), param.getPassword(), directory)); doc.setPages(param.getPages()); } } else if (directory != null) { isListing = true; Resource[] children = ResourceUtil.listResources(directory, filter); if (ascending) { for (int i = children.length - 1; i >= 0; i--) { if (destination != null && children[i].equals(destination)) destIsSource = true; docs.add(doc = toPDFDocument(children[i], password, null)); doc.setPages(pages); } } else { for (int i = 0; i < children.length; i++) { if (destination != null && children[i].equals(destination)) destIsSource = true; docs.add(doc = toPDFDocument(children[i], password, null)); doc.setPages(pages); } } } int doclen = docs.size(); if (doclen == 0) throw new ApplicationException("you have to define at leat 1 pdf file"); // output OutputStream os = null; if (!StringUtil.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } /*com.lowagie.text.Document document=null; PdfCopy copy=null; PdfReader pr; Set pages; int size;*/ try { if (!isListing) stopOnError = true; PDFUtil.concat( (PDFDocument[]) docs.toArray(new PDFDocument[docs.size()]), os, keepBookmark, false, stopOnError, version); /* boolean init=false; for(int d=0;d<doclen;d++) { doc=(PDFDocument) docs.get(d); pages=doc.getPages(); try { pr=doc.getPdfReader(); print.out(pr.getCatalog().getKeys()); } catch(Throwable t) { if(isListing && !stopOnError)continue; throw Caster.toPageException(t); } print.out("d+"+d); if(!init) { init=true; print.out("set"); document = new com.lowagie.text.Document(pr.getPageSizeWithRotation(1)); copy = new PdfCopy(document,os); document.open(); } size=pr.getNumberOfPages(); print.out("pages:"+size); for(int page=1;page<=size;page++) { if(pages==null || pages.contains(Constants.Integer(page))) { copy.addPage(copy.getImportedPage(pr, page)); } } }*/ } finally { // if(document!=null)document.close(); IOUtil.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) IOUtil.copy( new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true); // MUST overwrite if (!StringUtil.isEmpty(name)) pageContext.setVariable(name, ((ByteArrayOutputStream) os).toByteArray()); } } }
/** * @param directory the directory to set * @throws ExpressionException */ public void setDirectory(String directory) throws ExpressionException { this.directory = ResourceUtil.toResourceExisting(pageContext, directory); }
/** @param destination the destination to set */ public void setDestination(String destination) { this.destination = ResourceUtil.toResourceNotExisting(pageContext, destination); }
@Override public Resource getRealResource(String realpath) { realpath = ResourceUtil.merge(path, realpath); if (realpath.startsWith("../")) return null; return new CompressResource(provider, zip, realpath, caseSensitive); }
@Override public void createFile(boolean createParentWhenNotExists) throws IOException { ResourceUtil.checkCreateFileOK(this, createParentWhenNotExists); getRamResource().createFile(createParentWhenNotExists); zip.synchronize(provider.async); }
protected void _onRequest( PageContext pc, PageSource requestedPage, PageSource appPS, RequestListener rl) throws PageException { PageContextImpl pci = (PageContextImpl) pc; if (appPS != null) { String callPath = appPS.getComponentName(); ComponentAccess app = ComponentLoader.loadComponent(pci, null, appPS, callPath, false, false); // init initApplicationContext(pci, app); apps.put(pc.getApplicationContext().getName(), app); if (!pci.initApplicationContext()) return; if (rl != null) { requestedPage = rl.execute(pc, requestedPage); if (requestedPage == null) return; } String targetPage = requestedPage.getFullRealpath(); boolean doOnRequestEnd = true; // onRequestStart if (app.contains(pc, ON_REQUEST_START)) { Object rtn = call(app, pci, ON_REQUEST_START, new Object[] {targetPage}, true); if (!Caster.toBooleanValue(rtn, true)) return; } // onRequest boolean isCFC = ResourceUtil.getExtension(targetPage, "") .equalsIgnoreCase(pc.getConfig().getCFCExtension()); Object method; if (isCFC && app.contains(pc, ON_CFCREQUEST) && (method = pc.urlFormScope().get(ComponentPage.METHOD, null)) != null) { Struct url = (Struct) Duplicator.duplicate(pc.urlFormScope(), true); url.removeEL(KeyConstants._fieldnames); url.removeEL(ComponentPage.METHOD); Object args = url.get(KeyConstants._argumentCollection, null); Object returnFormat = url.removeEL(KeyConstants._returnFormat); 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 { pc.forceWrite( ComponentPage.convertResult( pc, app, method.toString(), returnFormat, queryFormat, rtn)); } catch (Exception e) { throw Caster.toPageException(e); } } } } // else if(!isCFC && app.contains(pc,ON_REQUEST)) {} else { // TODO impl die nicht so generisch ist try { if (!isCFC && app.contains(pc, ON_REQUEST)) call(app, pci, ON_REQUEST, new Object[] {targetPage}, false); else pci.doInclude(requestedPage); } catch (PageException pe) { if (!Abort.isSilentAbort(pe)) { if (pe instanceof MissingIncludeException) { if (((MissingIncludeException) pe).getPageSource().equals(requestedPage)) { if (app.contains(pc, ON_MISSING_TEMPLATE)) { if (!Caster.toBooleanValue( call(app, pci, ON_MISSING_TEMPLATE, new Object[] {targetPage}, true), true)) throw pe; } else throw pe; } else throw pe; } else throw pe; } else { doOnRequestEnd = false; if (app.contains(pc, ON_ABORT)) { call(app, pci, ON_ABORT, new Object[] {targetPage}, true); } } } } // onRequestEnd if (doOnRequestEnd && app.contains(pc, ON_REQUEST_END)) { call(app, pci, ON_REQUEST_END, new Object[] {targetPage}, true); } } else { apps.put(pc.getApplicationContext().getName(), null); pc.doInclude(requestedPage); } }
@Override public InputStream getInputStream() throws IOException { ResourceUtil.checkGetInputStreamOK(this); return getRamResource().getInputStream(); }