Web Science/Part1: Foundations of the web/Hypertext Transfer Protocol/Content negotiation/script

Da Wikiversità, l'apprendimento libero.

Mainly the following function was added to SimpleWebServer.java. There are some slighte adoptions to the Request class but this is mainly code completion displayed inside the video.

	private static String fetchAsciiFile(String path, String accept) {
		try {
			StringBuilder body = new StringBuilder(100000);
			BufferedReader br = new BufferedReader(new FileReader(new File(System.getProperty("user.dir") + "/webdirectory" + path)));
			String tmp = null; 
			
			if (accept != null && accept.equals("text/xml")){
				body.append("<?xml version=\"1.0\" encoding=\"ASCII\" standalone=\"yes\"?>\n<playlist>\n");
			}
			
			while ((tmp = br.readLine())!= null){
				if (accept == null)
					body.append(tmp + "\n");
				else if (accept.equals("text/plain")){
					body.append(tmp + "\n");
				} else if (accept.equals("text/xml")){
					String []values = tmp.split(" - ");
					body.append("<track id=\""+values[1]+"\">\n\t<time>"+values[0]+"</time>\n\t<artist>"+values[2]+"</artist>\n\t<title>"+values[3]+"</title>\n</track>\n");
				}
			}
			if (accept != null && accept.equals("text/xml")){
				body.append("</playlist>\n");
			}

			br.close();
			return body.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}