Package railo.commons.io.res

Examples of railo.commons.io.res.Resource


  }

  @Override
  protected void _clean() {
    ConfigWebImpl cwi=(ConfigWebImpl) engine.getFactory().getConfig();
    Resource dir=type==Scope.SCOPE_CLIENT?cwi.getClientScopeDir():cwi.getSessionScopeDir();
   
    // for old files only the defintion from admin can be used
    long timeout=type==Scope.SCOPE_CLIENT?cwi.getClientTimeout().getMillis():cwi.getSessionTimeout().getMillis();
    long time = new DateTimeImpl(cwi).getTime()-timeout;
   
    try {
      // delete files that has expired
      AndResourceFilter andFilter = new AndResourceFilter(new ResourceFilter[]{EXT_FILTER,new ExpiresFilter(time,true)});
      String appName,cfid2,cfid;
      Resource[] apps = dir.listResources(DIR_FILTER),cfidDir,files;
     
      if(apps!=null)for(int a=0;a<apps.length;a++){
        appName=StorageScopeFile.decode(apps[a].getName());
        cfidDir=apps[a].listResources(DIR_FILTER);
        if(cfidDir!=null)for(int b=0;b<cfidDir.length;b++){
View Full Code Here


    }


    private void initializeMultiPart(PageContext pc, boolean scriptProteced) {
      // get temp directory
      Resource tempDir = ((ConfigImpl)pc.getConfig()).getTempDirectory();
      Resource tempFile;
     
      // Create a new file upload handler
      final String encoding=getEncoding();
      FileItemFactory factory = tempDir instanceof File?
          new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,(File)tempDir):
            new DiskFileItemFactory();
     
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setHeaderEncoding(encoding);
      //ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest());
     
     
      HttpServletRequest req = pc.getHttpServletRequest();
      ServletRequestContext context = new ServletRequestContext(req) {
        public String getCharacterEncoding() {
          return encoding;
        }
      };
     
      // Parse the request
      try {
        FileItemIterator iter = upload.getItemIterator(context);
          //byte[] value;
          InputStream is;
          ArrayList<URLItem> list=new ArrayList<URLItem>();
      while (iter.hasNext()) {
          FileItemStream item = iter.next();

          is=IOUtil.toBufferedInputStream(item.openStream());
          if (item.getContentType()==null || StringUtil.isEmpty(item.getName())) {
            list.add(new URLItem(item.getFieldName(),new String(IOUtil.toBytes(is),encoding),false));      
          }
          else {
            tempFile=tempDir.getRealResource(getFileName());
            fileItems.put(item.getFieldName().toLowerCase(),
                new Item(tempFile,item.getContentType(),item.getName(),item.getFieldName()));
          String value=tempFile.toString();
            IOUtil.copy(is, tempFile,true);
           
            list.add(new URLItem(item.getFieldName(),value,false));      
          }      
      }
View Full Code Here

            if(ct!=null && !StringUtil.isEmpty(ct.getCharset(),true)) cs=ct.getCharset();
           
           
            if(doMultiPart) {
              try {
                Resource res = param.getFile();
                parts.add(new FormBodyPart(
                    param.getName(),
                    new ResourceBody(res, mt, res.getName(), cs)
                ));
                //parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset));
              }
              catch (FileNotFoundException e) {
                throw new ApplicationException("can't upload file, path is invalid",e.getMessage());
              }
            }
          }
        // XML
          else if(type.equals("xml")) {
            ContentType ct = HTTPUtil.toContentType(param.getMimeType(),null);
             
            String mt="text/xml";
            if(ct!=null && !StringUtil.isEmpty(ct.getMimeType(),true)) mt=ct.getMimeType();
           
            String cs=charset;
            if(ct!=null && !StringUtil.isEmpty(ct.getCharset(),true)) cs=ct.getCharset();
           
            hasBody=true;
            hasContentType=true;
            req.addHeader("Content-type", mt+"; charset="+cs);
              if(eem==null)throw new ApplicationException("type xml is only supported for type post and put");
              HTTPEngine4Impl.setBody(eem, param.getValueAsString(),mt,cs);
          }
        // Body
          else if(type.equals("body")) {
            ContentType ct = HTTPUtil.toContentType(param.getMimeType(),null);
             
            String mt=null;
            if(ct!=null && !StringUtil.isEmpty(ct.getMimeType(),true)) mt=ct.getMimeType();
           
            String cs=charset;
            if(ct!=null && !StringUtil.isEmpty(ct.getCharset(),true)) cs=ct.getCharset();
           
           
            hasBody=true;
            if(eem==null)throw new ApplicationException("type body is only supported for type post and put");
            HTTPEngine4Impl.setBody(eem, param.getValue(),mt,cs);
           
          }
                else {
                    throw new ApplicationException("invalid type ["+type+"]");
                }
           
        }
       
        // post params
        if(postParam!=null && postParam.size()>0)
          post.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(postParam,charset));
       
        if(compression){
          acceptEncoding.append("gzip");
        }
        else {
          acceptEncoding.append("deflate;q=0");
          req.setHeader("TE", "deflate;q=0");
        }
      req.setHeader("Accept-Encoding",acceptEncoding.toString());
       
       
       
        // multipart
        if(doMultiPart && eem!=null) {
          hasContentType=true;
          boolean doIt=true;
          if(!this.multiPart && parts.size()==1){
            ContentBody body = parts.get(0).getBody();
            if(body instanceof StringBody){
              StringBody sb=(StringBody)body;
              try {
                org.apache.http.entity.ContentType ct=org.apache.http.entity.ContentType.create(sb.getMimeType(),sb.getCharset());
                String str = IOUtil.toString(sb.getReader());
                StringEntity entity = new StringEntity(str,ct);
                eem.setEntity(entity);
               
              } catch (IOException e) {
                throw Caster.toPageException(e);
              }
              doIt=false;
            }
          }
          if(doIt) {
            MultipartEntity mpe = new MultipartEntity(HttpMultipartMode.STRICT);
            Iterator<FormBodyPart> it = parts.iterator();
            while(it.hasNext()) {
              FormBodyPart part = it.next();
              mpe.addPart(part.getName(),part.getBody());
            }
            eem.setEntity(mpe);
          }
            //eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType));
        }
       
       
       
        if(hasBody && hasForm)
          throw new ApplicationException("mixing httpparam  type file/formfield and body/XML is not allowed");
     
        if(!hasContentType) {
          if(isBinary) {
            if(hasBody) req.addHeader("Content-type", "application/octet-stream");
            else req.addHeader("Content-type", "application/x-www-form-urlencoded; charset="+charset);
          }
          else {
            if(hasBody)
              req.addHeader("Content-type", "text/html; charset="+charset );
          }
        }
       
       
        // set User Agent
          if(!hasHeaderIgnoreCase(req,"User-Agent"))
            req.setHeader("User-Agent",this.useragent);
       
      // set timeout
        if(this.timeout>0L)HTTPEngine4Impl.setTimeout(params, (int)this.timeout);
       
      // set Username and Password
        if(this.username!=null) {
          if(this.password==null)this.password="";
          if(AUTH_TYPE_NTLM==this.authType) {
            if(StringUtil.isEmpty(this.workStation,true))
                      throw new ApplicationException("attribute workstation is required when authentication type is [NTLM]");
            if(StringUtil.isEmpty(this.domain,true))
                      throw new ApplicationException("attribute domain is required when authentication type is [NTLM]");
             
            HTTPEngine4Impl.setNTCredentials(client, this.username, this.password, this.workStation,this.domain);
          }
          else httpContext=HTTPEngine4Impl.setCredentials(client, httpHost, this.username, this.password,preauth);
        }
     
      // set Proxy
        ProxyData proxy=null;
        if(!StringUtil.isEmpty(this.proxyserver)) {
          proxy=ProxyDataImpl.getInstance(this.proxyserver, this.proxyport, this.proxyuser, this.proxypassword) ;
        }
        if(pageContext.getConfig().isProxyEnableFor(host)) {
          proxy=pageContext.getConfig().getProxyData();
        }
        HTTPEngine4Impl.setProxy(client, req, proxy);
       
      }
     
     
     
     
     
      try {
      if(httpContext==null)httpContext = new BasicHttpContext();
       
/////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
    Executor4 e = new Executor4(this,client,httpContext,req,redirect);
    HTTPResponse4Impl rsp=null;
    if(timeout<0){
      try{
        rsp = e.execute(httpContext);
      }
     
      catch(Throwable t){
        if(!throwonerror){
          setUnknownHost(cfhttp, t);
          return;
        }
        throw toPageException(t);
       
      }
    }
    else {
      e.start();
      try {
        synchronized(this){//print.err(timeout);
          this.wait(timeout);
        }
      } catch (InterruptedException ie) {
        throw Caster.toPageException(ie);
      }
      if(e.t!=null){
        if(!throwonerror){
          setUnknownHost(cfhttp,e.t);
          return;
        }
        throw toPageException(e.t)
      }
     
      rsp=e.response;
     
     
      if(!e.done){
        req.abort();
        if(throwonerror)
          throw new HTTPException("408 Request Time-out","a timeout occurred in tag http",408,"Time-out",rsp.getURL());
        setRequestTimeout(cfhttp)
        return;
        //throw new ApplicationException("timeout"); 
      }
    }
   
/////////////////////////////////////////// EXECUTE /////////////////////////////////////////////////
    Charset responseCharset=CharsetUtil.toCharset(rsp.getCharset());
  // Write Response Scope
    //String rawHeader=httpMethod.getStatusLine().toString();
      String mimetype=null;
      String contentEncoding=null;
     
    // status code
      cfhttp.set(STATUSCODE,((rsp.getStatusCode()+" "+rsp.getStatusText()).trim()));
      cfhttp.set(STATUS_CODE,new Double(rsp.getStatusCode()));
      cfhttp.set(STATUS_TEXT,(rsp.getStatusText()));
      cfhttp.set(HTTP_VERSION,(rsp.getProtocolVersion()));
     
    //responseHeader
      railo.commons.net.http.Header[] headers = rsp.getAllHeaders();
      StringBuffer raw=new StringBuffer(rsp.getStatusLine()+" ");
      Struct responseHeader = new StructImpl();
      Struct cookie;
      Array setCookie = new ArrayImpl();
      Query cookies=new QueryImpl(new String[]{"name","value","path","domain","expires","secure","httpOnly"},0,"cookies");
     
          for(int i=0;i<headers.length;i++) {
            railo.commons.net.http.Header header=headers[i];
            //print.ln(header);
           
            raw.append(header.toString()+" ");
            if(header.getName().equalsIgnoreCase("Set-Cookie")) {
              setCookie.append(header.getValue());
              parseCookie(cookies,header.getValue());
            }
            else {
                //print.ln(header.getName()+"-"+header.getValue());
              Object value=responseHeader.get(KeyImpl.getInstance(header.getName()),null);
              if(value==null) responseHeader.set(KeyImpl.getInstance(header.getName()),header.getValue());
              else {
                  Array arr=null;
                  if(value instanceof Array) {
                      arr=(Array) value;
                  }
                  else {
                      arr=new ArrayImpl();
                      responseHeader.set(KeyImpl.getInstance(header.getName()),arr);
                      arr.appendEL(value);
                  }
                  arr.appendEL(header.getValue());
              }
            }
           
            // Content-Type
            if(header.getName().equalsIgnoreCase("Content-Type")) {
              mimetype=header.getValue();
              if(mimetype==null)mimetype=NO_MIMETYPE;
            }
           
            // Content-Encoding
            if(header.getName().equalsIgnoreCase("Content-Encoding")) {
              contentEncoding=header.getValue();
            }
           
          }
          cfhttp.set(RESPONSEHEADER,responseHeader);
          cfhttp.set(KeyConstants._cookies,cookies);
          responseHeader.set(STATUS_CODE,new Double(rsp.getStatusCode()));
          responseHeader.set(EXPLANATION,(rsp.getStatusText()));
          if(setCookie.size()>0)responseHeader.set(SET_COOKIE,setCookie);
         
      // is text
          boolean isText=
            mimetype == null || 
            mimetype == NO_MIMETYPE || HTTPUtil.isTextMimeType(mimetype);
           
        // is multipart
          boolean isMultipart= MultiPartResponseUtils.isMultipart(mimetype);       
        
          cfhttp.set(KeyConstants._text,Caster.toBoolean(isText));
         
      // mimetype charset
          //boolean responseProvideCharset=false;
          if(!StringUtil.isEmpty(mimetype,true)){
            if(isText) {
              String[] types=HTTPUtil.splitMimeTypeAndCharset(mimetype,null);
              if(types[0]!=null)cfhttp.set(KeyConstants._mimetype,types[0]);
              if(types[1]!=null)cfhttp.set(CHARSET,types[1]);
                 
            }
            else cfhttp.set(KeyConstants._mimetype,mimetype);
          }
          else cfhttp.set(KeyConstants._mimetype,NO_MIMETYPE);

      // File
          Resource file=null;
         
          if(strFile!=null && strPath!=null) {
              file=ResourceUtil.toResourceNotExisting(pageContext, strPath).getRealResource(strFile);
          }
          else if(strFile!=null) {
              file=ResourceUtil.toResourceNotExisting(pageContext, strFile);
          }
          else if(strPath!=null) {
              file=ResourceUtil.toResourceNotExisting(pageContext, strPath);
              //Resource dir = file.getParentResource();
              if(file.isDirectory()){
                file=file.getRealResource(req.getURI().getPath());// TODO was getName() ->http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/URI.html#getName()
              }
             
          }
          if(file!=null)pageContext.getConfig().getSecurityManager().checkFileLocation(file);
         
View Full Code Here

    }


    private int _doStartTag() throws PageException   {
        // check the file before doing anyrhing else
      Resource file=null;
    if(content==null && !StringUtil.isEmpty(strFile))
        file = ResourceUtil.toResourceExisting(pageContext,strFile);

    // get response object
    HttpServletResponse rsp = pageContext. getHttpServletResponse();
     
        // check committed
        if(rsp.isCommitted())
            throw new ApplicationException("content is already flushed","you can't rewrite head of response after part of the page is flushed");
       
        // set type
        if(!StringUtil.isEmpty(type,true)) {
          type=type.trim();
          rsp.setContentType(type);
         
          // TODO more dynamic implementation, configuration in admin?
          if(!HTTPUtil.isTextMimeType(type)) {
            ((PageContextImpl)pageContext).getRootOut().setAllowCompression(false);
          }
        }
       
        Range[] ranges=getRanges();
        boolean hasRanges=ranges!=null && ranges.length>0;
        if(_range==RANGE_YES || hasRanges){
            rsp.setHeader("Accept-Ranges", "bytes");
        }
        else if(_range==RANGE_NO) {
            rsp.setHeader("Accept-Ranges", "none");
            hasRanges=false;
        }
       
        // set content
        if(this.content!=null || file!=null) {
            pageContext.clear();
          InputStream is=null;
            OutputStream os=null;
            long totalLength,contentLength;
            try {
              os=getOutputStream();
             
              if(content!=null) {
                //ReqRspUtil.setContentLength(rsp,content.length);
                contentLength=content.length;
                totalLength=content.length;
                     is=new BufferedInputStream(new ByteArrayInputStream(content))
                }
                else {
                    //ReqRspUtil.setContentLength(rsp,file.length());
                    pageContext.getConfig().getSecurityManager().checkFileLocation(file);
                    contentLength=totalLength=file.length();
                    is=IOUtil.toBufferedInputStream(file.getInputStream());
                }
             
              // write
              if(!hasRanges)
                IOUtil.copy(is,os,false,false);
View Full Code Here

        roles=CredentialImpl.toRole(oRoles);
    }
   
  @Override
  public int doStartTag() throws PageException  {
    Resource rolesDir = pageContext.getConfig().getConfigDir().getRealResource("roles");
      CredentialImpl login = new CredentialImpl(name,password,roles,rolesDir);
      pageContext.setRemoteUser(login);
     
      Tag parent=getParent();
    while(parent!=null && !(parent instanceof Login)) {
View Full Code Here

        images[i] = new Image(srcs[i]);
      }
     
      // TODO use the same resource as for cfimage
      PageSource ps = pageContext.getCurrentTemplatePageSource();
      Resource curr = ps.getResource();
      Resource dir = curr.getParentResource();
      Resource cssDir = dir.getRealResource("css");
      Resource pathdir = cssDir;
      cssDir.mkdirs();
     
     
      //the base name for the files we are going to create as a css and image
      String baseRenderedFileName = MD5.getDigestAsString(_ids);
      Resource cssFileName = cssDir.getRealResource(baseRenderedFileName+".css");
      Resource imgFileName = pathdir.getRealResource(baseRenderedFileName+"."+ResourceUtil.getExtension(src,""));
     
      //if the files don't exist, then we create them, otherwise
      boolean bCreate = !cssFileName.isFile() || !imgFileName.isFile();
     
     
      //Are we going to create it, let's say no
      String css = "";
      if(bCreate){
        int imgMaxHeight = 0;
        int imgMaxWidth = 0;
        Image img;
        int actualWidth,actualHeight;
        //Setup the max height and width of the new image.
        for(int i=0;i<srcs.length;i++){
          img = images[i];
         
          //set the image original height and width
          actualWidth = img.getWidth();;
          actualHeight = img.getHeight();
                 
                 
         
          //Check if there is a height,
          imgMaxHeight += actualHeight;
          if(actualWidth  > imgMaxWidth) imgMaxWidth  =  actualWidth;
        }
       
        //Create the new image (hence we needed to do two of these items)
        Image spriteImage = (Image) ImageNew.call(pageContext,"", ""+imgMaxWidth,""+imgMaxHeight, "argb");
       
        int placedHeight = 0;
        //Loop again but this time, lets do the copy and paste
        for(int i=0;i<srcs.length;i++){
          img = images[i];
          spriteImage.paste(img,1,placedHeight);
         
            css += "#"+ids[i]+" {\n\tbackground: url("+baseRenderedFileName+"."+ResourceUtil.getExtension(strSrcs[i],"")+") 0px -"+placedHeight+"px no-repeat; width:"+img.getWidth()+"px; height:"+img.getHeight()+"px;\n} \n";
            placedHeight += img.getHeight();
        }
       
        //Now Write the CSS and the Sprite Image
       
        ImageWrite.call(pageContext, spriteImage, imgFileName.getAbsolutePath());
        IOUtil.write(cssFileName, css,"UTF-8",false);
       
      }

     
View Full Code Here


  private String touchDestination() throws IOException {
    if(destination==null) {
      String name=CreateUUID.call(pageContext)+"."+format;
      Resource folder = pageContext.getConfig().getTempDirectory().getRealResource("graph");
      if(!folder.exists())folder.createDirectory(true);
      destination = folder.getRealResource(name);
      cleanOld(folder);
     
      // create path
      String cp = pageContext.getHttpServletRequest().getContextPath();
      if(StringUtil.isEmpty(cp)) cp="";
View Full Code Here

   * @param contentID
   * @param disposition
   * @throws PageException
  **/
  public void setMimeattach(String strMimeattach, String type, String disposition, String contentID,boolean removeAfterSend) throws PageException  {
    Resource file=ResourceUtil.toResourceNotExisting(pageContext,strMimeattach);
        pageContext.getConfig().getSecurityManager().checkFileLocation(file);
    if(!file.exists())
      throw new ApplicationException("can't attach file "+strMimeattach+", this file doesn't exist");
   

        smtp.addAttachment(file,type,disposition,contentID,removeAfterSend);
   
View Full Code Here

      if(!mapping.hasPhysical()) return null;
     
      ConfigWeb config=pc.getConfig();
      PageContextImpl pci=(PageContextImpl) pc;
      if((mapping.getInspectTemplate()==ConfigImpl.INSPECT_NEVER || pci.isTrusted(page)) && isLoad(LOAD_PHYSICAL)) return page;
      Resource srcFile = getPhyscalFile();
     
      /*{
        String dp = getDisplayPath();
        String cn = getClassName();
        if(dp.endsWith(".cfc") && cn.startsWith("cfc")) {
          print.ds("->"+dp);
          print.e("trusted:"+mapping.isTrusted());
          print.e(mapping.getVirtual());
          print.e("mod:"+srcFile.lastModified());
        }
      }*/
     
     
    long srcLastModified = srcFile.lastModified();
        if(srcLastModified==0L) return null;
     
    // Page exists   
      if(page!=null) {
      //if(page!=null && !recompileAlways) {
        // java file is newer !mapping.isTrusted() &&
        if(srcLastModified!=page.getSourceLastModified()) {
          this.page=page=compile(config,mapping.getClassRootDirectory(),Boolean.TRUE);
                  page.setPageSource(this);
          page.setLoadType(LOAD_PHYSICAL);
        }
         
      }
    // page doesn't exist
      else {
                ///synchronized(this) {
                    Resource classRootDir=mapping.getClassRootDirectory();
                    Resource classFile=classRootDir.getRealResource(getJavaName()+".class");
                    boolean isNew=false;
                    // new class
                    if(!classFile.exists()) {
                    //if(!classFile.exists() || recompileAfterStartUp) {
                      this.page=page= compile(config,classRootDir,Boolean.FALSE);
                        isNew=true;
                    }
                    // load page
View Full Code Here

  }
 
 

  private synchronized void createComponentName() {
    Resource res = this.getPhyscalFile();
      String str=null;
    if(res!=null) {
     
      str=res.getAbsolutePath();
      str=str.substring(str.length()-realPath.length());
      if(!str.equalsIgnoreCase(realPath)) {
        str=realPath;
      }
    }
View Full Code Here

TOP

Related Classes of railo.commons.io.res.Resource

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.