All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.liferay.poshi.runner.PoshiRunnerGetterUtil Maven / Gradle / Ivy

/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.liferay.poshi.runner;

import com.google.common.reflect.ClassPath;

import com.liferay.poshi.runner.elements.PoshiElement;
import com.liferay.poshi.runner.elements.PoshiNode;
import com.liferay.poshi.runner.elements.PoshiNodeFactory;
import com.liferay.poshi.runner.prose.PoshiProseDefinition;
import com.liferay.poshi.runner.selenium.SeleniumUtil;
import com.liferay.poshi.runner.util.Dom4JUtil;
import com.liferay.poshi.runner.util.ExternalMethod;
import com.liferay.poshi.runner.util.FileUtil;
import com.liferay.poshi.runner.util.GetterUtil;
import com.liferay.poshi.runner.util.OSDetector;
import com.liferay.poshi.runner.util.PropsUtil;
import com.liferay.poshi.runner.util.PropsValues;
import com.liferay.poshi.runner.util.StringUtil;
import com.liferay.poshi.runner.util.Validator;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

import java.net.URL;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @author Karen Dang
 * @author Michael Hashimoto
 */
public class PoshiRunnerGetterUtil {

	public static List getAllChildElements(
		Element element, String elementName) {

		List allChildElements = new ArrayList<>();

		List childElements = element.elements();

		if (childElements.isEmpty()) {
			return allChildElements;
		}

		for (Element childElement : childElements) {
			String childElementName = childElement.getName();

			if (childElementName.equals(elementName)) {
				allChildElements.add(childElement);
			}

			allChildElements.addAll(
				getAllChildElements(childElement, elementName));
		}

		return allChildElements;
	}

	public static String getClassCommandNameFromNamespacedClassCommandName(
		String namespacedClassCommandName) {

		Matcher matcher = _namespacedClassCommandNamePattern.matcher(
			namespacedClassCommandName);

		if (matcher.find()) {
			String className = matcher.group("className");

			String commandName = matcher.group("commandName");

			if (Validator.isNotNull(commandName)) {
				return className + "#" + commandName;
			}

			return className;
		}

		throw new RuntimeException(
			"Unable to find class name and/or command name in " +
				namespacedClassCommandName);
	}

	public static String getClassNameFromFilePath(String filePath) {
		int x = filePath.lastIndexOf("/");
		int y = filePath.lastIndexOf(".");

		if ((x == -1) && OSDetector.isWindows()) {
			x = filePath.lastIndexOf("\\");
		}

		return filePath.substring(x + 1, y);
	}

	public static String getClassNameFromNamespacedClassCommandName(
		String namespacedClassCommandName) {

		Matcher matcher = _namespacedClassCommandNamePattern.matcher(
			namespacedClassCommandName);

		if (matcher.find()) {
			return matcher.group("className");
		}

		throw new RuntimeException(
			"Unable to find class name in " + namespacedClassCommandName);
	}

	public static String getClassNameFromNamespacedClassName(
		String namespacedClassName) {

		Matcher matcher = _namespacedClassCommandNamePattern.matcher(
			namespacedClassName);

		if (matcher.find()) {
			return matcher.group("className");
		}

		throw new RuntimeException(
			"Unable to find class name in " + namespacedClassName);
	}

	public static String getClassTypeFromFileExtension(String fileExtension) {
		String classType = fileExtension;

		if (fileExtension.equals("testcase") || fileExtension.equals("prose")) {
			classType = "test-case";
		}

		return classType;
	}

	public static String getClassTypeFromFilePath(String filePath) {
		String fileExtension = getFileExtensionFromFilePath(filePath);

		return getClassTypeFromFileExtension(fileExtension);
	}

	public static String getCommandNameFromNamespacedClassCommandName(
		String namespacedClassCommandName) {

		Matcher matcher = _namespacedClassCommandNamePattern.matcher(
			namespacedClassCommandName);

		if (matcher.find()) {
			String commandName = matcher.group("commandName");

			if (Validator.isNull(commandName)) {
				return namespacedClassCommandName;
			}

			return commandName;
		}

		throw new RuntimeException(
			"Unable to find command name in " + namespacedClassCommandName);
	}

	public static String getExtendedTestCaseName() {
		String testName = PropsValues.TEST_NAME;

		Element rootElement = PoshiRunnerContext.getTestCaseRootElement(
			getClassNameFromNamespacedClassCommandName(testName),
			getNamespaceFromNamespacedClassCommandName(testName));

		return getExtendedTestCaseName(rootElement);
	}

	public static String getExtendedTestCaseName(Element rootElement) {
		return rootElement.attributeValue("extends");
	}

	public static String getExtendedTestCaseName(String filePath) {
		Element rootElement = PoshiRunnerContext.getTestCaseRootElement(
			getClassNameFromFilePath(filePath),
			PoshiRunnerContext.getNamespaceFromFilePath(filePath));

		return getExtendedTestCaseName(rootElement);
	}

