-> Send to a friend

User:Remiss/JavaSoap

From LyricWiki

Jump to: navigation, search

[edit] Java and SOAP

I think there is a discussion on the talk page Soap talk concerning this issue. Unsure if the problem has been resolved. Nevertheless this code will still be useful if you want to avoid some of the overhead (as described on my main page) or pain of installing a java soap client.

Please let me know on my talk page if you have any problems with this code.

Code follows:

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;


public class LyricsWiki implements Serializable {

	private static URL url;
	private static final String SITE_NAME = "lyricwiki.org";
	private static final long serialVersionUID = 12L;
	private static final int DEFAULT_TIMEOUT = 15 * 1000; // X * 1000 ms
	
	private static final String NOT_FOUND = "Not found";

	public LyricsWiki() {
		try {
			url = new URL("http://lyricwiki.org/server.php");
		} catch (MalformedURLException e) {
			e.printStackTrace();
			url = null; 
		}
	}

	public XMLSearch search(String artist, String title) {
		Hashtable<String, String> params = new Hashtable<String, String>();
		params.put("artist", artist); 
		params.put("song", title); 
		InputStream b = sendCommand("searchSongs", params);
		XMLSearch s = new XMLSearch(artist, title, true); 
		XMLReader r = buildXMLReader(s, s);
		try {
			r.parse(new InputSource(b));
		} catch (Exception e) {
			System.out.println("Failed to do search: " + artist +"-"+ title);
			return null; 
		}
		return s; 
	}
	
	public XMLSong fetchLyric(String artist, String title) {
		Hashtable<String, String> params = new Hashtable<String, String>();
		params.put("artist", artist); 
		params.put("song", title); 
		
		InputStream b = sendCommand("getSong", params);
		if(b==null)
			return null; 
		XMLSong s = new XMLSong(); 
		XMLReader r = buildXMLReader(s,s);
		
		try {
			
			r.parse(new InputSource(b));
		} catch (Exception e) {
			return null; 
		}
		if(s.lyrics==null||(NOT_FOUND.equals(s.lyrics.toString())))
			return null; 
		
		return s; 
	}
	
	public InputStream sendCommand(String cmd, Hashtable<String, String> params) {
		HttpURLConnection connection = null;
	    try {
	        URLConnection uc = url.openConnection();
	        connection = (HttpURLConnection) uc;
	        
	        connection.setDoOutput(true);
	        connection.setDoInput(true);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "text/xml; charset=ISO-8859-1");
	        connection.setRequestProperty("Host", "lyricwiki.org");
	        connection.setRequestProperty("User-Agent", "Some user agent/0.1 (:o)");
	        connection.setRequestProperty("Accept-Charset", "iso-8859-1");
	        connection.setRequestProperty("SOAPAction", "urn:LyricWiki#" + cmd);
	        connection.setConnectTimeout(DEFAULT_TIMEOUT);
	        
	        
	        OutputStream out = connection.getOutputStream();
	        Writer wout = new OutputStreamWriter(out);
	        //wout = new OutputStreamWriter(System.out);
	        connection.connect(); 
	        wout.write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n");
	        wout.write("<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:tns=\"urn:LyricWiki\">\n");
	        wout.write("<SOAP-ENV:Body>\n<tns:");
	        wout.write(cmd);
	        wout.write(" xmlns:tns=\"urn:LyricWiki\">\n");

	        Iterator<Entry<String, String>> i = params.entrySet().iterator();
	        Entry<String, String> e;
	        while(i.hasNext()) {
	        	e = i.next();
	        	wout.write("<");
	        	wout.write(e.getKey()); 
	        	wout.write(" xsi:type=\"xsd:string\">");
	        	wout.write(escapeXml(e.getValue()));
	        	wout.write("</");
	        	wout.write(e.getKey());
	        	wout.write(">");
	        }
	        
	        wout.write("</tns:");
	        wout.write(cmd);
	        wout.write("></SOAP-ENV:Body></SOAP-ENV:Envelope>\n");

	        wout.flush();
	        wout.close();
	        
	        InputStream in = connection.getInputStream();
	        /*StringBuffer ret = new StringBuffer(); 
	         int c;
	        while ((c = in.read()) != -1) ret.append((char)c);

	        in.close();
	        return ret;*/
	        return in;
	      }
	      catch (Exception e) {
	        System.err.println(e);
	        try {
	        	InputStream in = connection.getErrorStream();
	        	int c; 
	        	while ((c = in.read()) != -1) System.out.write(c);
			} catch (Exception e1) {
				System.out.println("Unable to print error from previous exception");
			}
	      }
		
