W3C home > Mailing lists > Public > www-validator-cvs@w3.org > August 2009

2006/unicorn/src/org/w3c/unicorn/tests XMLBeansTest.java,NONE,1.1.2.1 UnicornCallTest.java,NONE,1.1.2.1 HiepTest.java,NONE,1.1.2.1 UnicornClientDirectInputTest.java,NONE,1.1.2.1 FirstServlet.java,NONE,1.1.2.1 UnicornClient.java,NONE,1.1.2.1 TaskTest.java,NONE,1.1.2.1 CommandLine.java,NONE,1.1.2.1

From: Thomas Gambet via cvs-syncmail <cvsmail@w3.org>
Date: Tue, 11 Aug 2009 16:05:33 +0000
To: www-validator-cvs@w3.org
Message-Id: <E1Matqv-000186-NC@lionel-hutz.w3.org>
Update of /sources/public/2006/unicorn/src/org/w3c/unicorn/tests
In directory hutz:/tmp/cvs-serv2609/src/org/w3c/unicorn/tests

Added Files:
      Tag: dev2
	XMLBeansTest.java UnicornCallTest.java HiepTest.java 
	UnicornClientDirectInputTest.java FirstServlet.java 
	UnicornClient.java TaskTest.java CommandLine.java 
Log Message:
all initialization actions in Init.java
+ compatibility windows/linux

--- NEW FILE: FirstServlet.java ---
// $Id: FirstServlet.java,v 1.1.2.1 2009/08/11 16:05:31 tgambet Exp $
// Author: Jean-Guilhem Rouel
// (c) COPYRIGHT MIT, ERCIM and Keio, 2006.
// Please first read the full copyright statement in file COPYRIGHT.html
package org.w3c.unicorn.tests;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.w3c.unicorn.Framework;
import org.w3c.unicorn.UnicornCall;
import org.w3c.unicorn.contract.EnumInputMethod;
import org.w3c.unicorn.exceptions.NoTaskException;
import org.w3c.unicorn.index.IndexGenerator;
import org.w3c.unicorn.output.OutputFactory;
import org.w3c.unicorn.output.OutputFormater;
import org.w3c.unicorn.output.OutputModule;
import org.w3c.unicorn.util.LocalizedString;
import org.w3c.unicorn.util.Property;

/**
 * FirstServlet<br />
 * Created: Jun 26, 2006 2:04:11 PM<br />
 * 
 * @author Jean-Guilhem ROUEL
 */
public class FirstServlet extends HttpServlet {

	private static final Log logger = LogFactory
			.getLog("org.w3c.unicorn.servlet");

	private static final long serialVersionUID = -1375355420965607571L;

	private static final DiskFileItemFactory factory = new DiskFileItemFactory();