	public static String getFileExtensionFromClassType(String classType) {
		String fileExtension = classType;

		if (fileExtension.equals("test-case")) {
			fileExtension = "testcase";
		}

		return fileExtension;
	}

	public static String getFileExtensionFromFilePath(String filePath) {
		int x = filePath.lastIndexOf(".");

		return filePath.substring(x + 1);
	}

	public static String getFileNameFromFilePath(String filePath) {
		String className = getClassNameFromFilePath(filePath);
		String fileExtension = getFileExtensionFromFilePath(filePath);

		return className + "." + fileExtension;
	}

	public static int getLineNumber(Element element) {
		if (element instanceof PoshiElement) {
			PoshiElement poshiElement = (PoshiElement)element;

			return poshiElement.getPoshiScriptLineNumber();
		}

		String lineNumber = element.attributeValue("line-number");

		if (lineNumber != null) {
			return Integer.valueOf(lineNumber);
		}

		return -1;
	}

	public static Object getMethodReturnValue(
			List args, String className, String methodName,
			Object object)
		throws Exception {

		if (!className.equals("selenium")) {
			if (!className.contains(".")) {
				className = getUtilityClassName(className);
			}
			else {
				if (!isValidUtilityClass(className)) {
					throw new IllegalArgumentException(
						className + " is not a valid class name");
				}
			}
		}

		Object[] parameters = new Object[args.size()];

		for (int i = 0; i < args.size(); i++) {
			String arg = args.get(i);

			Matcher matcher = _variablePattern.matcher(arg);

			Object parameter = null;

			if (matcher.matches()) {
				parameter = PoshiRunnerVariablesUtil.getValueFromCommandMap(
					matcher.group(1));
			}
			else {
				parameter = PoshiRunnerVariablesUtil.replaceCommandVars(arg);
			}

			if (className.endsWith("MathUtil") &&
				(parameter instanceof String)) {

				parameter = GetterUtil.getInteger((String)parameter);
			}
			else if (className.endsWith("StringUtil")) {
				parameter = String.valueOf(parameter);
			}

			parameters[i] = parameter;
		}

		Object returnObject = null;

		if (object != null) {
			returnObject = ExternalMethod.execute(
				methodName, object, parameters);
		}
		else {
			returnObject = ExternalMethod.execute(
				className, methodName, parameters);
		}

		return returnObject;
	}

	public static String getNamespacedClassNameFromNamespacedClassCommandName(
		String namespacedClassCommandName) {

		Matcher matcher = _namespacedClassCommandNamePattern.matcher(
			namespacedClassCommandName);

		if (matcher.find()) {
			String namespace = matcher.group("namespace");

			if (Validator.isNull(namespace)) {
				namespace = PoshiRunnerStackTraceUtil.getCurrentNamespace();
			}

			String className = matcher.group("className");

			return namespace + "." + className;
		}

		throw new RuntimeException(
			"Unable to find class name in " + namespacedClassCommandName);
	}

	public static String getNamespaceFromNamespacedClassCommandName(
		String namespacedClassCommandName) {

		Matcher matcher = _namespacedClassCommandNamePattern.matcher(
			namespacedClassCommandName);

		if (matcher.find()) {
			String namespace = matcher.group("namespace");

			if (Validator.isNull(namespace)) {
				namespace = PoshiRunnerStackTraceUtil.getCurrentNamespace();
			}

			return namespace;
		}

		throw new RuntimeException(
			"Unable to find namespace in " + namespacedClassCommandName);
	}

	public static String getNamespaceFromNamespacedClassName(
		String namespacedClassName) {

		Matcher matcher = _namespacedClassCommandNamePattern.matcher(
			namespacedClassName);

		if (matcher.find()) {
			String namespace = matcher.group("namespace");

			if (Validator.isNull(namespace)) {
				namespace = PoshiRunnerStackTraceUtil.getCurrentNamespace();
			}

			return namespace;
		}

		throw new RuntimeException(
			"Unable to find namespace in " + namespacedClassName);
	}

	public static String getProjectDirName() {
		return FileUtil.getCanonicalPath(PropsValues.PROJECT_DIR);
	}

	public static Element getRootElementFromURL(URL url) throws Exception {
		return getRootElementFromURL(url, true);
	}

	public static Element getRootElementFromURL(URL url, boolean addLineNumbers)
		throws Exception {

		String fileContent = FileUtil.read(url);
		String filePath = url.getFile();

		if (fileContent.endsWith("}") &&
			(filePath.endsWith(".function") || filePath.endsWith(".macro") ||
			 filePath.endsWith(".testcase"))) {

			PoshiNode poshiNode = PoshiNodeFactory.newPoshiNodeFromFile(
				url);

			if (poshiNode instanceof PoshiElement) {
				return (Element)poshiNode;
			}
		}

		if (filePath.endsWith(".prose")) {
			PoshiProseDefinition poshiProseDefinition =
				new PoshiProseDefinition(
					getFileNameFromFilePath(filePath), fileContent);

			fileContent = Dom4JUtil.format(poshiProseDefinition.toElement());
		}

		BufferedReader bufferedReader = new BufferedReader(
			new StringReader(fileContent));

		boolean cdata = false;
		String line = null;
		int lineNumber = 1;
		StringBuilder sb = new StringBuilder();

		while ((line = bufferedReader.readLine()) != null) {
			Matcher matcher = _tagPattern.matcher(line);

			if (line.contains("")) {
					cdata = false;
				}
				else {
					cdata = true;
				}

				if (line.contains("");

						if (y == -1) {
							y = line.indexOf(">");
						}
					}

					String tagName = line.substring(x + 1, y);

					throw new Exception(
						"Invalid \"" + tagName + "\" tag\n" + filePath + ":" +
							lineNumber);
				}
			}