		return null; 
	}
	
	public static final XMLReader buildXMLReader(ContentHandler c , ErrorHandler e) {
		XMLReader r;
		try {
			r = XMLReaderFactory.createXMLReader();
		} catch (SAXException e1) {
			e1.printStackTrace();
			return null; 
		}
		r.setContentHandler(c);
		r.setErrorHandler(e);
		
		return r; 
	}

	public static final String escapeXml(String in) {
		StringBuffer ret = new StringBuffer();
		char c; 
		for(int i=0; i < in.length(); i++) {
			switch((c=in.charAt(i))) {
				case '<': ret.append("&lt;") ; break; 
				case '>': ret.append("&gt;") ; break; 
				case '&': ret.append("&amp;"); break; 
				default:  ret.append(c); break; 
			}
		}
		return ret.toString(); 
	}

	public static void main(String args[]) {
		LyricsWiki w = new LyricsWiki(); 
		System.out.print(w.fetchLyric("My Chemical Romance", "House Of Wolves").lyrics.toString());
	}
	
	public class XMLSearch implements ContentHandler, ErrorHandler {

		String searchArtist, searchTitle;
		boolean requireExact;
		private StringBuffer write = null;
		private StringBuffer title=null, artist=null, bestTitle=null, bestArtist=null; 
		private int artistD = Integer.MAX_VALUE, titleD = Integer.MAX_VALUE;
		
		public XMLSearch(String artist, String title, boolean requireExact) {
			this.searchArtist = artist.toLowerCase().trim();
			this.searchTitle = title.toLowerCase().trim();
			this.requireExact = requireExact; 
		}
		
		public void characters(char[] ch, int start, int length) throws SAXException {
			if(write ==null)
				return; 
			for (int i = start; i < start + length; i++) {
				write.append(ch[i]);
			}
		}
		
		public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
			if(localName.equals("artist")) {
				if(artist!=null)
					pushBest(); 
				write = artist = new StringBuffer(); 
			}
			else if(localName.equals("song")) {
				write = title = new StringBuffer(); 
			}
		}
		
		private void pushBest() {
			int ad, td;
			ad = Distance.LD(searchArtist, artist.toString().toLowerCase().trim());
			td = Distance.LD(searchTitle, title.toString().toLowerCase().trim());
			if( ad<artistD || (ad==artistD && td<titleD)) {
				bestArtist = artist; 
				bestTitle = title;
			}
		}

		public void endDocument() throws SAXException {	
			pushBest(); 
		}
		
		public void endElement(String uri, String localName, String qName) throws SAXException {}
		public void endPrefixMapping(String prefix) throws SAXException {}
		public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {	}
		public void processingInstruction(String target, String data) throws SAXException {	}
		public void setDocumentLocator(Locator locator) {}
		public void skippedEntity(String name) throws SAXException {}
		public void startDocument() throws SAXException {}
		public void startPrefixMapping(String prefix, String uri) throws SAXException {	}
		public void error(SAXParseException exception) throws SAXException {}
		public void fatalError(SAXParseException exception) throws SAXException {}
		public void warning(SAXParseException exception) throws SAXException {	}
		
	}
	public class XMLSong implements ContentHandler, ErrorHandler {

		private StringBuffer write = null;
		public StringBuffer lyrics = null, artist = null, title = null; 
		
		public XMLSong() {}
		
		public void characters(char[] ch, int start, int length) throws SAXException {
			if(write ==null)
				return; 
			for (int i = start; i < start + length; i++) {
				write.append(ch[i]);
			}
		}
		
		public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
			//System.out.println(localName); 
			if(localName.equals("artist")) {
				write = artist = new StringBuffer(); 
			}
			else if(localName.equals("song")) {
				write = title = new StringBuffer(); 
			}
			else if(localName.equals("lyrics")) {
				write = lyrics = new StringBuffer(); 
			}
		}
		public void endElement(String uri, String localName, String qName) throws SAXException {}
		public void endDocument() throws SAXException {}
		public void endPrefixMapping(String prefix) throws SAXException {}
		public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {	}
		public void processingInstruction(String target, String data) throws SAXException {	}
		public void setDocumentLocator(Locator locator) {}
		public void skippedEntity(String name) throws SAXException {}
		public void startDocument() throws SAXException {}
		public void startPrefixMapping(String prefix, String uri) throws SAXException {	}
		public void error(SAXParseException exception) throws SAXException {}
		public void fatalError(SAXParseException exception) throws SAXException {}
		public void warning(SAXParseException exception) throws SAXException {	}
		
	}

}

why the ad?
Personal tools
LyricWiki Challenge
LyricWiki Challenge + Facebook App
Try the LyricWiki Challenge
Facebook App!
Friend spotlight (info)
Doctor Who Wiki - Tardis Index File