	/**
	 * Creates a new file upload handler.
	 */
	private static final ServletFileUpload upload = new ServletFileUpload(
			FirstServlet.factory);

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init()
	 */
	@Override
	public void init(final ServletConfig aServletConfig)
			throws ServletException {
		FirstServlet.logger.trace("init");

		FirstServlet.factory.setRepository(new File(Property
				.get("UPLOADED_FILES_REPOSITORY")));

		try {
			IndexGenerator.generateIndexes();
		} catch (final ResourceNotFoundException e) {
			FirstServlet.logger.error("ResourceNotFoundException : "
					+ e.getMessage(), e);
			e.printStackTrace();
		} catch (final ParseErrorException e) {
			FirstServlet.logger.error(
					"ParseErrorException : " + e.getMessage(), e);
			e.printStackTrace();
		} catch (final Exception e) {
			FirstServlet.logger.error("Exception : " + e.getMessage(), e);
			e.printStackTrace();
		}
		FirstServlet.logger.info("End of initialisation of servlet.");

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(final HttpServletRequest aHttpServletRequest,
			final HttpServletResponse aHttpServletResponse)
			throws ServletException, IOException {
		FirstServlet.logger.trace("doGet");

		// Variables related to the output
		final Map<String, String[]> mapOfSpecificParameter = new Hashtable<String, String[]>();
		final Map<String, String> mapOfOutputParameter = new Hashtable<String, String>();
		mapOfOutputParameter.put("output", "simple");
		mapOfOutputParameter.put("format", "xhtml10");
		mapOfOutputParameter.put("charset", "UTF-8");
		mapOfOutputParameter.put("mimetype", "text/html");

		// Returns the preferred Locale that the client will accept content in,
		// based on the Accept-Language header
		final String aLocale = convertEnumerationToString(aHttpServletRequest
				.getLocales());
		final UnicornCall aUnicornCall = new UnicornCall();

		// Language of the template
		// ucn_lang is a parameter which is define in xx_index.html.vm.
		// It is an hidden parameter of a form.
		String templateLang = null;
		if (aHttpServletRequest.getParameterValues(Property
				.get("UNICORN_PARAMETER_PREFIX")
				+ "lang") != null) {
			templateLang = aHttpServletRequest.getParameterValues(Property
					.get("UNICORN_PARAMETER_PREFIX")
					+ "lang")[0];
		} else {
			templateLang = chooseTemplateLang(aLocale);
		}

		mapOfOutputParameter.put("lang", templateLang);

		if (null == aLocale) {
			aUnicornCall.setLang(LocalizedString.DEFAULT_LANGUAGE);
		} else {
			aUnicornCall.setLang(templateLang + "," + aLocale);
		}

		for (final Enumeration aEnumParamName = aHttpServletRequest
				.getParameterNames(); aEnumParamName.hasMoreElements();) {
			final String sParamName = (String) aEnumParamName.nextElement();
			final String[] tStringParamValue = aHttpServletRequest
					.getParameterValues(sParamName);

			this.addParameter(sParamName, tStringParamValue, aUnicornCall,
					mapOfSpecificParameter, mapOfOutputParameter);
		} // For

		if (aUnicornCall.getTask() == null) {
			FirstServlet.logger.error("No task selected.");
			this.createError(aHttpServletResponse, new NoTaskException(),
					mapOfSpecificParameter, mapOfOutputParameter);
			return;
		}

		try {
			aUnicornCall.doTask();

			this.createOutput(aHttpServletResponse, aUnicornCall,
					mapOfSpecificParameter, mapOfOutputParameter);
		} catch (final Exception aException) {
			FirstServlet.logger.error("Exception : " + aException.getMessage(),
					aException);
			this.createError(aHttpServletResponse, aException,
					mapOfSpecificParameter, mapOfOutputParameter);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(final HttpServletRequest aHttpServletRequest,
			final HttpServletResponse aHttpServletResponse)
			throws ServletException, IOException {
		FirstServlet.logger.trace("doPost");

		// Check that we have a file upload request
		final boolean bIsMultipart = ServletFileUpload
				.isMultipartContent(new ServletRequestContext(
						aHttpServletRequest));

		if (!bIsMultipart) {
			this.doGet(aHttpServletRequest, aHttpServletResponse);
			return;
		}

		// Parse the request
		final List listOfItem;

		final UnicornCall aUnicornCall = new UnicornCall();

		// Variables related to the output
		final Map<String, String> mapOfOutputParameter = new Hashtable<String, String>();
		mapOfOutputParameter.put("output", "simple");
		mapOfOutputParameter.put("format", "xhtml10");
		mapOfOutputParameter.put("charset", "UTF-8");
		mapOfOutputParameter.put("mimetype", "text/html");

		// Returns the preferred Locale that the client will accept content in,
		// based on the Accept-Language header
		final String aLocale = convertEnumerationToString(aHttpServletRequest
				.getLocales());

		// Language of the template
		// ucn_lang is a parameter which is define in xx_index.html.vm.
		// It is an hidden parameter of a form.
		String templateLang = null;

		FirstServlet.logger.trace("doPost");

		final Map<String, String[]> mapOfSpecificParameter = new Hashtable<String, String[]>();

		FileItem aFileItemUploaded = null;

		try {
			listOfItem = FirstServlet.upload.parseRequest(aHttpServletRequest);

			// Process the uploaded items
			for (final Iterator aIterator = listOfItem.iterator(); aIterator
					.hasNext();) {
				final FileItem aFileItem = (FileItem) aIterator.next();
				if (aFileItem.isFormField()) {

					if (aFileItem.getFieldName().equals("ucn_lang")) {
						templateLang = aFileItem.getString();
					}

					addParameter(aFileItem.getFieldName(), aFileItem
							.getString(), aUnicornCall, mapOfSpecificParameter,
							mapOfOutputParameter);

				} else if (aFileItem.getFieldName().equals(
						Property.get("UNICORN_PARAMETER_PREFIX") + "file")) {
					aFileItemUploaded = aFileItem;
					aUnicornCall.setDocumentName(aFileItemUploaded.getName());
					aUnicornCall.setInputParameterValue(aFileItemUploaded);
					aUnicornCall.setEnumInputMethod(EnumInputMethod.UPLOAD);
				}
			}

			if (templateLang == null) {
				templateLang = chooseTemplateLang(aLocale);
			}

			if (null == aLocale) {
				aUnicornCall.setLang(LocalizedString.DEFAULT_LANGUAGE);
			} else {
				aUnicornCall.setLang(templateLang + "," + aLocale);
			}
			mapOfOutputParameter.put("lang", templateLang);

		}

		catch (final FileUploadException aFileUploadException) {
			FirstServlet.logger.error("FileUploadException : "
					+ aFileUploadException.getMessage(), aFileUploadException);
			this.createError(aHttpServletResponse, aFileUploadException,
					mapOfSpecificParameter, mapOfOutputParameter);
		}

		try {
			aUnicornCall.doTask();

			this.createOutput(aHttpServletResponse, aUnicornCall,
					mapOfSpecificParameter, mapOfOutputParameter);
		} catch (final Exception aException) {
			FirstServlet.logger.error("Exception : " + aException.getMessage(),
					aException);
			this.createError(aHttpServletResponse, aException,
					mapOfSpecificParameter, mapOfOutputParameter);
		} finally {
			if ("true".equals(Property.get("DELETE_UPLOADED_FILES"))
					&& aFileItemUploaded != null
					&& aFileItemUploaded instanceof FileItem) {
				aFileItemUploaded.delete();
			}
		}
	}

	/**
	 * Adds a parameter at the correct call.
	 * 
	 * @param sParamName
	 *            Name of the parameter.
	 * @param sParamValue
	 *            Value of the parameter.
	 * @param aUnicornCall
	 * @param mapOfSpecificParameter
	 * @param mapOfOutputParameter
	 */
	private void addParameter(final String sParamName,
			final String sParamValue, final UnicornCall aUnicornCall,
			final Map<String, String[]> mapOfSpecificParameter,
			final Map<String, String> mapOfOutputParameter) {
		final String[] tStringValues = { sParamValue };
		this.addParameter(sParamName, tStringValues, aUnicornCall,
				mapOfSpecificParameter, mapOfOutputParameter);
	}

	/**
	 * 
	 * @param sParamName
	 * @param tStringParamValue
	 * @param aUnicornCall
	 * @param mapOfSpecificParameter
	 * @param mapOfOutputParameter
	 */
	private void addParameter(String sParamName,
			final String[] tStringParamValue, final UnicornCall aUnicornCall,
			final Map<String, String[]> mapOfSpecificParameter,
			final Map<String, String> mapOfOutputParameter) {

		if (null == tStringParamValue || 0 == tStringParamValue.length) {
			// no value for this parameter
			// TODO log this info if necessary
			return;
		}

		if (!sParamName.startsWith(Property.get("UNICORN_PARAMETER_PREFIX"))) {
			// task parameter
			aUnicornCall.addParameter(sParamName, tStringParamValue);
			return;
		}

		// Unicorn parameter
		// TODO: Why is it here?
		sParamName = sParamName.substring(Property.get(
				"UNICORN_PARAMETER_PREFIX").length());

		// Output specific parameter
		if (sParamName.startsWith(Property
				.get("UNICORN_PARAMETER_OUTPUT_PREFIX"))) {
			sParamName = sParamName.substring(Property.get(
					"UNICORN_PARAMETER_OUTPUT_PREFIX").length());
			mapOfSpecificParameter.put(sParamName, tStringParamValue);
			return;
		}

		if (sParamName.equals("lang")) {
			aUnicornCall.addParameter(Property.get("UNICORN_PARAMETER_PREFIX")
					+ "lang", tStringParamValue);
		}

		// Global Unicorn parameter
		if (sParamName.equals("task")) {
			// FirstServlet.logger.debug("");
			aUnicornCall.setTask(tStringParamValue[0]);
		} else if (sParamName.equals("uri")) {
			aUnicornCall.setEnumInputMethod(EnumInputMethod.URI);

			if (!tStringParamValue[0].substring(0, 7).equals("http://")) {
				FirstServlet.logger.info("URI missing protocol : "
						+ tStringParamValue[0]);
				tStringParamValue[0] = "http://" + tStringParamValue[0];
				FirstServlet.logger.info("URI modified to : "
						+ tStringParamValue[0]);
			}

			aUnicornCall.setDocumentName(tStringParamValue[0]);
			aUnicornCall.setInputParameterValue(tStringParamValue[0]);
		} else if (sParamName.equals("text")) {
			aUnicornCall.setEnumInputMethod(EnumInputMethod.DIRECT);
			aUnicornCall.setDocumentName(tStringParamValue[0]);
			aUnicornCall.setInputParameterValue(tStringParamValue[0]);
		}
		// TODO add upload handle when it work
		else if (sParamName.equals("output") || sParamName.equals("format")
				|| sParamName.equals("charset")
				|| sParamName.equals("mimetype") || sParamName.equals("lang")) {
			mapOfOutputParameter.put(sParamName, tStringParamValue[0]);
		} else if (sParamName.equals("text_mime")) {
			aUnicornCall.addParameter(Property.get("UNICORN_PARAMETER_PREFIX")
					+ "mime", tStringParamValue);
		}
	}

	private void createError(final HttpServletResponse aHttpServletResponse,
			final Exception aExceptionError,
			final Map<String, String[]> mapOfSpecificParameter,
			final Map<String, String> mapOfOutputParameter) throws IOException {
		aHttpServletResponse.setContentType(mapOfOutputParameter
				.get("mimetype")
				+ "; charset=" + mapOfOutputParameter.get("charset"));

		try {
			final OutputFormater aOutputFormater = OutputFactory
					.getOutputFormater(mapOfOutputParameter.get("format"),
							mapOfOutputParameter.get("lang"),
							mapOfOutputParameter.get("mimetype"));
			final OutputModule aOutputModule = OutputFactory
					.getOutputModule(mapOfOutputParameter.get("output"));
			aOutputModule.produceError(aOutputFormater, aExceptionError,
					mapOfSpecificParameter, aHttpServletResponse.getWriter());
		} catch (final ResourceNotFoundException e) {
			FirstServlet.logger.error("ResourceNotFoundException : "
					+ e.getMessage(), e);
			aHttpServletResponse.getWriter().println("<pre>");
			e.printStackTrace(aHttpServletResponse.getWriter());
			aHttpServletResponse.getWriter().println("</pre>");
		} catch (final ParseErrorException e) {
			FirstServlet.logger.error(
					"ParseErrorException : " + e.getMessage(), e);
			aHttpServletResponse.getWriter().println("<pre>");
			e.printStackTrace(aHttpServletResponse.getWriter());
			aHttpServletResponse.getWriter().println("</pre>");
		} catch (final Exception e) {
			FirstServlet.logger.error("Exception : " + e.getMessage(), e);
			aHttpServletResponse.getWriter().println("<pre>");
			e.printStackTrace(aHttpServletResponse.getWriter());
			aHttpServletResponse.getWriter().println("</pre>");
		}
	}

	private void createOutput(final HttpServletResponse aHttpServletResponse,
			final UnicornCall aUnicornCall,
			final Map<String, String[]> mapOfSpecificParameter,
			final Map<String, String> mapOfOutputParameter) throws IOException {
		aHttpServletResponse.setContentType(mapOfOutputParameter
				.get("mimetype")
				+ "; charset=" + mapOfOutputParameter.get("charset"));
		try {
			Map<String, Object> mapOfStringObject = new LinkedHashMap<String, Object>();
			mapOfStringObject.put("unicorncall", aUnicornCall);

			final OutputFormater aOutputFormater = OutputFactory
					.getOutputFormater(mapOfOutputParameter.get("format"),
							mapOfOutputParameter.get("lang"),
							mapOfOutputParameter.get("mimetype"));
			final OutputModule aOutputModule = OutputFactory
					.getOutputModule(mapOfOutputParameter.get("output"));
			aOutputModule.produceOutput(aOutputFormater, mapOfStringObject,
					mapOfSpecificParameter, aHttpServletResponse.getWriter());
		}

		catch (final ResourceNotFoundException e) {
			FirstServlet.logger.error("ResourceNotFoundException : "
					+ e.getMessage(), e);
			aHttpServletResponse.getWriter().println("<pre>");
			e.printStackTrace(aHttpServletResponse.getWriter());
			aHttpServletResponse.getWriter().println("</pre>");
		} catch (final ParseErrorException e) {
			FirstServlet.logger.error(
					"ParseErrorException : " + e.getMessage(), e);
			aHttpServletResponse.getWriter().println("<pre>");
			e.printStackTrace(aHttpServletResponse.getWriter());
			aHttpServletResponse.getWriter().println("</pre>");
		} catch (final Exception e) {
			FirstServlet.logger.error("Exception : " + e.getMessage(), e);
			aHttpServletResponse.getWriter().println("<pre>");
			e.printStackTrace(aHttpServletResponse.getWriter());
			aHttpServletResponse.getWriter().println("</pre>");
		}
	}

	/**
	 * This method returns the first language of the accept language list which
	 * is equal to one of available index template language
	 * 
	 * @param aLocale
	 * @return The selected language or the default language.
	 */
	private String chooseTemplateLang(String aLocale) {
		String[] tabLang = aLocale.split(";|,");
		for (int i = 0; i < tabLang.length; i++) {
			if (Framework.outputLang.contains(tabLang[i])) {
				return tabLang[i];
			} else if (Framework.outputLang.contains(tabLang[i].split("-")[0])) {
				return tabLang[i].split("-")[0];
			}
		}

		return LocalizedString.DEFAULT_LANGUAGE;
	}

	/**
	 * Converts an Enumeration object to a string, the terms being separated by
	 * a coma.
	 * 
	 * @param myEnum
	 *            The enumeration to convert.
	 * @return The converted string.
	 */
	private String convertEnumerationToString(Enumeration myEnum) {
		String ret = "";
		while (myEnum.hasMoreElements()) {
			ret += myEnum.nextElement().toString() + ",";
		}
		return ret.substring(0, ret.length() - 1);
	}

}

--- NEW FILE: UnicornClient.java ---
package org.w3c.unicorn.tests;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import org.w3c.unicorn.UnicornCall;
import org.w3c.unicorn.contract.EnumInputMethod;
import org.w3c.unicorn.output.OutputFactory;
import org.w3c.unicorn.output.OutputFormater;
import org.w3c.unicorn.output.OutputModule;
import org.w3c.unicorn.util.Property;

public class UnicornClient {

	/**
	 * Prints help contents on the standard output.
	 * 
	 */
	public static void print_help() {
		System.out
				.println("[Usage] UnicornClient task inputType=[mimetype=]pageToValid templateLanguage outputTemplate [otherParameters]");
		System.out.println("");
		System.out
				.println("* tasks = one of task in tasklist.xml (eg: markup, css...)");
		System.out.println("* inputType       : uri|file");
		System.out
				.println("* mimetype        : text/html|text/css|... (required only if inputType='file')");
		System.out
				.println("* pageToValid     : an uri or a path to a file (depend on inputType)");
		System.out.println("* otherParameters : param1=val1,param2=val2...");
		System.out.println("");
		System.out
				.println("[Example] UnicornClient markup uri=http://w3.org en xhtml10");
		System.out
				.println("[Example] UnicornClient calculator uri=http://flyingman.sophia.w3.org/test en text10 x2=on,ptoto=titi");
		System.out
				.println("[Example] UnicornClient css file=text/css=./style/base.css fr text10 profile=css2,usermedium=screen,warning=2,lang=en");
	}

	/**
	 * Tests Unicorn client.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		if (args.length == 0) {
			print_help();
		} else if (args.length == 1 && args[0].equals("help")) {
			print_help();
		} else {
			// read parameters
			String task = args[0];
			String pageToValid = args[1];
			String language = args[2];
			String outputTemplate = args[3];
			String pParams = "";
			if (args.length > 4) { // this argument is optional
				pParams = args[4];
			}

			UnicornCall aUnicornCall = new UnicornCall();

			// parse other parameters: "x2=on,toto=titi" to a
			// map<String,String[]>
			if (pParams.length() != 0) {
				Map<String, String[]> mapOfParameter = new LinkedHashMap<String, String[]>();
				String[] couples = pParams.split(",");
				for (int i = 0; i < couples.length; i++) {
					String[] couple = couples[i].split("=");
					if (couple.length == 2) {
						String[] tmp = { couple[1] };
						mapOfParameter.put(couple[0], tmp);
					} else {
						System.err.println("Error parameter!");
					}
				}
				aUnicornCall.setMapOfStringParameter(mapOfParameter);
			}

			// parse input type: "uri=http://flyingman.sophia.w3.org/test" or
			// "file=text/css=./style/base.css"
			String[] pInput = pageToValid.split("=");
			if (pInput[0].equals("uri")) {
				aUnicornCall.setEnumInputMethod(EnumInputMethod.URI);
				aUnicornCall.setDocumentName(pInput[1]);
				aUnicornCall.setInputParameterValue(pInput[1]);
			} else { // direct input
				try {
					aUnicornCall.setEnumInputMethod(EnumInputMethod.DIRECT);

					// read content in the file pInput[2], example:
					// pInput[2]=base.css alors content=".h1{color:#FA0012}";
					BufferedReader bfr = new BufferedReader(new FileReader(
							pInput[2]));
					String content = "";
					String line;
					while ((line = bfr.readLine()) != null) {
						content = content + line + "\n";
					}
					bfr.close();

					// Ajouter mime type dans map of parameter
					Map<String, String[]> mapOfParameter = aUnicornCall
							.getMapOfStringParameter();
					if (mapOfParameter == null) {
						mapOfParameter = new LinkedHashMap<String, String[]>();
						aUnicornCall.setMapOfStringParameter(mapOfParameter);
					}
					String[] tmp = { pInput[1] };
					mapOfParameter.put(Property.get("UNICORN_PARAMETER_PREFIX")
							+ "mime", tmp);

					aUnicornCall.setInputParameterValue(content);

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			aUnicornCall.setTask(task); // task id
			aUnicornCall.setLang(language);

			long before = System.currentTimeMillis();
			try {
				aUnicornCall.doTask();

				Map<String, Object> mapOfStringObject = new LinkedHashMap<String, Object>();
				mapOfStringObject.put("unicorncall", aUnicornCall);
				OutputFormater aOutputFormater = OutputFactory
						.getOutputFormater(outputTemplate, // text or xhtml10,
															// see
															// unicorn.properties
								language, "text/html"); // MIME Type
				OutputModule aOutputModule = OutputFactory
						.getOutputModule("simple");
				PrintWriter pw = new PrintWriter(System.out);
				aOutputModule.produceOutput(aOutputFormater, mapOfStringObject,
						null, pw);
				pw.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}
			long after = System.currentTimeMillis();
			System.out.println("Elapsed time (s): " + (double) (after - before)
					/ 1000);
		}
	}
}

--- NEW FILE: UnicornCallTest.java ---
package org.w3c.unicorn.tests;

import java.io.InputStream;
import java.util.Iterator;

import javax.activation.MimeType;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.unicorn.contract.EnumInputMethod;
import org.w3c.unicorn.input.InputFactory;
import org.w3c.unicorn.input.InputModule;
import org.w3c.unicorn.request.Request;
import org.w3c.unicorn.response.Response;
import org.xml.sax.InputSource;

public class UnicornCallTest {

	public static Boolean evaluer(InputStream stream, String expression) {
		Boolean b = null;
		try {
			// cr�ation de la source
			InputSource source = new InputSource(stream);

			// cr�ation du XPath
			XPathFactory fabrique = XPathFactory.newInstance();

			XPath xpath = fabrique.newXPath();

			// test du namespace manuel

			NamespaceContext namespace = new NamespaceContext() {
				public String getNamespaceURI(String prefix) {
					if ("observationresponse".equals(prefix)) {
						return "http://www.w3.org/unicorn/observationresponse";
					} else {
						return null;
					}
				}

				public String getPrefix(String namespaceURI) {
					if ("http://www.w3.org/unicorn/observationresponse	"
							.equals(namespaceURI)) {
						return "observationresponse";
					} else {
						return null;
					}
				}

				public Iterator getPrefixes(String namespaceURI) {
					return null;
				}
			};
			xpath.setNamespaceContext(namespace);

			// �valuation de l'expression XPath
			XPathExpression exp = xpath.compile(expression);

			b = (Boolean) exp.evaluate(source, XPathConstants.BOOLEAN);
			System.out.println("namespace context : "
					+ xpath.getNamespaceContext());
		} catch (XPathExpressionException xpee) {
			xpee.printStackTrace();
		}
		return b;
	}

	public static void main(String[] args) {

		try {

			// First, the XML document

			/*
			 * String xmlStr =
			 *  "<?xml version=\"1.0\" ?>\n" +
			 *  "<Sales xmlns=\"http://www.davber.com/sales-format\">\n" +
			 *  "<Customer name=\"CostCo, Inc.\">\n" +
			 *  "<ord:Order xmlns:ord=\"http://www.davber.com/order-format\"
			 * price=\"12000\">\n" +
			 *  "<ord:Description>A bunch of stuff" +
			 *  "</ord:Description>\n" +
			 *  "</ord:Order>\n" +
			 *  "</Customer>\n" +
			 *  "</Sales>\n";
			 * 
			 */

			InputModule inputMod = InputFactory.createInputModule(
					(new MimeType()), EnumInputMethod.URI, "http://www.w3.org");
			Request req = Request.createRequest(inputMod,
					"http://validator.w3.org/check", "uri", false, "ucn");
			req.setLang("en");
			req.addParameter("output", "ucn");
			System.out.println("request created");
			System.out.println(req.getResponseType());
			Response res = req.doRequest();
			System.out.println("request done");

			DocumentBuilderFactory xmlFact = DocumentBuilderFactory
					.newInstance();
			xmlFact.setNamespaceAware(false);
			DocumentBuilder builder = xmlFact.newDocumentBuilder();
			Document doc = builder.parse(res.getXml().toString());

			// Now the XPath expression

			String xpathStr = "//false";

			XPathFactory xpathFact =

			XPathFactory.newInstance();

			XPath xpath = xpathFact.newXPath();

			String result = xpath.evaluate(xpathStr, doc);
			XPathExpression xpe = xpath.compile(xpathStr);
			boolean b = (Boolean) xpe.evaluate(doc, XPathConstants.BOOLEAN);
			System.out.println(b);
			System.out.println("xpath : " + (!result.equals("")));
			// System.out.println("XPath result is \"" +
			// result + "\"");

		}

		catch (Exception ex) {

			ex.printStackTrace();

		}

	}

}

/*
 * public static void main(String[] args) { try { System.out.println("Premier
 * test : URL"); // URL url = new //
 * URL("http://www.pms.ifi.lmu.de/forschung/xpath-eval.html");
 *  // String expression = "//category"; // String expression =
 * "//cadevraitetrefalse"; // (//doctype eq '-//W3C//DTD XHTML 1.0 Strict//EN') //
 * InputStream is = url.openStream(); // InputStreamReader isr = new
 * InputStreamReader(is); // BufferedReader br = new BufferedReader(isr); String
 * s = ""; // while ((s=br.readLine()) != null) // System.out.println(s); //
 * boolean b = evaluer(url.openStream(), expression); //
 * System.out.println(expression); // System.out.println("--> " + b);
 *  // System.out.println("Deuxi�me test : UPLOAD"); // Object fichier =
 * (Object) (new File("C:/w3.xht")); // FileItem f = (FileItem) fichier; //
 * expression = "//html";
 *  // � tester plus tard (voir firstservlet pour un exemple)
 *  // b = evaluer(f.getInputStream(),expression); // System.out.println("On
 * verra plus tard");
 *  // ystem.out.println("Troisi�me test : DIRECT");
 *  // System.out.println(b);
 *  // ObservationresponseDocument.Factory.parse();
 * 
 * //System.out.println("Premier test : URL");
 * 
 * String expr = "//result"; InputModule inputMod =
 * InputFactory.createInputModule( (new MimeType()), EnumInputMethod.URI,
 * "http://www.w3.org"); Request req = Request.createRequest(inputMod,
 * "http://validator.w3.org/check", "uri", false, "ucn"); req.setLang("en");
 * req.addParameter("output", "ucn"); System.out.println("request created");
 * System.out.println(req.getResponseType()); req.doRequest();
 * System.out.println("request done");
 *  // pour afficher le stream de response
 * 
 * InputStream resp = req.getResponseStream(); InputStreamReader isr = new
 * InputStreamReader(resp); BufferedReader br = new BufferedReader(isr); String
 * str = ""; while ((str=br.readLine()) != null) System.out.println(str);
 * 
 * 
 * br.close(); isr.close();resp.close();
 * 
 *  // trouver un moyen de // reset le responseStream de
 * 
 * //System.out.println(req.getResponseStream()); boolean xpathRes =
 * evaluer(req.getResponseStream(), expr); System.out.println(xpathRes);
 *  } catch (Exception e) { e.printStackTrace(); } }
 */

/*
 * public static void main(String[] args) throws Exception { Object ct; try { ct =
 * (new URL("http://www.w3.org")).openConnection().getContentType(); //XmlObject
 * bidule = XmlObject.Factory.parse("http://www.w3.org");
 * 
 * System.out.println(bidule); // System.out.println(ct);
 * //ct.selectPath(xPath); String xPath = "(//doctype eq '-//W3C//DTD XHTML 1.0
 * Strict//EN') or (//doctype eq '-//W3C//DTD HTML 4.01//EN')" ;
 * //System.out.println(ct.selectPath(xPath));
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 *  } catch (MalformedURLException e) { e.printStackTrace(); } catch
 * (IOException e) { e.printStackTrace(); }
 *  }
 */


--- NEW FILE: HiepTest.java ---
package org.w3c.unicorn.tests;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import org.w3c.unicorn.UnicornCall;
import org.w3c.unicorn.contract.EnumInputMethod;
import org.w3c.unicorn.output.OutputFactory;
import org.w3c.unicorn.output.OutputFormater;
import org.w3c.unicorn.output.OutputModule;

public class HiepTest {

	public static void main(String[] args) {

		UnicornCall aUnicornCall = new UnicornCall();
		aUnicornCall.setTask("conformance"); // task id
		aUnicornCall.setEnumInputMethod(EnumInputMethod.URI);
		aUnicornCall.setDocumentName("http://w3.org");
		aUnicornCall.setInputParameterValue("http://w3.org");
		aUnicornCall.setLang("en");

		try {
			aUnicornCall.doTask();

			Map<String, Object> mapOfStringObject = new LinkedHashMap<String, Object>();
			mapOfStringObject.put("unicorncall", aUnicornCall);
			OutputFormater aOutputFormater = OutputFactory.getOutputFormater(
					"xhtml10", // le template --> text ou xhtml10, see
								// unicorn.properties
					"en", // la langue
					"text/plain"); // MIME Type
			OutputModule aOutputModule = OutputFactory
					.getOutputModule("simple");
			PrintWriter pw = new PrintWriter(System.out);
			aOutputModule.produceOutput(aOutputFormater, mapOfStringObject,
					null, pw);
			pw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

--- NEW FILE: TaskTest.java ---
/**
 * 
 */
package org.w3c.unicorn.tests;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.xmlbeans.XmlException;
import org.w3.unicorn.tasklist.TaskType;
import org.w3.unicorn.tasklist.TasklistDocument;
import org.w3c.unicorn.tasklist.Task;
import org.w3c.unicorn.tasklist.TaskListUnmarshallerBeans;

/**
 * @author shenril
 * 
 */
public class TaskTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			TasklistDocument tasklist = TasklistDocument.Factory
					.parse(new File("./resources/tasklist/new-tasklist.xml"));
			TaskListUnmarshallerBeans unmarshaller = new TaskListUnmarshallerBeans();
			Task aTask = new Task();
			aTask.setTree(unmarshaller.ExpandTree(tasklist.getTasklist()
					.getTaskArray(0)));
			Map<String, Task> mapOfTask = new LinkedHashMap<String, Task>();
			for (TaskType myTask : tasklist.getTasklist().getTaskArray()) {
				Task bTask = new Task();
				aTask.setTree(unmarshaller.ExpandTree(myTask));
				mapOfTask.put(bTask.getID(), bTask);
			}
			aTask.setTree(aTask.expandNode(mapOfTask, aTask.getTree()));
			aTask.displayTree(aTask.getTree());
		} catch (XmlException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

--- NEW FILE: CommandLine.java ---
// $Id: CommandLine.java,v 1.1.2.1 2009/08/11 16:05:31 tgambet Exp $
// Author: Damien LEROY.
// (c) COPYRIGHT MIT, ERCIM ant Keio, 2006.
// Please first read the full copyright statement in file COPYRIGHT.html
package org.w3c.unicorn.tests;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.unicorn.UnicornCall;
import org.w3c.unicorn.contract.EnumInputMethod;
import org.w3c.unicorn.output.EnumOutputModule;
import org.w3c.unicorn.output.OutputFactory;
import org.w3c.unicorn.output.OutputModule;

/**
 * Class to call the framework by command line.
 * 
 * @author Damien LEROY
 */
public class CommandLine {

	private static final Log logger = LogFactory
			.getLog("org.w3c.unicorn.tests");

	private static String sTaskID = "all";

	private static Map<String, String[]> mapOfParameter = new LinkedHashMap<String, String[]>();

	private static EnumInputMethod aEnumInputMethod = null;

	private static String sEnumInputMethodValue = null;

	private static OutputModule aOutputModule = null;

	/**
	 * Launches the Unicorn Framework.
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		CommandLine.logger.trace("Unicorn Framework Begin.");

		CommandLine.logger.info("Read command-line arguments.");
		for (int i = 0; i < args.length; i++) {
			if (CommandLine.logger.isDebugEnabled()) {
				CommandLine.logger.debug("Argument : " + args[i] + ".");
			}
			if ("-task".equals(args[i])) {
				i++;
				CommandLine.sTaskID = args[i];
				if (CommandLine.logger.isDebugEnabled()) {
					CommandLine.logger.debug("Task : " + CommandLine.sTaskID
							+ ".");
				}
			} else if ("-inputmethod".equals(args[i])) {
				i++;
				String[] tString = args[i].split("=");
				CommandLine.aEnumInputMethod = EnumInputMethod
						.fromValue(tString[0]);
				if (2 <= tString.length) {
					CommandLine.sEnumInputMethodValue = tString[1];
				}
				if (CommandLine.logger.isDebugEnabled()) {
					CommandLine.logger.debug("Input method : "
							+ CommandLine.aEnumInputMethod.toString()
							+ ", value : " + CommandLine.sEnumInputMethodValue
							+ ".");
				}
			} else if ("-outputmethod".equals(args[i])) {
				i++;
				String sOutputMethod = args[i];
				final EnumOutputModule aEnumOutputModule = EnumOutputModule
						.fromValue(sOutputMethod);
				if (null == aEnumOutputModule) {
					CommandLine.logger.error("Unknow output method : "
							+ sOutputMethod + ".");
					return;
				}
				CommandLine.aOutputModule = OutputFactory
						.getOutputModule(aEnumOutputModule);
			} else if (args[i].contains("=")) {
				String[] tString = args[i].split("=");
				String[] val = { tString[1] };
				CommandLine.mapOfParameter.put(tString[0], val);
			}
		}

		if (null == CommandLine.aEnumInputMethod) {
			CommandLine.logger.error("No input method specified.");
			return;
		}

		if (null == CommandLine.aOutputModule) {
			CommandLine.logger
					.info("No output method specified use SimpleOutputModule by default.");
			CommandLine.aOutputModule = OutputFactory
					.getOutputModule(EnumOutputModule.SIMPLE);
		}

		if (EnumInputMethod.DIRECT.equals(CommandLine.aEnumInputMethod)) {
			// read on standard input and add to Main.eimValue
			String sEnumInputMethodValue = "";
			for (int i = System.in.read(); -1 != i; i = System.in.read()) {
				sEnumInputMethodValue += (char) i;
			}
			if (CommandLine.logger.isDebugEnabled()) {
				CommandLine.logger.debug("Direct Input :\n"
						+ sEnumInputMethodValue);
			}
			CommandLine.sEnumInputMethodValue = sEnumInputMethodValue;
		}

		CommandLine.logger.info("Initialize framework.");
		UnicornCall aUnicornCall = new UnicornCall();
		aUnicornCall.setTask(CommandLine.sTaskID);
		aUnicornCall.setEnumInputMethod(CommandLine.aEnumInputMethod);
		// CommandLine.sEnumInputMethodValue
		aUnicornCall.setMapOfStringParameter(CommandLine.mapOfParameter);
		if (CommandLine.logger.isDebugEnabled()) {
			CommandLine.logger.debug("UnicornCall : " + aUnicornCall + ".");
		}

		CommandLine.logger.info("Process request.");
		// Main.mapOfParameter.put("warning", "2");
		aUnicornCall.doTask();

		CommandLine.logger.trace("Unicorn Framework End.");
	}

}

--- NEW FILE: XMLBeansTest.java ---
// $Id: XMLBeansTest.java,v 1.1.2.1 2009/08/11 16:05:30 tgambet Exp $
// Author: Jean-Guilhem Rouel
// (c) COPYRIGHT MIT, ERCIM and Keio, 2006.
// Please first read the full copyright statement in file COPYRIGHT.html
package org.w3c.unicorn.tests;

import java.io.IOException;

import org.apache.xmlbeans.XmlException;
import org.w3.unicorn.observationresponse.ObservationresponseDocument;

/**
 * XmlBeansTest<br />
 * Created: Jun 26, 2006 12:05:50 PM<br />
 * 
 * @author Batard Florent
 */
public class XMLBeansTest {

	public static void main(String[] args) throws XmlException, IOException {

		// Bind the instance to the generated XMLBeans types.
		ObservationresponseDocument ObsDoc = null;
		try {
			ObsDoc = ObservationresponseDocument.Factory
					.parse(new java.io.File("./target.xml"));
		} catch (XmlException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		ObservationresponseDocument.Observationresponse obs = ObsDoc
				.getObservationresponse();
		// Get and print pieces of the XML instance.

		System.out.println(obs.getResult().getErrors().getErrorlistArray(0)
				.getErrorArray(0).getLongmessageArray(0));
		System.out.println(obs.getResult().getErrors().getErrorlistArray(0)
				.getErrorArray(0).getMessageArray(0));
	}

}

--- NEW FILE: UnicornClientDirectInputTest.java ---
package org.w3c.unicorn.tests;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import org.w3c.unicorn.UnicornCall;
import org.w3c.unicorn.contract.EnumInputMethod;
import org.w3c.unicorn.output.OutputFactory;
import org.w3c.unicorn.output.OutputFormater;
import org.w3c.unicorn.output.OutputModule;
import org.w3c.unicorn.util.Property;

public class UnicornClientDirectInputTest {

	public static void main(String[] args) {

		UnicornCall aUnicornCall = new UnicornCall();
		aUnicornCall.setTask("css"); // task id
		aUnicornCall.setEnumInputMethod(EnumInputMethod.DIRECT);
		aUnicornCall.setLang("en");

		aUnicornCall
				.setDocumentName("D:/stageW3C/unicorn/style/base_result.css");

		Map<String, String[]> mapOfParameter = new LinkedHashMap<String, String[]>();
		String[] tmp = { "text/css" };
		mapOfParameter.put(Property.get("UNICORN_PARAMETER_PREFIX") + "mime",
				tmp);
		aUnicornCall.setMapOfStringParameter(mapOfParameter);

		aUnicornCall
				.setInputParameterValue("p#msie { /* msie-bug note for text/plain */ float: right; border: 1px solid black; background: white;}");

		try {

			aUnicornCall.doTask();

			Map<String, Object> mapOfStringObject = new LinkedHashMap<String, Object>();
			mapOfStringObject.put("unicorncall", aUnicornCall);
			OutputFormater aOutputFormater = OutputFactory.getOutputFormater(
					"text10", // le template --> text ou xhtml10, see
								// unicorn.properties
					"en", // la langue
					"text/plain"); // MIME Type
			OutputModule aOutputModule = OutputFactory
					.getOutputModule("simple");
			PrintWriter pw = new PrintWriter(System.out);
			aOutputModule.produceOutput(aOutputFormater, mapOfStringObject,
					null, pw);
			pw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Received on Tuesday, 11 August 2009 16:09:04 UTC

This archive was generated by hypermail 2.3.1 : Wednesday, 7 January 2015 15:17:37 UTC