			sb.append(line);

			if (cdata) {
				sb.append("\n");
			}

			lineNumber++;
		}

		String content = sb.toString();

		InputStream inputStream = new ByteArrayInputStream(
			content.getBytes("UTF-8"));

		SAXReader saxReader = new SAXReader();

		Document document = null;

		try {
			document = saxReader.read(inputStream);
		}
		catch (DocumentException documentException) {
			throw new Exception(
				documentException.getMessage() + "\nInvalid syntax in " +
					filePath,
				documentException);
		}

		return document.getRootElement();
	}

	public static String getUtilityClassName(String simpleClassName) {
		if (_utilityClassMap.containsKey(simpleClassName)) {
			return _utilityClassMap.get(simpleClassName);
		}

		throw new IllegalArgumentException(
			simpleClassName + " is not a valid simple class name");
	}

	public static Object getVarMethodValue(
			String expression, String defaultNamespace)
		throws Exception {

		List args = new ArrayList<>();

		int x = expression.indexOf("(");
		int y = expression.lastIndexOf(")");

		if ((x + 1) < y) {
			String parameterString = expression.substring(x + 1, y);

			Matcher parameterMatcher = _parameterPattern.matcher(
				parameterString);

			while (parameterMatcher.find()) {
				String parameterValue = parameterMatcher.group();

				if (parameterValue.startsWith("'") &&
					parameterValue.endsWith("'")) {

					parameterValue = parameterValue.substring(
						1, parameterValue.length() - 1);
				}

				Matcher matcher = _locatorKeyPattern.matcher(parameterValue);

				if (matcher.matches()) {
					String namespace = matcher.group("namespace");

					if (namespace == null) {
						parameterValue = PoshiRunnerContext.getPathLocator(
							parameterValue, defaultNamespace);
					}
					else {
						parameterValue = PoshiRunnerContext.getPathLocator(
							parameterValue, namespace);
					}
				}

				if (parameterValue.contains("\'")) {
					parameterValue = parameterValue.replaceAll("\\\\'", "'");
				}

				args.add(parameterValue);
			}
		}

		y = expression.indexOf("#");

		String className = expression.substring(0, y);
		String methodName = expression.substring(y + 1, x);

		Object object = null;

		if (className.equals("selenium")) {
			object = SeleniumUtil.getSelenium();
		}

		return getMethodReturnValue(args, className, methodName, object);
	}

	public static boolean isValidUtilityClass(String className) {
		if (_utilityClassMap.containsValue(className)) {
			return true;
		}

		return false;
	}

	private static final Pattern _locatorKeyPattern = Pattern.compile(
		"(?[\\w]+\\.)?[\\w]+#[A-Z0-9_]+");
	private static final Pattern _namespacedClassCommandNamePattern =
		Pattern.compile(
			"((?\\w+)\\.)?(?\\w+)(\\#(?" +
				"(\\w+(\\-\\w+)*|\\$\\{\\w+\\}|\\w+|\\s*\\w+)*))?");
	private static final Pattern _parameterPattern = Pattern.compile(
		"('([^'\\\\]|\\\\.)*'|[^',\\s]+)");
	private static final List _reservedTags = Arrays.asList(
		"and", "arg", "body", "case", "command", "condition", "contains",
		"default", "definition", "description", "echo", "else", "elseif",
		"equals", "execute", "fail", "for", "if", "head", "html", "isset",
		"not", "off", "on", "or", "property", "prose", "return", "set-up",
		"table", "take-screenshot", "task", "tbody", "td", "tear-down", "thead",
		"then", "title", "tr", "var", "while");
	private static final Pattern _tagPattern = Pattern.compile("<[a-z\\-]+");

	private static final Map _utilityClassMap =
		new TreeMap() {
			{
				try {
					ClassPath classPath = ClassPath.from(
						PropsUtil.class.getClassLoader());

					for (ClassPath.ClassInfo classInfo :
							classPath.getTopLevelClasses(
								"com.liferay.poshi.runner.util")) {

						put(classInfo.getSimpleName(), classInfo.getName());
					}
				}
				catch (IOException ioException) {
					throw new RuntimeException(ioException);
				}
			}
		};

	private static final Pattern _variablePattern = Pattern.compile(
		"\\$\\{([^}]*)\\}");

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy