1 package org.exoplatform.services.xml.querying.impl.xtas.resource.plugins; 2 3 import java.io.FileOutputStream ; 4 import java.io.File ; 5 import java.io.IOException ; 6 7 8 import org.exoplatform.services.xml.querying.UniFormTransformationException; 9 import org.exoplatform.services.xml.querying.XMLWellFormedData; 10 import org.exoplatform.services.xml.querying.impl.xtas.WellFormedUniFormTree; 11 import org.exoplatform.services.xml.querying.impl.xtas.resource.Resource; 12 import org.xml.sax.InputSource ; 13 14 import javax.servlet.ServletContext ; 15 16 20 public class ServletResource extends Resource { 21 22 private static String SERVLET_RESOURCE = "servlet:/"; 23 private ServletContext context = null; 24 25 26 public ServletResource() 27 { 28 } 29 30 33 public void init(String resourceId) 34 { 35 this.resourceId = resourceId.substring(SERVLET_RESOURCE.length()); 36 } 38 39 public void setContext(Object context) 40 { 41 43 if( !(context instanceof ServletContext ) ) 44 throw new ClassCastException ("ServletResource.setContext():"+context.getClass().getName()+" not subclass of javax.servlet.ServletContext!"); 45 this.context = (ServletContext ) context; 46 47 48 } 49 50 53 public XMLWellFormedData load() throws UniFormTransformationException, IOException 54 { 55 56 58 try { 59 60 WellFormedUniFormTree tree = new WellFormedUniFormTree (); 61 tree.init ( new InputSource (getContext().getRealPath(resourceId)) ); 62 63 return tree; 64 65 } catch (Exception e) { 66 67 throw new UniFormTransformationException("ServletResource: Can not create WellFormedUniFormTree (XML) Reason: " + e); 68 } 69 } 70 71 public void save(XMLWellFormedData tree) throws IOException 72 { 73 74 75 FileOutputStream fos = new FileOutputStream ( getContext().getRealPath(resourceId) ); 76 77 byte[] b = tree.getAsByteArray(); 78 79 fos.write( b, 0, b.length ); 80 81 fos.flush(); 82 fos.close(); 83 84 } 85 86 89 public void create(XMLWellFormedData initTree) throws IOException 90 { 91 92 94 File res = new File (getContext().getRealPath(resourceId)); 95 96 if( !res.createNewFile() ) 97 throw new IOException (" Resource '"+context.getResource(resourceId).toString()+"' already exists."); 98 99 101 } 102 103 106 public void drop() throws IOException 107 { 108 110 File res = new File (getContext().getRealPath(resourceId)); 111 112 if( !res.delete() ) 113 throw new IOException (" Resource '"+context.getResource(resourceId).toString()+"' can not be deleted."); 114 115 } 117 118 private ServletContext getContext() throws IOException 119 { 120 if( context == null ) 121 throw new IOException ("ServletContext in ServletResource '"+resourceId+"' IS NULL!"); 122 return context; 123 } 124 125 } 126 | Popular Tags |