⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 localcatalogmanager.java

📁 基于jxta的文件共享和聊天系统源代码,下载下来分析吧
💻 JAVA
字号:
package local_catalog_manager;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import java.net.URL;import java.net.URLConnection;import org.apache.xerces.dom.DocumentImpl;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import java.net.MalformedURLException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.StringTokenizer;import java.nio.ByteBuffer;import java.io.RandomAccessFile;import java.nio.channels.FileChannel;import static java.nio.channels.FileChannel.MapMode.READ_ONLY;public class LocalCatalogManager {	private LocalCatalogEntry[] info;	private File lcmf;	private Document doc;		public boolean isEmpty()	{		boolean e=false;		if((info==null)||(info[0].getTitle()==null))			e=true;		return e;	}		/**	 * @return the doc	 */	public Document getDoc() {		return doc;	}	public LocalCatalogManager()		{						lcmf=new File("lmcf.xml");						if(!lcmf.exists())				{					doc=new DocumentImpl();					Element root=doc.createElement("lcm");					doc.appendChild(root);					try{System.out.println("saving");				 	  Transformer transformer= TransformerFactory.newInstance().newTransformer();				 	  //String systemID=doc.getDoctype().getSystemId();				 	  //transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"prodotti.dtd");				 	  transformer.setOutputProperty(OutputKeys.METHOD,"xml");				 	  transformer.setOutputProperty(OutputKeys.INDENT,"yes");				 	  DOMSource source=new DOMSource(doc);				 	  FileOutputStream fos=new FileOutputStream(lcmf);				 	  StreamResult result = new StreamResult (fos);				 	  transformer.transform(source,result);				  	}					catch(TransformerConfigurationException tce){System.out.println("tce");}					catch(TransformerException te){System.out.println("te");}					catch(IOException ioe){System.out.println("ioe");}}							else				{					DocumentBuilder db = null;					DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();					try {						db = dbf.newDocumentBuilder();					} catch (ParserConfigurationException pce) {pce.printStackTrace();}					try{doc=db.parse(lcmf);}					catch(IOException ioe){}					catch(SAXException saxe){}					NodeList nl=doc.getElementsByTagName("entry");					if (nl.getLength()>0)						{							info=new LocalCatalogEntry[nl.getLength()];							for(int i=0;i<nl.getLength();i++)							{								NodeList nl2=nl.item(i).getChildNodes();								String t=null;								String d=null;								String h=null;								URL u=null;								for(int j=0;j<nl2.getLength();j++)									{										Node n=nl2.item(j);										if(n.getNodeName().equals("title"))											{												NodeList tx=n.getChildNodes();												t=tx.item(0).getNodeValue();											}										if(n.getNodeName().equals("description"))											{												NodeList tx=n.getChildNodes();												d=tx.item(0).getNodeValue();											}										if(n.getNodeName().equals("url"))											{												NodeList tx=n.getChildNodes();												try{u=new URL(tx.item(0).getNodeValue());}												catch (MalformedURLException mue){}											}										if(n.getNodeName().equals("hash"))										{											NodeList tx=n.getChildNodes();											h=tx.item(0).getNodeValue();										}																			}								info[i]=new LocalCatalogEntry(t,d,u,h);							}						}				}			digestFiles();				}		public void digestFile(LocalCatalogEntry lce,boolean dw)		{			if(lce.getHash()==null){			String f=null;			OutputStream out = null;			URLConnection conn = null;			InputStream  in = null;			MessageDigest md=null;			try{URL u=lce.getUrl();			u.openStream();			String fn=u.getFile(); 	 		StringTokenizer st=new StringTokenizer(fn,"/"); 	 		while(st.hasMoreTokens())				 f=st.nextToken(); 								out = new BufferedOutputStream(				new FileOutputStream(f));			conn = u.openConnection();			in = conn.getInputStream();			byte[] buf = new byte[1024];			int numRead;			long numWritten = 0;			while ((numRead = in.read(buf)) != -1) {				out.write(buf, 0, numRead);				numWritten += numRead;			}		}catch (Exception e){}		finally {			try {				if (in != null) {					in.close();				}				if (out != null) {					out.close();				}				} catch (IOException ioe) {}				}				try{					FileChannel channel = new RandomAccessFile(f, "r").getChannel();					ByteBuffer buffer = channel.map(READ_ONLY, 0, (int)channel.size());					try {md = MessageDigest.getInstance("SHA");}					catch (NoSuchAlgorithmException nsa){}					md.update(buffer.duplicate());					byte[] digest = md.digest();					channel.close();					String d=null;					d=this.byteArrayToHexString(digest);					lce.setHash(d);											}				catch(Exception e){e.printStackTrace();}			if(!dw)			{				File de=new File(f);				de.delete();			}			}		}			public void digestFiles()		{			NodeList nl=doc.getElementsByTagName("url");						String f=null;			for (int i=0;i<nl.getLength();i++)			{				Node root=nl.item(i).getParentNode();				Element r =(Element) root;				if(r.getElementsByTagName("hash")==null){				NodeList nl2=nl.item(i).getChildNodes();				Node n=nl2.item(0);				OutputStream out = null;				URLConnection conn = null;				InputStream  in = null;				MessageDigest md=null;			try{				URL u=new URL(n.getNodeValue());				u.openStream();				String fn=u.getFile();	 	 		f=fn.substring(1);				out = new BufferedOutputStream(					new FileOutputStream(f));				conn = u.openConnection();				in = conn.getInputStream();				byte[] buf = new byte[1024];				int numRead;				long numWritten = 0;				while ((numRead = in.read(buf)) != -1) {					out.write(buf, 0, numRead);					numWritten += numRead;				}			}catch (Exception e){}			finally {				try {					if (in != null) {						in.close();					}					if (out != null) {						out.close();					}					} catch (IOException ioe) {}				}			try{				FileChannel channel = new RandomAccessFile(f, "r").getChannel();				ByteBuffer buffer = channel.map(READ_ONLY, 0, (int)channel.size());				try {md = MessageDigest.getInstance("SHA");}				catch (NoSuchAlgorithmException nsa){}				md.update(buffer.duplicate());				byte[] digest = md.digest();				channel.close();				String d=null;				d=this.byteArrayToHexString(digest);				System.out.println(d);												}			catch(Exception e){e.printStackTrace();}						}						}					}		static byte[] hexStringToByteArray(String in)		{			byte [] ba= new byte[in.length()/2];  			    for(int i=0; i<(in.length()/2); i++){			    	byte firstNibble  = Byte.parseByte(in.substring(2*i,2*i+1),16); // [x,y)			    	byte secondNibble = Byte.parseByte(in.substring(2*i+1,2*i+2),16);			    	int finalByte = (secondNibble) | (firstNibble << 4 ); // bit-operations only with numbers, not bytes.			    	ba[i] = (byte) finalByte;			    }  						return ba;		}		static String byteArrayToHexString(byte in[]) {	    byte ch = 0x00;	    int i = 0; 	    if (in == null || in.length <= 0)	        return null;	        	    String pseudo[] = {"0", "1", "2",	"3", "4", "5", "6", "7", "8",	"9", "a", "b", "c", "d", "e",	"f"};	    StringBuffer out = new StringBuffer(in.length * 2);	    	    while (i < in.length) {	        ch = (byte) (in[i] & 0xF0); // Strip off high nibble	        ch = (byte) (ch >>> 4);	     // shift the bits down	        ch = (byte) (ch & 0x0F);    //	 must do this is high order bit is on!	        out.append(pseudo[ (int) ch]); // convert the	nibble to a String Character	        ch = (byte) (in[i] & 0x0F); // Strip off	low nibble 	        out.append(pseudo[ (int) ch]); // convert the	nibble to a String Character	        i++;	    }	    String rslt = new String(out);	    return rslt;	}    		private boolean searchURL(URL u)	{		boolean r=false;		int i=0;		if (info==null)		{return false;}		while((!r)&&(i<info.length))		{			if(info[i].getUrl().equals(u))				{r=true;System.out.println("trovato");}			i++;		}		return r;			}		public void insert(String t,String d,URL u, boolean dw)		{			if(!searchURL(u)){			LocalCatalogEntry [] temp;			if(info!=null) 				{					temp=new LocalCatalogEntry[info.length+1];								for(int i=0;i<info.length;i++)							temp[i]=info[i];					temp[temp.length-1]=new LocalCatalogEntry(t,d,u);					info=temp;				}			else			{				temp=new LocalCatalogEntry[1];				temp[0]=new LocalCatalogEntry(t,d,u);				info=temp;			}			digestFile(info[temp.length-1],dw);			Element root=doc.createElement("entry");			NodeList n=doc.getElementsByTagName("lcm");			Node r=n.item(0);			r.appendChild(root);			Node titleE=doc.createElement("title");			Node titleT=doc.createTextNode(t);			titleE.appendChild(titleT);			root.appendChild(titleE);			Node descE=doc.createElement("description");			Node descT=doc.createTextNode(d);			descE.appendChild(descT);			root.appendChild(descE);			Node urlE=doc.createElement("url");			Node urlT=doc.createTextNode(u.toString());			urlE.appendChild(urlT);			root.appendChild(urlE);			Node hashE=doc.createElement("hash");			Node hashT=doc.createTextNode(info[temp.length-1].getHash());			hashE.appendChild(hashT);			root.appendChild(hashE);			try{			Transformer transformer= TransformerFactory.newInstance().newTransformer();		 	  //String systemID=doc.getDoctype().getSystemId();		 	  //transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"prodotti.dtd");		 	  transformer.setOutputProperty(OutputKeys.METHOD,"xml");		 	  transformer.setOutputProperty(OutputKeys.INDENT,"yes");		 	  DOMSource source=new DOMSource(doc);		 	  FileOutputStream fos=new FileOutputStream(lcmf);		 	  StreamResult result = new StreamResult (fos);		 	  transformer.transform(source,result);		  	}		 	catch(TransformerConfigurationException tce){System.out.println("tce");}			catch(TransformerException te){System.out.println("te");}			catch(IOException ioe){System.out.println("ioe");}			}		}		/**	 * @return the info	 */	public LocalCatalogEntry[] getInfo() {		return info;	}	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -