@Entity
@Table(name = "rdf_classes")
public class RdfClasses implements java.io.Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6332745975079568050L;
	private Integer idRdfClass;
	private String className;
	private String rdfType;
	private int count;
	private Set<Records> records = new HashSet<Records>(0);

	public RdfClasses() {
	}



	public RdfClasses(String className, String rdfType,int count) {
		super();
		this.className = className;
		this.rdfType = rdfType;
		this.count = count;
	}



	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id_rdf_class", unique = true, nullable = false)
	public Integer getIdRdfClass() {
		return this.idRdfClass;
	}

	public void setIdRdfClass(Integer idRdfClass) {
		this.idRdfClass = idRdfClass;
	}

	@Column(name = "class_name", length = 250)
	public String getClassName() {
		return this.className;
	}

	public void setClassName(String className) {
		this.className = className;
	}

	@Column(name = "rdf_type", length = 250)
	public String getRdfType() {
		return this.rdfType;
	}

	public void setRdfType(String rdfType) {
		this.rdfType = rdfType;
	}
	
	
	@Column(name = "count", nullable = false)
	public int getCount() {
		return this.count;
	}

	public void setCount(int count) {
		this.count = count;
	}
	
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "rdfClasses")
	public Set<Records> getRecords() {
		return this.records;
	}

	public void setRecords(Set<Records> records) {
		this.records = records;
	}

} @Entity
@Table(name = "record_types")
public class RecordTypes implements java.io.Serializable {
	private static final long serialVersionUID = -4586187414088019941L;
	private Integer idRecordType;
	private String label;
	private Set<Records> records = new HashSet<Records>(0);

	public RecordTypes() {
	}

	public RecordTypes(String label,Set<Records> records) {
		this.label = label;
		this.records = records;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id_record_type", unique = true, nullable = false)
	public Integer getIdRecordType() {
		return this.idRecordType;
	}

	public void setIdRecordType(Integer idRecordType) {
		this.idRecordType = idRecordType;
	}

	@Column(name = "label", length = 250)
	public String getLabel() {
		return this.label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "recordTypes")
	public Set<Records> getRecords() {
		return this.records;
	}

	public void setRecords(Set<Records> records) {
		this.records = records;
	}

} @Entity
@Table(name = "records")
public class Records implements java.io.Serializable {
	private static final long serialVersionUID = -2757072151721076046L;
	private Long idRecord;
	private byte[] rdf;
	private Date creationDate;
	private Date modifyDate;
	private String rdfAbout;
	private String contentType;
	private String etag;
	private String creationEtag;
	private String host;
	private RecordTypes recordTypes;
	private RdfClasses rdfClasses;
	private Set<Relations> relationsesForRefIdRecord1 = new HashSet<Relations>(0);
	private Set<Relations> relationsesForRefIdRecord2 = new HashSet<Relations>(0);
	
	
	public Records(RecordTypes recordTypes,RdfClasses rdfClasses,byte[] rdf, Date creationDate,Date modifyDate, String rdfAbout,String contentType, String etag,String creationEtag,String host) {
		super();
		this.recordTypes=recordTypes;
		this.rdfClasses=rdfClasses;
		this.rdf = rdf;
		this.creationDate = creationDate;
		this.modifyDate = modifyDate;
		this.rdfAbout = rdfAbout;
		this.contentType = contentType;
		this.etag = etag;
		this.creationEtag = creationEtag;
		this.host = host;
	}

	public Records() {
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id_record", unique = true, nullable = false)
	public Long getIdRecord() {
		return this.idRecord;
	}

	public void setIdRecord(Long idRecord) {
		this.idRecord = idRecord;
	}


	@Column(name = "rdf",columnDefinition="BLOB")
	public byte[] getRdf() {
		return this.rdf;
	}

	public void setRdf(byte[] rdf) {
		this.rdf = rdf;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "creation_date", length = 19)
	public Date getCreationDate() {
		return this.creationDate;
	}

	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "modify_date", length = 19)
	public Date getModifyDate() {
		return this.modifyDate;
	}

	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}


	@Column(name = "rdf_about")
	public String getRdfAbout() {
		return this.rdfAbout;
	}

	public void setRdfAbout(String rdfAbout) {
		this.rdfAbout = rdfAbout;
	}
    
	@Column(name = "content_type")
	public String getContentType() {
		return this.contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	
	
	@Column(name = "host")
	public String getHost() {
		return this.host;
	}

	public void setHost(String host) {
		this.host = host;
	}
	
	@Column(name = "creation_etag")
	public String getCreationEtag() {
		return this.creationEtag;
	}

	public void setCreationEtag(String creationEtag) {
		this.creationEtag = creationEtag;
	}
	
	@Column(name = "etag")
	public String getEtag() {
		return this.etag;
	}

	public void setEtag(String etag) {
		this.etag = etag;
	}
	
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "ref_id_record_type", nullable = false, insertable = true, updatable = true)
	public RecordTypes getRecordTypes() {
		return this.recordTypes;
	}

	public void setRecordTypes(RecordTypes recordTypes) {
		this.recordTypes = recordTypes;
	}
	
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "ref_id_rdf_class", nullable = true, insertable = true, updatable = true)
	public RdfClasses getRdfClasses() {
		return this.rdfClasses;
	}

	public void setRdfClasses(RdfClasses rdfClasses) {
		this.rdfClasses = rdfClasses;
	}
	
	@OneToMany (fetch = FetchType.LAZY,mappedBy="recordsByRefIdRecord1", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
	@org.hibernate.annotations.Cascade( {org.hibernate.annotations.CascadeType.SAVE_UPDATE})
	public Set<Relations> getRelationsesForRefIdRecord1() {
		return this.relationsesForRefIdRecord1;
	}

	public void setRelationsesForRefIdRecord1(
			Set<Relations> relationsesForRefIdRecord1) {
		this.relationsesForRefIdRecord1 = relationsesForRefIdRecord1;
	}

	@OneToMany (fetch = FetchType.LAZY,mappedBy="recordsByRefIdRecord2", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
	@org.hibernate.annotations.Cascade( {org.hibernate.annotations.CascadeType.SAVE_UPDATE})
	public Set<Relations> getRelationsesForRefIdRecord2() {
		return this.relationsesForRefIdRecord2;
	}

	public void setRelationsesForRefIdRecord2(Set<Relations> relationsesForRefIdRecord2) {
		this.relationsesForRefIdRecord2 = relationsesForRefIdRecord2;
	}
} @Entity
@Table(name = "slugs")
public class Slugs implements java.io.Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7796973244555499852L;
	private Integer idSlug;
	private String slug;

	public Slugs() {
	}

	public Slugs(String slug) {
		super();
		this.slug = slug;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id_slug", unique = true, nullable = false)
	public Integer getIdSlug() {
		return this.idSlug;
	}

	public void setIdSlug(Integer idSlug) {
		this.idSlug = idSlug;
	}

	@Column(name = "slug", length = 250)
	public String getSlug() {
		return this.slug;
	}

	public void setSlug(String slug) {
		this.slug = slug;
	}

} @Service("bygleService")
public class BygleService implements DBService{

	private static final long serialVersionUID = 1L;
	
	private DBManagerInterface dbManager;
	

	public List<?> getList(Class<?> genericClass) throws HibernateException{
		return dbManager.getList(genericClass);
	}
	public List<?> getPagedList(Class<?> genericClass,int start,int lenght) throws HibernateException{
		return dbManager.getPagedList(genericClass,start,lenght);
	}
	public List<?> getList(DetachedCriteria criteria) throws HibernateException{
		return dbManager.getList(criteria);
	}
	public List<?> getListFromSQL(Class<?> genericClass,String sql) throws HibernateException{
		return dbManager.getListFromSQL(genericClass,sql);
	}
	public List<?> getPagedList(DetachedCriteria criteria,int start,int lenght) throws HibernateException{
		return dbManager.getPagedList(criteria, start, lenght);
	}
	public List<?> getPagedListFromSQL(Class<?> genericClass,String sql,int start,int lenght) throws HibernateException{
		return dbManager.getPagedListFromSQL(genericClass,sql,start,lenght);
	}
	public void add(Object genericObj) throws HibernateException{
		dbManager.add(genericObj);
	}
	public Object getObject(Class<?> genericClass, Object id) throws HibernateException{
		Object object = null;
		try {
			object = dbManager.getObject(genericClass, id);
		} catch (HibernateException e) {
			throw e;
		}
		return object;
	}

	public void update(Object genericObj) throws HibernateException{
		dbManager.update(genericObj);
	}

	public void addAll(Set<?> genericObjects) throws HibernateException {
		dbManager.addAll(genericObjects);		
	}

	public void remove(Object genericObj) throws HibernateException {
		dbManager.remove(genericObj);
		
	}

	public void removeAll(Set<?> genericObjects) throws HibernateException {
		dbManager.removeAll(genericObjects);
		
	}
	public void removeAll(List<?> genericObjects) throws HibernateException {
		dbManager.removeAll(genericObjects);
		
	}
	public void updateAll(Set<?> genericObjects) throws HibernateException {
		dbManager.updateAll(genericObjects);
		
	}
	public int executeUpdate(String sql) throws HibernateException {
		return dbManager.executeUpdate(sql);
	}
	public int getCountFromSQL(String sql) throws HibernateException {
		return dbManager.getCountFromSQL(sql);
	}
	@Autowired
    public void setDBManager(DBManagerInterface dbManager) {
            this.dbManager = dbManager;
    }
	
} public class Content {
    private byte[] content;
    private int resourceType;
    private Model model;
    private String inputFormat;
    private String outputFormat;
    private Resource ENTITY_TYPE;
    private String rdfAbout;
    private RdfClasses rdfClasses;
	public Content(String rdfAbout,int resourceType,Resource ENTITY_TYPE,Model model,String inputFormat,String outputFormat) throws UnsupportedEncodingException, ConfigurationException, URISyntaxException {
		super();
		this.resourceType = resourceType;
		this.ENTITY_TYPE = ENTITY_TYPE;
		this.model = model;
		this.inputFormat = inputFormat;
		this.outputFormat = outputFormat;
		this.rdfAbout = rdfAbout;
	}
	public Content(byte[] content, String rdfAbout,int resourceType) {
		this.resourceType = resourceType;
		this.content = content;
		this.rdfAbout = rdfAbout;
	}
	public byte[] getContent() {
		if(resourceType!=BygleSystemUtils.RESOURCE_TYPE_BINARY){
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			model.write(byteArrayOutputStream,BygleSystemUtils.getWriter(outputFormat));
			content = byteArrayOutputStream.toByteArray();
		}
		return content;
	}
	public void setContent(byte[] content) {
		this.content = content;
	}
	public int getResourceType() {
		return resourceType;
	}
	public void setResourceType(int resourceType) {
		this.resourceType = resourceType;
	}
	
	public Resource getENTITY_TYPE() {
		return ENTITY_TYPE;
	}
	public void setENTITY_TYPE(Resource eNTITY_TYPE) {
		ENTITY_TYPE = eNTITY_TYPE;
	}
	public Model getModel() {
		return model;
	}
	public void setModel(Model model) {
		this.model = model;
	}
	public String getInputFormat() {
		return inputFormat;
	}
	public void setInputFormat(String inputFormat) {
		this.inputFormat = inputFormat;
	}
	public String getOutputFormat() {
		return outputFormat;
	}
	public void setOutputFormat(String outputFormat) {
		this.outputFormat = outputFormat;
	}
	
	public void add(Resource s,Property p,RDFNode o){
		model.add(s, p, o);
	}
	
	public void remove(Resource s,Property p,RDFNode o){
		model.remove(s, p, o);
	}
	public String getRdfAbout() {
		return rdfAbout;
	}
	public void setRdfAbout(String rdfAbout) {
		this.rdfAbout = rdfAbout;
	}
	public RdfClasses getRdfClasses() {
		return rdfClasses;
	}
	public void setRdfClasses(RdfClasses rdfClasses) {
		this.rdfClasses = rdfClasses;
	}
	
} @Component("BygleSystemUtils")
public class BygleSystemUtils {
	public final static String defaultOutputFormat = "text/turtle";
	public final static String defaultWriter = "TURTLE";
	
	public final static String acceptPostData = "text/turtle, application/turtle, application/x-turtle, application/rdf+xml, application/rdf+xml-abbr, application/rdf+json, application/ld+json, application/json, application/n-triples, text/rdf+n3, application/n3, text/n3, image/bmp, image/jpeg";
	public final static String acceptPatchData = "application/rdf+xml-abbr";
	public final static String acceptPostFile = "image/bmp, image/jpeg, application/octet-stream, text/plain";
	public final static AcceptList offeringRDF = new AcceptList(acceptPostData);
	public final static String[] allowedPostRDFMethods = {"GET","POST","PUT","DELETE","OPTIONS","HEAD","PATCH"};
	public final static String[] allowedPostContainerMethods = {"GET","POST","PUT","DELETE","OPTIONS","HEAD","PATCH"};
	public final static String[] allowedPostNonRDFMethods = {"GET","POST","PUT","DELETE","OPTIONS","HEAD"};
	
	public static final int RESOURCE_TYPE_RDF_CONTAINER = 1;
	public static final int RESOURCE_TYPE_RDF_BASIC_CONTAINER = 2;
	public static final int RESOURCE_TYPE_RDF_DIRECT_CONTAINER = 3;
	public static final int RESOURCE_TYPE_RDF_INDIRECT_CONTAINER = 4;
	public static final int RESOURCE_TYPE_RDF_RESOURCE = 5;
	public static final int RESOURCE_TYPE_BINARY = 6;
	
	
	public static final int ACTION_POST = 1;
	public static final int ACTION_PUT = 2;
	public static final int ACTION_PATCH = 3;
	public static final int ACTION_DELETE = 4;
	
	
	public static final int OUTPUTFORMAT_BIO = 1;
	public static final int OUTPUTFORMAT_CSV = 2;
	public static final int OUTPUTFORMAT_JSON = 3;
	public static final int OUTPUTFORMAT_RDF = 4;
	public static final int OUTPUTFORMAT_RDF_ABBR = 5;
	public static final int OUTPUTFORMAT_TSV = 6;
	public static final int OUTPUTFORMAT_XML = 7;
	public static final int OUTPUTFORMAT_N_TRIPLE = 8;
	public static final int OUTPUTFORMAT_TURTLE = 9;
	public static final int OUTPUTFORMAT_HTML = 10;
	
	
	public static final String INPUTFORMAT_TEXT_TURTLE = "text/turtle";
	public static final String INPUTFORMAT_APPLICATION_RDF_XML = "application/rdf+xml";
	public static final String INPUTFORMAT_APPLICATION_JSON = "application/json";
	public static final String INPUTFORMAT_APPLICATION_LD_JSON = "application/ld+json";
	public static final String INPUTFORMAT_APPLICATION_TURTLE = "application/turtle";
	public static final String INPUTFORMAT_APPLICATION_X_TURTLE = "application/x-turtle";
	public static final String INPUTFORMAT_APPLICATION_RDF_XML_ABBR = "application/rdf+xml-abbr";
	public static final String INPUTFORMAT_APPLICATION_RDF_JSON = "application/rdf+json";
	public static final String INPUTFORMAT_APPLICATION_NTRIPLES = "application/n-triples";
	public static final String INPUTFORMAT_TEXT_RDF_N3 = "text/rdf+n3";
	public static final String INPUTFORMAT_APPLICATION_N3 = "application/n3";
	public static final String INPUTFORMAT_TEXT_N3 = "text/n3";
	public static final String INPUTFORMAT_IMAGE_BMP = "image/bmp";
	public static final String INPUTFORMAT_IMAGE_JPEG = "image/jpeg";
	
	
	
	private static final String PROPERTIES_FILE_NAME = "bygle.properties";
	private static PropertiesConfiguration propertiesConfiguration;
	
	private static Configuration configuration = Configuration.newConfiguration();
	private static Configuration htmlconfiguration = Configuration.newConfiguration();
	private static Controller controller;
	private static Controller htmlController;
    
	public static PropertiesConfiguration getPropertiesConfiguration() throws ConfigurationException {
		loadProperties();
		return propertiesConfiguration;
	}
	public static String getStringProperty(String key) throws ConfigurationException{
    	loadProperties();
    	return propertiesConfiguration.getString(key).trim();
    }
    public static boolean getBooleanProperty(String key) throws ConfigurationException{
    	loadProperties();
    	return propertiesConfiguration.getBoolean(key);
    }
    public static int getIntProperty(String key) throws ConfigurationException{
    	loadProperties();
    	return propertiesConfiguration.getInt(key);
    }
    private static void loadProperties() throws ConfigurationException{
    	if(propertiesConfiguration==null){
    		propertiesConfiguration = new PropertiesConfiguration(BygleSystemUtils.class.getClassLoader().getResource(PROPERTIES_FILE_NAME));
    	}
    }
    
    public static Controller getXSLTController() throws ConfigurationException, TransformerConfigurationException{
    	if(controller==null){
    		Source styleSource = new StreamSource( BygleSystemUtils.class.getClassLoader().getResourceAsStream("sort-toUTF8.xsl"));
			CompilerInfo compilerInfo = configuration.getDefaultXsltCompilerInfo();
			PreparedStylesheet sheet = PreparedStylesheet.compile(styleSource, configuration, compilerInfo);
			controller = (Controller) sheet.newTransformer();
    	}
    	return controller;
    }
    
    public static Controller getXSLHTMLTController() throws ConfigurationException, TransformerConfigurationException{
    	if(htmlController==null){
    		Source styleSource = new StreamSource( BygleSystemUtils.class.getClassLoader().getResourceAsStream("xml-to-html.xsl"));
			CompilerInfo compilerInfo = htmlconfiguration.getDefaultXsltCompilerInfo();
			PreparedStylesheet sheet = PreparedStylesheet.compile(styleSource, htmlconfiguration, compilerInfo);
			htmlController = (Controller) sheet.newTransformer();
    	}
    	return htmlController;
    }
    
    public static String getWriter(String outputFormat){
		MediaType matchItemInput;
		try {
			String format = outputFormat.toLowerCase();
			AcceptList input = AcceptList.create(format.split(","));
			matchItemInput = AcceptList.match(BygleSystemUtils.offeringRDF, input);
			Lang lang = RDFLanguages.contentTypeToLang(matchItemInput.getContentType());
			return lang.getName();
		} catch (Exception e) {
			return defaultWriter;
		}
	}
    
    public static DatabaseType getDBType(String databaseType){
		switch (databaseType) {
			case "derby":
				return DatabaseType.Derby;
			case "H2":
				return DatabaseType.H2;
			case "HSQLDB":
				return DatabaseType.HSQLDB;
			case "MySQL":
				return DatabaseType.MySQL;
			case "PostgreSQL":
				return DatabaseType.PostgreSQL;
			case "SQLServer":
				return DatabaseType.SQLServer;
			case "Oracle":
				return DatabaseType.Oracle;
			case "DB2":
				return DatabaseType.DB2;
			case "sap":
				return DatabaseType.SAP;
			default:
				return null;
		}
	}
} public class FileInfoReader {
	private static int kDEFAULT_CHUNK_SIZE = 256;

	public static String extractText(InputStream input) throws IOException {
		String result = "";
		String resultSplitted = "";
		String words[] = null;
		LinkedHashSet<String> uniqueWords = null;
		try {
			ContentHandler handler = new BodyContentHandler(10 * 1024 * 1024);
			Metadata metadata = new Metadata();
			Parser parser = new AutoDetectParser();
			parser.parse(input, handler, metadata, new ParseContext());
			result = handler.toString();

			uniqueWords = new LinkedHashSet<String>();
			words = result.split("[\\W]+");
			for (int i = 0; i < words.length; i++) {
				uniqueWords.add(words[i].toLowerCase());
			}
			int i = 0;
			for (String unique : uniqueWords) {
				if (((1 + i) % 100) == 0) {
					resultSplitted += unique + ",\n";
				} else
					resultSplitted += unique + ", ";
				i++;
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null)
				input.close();
		}

		return stripWhiteSpace(resultSplitted);

	}
    
	public static String stripWhiteSpace(String in) {
		StringBuilder out = new StringBuilder();
		char current;

		if (in == null || ("".equals(in)))
			return "";
		for (int i = 0; i < in.length(); i++) {
			current = in.charAt(i);
			if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF)))
				out.append(current);
		}
		return out.toString();
	}
	
	
	public static String extractMD5(InputStream input) throws IOException {
		String result = "";
		try {
			result = DigestUtils.md5Hex(input);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null)
				input.close();
		}
		return result;
	}

	public static TreeMap<String, String> extractMetaData(InputStream input) throws IOException {
		TreeMap<String, String> treeMap = new TreeMap<String, String>();
		try {
			ContentHandler handler = new DefaultHandler();
			Metadata metadata = new Metadata();
			Parser parser = new AutoDetectParser();
			parser.parse(input, handler, metadata, new ParseContext());
			for (int i = 0; i < metadata.names().length; i++) {
				String name = metadata.names()[i];
				treeMap.put(name, stripWhiteSpace(metadata.get(name)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null)
				input.close();
		}
		return treeMap;
	}

	
	public static String extractStringMetaData(InputStream input) throws IOException {
		String result="";
		try {
			ContentHandler handler = new DefaultHandler();
			Metadata metadata = new Metadata();
			Parser parser = new AutoDetectParser();
			parser.parse(input, handler, metadata, new ParseContext());
			for (int i = 0; i < metadata.names().length; i++) {
				String name = metadata.names()[i];
				result+=name.toUpperCase()+" : "+stripWhiteSpace(metadata.get(name))+"\n";
			}
		} catch (Exception e) {
		} finally {
			if (input != null)
				input.close();
		}
		return result;
	}
	
	public static String getMetaData(InputStream input, String metaData) throws IOException {
		String result = "";
		try {
			ContentHandler handler = new DefaultHandler();
			Metadata metadata = new Metadata();
			Parser parser = new AutoDetectParser();
			parser.parse(input, handler, metadata, new ParseContext());
			result = metadata.get(metaData);
		} catch (Exception e) {
		} finally {
			if (input != null)
				input.close();
		}
		return result;
	}

	public static byte[] loadBytesFromURL(URL url) throws Exception {
		byte[] b = null;

		URLConnection con = url.openConnection();

		int size = con.getContentLength();
		InputStream in = null;

		try {
			if ((in = con.getInputStream()) != null)
				b = (size != -1) ? loadBytesFromStreamForSize(in, size) : loadBytesFromStream(in);
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException ioe) {
				}
		}

		return b;
	}

	private static byte[] loadBytesFromStream(InputStream in) throws IOException {
		return loadBytesFromStream(in, kDEFAULT_CHUNK_SIZE);
	}

	private static byte[] loadBytesFromStreamForSize(InputStream in, int size) throws IOException {
		int count, index = 0;
		byte[] b = new byte[size];
		while ((count = in.read(b, index, size)) > 0) {
			size -= count;
			index += count;
		}
		return b;
	}

	private static byte[] loadBytesFromStream(InputStream in, int chunkSize) throws IOException {
		if (chunkSize < 1)
			chunkSize = kDEFAULT_CHUNK_SIZE;

		int count;
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		byte[] b = new byte[chunkSize];
		try {
			while ((count = in.read(b, 0, chunkSize)) > 0)
				bo.write(b, 0, count);
			byte[] thebytes = bo.toByteArray();
			return thebytes;
		} finally {
			bo.close();
			bo = null;
		}
	}
	public static String getFileSizeString(long sizeInBytes){
		String result="";
		double bytes = sizeInBytes;
		double kilobytes = Math.round((bytes / 1024));
		double megabytes = Math.round((kilobytes / 1024));
		double gigabytes = Math.round((megabytes / 1024));
		double terabytes = Math.round((gigabytes / 1024));
		if(terabytes>=1)
			result = StringUtils.substringBeforeLast(Double.toString(terabytes), ".")+" TB";
		else if(gigabytes>=1)
			result = StringUtils.substringBeforeLast(Double.toString(gigabytes), ".")+" GB";
		else if(megabytes>=1)
			result = StringUtils.substringBeforeLast(Double.toString(megabytes), ".")+" MB";
		else if(kilobytes>=1)
			result = StringUtils.substringBeforeLast(Double.toString(kilobytes), ".")+" KB";
		else
			result = StringUtils.substringBeforeLast(Double.toString(bytes),".")+" byte";
		return result;
	}
	
	public static void main(String args[]) throws Exception {
		try {

//			byte[] bytes = FileInfoReader.loadBytesFromURL(new URL("http://www.repubblica.it"));
//			InputStream input = new ByteArrayInputStream(bytes);
//			System.out.println(FileInfoReader.extractMetaData(input).toString());
			
			InputStream input = new FileInputStream(new File("C:\\Users\\sandro.REGESTAEXE\\Desktop\\usa.JPG"));
			//System.out.println(FileInfoReader.extractMetaData(input).toString());
			System.out.println(FileInfoReader.extractStringMetaData(input));
			
			
			// String[] words = null;
			// String test1 = "";
			// LinkedHashSet<String> uniqueWords = null;
			// File f = new File("/home/diego/Scaricati/D13104.pdf");
			// InputStream input = new FileInputStream(f);
			// System.out.println(FileInfoReader.extractMetaData(input).toString());
			// input = new FileInputStream(f);
			// try {
			//
			// String text = FileInfoReader.extractText(input);
			// uniqueWords = new LinkedHashSet<String>();
			// words = text.split("[\\W]+");
			// System.err.println(words.length);
			// for (int i = 0; i < words.length; i++) {
			// if ((i % 100) == (i / 100))
			// uniqueWords.add(words[i] + ",\n");
			// else
			// uniqueWords.add(words[i] + ",");
			//
			// }
			// } catch (IOException e) {
			// System.out.println("intercettata");
			// }
			//
			// for (String test : uniqueWords) {
			//
			// test1 += test;
			//
			// }
			//
			// input = new FileInputStream(f);
			// System.out.println(FileInfoReader.extractMD5(input));
			// input = new FileInputStream(f);
			// System.out.println(FileInfoReader.getMetaData(input,
			// "Content-Type"));

			/*
			 * byte[] bytes = FileInfoReader.loadBytesFromURL(new URL(
			 * "http://www.salute.gov.it/imgs/C_17_pubblicazioni_605_allegato.pdf"
			 * )); InputStream input = new ByteArrayInputStream(bytes);
			 * System.out
			 * .println(FileInfoReader.extractMetaData(input).toString()); input
			 * = new ByteArrayInputStream(bytes);
			 * System.out.println(FileInfoReader.extractText(input)); input =
			 * new ByteArrayInputStream(bytes);
			 * System.out.println(FileInfoReader.extractMD5(input)); input = new
			 * ByteArrayInputStream(bytes);
			 * System.out.println(FileInfoReader.getMetaData
			 * (input,"Content-Type"));
			 */

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
} public class LDPVoc {
	public static final String NAMESPACE = "http://www.w3.org/ns/ldp#";
	public static final String PREFIX = "ldp";
	public static final URI BasicContainer;
	public static final URI Container;
	public static final URI contains;
	public static final URI DirectContainer;
	public static final URI hasMemberRelation;
	public static final URI IndirectContainer;
	public static final URI insertedContentRelation;
	public static final URI isMemberOfRelation;
	public static final URI member;
	public static final URI membershipResource;
	public static final URI MemberSubject;
	public static final URI NonRDFSource;
	public static final URI PreferContainment;
	public static final URI PreferEmptyContainer;
	public static final URI PreferMembership;
	public static final URI RDFSource;
	public static final URI Resource;
	public static final URI constrainedBy;

	static {
		ValueFactory factory = ValueFactoryImpl.getInstance();
		BasicContainer = factory.createURI(LDPVoc.NAMESPACE, "BasicContainer");
		Container = factory.createURI(LDPVoc.NAMESPACE, "Container");
		contains = factory.createURI(LDPVoc.NAMESPACE, "contains");
		DirectContainer = factory.createURI(LDPVoc.NAMESPACE, "DirectContainer");
		hasMemberRelation = factory.createURI(LDPVoc.NAMESPACE, "hasMemberRelation");
		IndirectContainer = factory.createURI(LDPVoc.NAMESPACE, "IndirectContainer");
		insertedContentRelation = factory.createURI(LDPVoc.NAMESPACE, "insertedContentRelation");
		isMemberOfRelation = factory.createURI(LDPVoc.NAMESPACE, "isMemberOfRelation");
		member = factory.createURI(LDPVoc.NAMESPACE, "member");
		membershipResource = factory.createURI(LDPVoc.NAMESPACE, "membershipResource");
		MemberSubject = factory.createURI(LDPVoc.NAMESPACE, "MemberSubject");
		NonRDFSource = factory.createURI(LDPVoc.NAMESPACE, "NonRDFSource");
		PreferContainment = factory.createURI(LDPVoc.NAMESPACE, "PreferContainment");
		PreferEmptyContainer = factory.createURI(LDPVoc.NAMESPACE, "PreferEmptyContainer");
		PreferMembership = factory.createURI(LDPVoc.NAMESPACE, "PreferMembership");
		RDFSource = factory.createURI(LDPVoc.NAMESPACE, "RDFSource");
		Resource = factory.createURI(LDPVoc.NAMESPACE, "Resource");
		constrainedBy = factory.createURI(LDPVoc.NAMESPACE, "constrainedBy");
	}

	private LDPVoc() {
	}

} public class XMLBuilder {
	private org.jdom2.Document JDomDocument = null;
	private org.w3c.dom.Document DomDocument = null;
	private Document dom4JDocument = null;
	private Element root = null;
	private String htmlTagClass = "";
	
	public XMLBuilder()throws XMLException {}
	
	public XMLBuilder(String rootNode) throws XMLException {
		try {
			dom4JDocument = DocumentHelper.createDocument();
			root = dom4JDocument.addElement( rootNode );
		} catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
	}
	
	public XMLBuilder(String rootNode,Map<String, String> uris) throws XMLException {
		try {
			DocumentFactory factory = new DocumentFactory();
			factory.setXPathNamespaceURIs(uris);
			dom4JDocument = factory.createDocument();
			root = dom4JDocument.addElement( rootNode );
			Iterator<?> iterator = uris.entrySet().iterator();
			 while (iterator.hasNext()) {
			        @SuppressWarnings("rawtypes")
					Map.Entry pairs = (Map.Entry)iterator.next();
			        root.add(Namespace.get((String)pairs.getKey(), (String) pairs.getValue()));
			 }
		} catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
	}
	
	public XMLBuilder(String rootNode,Map<String, String> uris,String encoding) throws XMLException {
		try {
			DocumentFactory factory = new DocumentFactory();
			factory.setXPathNamespaceURIs(uris);
			dom4JDocument = factory.createDocument();
			if(encoding!=null)
				dom4JDocument.setXMLEncoding(encoding);
			root = dom4JDocument.addElement( rootNode );
			Iterator<?> iterator = uris.entrySet().iterator();
			 while (iterator.hasNext()) {
				 	@SuppressWarnings("rawtypes")
			        Map.Entry pairs = (Map.Entry)iterator.next();
			        root.add(Namespace.get((String)pairs.getKey(), (String) pairs.getValue()));
			 }
		} catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
	}
	public XMLBuilder(ByteArrayInputStream docXml) throws XMLException {
		try {
			SAXReader reader = new SAXReader();
			dom4JDocument = reader.read(docXml);
			root = dom4JDocument.getRootElement();
		} catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
	}
	
	public XMLBuilder(byte[] docXml) throws XMLException {
		try {
			SAXReader reader = new SAXReader();
			dom4JDocument = reader.read(new ByteArrayInputStream(docXml));
			root = dom4JDocument.getRootElement();
		} catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
	}
	
	public XMLBuilder(File file) throws XMLException {
		try {
			SAXReader reader = new SAXReader();
			dom4JDocument = reader.read(file);
			root = dom4JDocument.getRootElement();
		} catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
	}
	public XMLBuilder(String strDocXml, String strEncoding, String htmlTagClass) throws XMLException {
		strDocXml = strDocXml.replaceAll("<\\?xw-sr\\?>", "IniZioTagHtMlspan class=LeViRGoleTte" + htmlTagClass + "LeViRGoleTteFinETagHtMl");
		strDocXml = strDocXml.replaceAll("<\\?xw-er\\?>", "IniZioTagHtMl/spanFinETagHtMl");
        this.htmlTagClass = htmlTagClass;
		boolean isoPass = false;
		String strIso = "";
		if (strDocXml.indexOf("?>\n") != -1) {
			strIso = strDocXml.substring(0, strDocXml.indexOf("?>\n") + 3);
			strDocXml = strDocXml.substring(strDocXml.indexOf("?>\n") + 3);
			isoPass = true;
		}
		if (!isoPass && strEncoding != null && !(strEncoding.trim()).equals("")) {
			strDocXml = "<?xml version=\"1.0\" encoding=\"" + strEncoding + "\"?>\n" + strDocXml;
		}
		if (isoPass) {
			strDocXml = strIso + strDocXml;
		}
		try {
			strDocXml=parseAttribute(strDocXml);
			dom4JDocument = DocumentHelper.parseText(strDocXml);
			root = dom4JDocument.getRootElement();
		} catch (DocumentException e) {
			throw new XMLException(e.getMessage());
		}
					
	}
	public XMLBuilder(String strDocXml, String strEncoding,Map<String, String> uris) throws XMLException {
		strDocXml = "<?xml version=\"1.0\" encoding=\"" + strEncoding + "\"?>\n" + strDocXml;
		try {
			DocumentFactory factory = new DocumentFactory();
			factory.setXPathNamespaceURIs(uris);
			dom4JDocument = factory.createDocument();
			dom4JDocument = DocumentHelper.parseText(strDocXml);
			root = dom4JDocument.getRootElement();
		}catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
					
	}
	public XMLBuilder(String strDocXml, String strEncoding) throws XMLException {
		try {		
			strDocXml=parseAttribute(strDocXml);
			dom4JDocument = DocumentHelper.parseText(strDocXml);
			root = dom4JDocument.getRootElement();
		}catch (DocumentException e) {
			e.printStackTrace();
			throw new XMLException(e.getMessage());
		}
					
	}
	
/*	public void insertNodeAt(String xPath,String nodeValue,int position) throws XMLException {
		try {
			
			NodeList listNode = XPathAPI.selectNodeList(DomDocument,newXPath);
			if(listNode!=null && listNode.getLength()>0){
				listNode.
			}else{
				insertNode(xPath,nodeValue);
			}
		} catch (TransformerException e) {
			
		}
	}*/
	public void insertNode(String xPath, String nodeValue) throws XMLException{
		String value = StringEscapeUtils.escapeHtml4(nodeValue);
		insertNodeEscaped(xPath,value,false);
	}
	public void insertNode(String xPath, String nodeValue,boolean isCData) throws XMLException{
		String value = StringEscapeUtils.escapeHtml4(nodeValue);
		insertNodeEscaped(xPath,value,isCData);
	}
	@SuppressWarnings("unchecked")
	private void insertNodeEscaped(String xPath, String nodeValue,boolean isCData) throws XMLException {
			xPath=testXPath(xPath);
			if (xPath != null && !xPath.trim().equals("")) {
				if(xPath.indexOf("//")!=-1)
					xPath = xPath.replaceAll("//", "~");
				StringTokenizer stringTokenizer = new StringTokenizer(xPath, "/");
				String currentXPath = "";
				int count = 0;
				int tot = stringTokenizer.countTokens();
				while (stringTokenizer.hasMoreTokens()) {
					count++;
					String nodeName = stringTokenizer.nextToken();
					String realName = nodeName.replace('~','/');
					nodeName = nodeName.replace('~','/');
					Attribute appoAttribute = null;
					Namespace apponNamespace = null;
					ArrayList<Attribute> appoAttributesList = null;
					try {
						if (realName.indexOf("[") != -1) {
							try {
								try {
									Integer.parseInt(realName.substring(realName.indexOf("[") + 1, realName.indexOf("]")));
								} catch (StringIndexOutOfBoundsException e1) {
									String endName=stringTokenizer.nextToken();
									realName+="/"+endName;
									nodeName+="/"+endName;
									tot=tot-1;
									Integer.parseInt(realName.substring(realName.indexOf("[") + 1, realName.indexOf("]")));
								}
							
							} catch (NumberFormatException exc) {
							
								String appo = realName.substring(realName.indexOf("[") + 1, realName.indexOf("]"));							
								 if(appo.indexOf("@")!=-1){
									    if(appo.indexOf("' and @")!=-1){
											appoAttributesList=new ArrayList<Attribute>();		
											String appoName2 = appo;		
											while(appoName2.indexOf("' and @")!=-1 ){		    
												appoName2=appoName2.substring(0,appoName2.toLowerCase().indexOf("' and @"))+"'~@"+appoName2.substring(appoName2.toLowerCase().indexOf("' and @")+"' and @".length(),appoName2.length());		    
											} 
											StringTokenizer stringTokenizer2 = new StringTokenizer(appoName2,"~");    
											 while(stringTokenizer2.hasMoreTokens()){    
												String currentName = stringTokenizer2.nextToken();			
												String appoName = currentName.substring(currentName.indexOf("@") + 1, currentName.indexOf("="));
												String appoValue = currentName.substring(currentName.indexOf("'") + 1, currentName.lastIndexOf("'"));
												if(currentName.indexOf("child::")!=-1){
													String appoName3 = currentName.substring(appo.indexOf("child::")+"child::".length(), currentName.indexOf("=")).trim();
													String appoValue3 = currentName.substring(appo.indexOf("'") + 1, currentName.lastIndexOf("'"));
													String newNode=currentXPath.trim()+"/"+realName.substring(0,realName.indexOf("[")).trim();									
													List<?> list=dom4JDocument.selectNodes(newNode);									
													if(list!=null){
														
														insertNodeEscaped(newNode+"/"+appoName3,appoValue3,isCData);
																							
													}
													else{
														insertNodeEscaped(newNode,"",isCData);
													}
												}
												appoAttribute = new Attribute(appoName.trim(),appoValue);
												appoAttributesList.add(appoAttribute);	
											 }
										}else{
											
											String appoName = appo.substring(appo.indexOf("@") + 1, appo.indexOf("="));
											String appoValue = appo.substring(appo.indexOf("'") + 1, appo.lastIndexOf("'"));
											if(appoName.toLowerCase().startsWith("xmlns")){
												apponNamespace = Namespace.get(appoName, appoValue);
											}else{
												appoAttribute = new Attribute(appoName.trim(),appoValue);
											}
											
										}
								 }else{
									 if(appo.indexOf("child::")!=-1){
										String appoName = appo.substring(appo.indexOf("child::")+"child::".length(), appo.indexOf("=")).trim();
										String appoValue = appo.substring(appo.indexOf("'") + 1, appo.lastIndexOf("'"));
										String newNode=currentXPath.trim()+"/"+realName.substring(0,realName.indexOf("[")).trim();									
										List<?> list=dom4JDocument.selectNodes(newNode);									
										if(list!=null){
											if(dom4JDocument.selectSingleNode(currentXPath+"/"+nodeName)==null){										   
												insertNodeEscaped(newNode+"["+list.size()+1+"]"+"/"+appoName,appoValue,isCData);
											}
											else{
												insertNodeEscaped(newNode+"/"+appoName,appoValue,isCData);
											}									
										}
										else{
											insertNodeEscaped(newNode,"",isCData);
										}
									}else if(appo.indexOf("=")!=-1){
										String appoName = appo.substring(0, appo.indexOf("=")).trim();
										String appoValue = appo.substring(appo.indexOf("'") + 1, appo.lastIndexOf("'"));
										String newNode=currentXPath.trim()+"/"+realName.substring(0,realName.indexOf("[")).trim();									
										List<?> list=dom4JDocument.selectNodes(newNode);									
										if(list!=null){
											if(dom4JDocument.selectSingleNode(currentXPath+"/"+nodeName)==null){										   
												insertNodeEscaped(newNode+"["+list.size()+1+"]"+"/"+appoName,appoValue,isCData);
											}
											else{
												insertNodeEscaped(newNode+"/"+appoName,appoValue,isCData);
											}									
										}else{
											insertNodeEscaped(newNode,"",isCData);
										}
									}	
								 }
							}
							realName = realName.substring(0, realName.indexOf("["));
					
						}
						Node testNode = null;
						try {
							testNode = dom4JDocument.selectSingleNode(currentXPath + "/" + nodeName);
						} catch (XPathException e2) {
						}
						if (testNode == null && count>1) {
							if (realName.indexOf("@") == -1) {							
								try {
									if(!currentXPath.trim().equals("")){
										List<Node> nodeList = dom4JDocument.selectNodes(currentXPath);
										//System.err.println(currentXPath);
										for (int j = 0; j < nodeList.size(); j++) {
											Node node = null;
											if (!realName.trim().equalsIgnoreCase("text()")) {
												node = DocumentHelper.createElement(realName);
												if (count == tot) {
													if(isCData){
														((Element)node).add(DocumentHelper.createCDATA(nodeValue));
													}else{
														node.setText(nodeValue);
													}
													
												}
											} else {
												if(isCData){
													node = DocumentHelper.createCDATA(nodeValue);
												}else{
													node = DocumentHelper.createText(nodeValue);
												}
												
											}							
											if (appoAttributesList != null) {
												for(int xx=0;xx<appoAttributesList.size();xx++)
												    ((Element)node).addAttribute( ((Attribute)appoAttributesList.get(xx)).getAttributeName() , ((Attribute)appoAttributesList.get(xx)).getAttributeValue());
												
											}else if (appoAttribute != null) {
												((Element)node).addAttribute(appoAttribute.getAttributeName(),appoAttribute.getAttributeValue());
											}else if (apponNamespace != null) {
												((Element)node).add(apponNamespace);
											}
											((Element)dom4JDocument.selectNodes(currentXPath).get(j)).add(node);
										}
										//((Element)dom4JDocument.selectSingleNode(currentXPath)).add(node);
									
									}
								} catch (NullPointerException e1) {								
									try{			
										Node node = null;
										if (!realName.trim().equalsIgnoreCase("text()")) {
											node = DocumentHelper.createElement(realName);
											if (count == tot) {
												if(isCData){
													((Element)node).add(DocumentHelper.createCDATA(nodeValue));
												}else{
													node.setText(nodeValue);
												}
												
											}
										} else {
											if(isCData){
												node = DocumentHelper.createCDATA(nodeValue);
											}else{
												node = DocumentHelper.createText(nodeValue);
											}
											
										}							
										if (appoAttributesList != null) {
											for(int xx=0;xx<appoAttributesList.size();xx++)
											    ((Element)node).addAttribute( ((Attribute)appoAttributesList.get(xx)).getAttributeName() , ((Attribute)appoAttributesList.get(xx)).getAttributeValue());
											
										}else if (appoAttribute != null) {
											((Element)node).addAttribute(appoAttribute.getAttributeName(),appoAttribute.getAttributeValue());
										}else if (apponNamespace != null) {
											((Element)node).add(apponNamespace);
										}
										int wrongNum=Integer.parseInt(currentXPath.substring(currentXPath.lastIndexOf("[")+1,currentXPath.lastIndexOf("]")));
										wrongNum=wrongNum-1;
										while(wrongNum!=0){
											currentXPath=currentXPath.substring(0,currentXPath.lastIndexOf("[")+1)+Integer.toString(wrongNum)+currentXPath.substring(currentXPath.lastIndexOf("]"),currentXPath.length());
											try{
												((Element)dom4JDocument.selectSingleNode(currentXPath)).add(node);
												break;
											}catch(NullPointerException exc){}
											wrongNum=wrongNum-1;
										}
									}
									catch(StringIndexOutOfBoundsException stex){								
									}
									catch(NumberFormatException stex){								
									}
								}										
							} else {
								if(realName.substring(realName.indexOf("@") + 1).toLowerCase().startsWith("xmlns")){
									String namespaceName = "";
									try{
										namespaceName = realName.substring(realName.indexOf("@xmlns:") + "@xmlns:".length());
									}catch (StringIndexOutOfBoundsException e) {
									}
									Namespace namespace = new Namespace(namespaceName, nodeValue);
									try{
										   ((Element) dom4JDocument.selectSingleNode(currentXPath)).add(namespace);
									}catch(NullPointerException exc){
										try{										   
											int wrongNum=Integer.parseInt(currentXPath.substring(currentXPath.lastIndexOf("[")+1,currentXPath.lastIndexOf("]")));
											wrongNum=wrongNum-1;
											while(wrongNum!=0){
												currentXPath=currentXPath.substring(0,currentXPath.lastIndexOf("[")+1)+Integer.toString(wrongNum)+currentXPath.substring(currentXPath.lastIndexOf("]"),currentXPath.length());
												try{
												((Element) dom4JDocument.selectSingleNode(currentXPath)).add(namespace);
													 break;
												}catch(NullPointerException exct){}
												wrongNum=wrongNum-1;
											}
										}
										catch(StringIndexOutOfBoundsException stex){										
										}
										catch(NumberFormatException stex){										
										}	
									}
								}else{
										Attribute attribute = new Attribute();
										attribute.setAttributeName(realName.substring(realName.indexOf("@") + 1));
										if (count == tot) {
											attribute.setAttributeValue(nodeValue);
										}
										try{
										   ((Element) dom4JDocument.selectSingleNode(currentXPath)).addAttribute(attribute.getAttributeName(),attribute.getAttributeValue());
										}
										catch(NullPointerException exc){
												try{										   
													int wrongNum=Integer.parseInt(currentXPath.substring(currentXPath.lastIndexOf("[")+1,currentXPath.lastIndexOf("]")));
													wrongNum=wrongNum-1;
													while(wrongNum!=0){
														currentXPath=currentXPath.substring(0,currentXPath.lastIndexOf("[")+1)+Integer.toString(wrongNum)+currentXPath.substring(currentXPath.lastIndexOf("]"),currentXPath.length());
														try{
														((Element) dom4JDocument.selectSingleNode(currentXPath)).addAttribute(attribute.getAttributeName(),attribute.getAttributeValue());
															 break;
														}catch(NullPointerException exct){}
														wrongNum=wrongNum-1;
													}
												}
												catch(StringIndexOutOfBoundsException stex){										
												}
												catch(NumberFormatException stex){										
												}
										}
								}	
							}
						}
						currentXPath += "/" + nodeName;
						dom4JDocument = DocumentHelper.parseText(dom4JDocument.asXML());
					} catch (Exception e) {
						throw new XMLException(e.getMessage());
					} 
				}
				
			} else {
				throw new XMLException("Invalid xPath value [" + xPath + "]");
			}
			
		}
	public void insertValueAt(String xPath, String val,boolean isCData) throws XMLException {
		insertValueAtInternal(xPath,val,isCData);
	}
	public void insertValueAt(String xPath, String val) throws XMLException {
		insertValueAtInternal(xPath,val,false);
	}
	private void insertValueAtInternal(String xPath, String val,boolean isCData) throws XMLException {
		String value = StringEscapeUtils.escapeHtml4(val);
		try {			
			if(xPath.trim().endsWith("text()")){
				List<?> textList= dom4JDocument.selectNodes(xPath);
				for(int i=0;i<textList.size();i++){
					((Node)textList.get(i)).setText("");
				}
				dom4JDocument.selectSingleNode(xPath).setText(value);
			}else{
				dom4JDocument.selectSingleNode(xPath).setText(value);
			}
		} catch (NullPointerException e) {
			insertNodeEscaped(xPath, value,isCData);
		} catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
	}
	public Document deleteNode(Document aDoc, String xPath) throws XMLException {
		//String app = xPath;
		Document doc = aDoc;
		if (xPath != null && !xPath.trim().equals("")) {
			try {
				List<?> list = aDoc.selectNodes( xPath);
				if (list != null && list.size() != 0) {
					for (int i = 0; i < list.size(); i++) {
						Node node = (Node)list.get(i);
						node.getParent().remove(node);
					}
				}
				doc.normalize();
			} catch (Exception e) {
				e.printStackTrace();
				throw new XMLException(e.getMessage());
			}
		}
		return doc;
	}
	public void deleteNode(String xPath) throws XMLException {
		if (xPath != null && !xPath.trim().equals("")) {
			try {
				List<?> list = dom4JDocument.selectNodes(xPath);
				if (list != null && list.size() != 0) {
					for (int i = 0; i < list.size(); i++) {
						Node node =  (Node)list.get(i);
						node.getParent().remove(node);
					}
				}
				dom4JDocument.normalize();
			} catch (Exception e) {
				e.printStackTrace();
				throw new XMLException(e.getMessage());
			}
		}
	}
	public String getXML(String encoding,boolean indent) throws XMLException {
		if(dom4JDocument!=null){
			OutputFormat outputFormat = new OutputFormat();
			outputFormat.setEncoding(encoding);
			StringWriter stringWriter = new StringWriter();
			XMLWriter xmlWriter = null;
			if(indent){		
			    outputFormat.setNewlines(true);
			    outputFormat.setIndent(true);
			    outputFormat.setIndentSize(2);							    
			    xmlWriter = new XMLWriter(stringWriter, outputFormat);
			    xmlWriter.setMaximumAllowedCharacter(255);
			    try {
					xmlWriter.write(dom4JDocument);
					xmlWriter.flush();
					xmlWriter.close();
					stringWriter.flush();
					stringWriter.close();
				} catch (IOException e) {
					throw new XMLException(e.getMessage());
				}
			    return stringWriter.toString();
			}else{
			    xmlWriter = new XMLWriter(stringWriter, outputFormat);
			    xmlWriter.setMaximumAllowedCharacter(255);
			    try {
					xmlWriter.write(dom4JDocument);
					xmlWriter.flush();
					xmlWriter.close();
					stringWriter.flush();
					stringWriter.close();
				} catch (IOException e) {
					throw new XMLException(e.getMessage());
				}
				return stringWriter.toString();
			}
		}else{
			throw new XMLException("Invalid operation! Document = null");
		}
	}	
	public String getXML(String encoding) throws XMLException {
			return getXML(encoding,false);
	}	
	public org.jdom2.Document getJDomDocument() throws XMLException {
		org.dom4j.io.DOMWriter d4Writer = new org.dom4j.io.DOMWriter();
		try {
			DomDocument = d4Writer.write(dom4JDocument);
		} catch (DocumentException e) {
			throw new XMLException(e.getMessage());
		}
		JDomDocument = new DOMBuilder().build(DomDocument);
		if (JDomDocument != null)
			return JDomDocument;
		else
			throw new XMLException("Invalid operation! Document = null");
	}
	public org.w3c.dom.Document getDomDocument() throws XMLException {
		try {
			org.dom4j.io.DOMWriter d4Writer = new org.dom4j.io.DOMWriter();
			org.w3c.dom.Document domDocument = d4Writer.write(dom4JDocument);
			return domDocument;
		} catch (Exception e) {
			throw new XMLException(e.getMessage());
		}
	}
	private String testXPath(String xpath){
		String result="";
		try {
			String xpathToTest = xpath.replaceAll("\"", "'");
			if (xpathToTest.indexOf("[") != -1) {
			   int start=xpathToTest.indexOf("[") + 1;
			   int end=xpathToTest.indexOf("]");
			   String toTest=xpathToTest.substring(xpathToTest.indexOf("[") + 1, xpathToTest.indexOf("]"));
			   try{
					Integer.parseInt(toTest);
				    result=xpathToTest;
			   }catch (NumberFormatException e) {
						toTest=toTest.replace('/','~');
						result=xpathToTest.substring(0,start)+toTest+xpathToTest.substring(end,xpathToTest.length());
			   }
			}
			else{
				result=xpathToTest;
			}
		} catch (StringIndexOutOfBoundsException e) {
			throw e;			
		}
		return result;
	}
	public boolean testNode(String xPath){
			Node node = dom4JDocument.selectSingleNode(xPath);
			boolean result = false;
			if (node != null) {
				if (node.getText() != null && node.getText() != "") {
					result = true;
				} else {
					result = false;
				}
			} else {
				result = false;
			}
			return result;
		}

		public int countNodes(String xPath){
			int nodes = 0;
			List<?> nodeList = dom4JDocument.selectNodes(xPath);
			if (nodeList != null) {
				nodes = nodeList.size();
			}
			return nodes;
		}
		private String getValue(String xPath){
			String value = "";
			if (xPath.endsWith("/text()")) {
				List<?> nodeList = dom4JDocument.selectNodes(xPath);
				for (int i = 0; i < nodeList.size(); i++) {
					try {
						if(((Node)nodeList.get(i)).getText().indexOf("\\n")!=-1)
							value += ((Node)nodeList.get(i)).getText() + "\n";
						else		
							value += ((Node)nodeList.get(i)).getText();	
					} catch (NullPointerException exc) {
					}
				}
			} else {
				Node ilNodo = dom4JDocument.selectSingleNode(xPath);
				if (ilNodo != null) {
					value = ilNodo.getText();
				} else {
					value = "";
				}
			}
			if (value.equals(null)) {
				value = "";
			}
			OutputFormat outputFormat = new OutputFormat();
			if(dom4JDocument.getXMLEncoding()!=null)
				outputFormat.setEncoding(dom4JDocument.getXMLEncoding());
			StringWriter stringWriter = new StringWriter();
			XMLWriter xmlWriter = null;
			outputFormat.setNewlines(true);
			xmlWriter = new XMLWriter(stringWriter, outputFormat);
			xmlWriter.setMaximumAllowedCharacter(255);
			try {
				xmlWriter.write(value);
				xmlWriter.flush();
				xmlWriter.close();
				stringWriter.close();
			} catch (IOException e) {
				return "";
			}
			return stringWriter.toString();						
		}
	    
		public String getNodeValue(String xPath){
			String value = getValue(xPath);
			value = ((value.replaceAll("\"", "&#34;")).replaceAll("&#60;", "<")).replaceAll("&#62;", ">");
			return value.trim();
		}

		public String getNodeValue(String xPath, boolean doConvert){
			String value = getValue(xPath);
			if (doConvert)
				value = ((value.replaceAll("\"", "&#34;")).replaceAll("&#60;", "<")).replaceAll("&#62;", ">");
			return value.trim();
		}

		public String getNodeValue(String xPath, String returnChar){
			String value = getValue(xPath);
			value = ((value.replaceAll("\"", "&#34;")).replaceAll("&#60;", "<")).replaceAll("&#62;", ">");
			return (value.replaceAll("\n", returnChar)).trim();
		}

		public String getHTMLNodeValue(String xPath, String returnChar){
			String value = getValue(xPath);
			value = value.replaceAll("\"", "&quot;");
			value = value.replaceAll("<em>", "IniZioTagHtMlemFinETagHtMl");
			value = value.replaceAll("</em>", "IniZioTagHtMl/emFinETagHtMl");
			value = value.replaceAll("<EM>", "IniZioTagHtMlemFinETagHtMl");
			value = value.replaceAll("</EM>", "IniZioTagHtMl/emFinETagHtMl");
			value = value.replaceAll("<P>", "IniZioTagHtMlpFinETagHtMl");
			value = value.replaceAll("</P>", "IniZioTagHtMl/pFinETagHtMl");
			value = value.replaceAll("<p>", "IniZioTagHtMlpFinETagHtMl");
			value = value.replaceAll("</p>", "IniZioTagHtMl/pFinETagHtMl");
			value = value.replaceAll("<STRONG>", "IniZioTagHtMlstrongFinETagHtMl");
			value = value.replaceAll("</STRONG>", "IniZioTagHtMl/strongFinETagHtMl");
			value = value.replaceAll("<strong>", "IniZioTagHtMlstrongFinETagHtMl");
			value = value.replaceAll("</strong>", "IniZioTagHtMl/strongFinETagHtMl");
			value = value.replaceAll("<br>", "IniZioTagHtMlbrFinETagHtMl");
			value = value.replaceAll("<BR>", "IniZioTagHtMlbrFinETagHtMl");
			value = (value.replaceAll("&#60;", "<")).replaceAll("&#62;", ">");
			value = (value.replaceAll("IniZioTagHtMl", "<")).replaceAll("FinETagHtMl", ">");
			return (value.replaceAll("\n", returnChar)).trim();
		}

		public String getHTMLNodeValue(String xPath){
			String value = getValue(xPath);
			value = value.replaceAll("\"", "&quot;");
			value = value.replaceAll("<em>", "IniZioTagHtMlemFinETagHtMl");
			value = value.replaceAll("</em>", "IniZioTagHtMl/emFinETagHtMl");
			value = value.replaceAll("<EM>", "IniZioTagHtMlemFinETagHtMl");
			value = value.replaceAll("</EM>", "IniZioTagHtMl/emFinETagHtMl");
			value = value.replaceAll("<P>", "IniZioTagHtMlpFinETagHtMl");
			value = value.replaceAll("</P>", "IniZioTagHtMl/pFinETagHtMl");
			value = value.replaceAll("<p>", "IniZioTagHtMlpFinETagHtMl");
			value = value.replaceAll("</p>", "IniZioTagHtMl/pFinETagHtMl");
			value = value.replaceAll("<STRONG>", "IniZioTagHtMlstrongFinETagHtMl");
			value = value.replaceAll("</STRONG>", "IniZioTagHtMl/strongFinETagHtMl");
			value = value.replaceAll("<strong>", "IniZioTagHtMlstrongFinETagHtMl");
			value = value.replaceAll("</strong>", "IniZioTagHtMl/strongFinETagHtMl");
			value = value.replaceAll("<br>", "IniZioTagHtMlbrFinETagHtMl");
			value = value.replaceAll("<BR>", "IniZioTagHtMlbrFinETagHtMl");
			value = (value.replaceAll("&#60;", "<")).replaceAll("&#62;", ">");
			value = (value.replaceAll("IniZioTagHtMl", "<")).replaceAll("FinETagHtMl", ">");
			return value.trim();
		}

		public String getNodeValue(String xPath, String returnChar, String toHighlight){
			String value = getValue(xPath);
			value = ((value.replaceAll("\"", "&#34;")).replaceAll("&#60;", "<")).replaceAll("&#62;", ">");
			String[] strToHighlight = toHighlight.split(",");
			for (int i = 0; i < strToHighlight.length; i++) {
				value = value.replaceAll(strToHighlight[i], "<span class=\""+htmlTagClass+"\">" + strToHighlight[i] + "</span>");
			}
			return (value.replaceAll("\n", returnChar)).trim();
		}
		private class Attribute {
		   private String attributeName="";
		   private String attributeValue="";
		public Attribute() {

		}
		public Attribute(String attributeName,String attributeValue) {
			this.attributeName = attributeName;
			this.attributeValue = attributeValue;
		}
		public String getAttributeName() {
			return attributeName;
		}

		/**
		 * @return
		 */
		public String getAttributeValue() {
			return attributeValue;
		}

		/**
		 * @param string
		 */
		public void setAttributeName(String string) {
			attributeName = string;
		}

		/**
		 * @param string
		 */
		public void setAttributeValue(String string) {
			attributeValue = string;
		}

		}
	/**
	 * @return
	 */
	public String getHtmlTagClass() {
		return htmlTagClass;
	}

	/**
	 * @param string
	 */
	public void setHtmlTagClass(String string) {
		htmlTagClass = string;
	}
	
	public void addNodeNamespaceURIs(String xPath,Map<?, ?> uris) throws XMLException {
		List<?> list = dom4JDocument.selectNodes(xPath);
		if(list!=null && list.size()>0){
			Set<?> set = uris.keySet();
			for (int i = 0; i < list.size(); i++) {
			    Iterator<?> iterator = set.iterator();		
				while(iterator.hasNext()){
					String keyName = (String) iterator.next();
					String keyValue = (String) uris.get(keyName);
					((Element)list.get(i)).add(Namespace.get(keyName, keyValue));
				}
	        }
		}
	}
	public void removeEmptyNodes() throws XMLException{		
		try {
			removeEmptyTextNode();
			List<?> list = dom4JDocument.selectNodes("//*[not(node())]");
			if (list != null && list.size() != 0) {
				for (int i = 0; i < list.size(); i++) {
					Node node =  (Node)list.get(i);
					node.getParent().remove(node);
				}
			}
			dom4JDocument.normalize();
		} catch (Exception e) {
			e.printStackTrace();
			throw new XMLException(e.getMessage());
		}
	}
	public void removeEmptyTextNode() throws XMLException{
		try {
			
			List<?> list = dom4JDocument.selectNodes("//text()");
			if (list != null && list.size() != 0) {
				for (int i = 0; i < list.size(); i++) {
					Node node =  (Node)list.get(i);
	                String value = node.getText().trim();
	                if(value.equals("")){
	                	node.getParent().remove(node);
	                }
				}
			}
			dom4JDocument.normalize();
		} catch (Exception e) {
			e.printStackTrace();
			throw new XMLException(e.getMessage());
		}
	}
	public void addNameSpace(String prefix,String uri){
		dom4JDocument.getRootElement().add(new Namespace(prefix, uri));
	}
	public void testEscapeXML() throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        OutputFormat format = new OutputFormat(null, false, "ISO-8859-2");
        format.setSuppressDeclaration(true);

        XMLWriter writer = new XMLWriter(os, format);

        Document document = DocumentFactory.getInstance().createDocument();
        Element root = document.addElement("root");
        root.setText("bla &#c bla");

        writer.write(document);

        String result = os.toString();

        Document doc2 = DocumentHelper.parseText(result);
        doc2.normalize(); 
    }

		private String parseAttribute(String xml){
			String[] strings = xml.split("[\\<]");
			String result="";
			for (int i = 0; i < strings.length; i++) {
				if(!strings[i].trim().equals("")){
						String node="<"+strings[i];
						String toTest=node.substring(node.indexOf("<"), node.indexOf(">")+1);
						if(toTest.indexOf("\"")!=-1){//se ha attributi
							char[] chars = toTest.toCharArray();
							ArrayList<CharUtil> vector = new ArrayList<CharUtil>();							
							for (int j = 0; j < chars.length; j++) {
								char c = chars[j];
								if(c=='<' || c=='>' || c=='=' || c=='"'){
									vector.add(new CharUtil(new Character(c).toString(),j));
								}
							}
							int lastPosition = -1;
							boolean start = false; 
							for (int j = 0; j < vector.size(); j++) {
								CharUtil charUtil = (CharUtil)vector.get(j);
								if(charUtil.c.equals("\"")){
								   if(start==false){
									   start=true;
								   }else{
									   lastPosition=j;
									   charUtil.c="&quot;"; 
									   vector.set(j, charUtil);
								   }
								}else if(charUtil.c.equals("=") || charUtil.c.equals(">")){	
									if(lastPosition!=-1){
										((CharUtil)vector.get(lastPosition)).c="\"";
										start = false;
									}
								}								
							}
							String parsed="";
							for (int k = 0; k < chars.length; k++) {
								boolean addChar=true;
								String addString="";
								for (int j = 0; j < vector.size(); j++) {
								     CharUtil charUtil = (CharUtil)vector.get(j);
								     if(k==charUtil.position){
								    	 addString=charUtil.c;
										 addChar=false;
										 break;
									 }else{
										 addChar=true;
									 }						
								}
								if(addChar)
									parsed+=chars[k];
								else
									parsed+=addString;
							}
							result+=parsed;
						}else{
							result+=toTest;
						}
						try {
							result+=node.substring(node.indexOf(">")+1,node.length());
						} catch (StringIndexOutOfBoundsException e) {							
						}
				}
			}		
			return result;
		}
		private class CharUtil {
			protected String c;
			protected int position=-1;
			public CharUtil(String c,int position) {
               this.c=c;
               this.position=position;
			}
		}
} public class XMLReader {
    private Element root = null;
    private String defaultEncoding;
	
	public XMLReader(FileInputStream fileInputStream) throws DocumentException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(fileInputStream);
		defaultEncoding = document.getXMLEncoding();
		root = document.getRootElement();		
	}
	public XMLReader(InputStreamReader inputStreamReader) throws DocumentException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(inputStreamReader);
		defaultEncoding = document.getXMLEncoding();
		root = document.getRootElement();		
	}
	public XMLReader(File file) throws DocumentException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(file);
		defaultEncoding = document.getXMLEncoding();
		root = document.getRootElement();
	}
	public XMLReader(String strDocXml) throws DocumentException {
		Document document = DocumentHelper.parseText(strDocXml);
		defaultEncoding = document.getXMLEncoding();
		root = document.getRootElement();
	}
	public XMLReader(byte[] bytes) throws DocumentException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(new ByteArrayInputStream(bytes));
		defaultEncoding = document.getXMLEncoding();
		root = document.getRootElement();
	}
	public void analyzeNodes(HashMap<String, ArrayList<String>> xpaths){
		analyzeNodes(root,xpaths);
	}
	
	@SuppressWarnings("unchecked")
	public List<Namespace> getNamespaces(){
		return (List<Namespace>)root.declaredNamespaces();
	}
	
	@SuppressWarnings("unchecked")
	public void analyzeNodes(Element node,HashMap<String, ArrayList<String>> xpaths){
		if(node!=null){
			if(node.getText()!=null && !node.getText().trim().equals("")){
				if(xpaths.get(node.getPath())==null){
					ArrayList<String> arrayList = new ArrayList<String>();
					arrayList.add(node.getText().trim());
					xpaths.put(node.getPath(),arrayList);
				}else{
					ArrayList<String> arrayList = xpaths.get(node.getPath());
					arrayList.add(node.getText().trim());
					xpaths.put(node.getPath(),arrayList);
				}
			}
			if(node.attributes()!=null){
				List<?> list =node.attributes();
				for (Iterator<Attribute> iterator = (Iterator<Attribute>)list.iterator(); iterator.hasNext();) {
					Attribute attribute = iterator.next();
					if(attribute.getText()!=null && !attribute.getText().trim().equals("")){
						if(xpaths.get(attribute.getPath())==null){
							ArrayList<String> arrayList = new ArrayList<String>();
							arrayList.add(attribute.getText().trim());
							xpaths.put(attribute.getPath(),arrayList);
						}else{
							ArrayList<String> arrayList = xpaths.get(attribute.getPath());
							arrayList.add(attribute.getText().trim());
							xpaths.put(attribute.getPath(),arrayList);
						}	
					}
				}
			}
			if(node.elements()!=null){
				List<?> list =node.elements();
				for (Iterator<Element> iterator = (Iterator<Element>)list.iterator(); iterator.hasNext();) {
					Element element = iterator.next(); 
					analyzeNodes(element,xpaths);	
				}
			}
		}
	}
	private String getValue(String xPath,String separator){
		String value = "";
		if (xPath.endsWith("/text()")) {
			List<?> nodeList = root.selectNodes(xPath);
			for (int i = 0; i < nodeList.size(); i++) {
				try {
					if(((Node)nodeList.get(i)).getText().indexOf("\\n")!=-1)
						value += ((Node)nodeList.get(i)).getText() + "\n";
					else		
						value += ((Node)nodeList.get(i)).getText();	
				} catch (NullPointerException exc) {
				}
				if(separator!=null && i<nodeList.size()-1)
					value+=separator;
			}
		} else {
			Node node = root.selectSingleNode(xPath);
			if (node != null) {
				value = node.getText();
			} else {
				value = "";
			}
		}
		if (value.equals(null)) {
			value = "";
		}
		//value = StringEscapeUtils.unescapeXml(value);
		OutputFormat outputFormat = new OutputFormat();
		outputFormat.setEncoding(defaultEncoding);
		StringWriter stringWriter = new StringWriter();
		XMLWriter xmlWriter = null;
		outputFormat.setNewlines(true);
		xmlWriter = new XMLWriter(stringWriter, outputFormat);
		xmlWriter.setMaximumAllowedCharacter(255);
		try {
			xmlWriter.write(value);
			xmlWriter.flush();
			xmlWriter.close();
			stringWriter.close();
		} catch (IOException e) {
			return "";
		}
		return StringEscapeUtils.unescapeXml(stringWriter.toString());
	}
	public String getNodeAsXML(String xPath){
		try {
			Node node = root.selectSingleNode(xPath);
			OutputFormat outputFormat = new OutputFormat();
			outputFormat.setEncoding(defaultEncoding);
			StringWriter stringWriter = new StringWriter();
			XMLWriter xmlWriter = null;
			outputFormat.setNewlines(true);
			xmlWriter = new XMLWriter(stringWriter, outputFormat);
			xmlWriter.setMaximumAllowedCharacter(255);
			try {
				xmlWriter.write(node.asXML());
				xmlWriter.flush();
				xmlWriter.close();
				stringWriter.close();
			} catch (IOException e) {
				return null;
			}
			return stringWriter.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;			
		}
	}
	public String getNodeListAsXML(String xPath){
		try {
			List<?> nodeList = root.selectNodes(xPath);
			OutputFormat outputFormat = new OutputFormat();
			outputFormat.setEncoding(defaultEncoding);
			StringWriter stringWriter = new StringWriter();
			XMLWriter xmlWriter = null;
			outputFormat.setNewlines(true);
			xmlWriter = new XMLWriter(stringWriter, outputFormat);
			xmlWriter.setMaximumAllowedCharacter(255);			
			try {
				for (int i = 0; i < nodeList.size(); i++) {
					xmlWriter.write(((Node)nodeList.get(i)).asXML());
					if(i< nodeList.size()-1)
						xmlWriter.write("\r\n");
				}
				xmlWriter.flush();
				xmlWriter.close();
				stringWriter.close();
			} catch (IOException e) {
				return null;
			}
			return stringWriter.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;			
		}
	}
	public int getNodeCount(String xPath){		
		try {			
			return root.selectNodes(xPath).size();
		} catch (Exception e) {
			return 0;
		}
	}
	private ArrayList<String> getValues(String xPath){
		ArrayList<String> result = new ArrayList<String>();
		List<?> nodeList = root.selectNodes(xPath);
		for (int i = 0; i < nodeList.size(); i++) {
			if(((Node)nodeList.get(i)).getNodeType()== Node.ATTRIBUTE_NODE){
				result.add(((Attribute)nodeList.get(i)).getStringValue());
			}else{
				try {
					if(((Node)nodeList.get(i)).getText().indexOf("\\n")!=-1)
						result.add(((Node)nodeList.get(i)).getText());
					else		
						result.add(((Node)nodeList.get(i)).getText());	
				} catch (NullPointerException exc) {
				}
			}
		}
		return result;
	}
	public List<?> getNodeList(String xPath){
		return root.selectNodes(xPath);
	}
	public String getNodeValue(String xPath,String separator){
		return getValue(xPath,separator);
	} 
	public String getNodeValue(String xPath){
		return getValue(xPath,null);
	}
	public String getTrimmedNodeValue(String xPath,String separator){
		return getValue(xPath,separator).trim();
	} 
	public String getTrimmedNodeValue(String xPath){
		return getValue(xPath,null).trim();
	}
	public String getValueOf(String xPath){
		return root.valueOf(xPath);
	}
	public ArrayList<String> getNodesValues(String xPath){
		return getValues(xPath);
	}
	public String getDefaultEncoding() {
		return defaultEncoding;
	}
	public void setDefaultEncoding(String defaultEncoding) {
		this.defaultEncoding = defaultEncoding;
	}
	public String getRootNode(){
		return root.getName();
	}
} public class XMLException extends Exception {

	private static final long serialVersionUID = 943833695318819354L;

	/**
	 * 
	 */
	public XMLException() {
		super();
	}

	/**
	 * @param arg0
	 */
	public XMLException(String arg0) {
		super(arg0);
	}

} public class TrasformXslt {

	private static Configuration configuration = Configuration.newConfiguration();

	public TrasformXslt() {

	}
    
	
	public static String xslt(String xmlInput, Controller controller) throws Exception {
		String strResult = "";
		try {
			Source sourceInput = new StreamSource(new StringReader(xmlInput));
			StringWriter outWriter = new StringWriter();
			javax.xml.transform.Result result = new StreamResult(outWriter);
			try {
				controller.transform(sourceInput, result);
				strResult = outWriter.getBuffer().toString();
			} catch (XPathException err) {
				if (!err.hasBeenReported()) {
					err.printStackTrace();
				}
				throw new XPathException("Run-time errors were reported");
			}
		} catch (Exception e) {
			throw e;
		}
		return strResult;
	}
	
	
	public static String xslt(InputStream xmlInput, Controller controller) {
		String strResult = null;
		try {
			Source sourceInput = new StreamSource(xmlInput);
			StringWriter outWriter = new StringWriter();
			javax.xml.transform.Result result = new StreamResult(outWriter);
			try {
				controller.transform(sourceInput, result);
				strResult = outWriter.getBuffer().toString();
			} catch (XPathException err) {
				if (!err.hasBeenReported()) {
					err.printStackTrace();
				}
				throw new XPathException("Run-time errors were reported");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;
	}
		
	public static String xslt(String xmlInput, InputStream xsltTrasform) throws Exception {
		String strResult = "";
		try {
			Source sourceInput = new StreamSource(new StringReader(xmlInput));
			Source styleSource = new StreamSource(xsltTrasform);
			CompilerInfo compilerInfo = configuration.getDefaultXsltCompilerInfo();
			PreparedStylesheet sheet = PreparedStylesheet.compile(styleSource, configuration, compilerInfo);
			Controller controller = (Controller) sheet.newTransformer();
			StringWriter outWriter = new StringWriter();
			javax.xml.transform.Result result = new StreamResult(outWriter);
			try {
				controller.transform(sourceInput, result);
				strResult = outWriter.getBuffer().toString();
			} catch (XPathException err) {
				if (!err.hasBeenReported()) {
					err.printStackTrace();
				}
				throw new XPathException("Run-time errors were reported");
			}
		} catch (Exception e) {
			throw e;
		}
		return strResult;
	}

	public String xslt(InputStream xmlInput, String xsltTrasform) {
		String strResult = null;
		try {
			Source sourceInput = new StreamSource(xmlInput);
			Source styleSource = new StreamSource(new StringReader(xsltTrasform));
			CompilerInfo compilerInfo = configuration.getDefaultXsltCompilerInfo();
			PreparedStylesheet sheet = PreparedStylesheet.compile(styleSource, configuration, compilerInfo);
			Controller controller = (Controller) sheet.newTransformer();
			StringWriter outWriter = new StringWriter();
			javax.xml.transform.Result result = new StreamResult(outWriter);
			try {
				controller.transform(sourceInput, result);
				strResult = outWriter.getBuffer().toString();
			} catch (XPathException err) {
				if (!err.hasBeenReported()) {
					err.printStackTrace();
				}
				throw new XPathException("Run-time errors were reported");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;
	}
    
	public static String xslt(String xmlInput, String xsltTrasform) throws Exception {
		return xslt(xmlInput, xsltTrasform, null);
	}

	public static String xslt(InputStream xmlInput, InputStream xsltTrasform, Map<String, String> mapParams) throws Exception {
		String strResult = "";
		try {
			Source sourceInput = new StreamSource(xmlInput);
			Source styleSource = new StreamSource(xsltTrasform);
			CompilerInfo compilerInfo = configuration.getDefaultXsltCompilerInfo();
			PreparedStylesheet sheet = PreparedStylesheet.compile(styleSource, configuration, compilerInfo);
			Controller controller = (Controller) sheet.newTransformer();
			if (mapParams != null) {
				for (Entry<String, String> entry : mapParams.entrySet()) {
					controller.setParameter(entry.getKey(), entry.getValue());
				}
			}
			StringWriter outWriter = new StringWriter();
			javax.xml.transform.Result result = new StreamResult(outWriter);
			try {
				controller.transform(sourceInput, result);
				strResult = outWriter.getBuffer().toString();
			} catch (XPathException err) {
				if (!err.hasBeenReported()) {
					err.printStackTrace();
				}
				throw new XPathException("Run-time errors were reported");
			}
		} catch (Exception e) {
			throw e;
		}
		return strResult;
	}

	public static String xslt(String xmlInput, String xsltTrasform, Map<String, String> mapParams) throws Exception {
		String strResult = "";
		try {
			Source sourceInput = new StreamSource(new StringReader(xmlInput));
			Source styleSource = new StreamSource(new StringReader(xsltTrasform));
			CompilerInfo compilerInfo = configuration.getDefaultXsltCompilerInfo();
			PreparedStylesheet sheet = PreparedStylesheet.compile(styleSource, configuration, compilerInfo);
			Controller controller = (Controller) sheet.newTransformer();
			if (mapParams != null) {
				for (Entry<String, String> entry : mapParams.entrySet()) {
					controller.setParameter(entry.getKey(), entry.getValue());
				}
			}

			StringWriter outWriter = new StringWriter();
			javax.xml.transform.Result result = new StreamResult(outWriter);
			try {
				controller.transform(sourceInput, result);
				strResult = outWriter.getBuffer().toString();
			} catch (XPathException err) {
				if (!err.hasBeenReported()) {
					err.printStackTrace();
				}
				throw new XPathException("Run-time errors were reported");
			}
		} catch (Exception e) {
			throw e;
		}
		return strResult;
	}

	public static String xsltFromFile(String inFilename, String xslFilename) {
		String strResult = "";
		try {
			Source sourceInput = new StreamSource(new FileInputStream(inFilename));
			Source styleSource = new StreamSource(new FileInputStream(xslFilename));
			CompilerInfo compilerInfo = configuration.getDefaultXsltCompilerInfo();
			PreparedStylesheet sheet = PreparedStylesheet.compile(styleSource, configuration, compilerInfo);
			Controller controller = (Controller) sheet.newTransformer();
			StringWriter outWriter = new StringWriter();
			javax.xml.transform.Result result = new StreamResult(outWriter);
			try {
				controller.transform(sourceInput, result);
				strResult = outWriter.getBuffer().toString();
			} catch (XPathException err) {
				if (!err.hasBeenReported()) {
					err.printStackTrace();
				}
				throw new XPathException("Run-time errors were reported");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;
	}

	public static void xsltFromFile(String inFilename, String xslFilename, String outFilename) {
		try {
			Source sourceInput = new StreamSource(new FileInputStream(inFilename));
			Source styleSource = new StreamSource(new FileInputStream(xslFilename));
			CompilerInfo compilerInfo = configuration.getDefaultXsltCompilerInfo();
			PreparedStylesheet sheet = PreparedStylesheet.compile(styleSource, configuration, compilerInfo);
			Controller controller = (Controller) sheet.newTransformer();
			javax.xml.transform.Result result = new StreamResult(new File(outFilename));
			try {
				controller.transform(sourceInput, result);
			} catch (XPathException err) {
				if (!err.hasBeenReported()) {
					err.printStackTrace();
				}
				throw new XPathException("Run-time errors were reported");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.TransformerConfigurationException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.jena.atlas.web.AcceptList;
import org.apache.jena.atlas.web.MediaType;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFLanguages;
import org.bygle.bean.RdfClasses;
import org.bygle.bean.RecordTypes;
import org.bygle.bean.Records;
import org.bygle.bean.Slugs;
import org.bygle.db.services.BygleService;
import org.bygle.service.bean.Content;
import org.bygle.utils.BygleSystemUtils;
import org.bygle.utils.io.FileInfoReader;
import org.bygle.vocabulary.LDPVoc;
import org.bygle.xml.XMLBuilder;
import org.bygle.xml.XMLReader;
import org.bygle.xml.exception.XMLException;
import org.bygle.xslt.TrasformXslt;
import org.dom4j.DocumentException;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.DC;
import com.hp.hpl.jena.vocabulary.DCTerms;
import com.hp.hpl.jena.vocabulary.RDF;
package org.bygle.service;





@Service(value = "ldpService")
public class LDPService {

	@javax.annotation.Resource(name = "rdfPresentationIncludeMap")
	HashMap<String, ArrayList<String>> rdfPresentationIncludeMap;

	@javax.annotation.Resource(name = "rdfPresentationOmitMap")
	HashMap<String, ArrayList<String>> rdfPresentationOmitMap;

	@javax.annotation.Resource(name = "defaultNamespaces")
	HashMap<String, String> defaultNamespaces;

	@javax.annotation.Resource(name = "readOnlyProperties")
	ArrayList<String> readOnlyProperties;

	@javax.annotation.Resource(name = "invalidProperties")
	ArrayList<String> invalidProperties;

	@Autowired
	RelationsService relationsService;
	@Autowired
	BygleService bygleService;

	private String defaultDomain;
	private String defaultEncoding;

	public String getAbout(HttpServletRequest request) {
		String result = "";
		try {
			result = URLDecoder.decode(StringUtils.substringAfter(request.getRequestURI(), request.getContextPath()), defaultEncoding);
		} catch (UnsupportedEncodingException e) {
			result = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath());
		}
		return result.isEmpty() ? "/" : result.replaceAll("^/", "");
	}

	public ResponseEntity<?> get(String about, String accept, String prefer, String headerHost) throws ConfigurationException, XMLException, UnsupportedEncodingException, URISyntaxException {
		String rdfAbout = about;// + (!about.endsWith("/") ? "/" : "");
		String host = defaultDomain;
		if (headerHost != null && !headerHost.trim().isEmpty())
			host = headerHost;
		host = host.replaceAll("/$", "") + "/";
		host = host.startsWith("http://") ? host : "http://" + host;
		List<?> recordsList = bygleService.getList(getCriteria(Records.class, Restrictions.or(Restrictions.eq("rdfAbout", rdfAbout), Restrictions.eq("rdfAbout", about)), Restrictions.eq("host", host)));