diff --git a/Common/pom.xml b/Common/pom.xml index 6b76a6b8..d49a9fe4 100644 --- a/Common/pom.xml +++ b/Common/pom.xml @@ -5,7 +5,7 @@ com.ing ingenious-playwright - 2.3.1 + 2.4 Common diff --git a/Datalib/pom.xml b/Datalib/pom.xml index 0ce83e3c..d414f53e 100644 --- a/Datalib/pom.xml +++ b/Datalib/pom.xml @@ -4,7 +4,7 @@ com.ing ingenious-playwright - 2.3.1 + 2.4 ingenious-datalib jar diff --git a/Datalib/src/main/java/com/ing/datalib/component/Project.java b/Datalib/src/main/java/com/ing/datalib/component/Project.java index 18ec1bfc..1f099678 100644 --- a/Datalib/src/main/java/com/ing/datalib/component/Project.java +++ b/Datalib/src/main/java/com/ing/datalib/component/Project.java @@ -11,9 +11,12 @@ import com.ing.datalib.util.data.FileScanner; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.ing.datalib.or.web.WebOR.ORScope; import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.LinkedHashSet; +import java.util.Set; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; @@ -23,8 +26,21 @@ import javax.swing.table.TableModel; /** + * Represents an automation project and acts as the central entry point for loading, managing, + * and persisting project data from disk. + *

+ * A {@code Project} encapsulates the project’s filesystem location and name, and maintains the + * in-memory model of core assets such as scenarios (TestPlan), releases/test sets (TestLab), + * environment test data, project settings, and the {@link ObjectRepository}. It supports loading + * and reloading from disk, saving all managed components, and producing table models for UI + * components via {@code getTableModelFor(...)}. + *

* - * + *

+ * The class also provides refactoring utilities that propagate renames across scenarios, releases, + * and test data (e.g., scenario/test case renames, page/object reference updates, and test data + * renames), including scope-aware refactoring for Object Repository references where applicable. + *

*/ public class Project { @@ -211,7 +227,9 @@ public Boolean rename(String newName) { } } getObjectRepository().getWebOR().setName(newName); + getObjectRepository().getWebSharedOR().setName(newName); getObjectRepository().getMobileOR().setName(newName); + getObjectRepository().getMobileSharedOR().setName(newName); return true; } return false; @@ -395,7 +413,7 @@ public void refactorTestCaseScenario(String testCaseName, String oldScenarioName .ifPresent(scn -> scn.setName(newScenarioName)); }); } - + public void refactorObjectName(String pageName, String oldName, String newName) { for (Scenario scenario : scenarios) { scenario.refactorObjectName(pageName, oldName, newName); @@ -408,12 +426,57 @@ public void refactorObjectName(String oldpageName, String oldObjName, String new } } + /** + * Renames an object reference on the given page for the specified OR scope across the project, + * by delegating to all scenarios. + * + * @param scope OR scope to match (e.g., shared vs project) + * @param pageName page (screen) name containing the object reference + * @param oldName existing object name to replace + * @param newName new object name to apply + */ + public void refactorObjectName(ORScope scope, String pageName, String oldName, String newName) { + for (Scenario scenario : scenarios) { + scenario.refactorObjectName(scope, pageName, oldName, newName); + } + } + public void refactorPageName(String oldPageName, String newPageName) { for (Scenario scenario : scenarios) { scenario.refactorPageName(oldPageName, newPageName); } } + /** + * Refactors (renames) a page reference across the project for a given Object Repository scope. + *

+ * In addition to delegating the rename for the raw page names, this method also renames + * scope-qualified page names using the convention: + *

+ * For each {@link Scenario}, it applies both: + * {@code scenario.refactorPageName(oldPageName, newPageName)} and + * {@code scenario.refactorPageName(oldScoped, newScoped)}. + *

+ * + * @param scope the Object Repository scope used to derive the scoped page name prefix + * @param oldPageName the original page name to be replaced + * @param newPageName the new page name to apply + * + * @implNote This method performs two refactors per scenario: one for the plain page name and one + * for the derived scoped form (e.g., {@code "[Shared] Login"}). + */ + public void refactorPageName(ORScope scope, String oldPageName, String newPageName) { + String oldScoped = scope == ORScope.SHARED ? "[Shared] " + oldPageName : "[Project] " + oldPageName; + String newScoped = scope == ORScope.SHARED ? "[Shared] " + newPageName : "[Project] " + newPageName; + for (Scenario scenario : scenarios) { + scenario.refactorPageName(oldPageName, newPageName); + scenario.refactorPageName(oldScoped, newScoped); + } + } + public void refactorTestData(String oldTDName, String newTDName) { for (Scenario scenario : scenarios) { scenario.refactorTestData(oldTDName, newTDName); @@ -434,6 +497,23 @@ public List getImpactedObjectTestCases(String pageName, String objectN return impactedTestCases; } + public List getImpactedObjectTestCases(ORScope scope, String pageName, String objectName) { + Set impacted = new LinkedHashSet<>(); + String scopedPageName = null; + if (scope != null) { + scopedPageName = (scope == ORScope.SHARED) + ? "[Shared] " + pageName + : "[Project] " + pageName; + } + for (Scenario scenario : scenarios) { + impacted.addAll(scenario.getImpactedObjectTestCases(pageName, objectName)); + if (scopedPageName != null) { + impacted.addAll(scenario.getImpactedObjectTestCases(scopedPageName, objectName)); + } + } + return new ArrayList<>(impacted); + } + public List getImpactedTestCaseTestCases(String scenarioName, String testCaseName) { List impactedTestCases = new ArrayList<>(); for (Scenario scenario : scenarios) { @@ -520,5 +600,4 @@ private static DataItem fromTS(TestSet ts) { } } } - -} +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/component/Scenario.java b/Datalib/src/main/java/com/ing/datalib/component/Scenario.java index 25adef32..2e9a36be 100644 --- a/Datalib/src/main/java/com/ing/datalib/component/Scenario.java +++ b/Datalib/src/main/java/com/ing/datalib/component/Scenario.java @@ -2,13 +2,25 @@ package com.ing.datalib.component; import com.ing.datalib.component.utils.FileUtils; +import com.ing.datalib.or.web.WebOR.ORScope; import java.io.File; import java.util.ArrayList; import java.util.List; /** + * Represents a scenario within a project’s TestPlan and serves as a container for related test cases. + *

+ * A {@code Scenario} is backed by a filesystem folder under {@code /TestPlan/}, + * automatically loads its {@link TestCase} CSV files on construction, and exposes methods for adding, + * removing, loading, and saving test cases. + *

* - * + *

+ * The class also implements {@code DataModel} table-model behavior for UI consumption by presenting + * a scenario-level view of non-reusable test cases, and provides refactoring and impact-analysis helpers + * that delegate to contained test cases (e.g., object/page/test data reference updates and impacted test + * case discovery). + *

*/ public class Scenario extends DataModel { @@ -279,6 +291,21 @@ public void refactorObjectName(String oldpageName, String oldObjName, String new } } + /** + * Renames an object reference on the given page for the specified OR scope within this scenario, + * by delegating to all test cases. + * + * @param scope OR scope to match (e.g., shared vs project) + * @param pageName page (screen) name containing the object reference + * @param oldName existing object name to replace + * @param newName new object name to apply + */ + public void refactorObjectName(ORScope scope, String pageName, String oldName, String newName) { + for (TestCase testCase : testCases) { + testCase.refactorObjectName(scope, pageName, oldName, newName); + } + } + public void refactorPageName(String oldPageName, String newPageName) { for (TestCase testCase : testCases) { testCase.refactorPageName(oldPageName, newPageName); @@ -350,5 +377,4 @@ public Boolean delete() { } return false; } - -} +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/component/TestCase.java b/Datalib/src/main/java/com/ing/datalib/component/TestCase.java index c0332c6e..a22eb8a9 100644 --- a/Datalib/src/main/java/com/ing/datalib/component/TestCase.java +++ b/Datalib/src/main/java/com/ing/datalib/component/TestCase.java @@ -4,6 +4,7 @@ import com.ing.datalib.component.TestStep.HEADERS; import com.ing.datalib.component.utils.FileUtils; import com.ing.datalib.component.utils.SaveListener; +import com.ing.datalib.or.web.WebOR.ORScope; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; @@ -18,8 +19,21 @@ import org.apache.commons.csv.CSVRecord; /** + * Represents a test case composed of ordered {@link TestStep} entries and implements a table model + * suitable for direct editing in UI components. + *

+ * A {@code TestCase} belongs to a {@link Scenario}, loads and persists its steps from/to a CSV file, + * and supports common editing operations such as inserting, removing, moving, replicating steps, + * clearing values, toggling comments/breakpoints, and bulk removal. Save state is tracked and propagated + * via a {@link SaveListener}. + *

* - * + *

+ * The class also supports creating and managing reusable test cases (represented as “Execute” steps), + * provides utilities for refactoring references (scenario/test case reuse links, object/page names, + * test data and columns—including scope-aware OR references), and can report impact when a given object, + * reusable, or test data reference is used. + *

*/ public class TestCase extends DataModel { @@ -557,7 +571,11 @@ public void refactorObjectName(String pageName, String oldName, String newName) Boolean clearOnExit = getTestSteps().isEmpty(); loadTableModel(); for (TestStep testStep : testSteps) { - if (testStep.getReference().equals(pageName) && testStep.getObject().equals(oldName)) { + String ref = Objects.toString(testStep.getReference(), ""); + String obj = Objects.toString(testStep.getObject(), ""); + String normalizedRef = normalizePageRef(ref); + + if (normalizedRef.equals(pageName) && obj.equals(oldName)) { testStep.setObject(newName); } } @@ -566,22 +584,85 @@ public void refactorObjectName(String pageName, String oldName, String newName) getTestSteps().clear(); } } - + public void refactorObjectName(String oldpageName, String oldObjName, String newPageName, String newObjName) { Boolean clearOnExit = getTestSteps().isEmpty(); loadTableModel(); + for (TestStep testStep : testSteps) { - if (testStep.getReference().equals(oldpageName) && testStep.getObject().equals(oldObjName)) { + String ref = normalizePageRef(Objects.toString(testStep.getReference(), "")); + String obj = Objects.toString(testStep.getObject(), ""); + if (ref.equals(oldpageName) && obj.equals(oldObjName)) { testStep.setObject(newObjName); testStep.setReference(newPageName); } } + if (clearOnExit) { save(); getTestSteps().clear(); } } + /** + * Renames an object reference on the given page within this test case, restricted to the specified OR scope. + * A step matches when its reference has the expected scope prefix and its normalized page name equals {@code pageName}. + * + * @param scope OR scope to match (e.g., {@code PROJECT} or {@code SHARED}) + * @param pageName page (screen) name (without scope prefix) to match + * @param oldName existing object name to replace + * @param newName new object name to apply + */ + public void refactorObjectName(ORScope scope, String pageName, String oldName, String newName) { + Boolean clearOnExit = getTestSteps().isEmpty(); + loadTableModel(); + for (TestStep testStep : testSteps) { + String refRaw = Objects.toString(testStep.getReference(), ""); + String obj = Objects.toString(testStep.getObject(), ""); + boolean scopedMatch = matchesScope(refRaw, scope) && normalizePageRef(refRaw).equals(pageName); + if (scopedMatch && obj.equals(oldName)) { + testStep.setObject(newName); + } + } + if (clearOnExit) { + save(); + getTestSteps().clear(); + } + } + + /** + * Checks whether a reference string is explicitly scoped for the given OR scope. + * Returns {@code true} only when {@code ref} starts with the expected scope prefix + * (e.g., {@code "[Project] "} or {@code "[Shared] "}); otherwise returns {@code false}. + * + * @param ref raw reference value (may be {@code null}) + * @param scope scope to match against + * @return {@code true} if {@code ref} begins with the prefix for {@code scope}; {@code false} otherwise + */ + private boolean matchesScope(String ref, ORScope scope) { + if (ref == null) return false; + ref = ref.trim(); + if (scope == ORScope.PROJECT) return ref.startsWith("[Project] "); + if (scope == ORScope.SHARED) return ref.startsWith("[Shared] "); + return false; + } + + /** + * Normalizes a page reference by removing known scope prefixes. + * Trims the input and strips {@code "[Project] "} or {@code "[Shared] "} when present; + * otherwise returns the trimmed reference. Returns an empty string when {@code ref} is {@code null}. + * + * @param ref raw reference value (may be {@code null}) + * @return normalized page name without scope prefix (never {@code null}) + */ + private String normalizePageRef(String ref) { + if (ref == null) return ""; + ref = ref.trim(); + if (ref.startsWith("[Project] ")) return ref.substring("[Project] ".length()).trim(); + if (ref.startsWith("[Shared] ")) return ref.substring("[Shared] ".length()).trim(); + return ref; + } + public void refactorPageName(String oldPageName, String newPageName) { Boolean clearOnExit = getTestSteps().isEmpty(); loadTableModel(); @@ -662,5 +743,4 @@ public Boolean rename(String newName) { } return false; } - -} +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/component/TestStep.java b/Datalib/src/main/java/com/ing/datalib/component/TestStep.java index 96adb007..b72f3031 100644 --- a/Datalib/src/main/java/com/ing/datalib/component/TestStep.java +++ b/Datalib/src/main/java/com/ing/datalib/component/TestStep.java @@ -44,27 +44,31 @@ public static int size() { } - private final TestCase testcase; + private final TestCase testCase; List stepDetails = Collections.synchronizedList(new ArrayList(HEADERS.values().length) { @Override public String set(int index, String element) { String val = super.set(index, element); - if (testcase != null && testcase.getTestSteps().contains(TestStep.this)) { - testcase.fireTableCellUpdated(testcase.getTestSteps().indexOf(TestStep.this), + if (testCase != null && testCase.getTestSteps().contains(TestStep.this)) { + testCase.fireTableCellUpdated(testCase.getTestSteps().indexOf(TestStep.this), index); } return val; } }); + + public List getStepDetails(){ + return this.stepDetails; + } public TestStep(TestCase testcase, CSVRecord record) { - this.testcase = testcase; + this.testCase = testcase; loadStep(record); } public TestStep(TestCase testcase) { - this.testcase = testcase; + this.testCase = testcase; loadEmptyStep(); } @@ -131,11 +135,11 @@ public TestStep setDescription(String description) { } public Project getProject() { - return testcase.getProject(); + return testCase.getProject(); } - public TestCase getTestcase() { - return testcase; + public TestCase getTestCase() { + return testCase; } private void loadStep(CSVRecord record) { diff --git a/Datalib/src/main/java/com/ing/datalib/or/ObjectRepository.java b/Datalib/src/main/java/com/ing/datalib/or/ObjectRepository.java index 55c946fc..a4547c45 100644 --- a/Datalib/src/main/java/com/ing/datalib/or/ObjectRepository.java +++ b/Datalib/src/main/java/com/ing/datalib/or/ObjectRepository.java @@ -5,50 +5,116 @@ import com.ing.datalib.or.common.ORPageInf; import com.ing.datalib.or.common.ObjectGroup; import com.ing.datalib.or.mobile.MobileOR; +import com.ing.datalib.or.mobile.MobileORObject; +import com.ing.datalib.or.mobile.MobileORPage; import com.ing.datalib.or.web.WebOR; import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.ing.datalib.or.mobile.ResolvedMobileObject; +import com.ing.datalib.or.web.ResolvedWebObject; +import com.ing.datalib.or.web.WebOR.ORScope; +import com.ing.datalib.or.web.WebORObject; +import com.ing.datalib.or.web.WebORPage; import java.io.File; import java.io.IOException; +import java.util.HashSet; +import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** - * - * + * Manages all Object Repository types (Web Project OR, Web Shared OR, Mobile OR) + * for a project. Handles loading, saving, renaming, lookup, copying of pages and + * objects, and resolving objects across project/shared scopes. */ public class ObjectRepository { - private static final XmlMapper XML_MAPPER = new XmlMapper(); + private static final Logger LOG = Logger.getLogger(ObjectRepository.class.getName()); private final Project sProject; + private WebOR webSharedOR; + private WebOR webProjectOR; + private MobileOR mobileProjectOR; + private MobileOR mobileSharedOR; + + private final Set sharedUsageProjects = new HashSet<>(); - private WebOR webOR; - private MobileOR mobileOR; - + /** + * Creates an ObjectRepository for the given project and loads all OR files + * (project WebOR, shared WebOR, and MobileOR), initializing defaults when missing. + * + * @param sProject the project owning this repository + */ public ObjectRepository(Project sProject) { this.sProject = sProject; init(); } + /** + * Loads OR files from disk (shared, project, mobile), updates names, sets scopes, + * and links them to this repository. + */ private void init() { try { - if (new File(getORLocation()).exists()) { - webOR = XML_MAPPER.readValue(new File(getORLocation()), WebOR.class); - webOR.setName(sProject.getName()); + File sharedFile = new File(getSharedORLocation()); + if (sharedFile.exists()) { + webSharedOR = XML_MAPPER.readValue(sharedFile, WebOR.class); + webSharedOR.setName("Shared Web Objects"); + } else { + webSharedOR = new WebOR("Shared Web Objects"); + } + + File projFile = new File(getORLocation()); + if (projFile.exists()) { + webProjectOR = XML_MAPPER.readValue(projFile, WebOR.class); + webProjectOR.setName(sProject.getName()); + } else { + webProjectOR = new WebOR(sProject.getName()); + } + + File sharedmorFile = new File(getSharedMORLocation()); + if (sharedmorFile.exists()) { + mobileSharedOR = XML_MAPPER.readValue(sharedmorFile, MobileOR.class); + mobileSharedOR.setName("Shared Mobile Objects"); } else { - webOR = new WebOR(sProject.getName()); + mobileSharedOR = new MobileOR("Shared Mobile Objects"); } - if (new File(getMORLocation()).exists()) { - mobileOR = XML_MAPPER.readValue(new File(getMORLocation()), MobileOR.class); - mobileOR.setName(sProject.getName()); + + File morFile = new File(getMORLocation()); + if (morFile.exists()) { + mobileProjectOR = XML_MAPPER.readValue(morFile, MobileOR.class); + mobileProjectOR.setName(sProject.getName()); } else { - mobileOR = new MobileOR(sProject.getName()); + mobileProjectOR = new MobileOR(sProject.getName()); } - webOR.setObjectRepository(this); - webOR.setSaved(true); - mobileOR.setObjectRepository(this); - + if (webSharedOR != null) { + webSharedOR.setObjectRepository(this); + webSharedOR.setSaved(true); + webSharedOR.setRepLocationOverride(getSharedORRepLocation()); + webSharedOR.setScope(ORScope.SHARED); + } + if (webProjectOR != null) { + webProjectOR.setObjectRepository(this); + webProjectOR.setSaved(true); + webProjectOR.setScope(ORScope.PROJECT); + } + if (mobileSharedOR != null) { + mobileSharedOR.setObjectRepository(this); + mobileSharedOR.setSaved(true); + mobileSharedOR.setRepLocationOverride(getSharedMORRepLocation()); + mobileSharedOR.setScope(MobileOR.ORScope.SHARED); + + } + if (mobileProjectOR != null) { + mobileProjectOR.setObjectRepository(this); + mobileProjectOR.setSaved(true); + mobileProjectOR.setScope(MobileOR.ORScope.PROJECT); + } + + LOG.log(Level.INFO, "Shared WebOR loaded: {0}", (webSharedOR != null)); + LOG.log(Level.INFO, "Project WebOR loaded: {0}", (webProjectOR != null)); + LOG.log(Level.INFO, "Shared MobileOR loaded: {0}", (mobileSharedOR != null)); + LOG.log(Level.INFO, "Project MobileOR loaded: {0}", (mobileProjectOR != null)); } catch (IOException ex) { Logger.getLogger(ObjectRepository.class.getName()).log(Level.SEVERE, null, ex); } @@ -57,71 +123,560 @@ private void init() { public String getORLocation() { return sProject.getLocation() + File.separator + "OR.object"; } - + public String getSharedORLocation() { + return "Shared" + File.separator + "SharedWebObjects" + File.separator + "SharedOR.object"; + } public String getIORLocation() { return sProject.getLocation() + File.separator + "IOR.object"; } - public String getMORLocation() { return sProject.getLocation() + File.separator + "MOR.object"; } - + public String getSharedMORLocation() { + return "Shared" + File.separator + "SharedMobileObjects" + File.separator + "SharedMOR.object"; + } public String getORRepLocation() { return sProject.getLocation() + File.separator + "ObjectRepository"; } - + public String getSharedORRepLocation() { + return "Shared" + File.separator + "SharedWebObjects" + File.separator + "SharedObjectRepository"; + } public String getIORRepLocation() { return sProject.getLocation() + File.separator + "ImageObjectRepository"; } - public String getMORRepLocation() { return sProject.getLocation() + File.separator + "MobileObjectRepository"; } - + public String getSharedMORRepLocation() { + return "Shared" + File.separator + "SharedMobileObjects" + File.separator + "MobileObjectRepository"; + } public Project getsProject() { return sProject; } - public WebOR getWebOR() { - return webOR; + return webProjectOR; + } + public WebOR getWebSharedOR() { + return webSharedOR; } - public MobileOR getMobileOR() { - return mobileOR; + return mobileProjectOR; + } + public MobileOR getMobileSharedOR() { + return mobileSharedOR; } - - + /** + * Saves updated shared, project, and mobile ORs to disk. + * Also updates shared project usage metadata when required. + */ public void save() { try { - if (!webOR.isSaved()) { - XML_MAPPER.writerWithDefaultPrettyPrinter().writeValue(new File(getORLocation()), webOR); + java.util.List existingProjects = (webSharedOR != null) ? webSharedOR.getProjects() : java.util.List.of(); + java.util.LinkedHashSet mergedProjects = new java.util.LinkedHashSet<>(); + if (existingProjects != null) mergedProjects.addAll(existingProjects); + mergedProjects.addAll(sharedUsageProjects); + boolean projectsChanged = false; + if (webSharedOR != null) { + java.util.ArrayList mergedList = new java.util.ArrayList<>(mergedProjects); + java.util.List current = webSharedOR.getProjects(); + projectsChanged = (current == null) || !new java.util.LinkedHashSet<>(current).equals(mergedProjects); + if (projectsChanged) { + webSharedOR.setProjects(mergedList); + } + } + java.util.List mExisting = (mobileSharedOR != null) ? mobileSharedOR.getProjects() : java.util.List.of(); + java.util.LinkedHashSet mMerged = new java.util.LinkedHashSet<>(); + if (mExisting != null) mMerged.addAll(mExisting); + mMerged.addAll(sharedUsageProjects); + boolean mProjectsChanged = false; + if (mobileSharedOR != null) { + java.util.ArrayList mList = new java.util.ArrayList<>(mMerged); + java.util.List mCurrent = mobileSharedOR.getProjects(); + mProjectsChanged = (mCurrent == null) || !new java.util.LinkedHashSet<>(mCurrent).equals(mMerged); + if (mProjectsChanged) { + mobileSharedOR.setProjects(mList); + } + } + if (webSharedOR != null && (!webSharedOR.isSaved() || projectsChanged)) { + XML_MAPPER.writerWithDefaultPrettyPrinter() + .writeValue(new File(getSharedORLocation()), webSharedOR); + webSharedOR.setSaved(true); + } + if (webProjectOR != null && !webProjectOR.isSaved()) { + XML_MAPPER.writerWithDefaultPrettyPrinter() + .writeValue(new File(getORLocation()), webProjectOR); + webProjectOR.setSaved(true); + } + if (mobileSharedOR != null && !mobileSharedOR.isSaved()) { + XML_MAPPER.writerWithDefaultPrettyPrinter() + .writeValue(new File(getSharedMORLocation()), mobileSharedOR); + mobileSharedOR.setSaved(true); + } + if (mobileProjectOR != null && !mobileProjectOR.isSaved()) { + XML_MAPPER.writerWithDefaultPrettyPrinter() + .writeValue(new File(getMORLocation()), mobileProjectOR); + mobileProjectOR.setSaved(true); } - XML_MAPPER.writerWithDefaultPrettyPrinter().writeValue(new File(getMORLocation()), mobileOR); } catch (IOException ex) { Logger.getLogger(ObjectRepository.class.getName()).log(Level.SEVERE, null, ex); } } + /** + * Checks whether the given object exists in either PROJECT or SHARED scope. + * + * @param pageName page containing the object + * @param objectName object name + * @return true if present in project or shared OR + */ public Boolean isObjectPresent(String pageName, String objectName) { - Boolean present = false; - if (webOR.getPageByName(pageName) != null) { - present = webOR.getPageByName(pageName).getObjectGroupByName(objectName) != null; + return resolveWebObjectWithScope(pageName, objectName) != null; + } + + public Boolean isMobileObjectPresent(String pageName, String objectName) { + return resolveMobileObjectWithScope(pageName, objectName) != null; + } + + /** + * Renames an object (object group) within its parent page. Determines whether the object + * is in project or shared scope and triggers corresponding scenario refactor in Project. + * + * @param group object group containing the object + * @param newName new object name + */ + public void renameObject(ObjectGroup group, String newName) { + if (group == null || newName == null || newName.isBlank()) return; + var parentPage = group.getParent(); + if (parentPage == null) return; + String oldName = group.getName(); + if (oldName.equals(newName)) return; + boolean inProject = (webProjectOR != null) && + (webProjectOR.getPageByName(parentPage.getName()) == parentPage); + boolean inShared = !inProject && (webSharedOR != null) && + (webSharedOR.getPageByName(parentPage.getName()) == parentPage); + if (inProject && webProjectOR != null) { + webProjectOR.setSaved(false); + sProject.refactorObjectName(WebOR.ORScope.PROJECT, parentPage.getName(), oldName, newName); + } else if (inShared && webSharedOR != null) { + webSharedOR.setSaved(false); + markSharedUsage(); + sProject.refactorObjectName(WebOR.ORScope.SHARED, parentPage.getName(), oldName, newName); + } else { + sProject.refactorObjectName(parentPage.getName(), oldName, newName); } - if (!present) { - if (mobileOR.getPageByName(pageName) != null) { - present = mobileOR.getPageByName(pageName).getObjectGroupByName(objectName) != null; + } + + /** + * Renames a page in project or shared OR, respecting scope rules and preventing collisions, + * then propagates refactor changes into Project. + * + * @param page page object reference + * @param newName new page name + */ + public void renamePage(ORPageInf page, String newName) { + if (page == null || newName == null || newName.isBlank()) return; + String oldName = page.getName(); + if (oldName.equals(newName)) return; + boolean renamed = false; + ORScope scopeRenamed = null; + if (webProjectOR != null) { + var p = webProjectOR.getPageByName(oldName); + if (p == page) { + var existsSameScope = webProjectOR.getPageByName(newName); + if (existsSameScope != null && existsSameScope != page) { + return; + } + p.setName(newName); + webProjectOR.setSaved(false); + renamed = true; + scopeRenamed = ORScope.PROJECT; } } - return present; + if (!renamed && webSharedOR != null) { + var s = webSharedOR.getPageByName(oldName); + if (s == page) { + var existsSameScope = webSharedOR.getPageByName(newName); + if (existsSameScope != null && existsSameScope != page) { + return; + } + s.setName(newName); + webSharedOR.setSaved(false); + renamed = true; + scopeRenamed = ORScope.SHARED; + } + } + if (renamed) { + sProject.refactorPageName(scopeRenamed, oldName, newName); + } else { + sProject.refactorPageName(oldName, newName); + } } - public void renameObject(ObjectGroup group, String newName) { - sProject.refactorObjectName(group.getParent().getName(), group.getName(), newName); + public void renamePage(com.ing.datalib.or.mobile.MobileORPage page, String newName) { + if (page == null || newName == null || newName.isBlank()) return; + String oldName = page.getName(); + if (oldName.equals(newName)) return; + boolean renamed = false; + com.ing.datalib.or.mobile.MobileOR.ORScope mScope = null; + if (mobileProjectOR != null) { + var p = mobileProjectOR.getPageByName(oldName); + if (p == page) { + var existsSameScope = mobileProjectOR.getPageByName(newName); + if (existsSameScope != null && existsSameScope != page) return; + p.setName(newName); + mobileProjectOR.setSaved(false); + renamed = true; + mScope = com.ing.datalib.or.mobile.MobileOR.ORScope.PROJECT; + } + } + if (!renamed && mobileSharedOR != null) { + var s = mobileSharedOR.getPageByName(oldName); + if (s == page) { + var existsSameScope = mobileSharedOR.getPageByName(newName); + if (existsSameScope != null && existsSameScope != page) return; + s.setName(newName); + mobileSharedOR.setSaved(false); + renamed = true; + mScope = com.ing.datalib.or.mobile.MobileOR.ORScope.SHARED; + } + } + if (renamed) { + var webLikeScope = (mScope == com.ing.datalib.or.mobile.MobileOR.ORScope.PROJECT) + ? com.ing.datalib.or.web.WebOR.ORScope.PROJECT + : com.ing.datalib.or.web.WebOR.ORScope.SHARED; + sProject.refactorPageName(webLikeScope, oldName, newName); + } else { + sProject.refactorPageName(oldName, newName); + } } - public void renamePage(ORPageInf page, String newName) { - sProject.refactorPageName(page.getName(), newName); + /** + * Resolves a WebOR object from a scoped PageRef and object name, returning a + * ResolvedWebObject containing scope, page, object name, and object group. + */ + public ResolvedWebObject resolveWebObject(ResolvedWebObject.PageRef pageRef, String objectName) { + if (pageRef == null || objectName == null) return null; + if (pageRef.scope == WebOR.ORScope.PROJECT) { + var g = getFrom(webProjectOR, pageRef.name, objectName); + if (g != null) { + String actualPageName = g.getParent() != null ? g.getParent().getName() : pageRef.name; + return new ResolvedWebObject(WebOR.ORScope.PROJECT, actualPageName, objectName, g); + } + return null; + } + if (pageRef.scope == WebOR.ORScope.SHARED) { + var g = getFrom(webSharedOR, pageRef.name, objectName); + if (g != null) { + markSharedUsage(); + String actualPageName = g.getParent() != null ? g.getParent().getName() : pageRef.name; + return new ResolvedWebObject(WebOR.ORScope.SHARED, actualPageName, objectName, g); + } + return null; + } + var proj = getFrom(webProjectOR, pageRef.name, objectName); + if (proj != null) { + String actualPageName = proj.getParent() != null ? proj.getParent().getName() : pageRef.name; + return new ResolvedWebObject(WebOR.ORScope.PROJECT, actualPageName, objectName, proj); + } + var shared = getFrom(webSharedOR, pageRef.name, objectName); + if (shared != null) { + markSharedUsage(); + String actualPageName = shared.getParent() != null ? shared.getParent().getName() : pageRef.name; + return new ResolvedWebObject(WebOR.ORScope.SHARED, actualPageName, objectName, shared); + } + return null; + } + + public ResolvedMobileObject resolveMobileObject(ResolvedMobileObject.PageRef pageRef, String objectName) { + if (pageRef == null || objectName == null) return null; + if (pageRef.scope == ORScope.PROJECT) { + var g = getFrom(mobileProjectOR, pageRef.name, objectName); + if (g != null) { + String actualPageName = g.getParent() != null ? g.getParent().getName() : pageRef.name; + return new ResolvedMobileObject(ORScope.PROJECT, actualPageName, objectName, g); + } + return null; + } + if (pageRef.scope == ORScope.SHARED) { + var g = getFrom(mobileSharedOR, pageRef.name, objectName); + if (g != null) { + markSharedUsage(); + String actualPageName = g.getParent() != null ? g.getParent().getName() : pageRef.name; + return new ResolvedMobileObject(ORScope.SHARED, actualPageName, objectName, g); + } + return null; + } + return resolveMobileObjectWithScope(pageRef.name, objectName); + } + + /** + * Resolves a WebOR object by searching project scope first, then shared scope. + * + * @param pageName page to search + * @param objectName object group name + * @return resolved WebOR object with scope metadata + */ + public ResolvedWebObject resolveWebObjectWithScope(String pageName, String objectName) { + var proj = getFrom(webProjectOR, pageName, objectName); + if (proj != null) { + String actualPageName = proj.getParent() != null ? proj.getParent().getName() : pageName; + return new ResolvedWebObject(ORScope.PROJECT, actualPageName, objectName, proj); + } + var shared = getFrom(webSharedOR, pageName, objectName); + if (shared != null) { + markSharedUsage(); + String actualPageName = shared.getParent() != null ? shared.getParent().getName() : pageName; + return new ResolvedWebObject(ORScope.SHARED, actualPageName, objectName, shared); + } + return null; + } + + /** + * Resolves a MobileOR object by searching project scope first, then shared scope. + * + * @param pageName page to search + * @param objectName object group name + * @return resolved MobileOR object with scope metadata + */ + public ResolvedMobileObject resolveMobileObjectWithScope(String pageName, String objectName) { + var proj = getFrom(mobileProjectOR, pageName, objectName); + if (proj != null) { + String actualPageName = proj.getParent() != null ? proj.getParent().getName() : pageName; + return new ResolvedMobileObject(ORScope.PROJECT, actualPageName, objectName, proj); + } + var shared = getFrom(mobileSharedOR, pageName, objectName); + if (shared != null) { + markSharedUsage(); + String actualPageName = shared.getParent() != null ? shared.getParent().getName() : pageName; + return new ResolvedMobileObject(ORScope.SHARED, actualPageName, objectName, shared); + } + return null; + } + + private ObjectGroup getFrom(WebOR or, String page, String obj) { + if (or == null) return null; + var p = or.getPageByName(page); + return (p == null) ? null : p.getObjectGroupByName(obj); + } + + private ObjectGroup getFrom(MobileOR or, String page, String obj) { + if (or == null) return null; + MobileORPage p = or.getPageByName(page); + return (p == null) ? null : p.getObjectGroupByName(obj); + } + + /** + * Deep-clones an object group and its objects into another page. + */ + private ObjectGroup cloneGroupIntoPage(ObjectGroup originalGroup, WebORPage targetPage) { + ObjectGroup newGroup = new ObjectGroup<>(originalGroup.getName(), targetPage); + for (WebORObject obj : originalGroup.getObjects()) { + WebORObject cloned = new WebORObject(); + cloned.setName(obj.getName()); + cloned.setParent(newGroup); + obj.clone(cloned); + newGroup.getObjects().add(cloned); + } + return newGroup; + } + + /** + * Generates a unique name by appending "(n)" when duplicates exist. + */ + private String generateUniqueName(String baseName, java.util.function.Predicate exists) { + if (baseName == null || baseName.isBlank()) return baseName; + String candidate = baseName; + int counter = 1; + while (exists.test(candidate)) { + candidate = baseName + " (" + counter + ")"; + counter++; + } + return candidate; + } + + private String generateUniquePageName(WebOR or, String baseName) { + if (or == null) return baseName; + return generateUniqueName(baseName, name -> or.getPageByName(name) != null); + } + + private String generateUniqueGroupName(WebORPage page, String baseName) { + if (page == null) return baseName; + return generateUniqueName(baseName, name -> page.getObjectGroupByName(name) != null); + } + + /** + * Ensures a page exists in the given OR; creates one if missing. + */ + private WebORPage getOrCreatePage(WebOR or, String pageName) { + if (or == null || pageName == null) return null; + WebORPage page = or.getPageByName(pageName); + return (page != null) ? page : or.addPage(pageName); + } + + /** + * Copies all object groups from a source page to a target page. + */ + private void copyAllGroups(WebORPage sourcePage, WebORPage targetPage) { + if (sourcePage == null || targetPage == null) return; + for (ObjectGroup originalGroup : sourcePage.getObjectGroups()) { + if (originalGroup == null) continue; + targetPage.getObjectGroups().add(cloneGroupIntoPage(originalGroup, targetPage)); + } + } + + private ObjectGroup cloneGroupIntoPage(ObjectGroup originalGroup, WebORPage targetPage, String newGroupName) { + ObjectGroup newGroup = new ObjectGroup<>(newGroupName, targetPage); + if (originalGroup.getObjects() != null && !originalGroup.getObjects().isEmpty()) { + WebORObject sourceObj = originalGroup.getObjects().get(0); + WebORObject cloned = new WebORObject(); + cloned.setName(newGroupName); + cloned.setParent(newGroup); + sourceObj.clone(cloned); + newGroup.getObjects().add(cloned); + } + return newGroup; + } + + /** + * Copies a project WebOR page into the shared OR using a unique name. + * + * @param sourcePageName project page + * @param targetPageName desired shared page name + * @return actual created page name + */ + public String copyWebPage(String sourcePageName, String targetPageName) { + WebOR projectOR = getWebOR(); + WebOR sharedOR = getWebSharedOR(); + if (projectOR == null || sharedOR == null) { + return null; + } + WebORPage sourcePage = projectOR.getPageByName(sourcePageName); + if (sourcePage == null) { + return null; + } + String uniqueTargetName = generateUniquePageName(sharedOR, targetPageName); + WebORPage targetPage = getOrCreatePage(sharedOR, uniqueTargetName); + copyAllGroups(sourcePage, targetPage); + sharedOR.setSaved(false); + LOG.info(() -> "Copied Web Page '" + sourcePageName + "' to SHARED page '" + uniqueTargetName + "' successfully."); + return uniqueTargetName; + } + + /** + * Copies a WebOR object into a shared page (creating the page if needed) + * using a unique object group name. + * + * @param source resolved web object + * @param targetPageName target page in shared OR + * @return new object name + */ + public String copyWebObject(ResolvedWebObject source, String targetPageName) { + if (source == null) return null; + WebOR sharedOR = getWebSharedOR(); + if (sharedOR == null) return null; + WebORPage targetPage = getOrCreatePage(sharedOR, targetPageName); + if (targetPage == null) return null; + ObjectGroup originalGroup = source.getGroup(); + if (originalGroup == null) return null; + String baseName = originalGroup.getName(); + String uniqueName = generateUniqueGroupName(targetPage, baseName); + ObjectGroup newGroup = cloneGroupIntoPage(originalGroup, targetPage, uniqueName); + targetPage.getObjectGroups().add(newGroup); + sharedOR.setSaved(false); + LOG.info(() -> "Copied Web Object '" + baseName + "' to SHARED as '" + uniqueName + "'"); + return uniqueName; + } + + /** + * Copies a project MobileOR page into the shared Mobile OR using a unique name. + * @param sourcePageName project page to copy from + * @param targetPageName desired shared page name (will uniquify if needed) + * @return actual created page name in shared OR, or null on failure + */ + public String copyMobilePage(String sourcePageName, String targetPageName) { + MobileOR projectMOR = getMobileOR(); + MobileOR sharedMOR = getMobileSharedOR(); + if (projectMOR == null || sharedMOR == null) return null; + MobileORPage sourcePage = projectMOR.getPageByName(sourcePageName); + if (sourcePage == null) return null; + String uniqueTargetName = generateUniquePageName(sharedMOR, targetPageName); + MobileORPage targetPage = getOrCreateMobilePage(sharedMOR, uniqueTargetName); + copyAllMobileGroups(sourcePage, targetPage); + sharedMOR.setSaved(false); + LOG.info(() -> "Copied Mobile Page '" + sourcePageName + + "' to SHARED page '" + uniqueTargetName + "' successfully."); + return uniqueTargetName; + } + + /** + * Copies a MobileOR object into a target shared Mobile page (creates page if needed) + * using a unique object group name. + * @param source resolved mobile object (from project OR) + * @param targetPageName target page name in shared Mobile OR + * @return new object name created in shared OR, or null on failure + */ + public String copyMobileObject(ResolvedMobileObject source, String targetPageName) { + if (source == null) return null; + MobileOR sharedMOR = getMobileSharedOR(); + if (sharedMOR == null) return null; + MobileORPage targetPage = getOrCreateMobilePage(sharedMOR, targetPageName); + if (targetPage == null) return null; + ObjectGroup originalGroup = source.getGroup(); + if (originalGroup == null) return null; + String baseName = originalGroup.getName(); + String uniqueName = generateUniqueMobileGroupName(targetPage, baseName); + ObjectGroup newGroup = cloneMobileGroupIntoPage(originalGroup, targetPage, uniqueName); + targetPage.getObjectGroups().add(newGroup); + sharedMOR.setSaved(false); + LOG.info(() -> "Copied Mobile Object '" + baseName + "' to SHARED as '" + uniqueName + "'"); + return uniqueName; } -} + private String generateUniquePageName(MobileOR mor, String baseName) { + if (mor == null) return baseName; + return generateUniqueName(baseName, name -> mor.getPageByName(name) != null); + } + + private String generateUniqueMobileGroupName(MobileORPage page, String baseName) { + if (page == null) return baseName; + return generateUniqueName(baseName, name -> page.getObjectGroupByName(name) != null); + } + + private MobileORPage getOrCreateMobilePage(MobileOR mor, String pageName) { + if (mor == null || pageName == null) return null; + MobileORPage page = mor.getPageByName(pageName); + return (page != null) ? page : mor.addPage(pageName); + } + + private void copyAllMobileGroups(MobileORPage sourcePage, MobileORPage targetPage) { + if (sourcePage == null || targetPage == null) return; + for (ObjectGroup originalGroup : sourcePage.getObjectGroups()) { + if (originalGroup == null) continue; + targetPage.getObjectGroups().add(cloneMobileGroupIntoPage(originalGroup, targetPage, originalGroup.getName())); + } + } + + private ObjectGroup cloneMobileGroupIntoPage(ObjectGroup originalGroup, MobileORPage targetPage, String newGroupName) { + ObjectGroup newGroup = new ObjectGroup<>(newGroupName, targetPage); + if (originalGroup.getObjects() != null && !originalGroup.getObjects().isEmpty()) { + MobileORObject sourceObj = originalGroup.getObjects().get(0); + MobileORObject cloned = new MobileORObject(); + cloned.setName(newGroupName); + cloned.setParent(newGroup); + sourceObj.clone(cloned); + newGroup.getObjects().add(cloned); + } + return newGroup; + } + + /** + * Marks that the current project has used a shared object, + * updating shared OR metadata. + */ + private void markSharedUsage() { + if (sProject != null && sProject.getName() != null && !sProject.getName().isBlank()) { + sharedUsageProjects.add(sProject.getName()); + } + } +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/or/common/ObjectGroup.java b/Datalib/src/main/java/com/ing/datalib/or/common/ObjectGroup.java index 9648a8a3..da60a75f 100644 --- a/Datalib/src/main/java/com/ing/datalib/or/common/ObjectGroup.java +++ b/Datalib/src/main/java/com/ing/datalib/or/common/ObjectGroup.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import com.ing.datalib.or.web.WebORObject; import java.io.File; import java.util.ArrayList; import java.util.Collections; @@ -179,7 +180,7 @@ public TreePath getTreePath() { public Boolean rename(String newName) { if (getParent().getObjectGroupByName(newName) == null) { if (FileUtils.renameFile(getRepLocation(), newName)) { - getParent().getRoot().getObjectRepository().renameObject(this, newName); + getParent().getRoot().getObjectRepository().renameObject((ObjectGroup) this, newName); setName(newName); getParent().getRoot().setSaved(false); return true; diff --git a/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileOR.java b/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileOR.java index 4d3a93c8..4f3c7e1e 100644 --- a/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileOR.java +++ b/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileOR.java @@ -17,6 +17,11 @@ import java.util.List; import javax.swing.tree.TreeNode; +/** + * Represents the Mobile Object Repository (MobileOR), containing pages and their objects, + * along with metadata such as scope, type, associated projects, and save state. + * Provides page management, tree navigation, sorting, and repository integration. + */ @JsonInclude(JsonInclude.Include.NON_NULL) @JacksonXmlRootElement(localName = "Root") public class MobileOR implements ORRootInf { @@ -43,12 +48,22 @@ public class MobileOR implements ORRootInf { @JacksonXmlProperty(isAttribute = true) private String type; + + @JacksonXmlProperty(isAttribute = true) + private ORScope scope = ORScope.PROJECT; + + @JacksonXmlElementWrapper(localName = "projects") + @JacksonXmlProperty(localName = "project") + private List projects = new ArrayList<>(); @JsonIgnore private ObjectRepository objectRepository; @JsonIgnore private Boolean saved = true; + + @JsonIgnore + private String repLocationOverride; public MobileOR() { this.pages = new ArrayList<>(); @@ -120,6 +135,7 @@ public MobileORPage addPage() { public MobileORPage addPage(String pageName) { if (getPageByName(pageName) == null) { MobileORPage page = new MobileORPage(pageName, this); + page.setSource(this.isShared() ? ORScope.SHARED : ORScope.PROJECT); pages.add(page); new File(page.getRepLocation()).mkdirs(); setSaved(false); @@ -216,10 +232,17 @@ public TreeNode[] getPath() { return new TreeNode[]{this}; } + @JsonIgnore + public void setRepLocationOverride(String path) { + this.repLocationOverride = path; + } + @JsonIgnore @Override public String getRepLocation() { - return getObjectRepository().getMORRepLocation(); + return repLocationOverride != null + ? repLocationOverride + : getObjectRepository().getMORRepLocation(); } @JsonIgnore @@ -227,4 +250,30 @@ public String getRepLocation() { public void sort() { ORUtils.sort(this); } -} + + public enum ORScope { + PROJECT, SHARED + } + + @JsonIgnore + public ORScope getScope() { + return scope; + } + + public void setScope(ORScope scope) { + this.scope = scope; + } + + @JsonIgnore + public boolean isShared() { + return scope == ORScope.SHARED; + } + + public List getProjects() { + return projects; + } + + public void setProjects(List projects) { + this.projects = (projects == null) ? new ArrayList<>() : projects; + } +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileORObject.java b/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileORObject.java index 6469bab6..3ec64033 100644 --- a/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileORObject.java +++ b/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileORObject.java @@ -22,6 +22,12 @@ import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; +/** + * Represents a single mobile object inside a MobileOR page, containing a collection of + * OR attributes, frame information, and references to its parent object group. + * Supports attribute editing, table model operations, cloning, renaming, + * and object repository persistence updates. + */ public class MobileORObject extends UndoRedoModel implements ORObjectInf { @JacksonXmlProperty(isAttribute = true, localName = "ref") @@ -514,4 +520,4 @@ public void insertColumnAt(int colIndex, String colName, Object[] values) { public void removeColumn(int colIndex) { throw new UnsupportedOperationException("Not supported yet."); } -} +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileORPage.java b/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileORPage.java index 4b0877e8..f4d45059 100644 --- a/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileORPage.java +++ b/Datalib/src/main/java/com/ing/datalib/or/mobile/MobileORPage.java @@ -9,6 +9,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import com.ing.datalib.or.mobile.MobileOR.ORScope; import java.io.File; import java.util.ArrayList; import java.util.Collections; @@ -17,6 +18,12 @@ import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; +/** + * Represents a single mobile object inside a MobileOR page, containing a collection of + * OR attributes, frame information, and references to its parent object group. + * Supports attribute editing, table model operations, cloning, renaming, + * and object repository persistence updates. + */ @JsonInclude(JsonInclude.Include.NON_NULL) public class MobileORPage implements ORPageInf { @@ -32,6 +39,9 @@ public class MobileORPage implements ORPageInf { @JsonIgnore private MobileOR root; + + @JacksonXmlProperty(isAttribute = true, localName = "source") + private ORScope source = ORScope.PROJECT; public MobileORPage() { this.objectGroups = new ArrayList<>(); @@ -259,4 +269,12 @@ public String getRepLocation() { public void sort() { ORUtils.sort(this); } -} + + public ORScope getSource() { + return source; + } + + public void setSource(ORScope source) { + this.source = source; + } +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/or/mobile/ResolvedMobileObject.java b/Datalib/src/main/java/com/ing/datalib/or/mobile/ResolvedMobileObject.java new file mode 100644 index 00000000..688a4763 --- /dev/null +++ b/Datalib/src/main/java/com/ing/datalib/or/mobile/ResolvedMobileObject.java @@ -0,0 +1,112 @@ +package com.ing.datalib.or.mobile; + +import com.ing.datalib.or.common.ObjectGroup; +import com.ing.datalib.or.web.WebOR.ORScope; + +/** + * Represents a resolved mobile object within the Object Repository, including its scope, + * page name, object name, and resolved object group. + * + */ +public class ResolvedMobileObject { + + private final ORScope scope; + private final String pageName; + private final String objectName; + private final ObjectGroup group; + + public ResolvedMobileObject(ORScope scope, String pageName, String objectName, ObjectGroup group) { + this.scope = scope; + this.pageName = pageName; + this.objectName = objectName; + this.group = group; + } + + public ORScope getScope() { + return scope; + } + + public String getPageName() { + return pageName; + } + + public String getObjectName() { + return objectName; + } + + public ObjectGroup getGroup() { + return group; + } + + /** + * Returns the first resolved MobileORObject from the group, or null if none exist. + */ + public MobileORObject getObject() { + return (group != null && !group.getObjects().isEmpty()) ? group.getObjects().get(0) : null; + } + + public boolean isFromProject() { + return scope == ORScope.PROJECT; + } + + public boolean isFromShared() { + return scope == ORScope.SHARED; + } + + public boolean isPresent() { + return group != null && !group.getObjects().isEmpty(); + } + + public String debugString() { + return "ResolvedMobileObject{scope=" + scope + + ", page='" + pageName + '\'' + + ", object='" + objectName + '\'' + + ", objectCount=" + (group == null ? 0 : group.getObjects().size()) + + '}'; + } + + /** + * Optional: reuse the same PageRef concept as web if you want scoped tokens like: + * "[Shared] Login" / "[Project] Home" + * + * If you already want Mobile page tokens to behave the same way, you can keep this. + */ + public static final class PageRef { + public final String name; + public final ORScope scope; + + public PageRef(String name, ORScope scope) { + this.name = name; + this.scope = scope; + } + + public String qualified() { + if (scope == null) return name; + switch (scope) { + case PROJECT: return "[Project] " + name; + case SHARED: return "[Shared] " + name; + default: return name; + } + } + + public static PageRef parse(String token) { + String s = token == null ? "" : token.trim(); + if (s.isEmpty()) return new PageRef("", ORScope.PROJECT); + + if (s.startsWith("[") && s.contains("]")) { + int end = s.indexOf(']'); + String scopeText = s.substring(1, end).trim().toUpperCase(); + String base = s.substring(end + 1).trim(); + ORScope sc; + switch (scopeText) { + case "PROJECT": sc = ORScope.PROJECT; break; + case "SHARED": sc = ORScope.SHARED; break; + default: sc = ORScope.PROJECT; + } + return new PageRef(base, sc); + } + + return new PageRef(s, ORScope.PROJECT); + } + } +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/or/web/ResolvedWebObject.java b/Datalib/src/main/java/com/ing/datalib/or/web/ResolvedWebObject.java new file mode 100644 index 00000000..158e9ef6 --- /dev/null +++ b/Datalib/src/main/java/com/ing/datalib/or/web/ResolvedWebObject.java @@ -0,0 +1,137 @@ + +package com.ing.datalib.or.web; + +import com.ing.datalib.or.common.ObjectGroup; +import com.ing.datalib.or.web.WebOR.ORScope; + +/** + * Represents a resolved web object within the Object Repository, including its scope, + * page name, object name, and resolved object group. + */ +public class ResolvedWebObject { + private final ORScope scope; + private final String pageName; + private final String objectName; + private final ObjectGroup group; + + /** + * Creates a resolved web object record tying together scope, page name, object name, + * and the matched object group. + * + * @param scope OR scope (Project or Shared) + * @param pageName logical page name + * @param objectName name of the web object + * @param group group of matching WebORObject instances + */ + public ResolvedWebObject(ORScope scope, String pageName, String objectName, ObjectGroup group) { + this.scope = scope; + this.pageName = pageName; + this.objectName = objectName; + this.group = group; + } + + /** + * Represents a reference to a page along with its OR scope, and provides utilities + * for formatting and parsing scoped page tokens. + */ + public static final class PageRef { + public final String name; + public final ORScope scope; + + /** + * Creates a page reference with the given name and scope. + * + * @param name page name without prefix + * @param scope OR scope of the page + */ + public PageRef(String name, ORScope scope) { + this.name = name; + this.scope = scope; + } + + /** + * Returns the page name prefixed with its scope (e.g., "[Project] Login"), + * or the raw name if scope is null. + * + * @return fully qualified scoped page name + */ + public String qualified() { + if (null == scope) { + return name; + } + else switch (scope) { + case PROJECT: + return "[Project] " + name; + case SHARED: + return "[Shared] " + name; + default: + return name; + } + } + + /** + * Parses a scoped page token (e.g., "[Shared] Home") into a PageRef. + * Defaults to PROJECT scope when missing or unrecognized. + * + * @param token raw page reference text + * @return parsed PageRef instance + */ + public static PageRef parse(String token) { + String s = token == null ? "" : token.trim(); + if (s.isEmpty()) { + return new PageRef("", ORScope.PROJECT); + } + if (s.startsWith("[") && s.contains("]")) { + int end = s.indexOf(']'); + String scopeText = s.substring(1, end).trim().toUpperCase(); + String base = s.substring(end + 1).trim(); + ORScope sc; + switch (scopeText) { + case "PROJECT": + sc = ORScope.PROJECT; + break; + case "SHARED": + sc = ORScope.SHARED; + break; + default: + sc = ORScope.PROJECT; + } + + return new PageRef(base, sc); + } + return new PageRef(s, ORScope.PROJECT); + } + } + + public ORScope getScope() { return scope; } + public String getPageName() { return pageName; } + public String getObjectName() { return objectName; } + public ObjectGroup getGroup() { return group; } + + /** + * Returns the first resolved WebORObject from the group, or null if none exist. + * + * @return a resolved WebORObject or null + */ + public WebORObject getObject() { + return (group != null && !group.getObjects().isEmpty()) ? group.getObjects().get(0) : null; + } + + public boolean isFromProject() { return scope == ORScope.PROJECT; } + public boolean isFromShared() { return scope == ORScope.SHARED; } + public boolean isPresent() { return group != null && !group.getObjects().isEmpty(); } + + /** + * Returns a debug-friendly string summarizing the scope, page, object name, + * and number of resolved objects. + * + * @return formatted debug information + */ + public String debugString() { + return "ResolvedWebObject{scope=" + scope + + ", page='" + pageName + '\'' + + ", object='" + objectName + '\'' + + ", objectCount=" + (group == null ? 0 : group.getObjects().size()) + + '}'; + } +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/or/web/WebOR.java b/Datalib/src/main/java/com/ing/datalib/or/web/WebOR.java index 1966fabd..6718b231 100644 --- a/Datalib/src/main/java/com/ing/datalib/or/web/WebOR.java +++ b/Datalib/src/main/java/com/ing/datalib/or/web/WebOR.java @@ -17,6 +17,11 @@ import java.util.List; import javax.swing.tree.TreeNode; +/** + * Represents the Web Object Repository (WebOR), containing pages and their objects, + * along with metadata such as scope, type, associated projects, and save state. + * Provides page management, tree navigation, sorting, and repository integration. + */ @JsonInclude(JsonInclude.Include.NON_NULL) @JacksonXmlRootElement(localName = "Root") public class WebOR implements ORRootInf { @@ -43,12 +48,22 @@ public class WebOR implements ORRootInf { @JacksonXmlProperty(isAttribute = true) private String type; + + @JacksonXmlProperty(isAttribute = true) + private ORScope scope = ORScope.PROJECT; + + @JacksonXmlElementWrapper(localName = "projects") + @JacksonXmlProperty(localName = "project") + private List projects = new ArrayList<>(); @JsonIgnore private ObjectRepository objectRepository; @JsonIgnore private Boolean saved = true; + + @JsonIgnore + private String repLocationOverride; public WebOR() { this.pages = new ArrayList<>(); @@ -80,6 +95,9 @@ public void setPages(List pages) { this.pages = pages; for (WebORPage page : pages) { page.setRoot(this); + if (page.getSource() == null || page.getSource().isBlank()) { + page.setSource(isShared() ? "SHARED" : "PROJECT"); + } } } @@ -131,6 +149,7 @@ public WebORPage addPage(String pageName) { if (getPageByName(pageName) == null) { WebORPage page = new WebORPage(pageName, this); pages.add(page); + page.setSource(isShared() ? "SHARED" : "PROJECT"); new File(page.getRepLocation()).mkdirs(); setSaved(false); return page; @@ -226,10 +245,17 @@ public TreeNode[] getPath() { return new TreeNode[]{this}; } + @JsonIgnore + public void setRepLocationOverride(String path) { + this.repLocationOverride = path; + } + @JsonIgnore @Override public String getRepLocation() { - return getObjectRepository().getORRepLocation(); + return repLocationOverride != null + ? repLocationOverride + : getObjectRepository().getORRepLocation(); } @JsonIgnore @@ -237,4 +263,30 @@ public String getRepLocation() { public void sort() { ORUtils.sort(this); } -} + + public enum ORScope { + PROJECT, SHARED + } + + @JsonIgnore + public ORScope getScope() { + return scope; + } + + public void setScope(ORScope scope) { + this.scope = scope; + } + + @JsonIgnore + public boolean isShared() { + return scope == ORScope.SHARED; + } + + public List getProjects() { + return projects; + } + + public void setProjects(List projects) { + this.projects = (projects == null) ? new ArrayList<>() : projects; + } +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/or/web/WebORObject.java b/Datalib/src/main/java/com/ing/datalib/or/web/WebORObject.java index c9bd9af5..eebf033d 100644 --- a/Datalib/src/main/java/com/ing/datalib/or/web/WebORObject.java +++ b/Datalib/src/main/java/com/ing/datalib/or/web/WebORObject.java @@ -23,6 +23,12 @@ import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; +/** + * Represents a single web object inside a WebOR page, containing a collection of + * OR attributes, frame information, and references to its parent object group. + * Supports attribute editing, table model operations, cloning, renaming, + * and object repository persistence updates. + */ @JsonInclude(JsonInclude.Include.NON_NULL) public class WebORObject extends UndoRedoModel implements ORObjectInf { @@ -586,5 +592,4 @@ public void insertColumnAt(int colIndex, String colName, Object[] values) { public void removeColumn(int colIndex) { throw new UnsupportedOperationException("Not supported yet."); } - -} +} \ No newline at end of file diff --git a/Datalib/src/main/java/com/ing/datalib/or/web/WebORPage.java b/Datalib/src/main/java/com/ing/datalib/or/web/WebORPage.java index 96991f00..43863de5 100644 --- a/Datalib/src/main/java/com/ing/datalib/or/web/WebORPage.java +++ b/Datalib/src/main/java/com/ing/datalib/or/web/WebORPage.java @@ -18,6 +18,11 @@ import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; +/** + * Represents a page in the Web Object Repository (WebOR), containing object groups + * and metadata such as title, source, and its parent WebOR root. Supports object + * group management, tree navigation, renaming, and persistence utilities. + */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties({"root"}) public class WebORPage implements ORPageInf { @@ -34,6 +39,9 @@ public class WebORPage implements ORPageInf { @JsonIgnore private WebOR root; + + @JacksonXmlProperty(isAttribute = true) + private String source; public WebORPage() { this.objectGroups = new ArrayList<>(); @@ -260,4 +268,7 @@ public String getRepLocation() { public void sort() { ORUtils.sort(this); } + + public String getSource() { return source; } + public void setSource(String source) { this.source = source; } } diff --git a/Datalib/src/main/java/com/ing/datalib/settings/DriverProperties.java b/Datalib/src/main/java/com/ing/datalib/settings/DriverProperties.java index d858750c..e5705d8e 100644 --- a/Datalib/src/main/java/com/ing/datalib/settings/DriverProperties.java +++ b/Datalib/src/main/java/com/ing/datalib/settings/DriverProperties.java @@ -3,15 +3,15 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Properties; import com.ing.datalib.util.data.LinkedProperties; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; /** @@ -195,7 +195,7 @@ private Properties setAPIProperties(Properties prop, String apiAlias) { * This method initializes the following keys with default values: *
    *
  • {@code proxyPort} – empty string
  • - *
  • {@code setSSLCertVerification} – {@code false}
  • + *
  • {@code sslCertificateVerification} – {@code false}
  • *
  • {@code useProxy} – {@code false}
  • *
  • {@code proxyHost} – empty string
  • *
@@ -204,9 +204,10 @@ private Properties setAPIProperties(Properties prop, String apiAlias) { */ private void setDefaultProperties(Properties prop) { prop.setProperty("proxyPort", ""); - prop.setProperty("setSSLCertVerification", "false"); + prop.setProperty("sslCertificateVerification", "false"); prop.setProperty("useProxy", "false"); prop.setProperty("proxyHost", ""); + prop.setProperty("httpClientRedirect", "NEVER"); } @@ -471,6 +472,21 @@ public String getKeyStorePassword() { return apiConfigFilePropMap.get(currLoadedAPIConfig).getProperty("keyStorePassword", ""); } + /** + * Retrieves the configured HTTP redirect policy for the currently loaded API configuration. + *

+ * This method looks up the property httpClientRedirect inside the API configuration + * identified by {@code currLoadedAPIConfig}. If the property is not defined, the method returns the + * default value "NEVER". + *

+ * + * @return the redirect policy defined for the current API configuration, or "NEVER" + * if the property is missing + */ + public String getHttpClientRedirect() { + return apiConfigFilePropMap.get(currLoadedAPIConfig).getProperty("httpClientRedirect", "NEVER"); + } + //Setters for some specific properties. //Commented out as these are not set programmatically but are extracted from //configurations files. diff --git a/Dist/pom.xml b/Dist/pom.xml index eeb86385..385c8830 100644 --- a/Dist/pom.xml +++ b/Dist/pom.xml @@ -4,7 +4,7 @@ com.ing ingenious-playwright - 2.3.1 + 2.4 Dist pom @@ -14,6 +14,7 @@ org.apache.maven.plugins maven-dependency-plugin + 3.9.0 copy-jar diff --git a/Engine/pom.xml b/Engine/pom.xml index dbde6ba6..6d3178e2 100644 --- a/Engine/pom.xml +++ b/Engine/pom.xml @@ -5,7 +5,7 @@ com.ing ingenious-playwright - 2.3.1 + 2.4 ingenious-engine jar @@ -58,18 +58,60 @@ org.apache.poi poi ${apache.poi.version} + + + org.apache.logging.log4j + log4j-core + + + org.apache.logging.log4j + log4j-api + + + log4j + log4j + + org.apache.poi poi-ooxml ${apache.poi.version} + + + org.apache.logging.log4j + log4j-core + + + org.apache.logging.log4j + log4j-api + + + log4j + log4j + + org.apache.poi poi-ooxml-schemas ${apache.poi.schemas.version} + + + org.apache.logging.log4j + log4j-core + + + org.apache.logging.log4j + log4j-api + + + log4j + log4j + + @@ -130,6 +172,17 @@ com.jayway.jsonpath json-path ${json-path.version} + + + net.minidev + json-smart + + + + + net.minidev + json-smart + 2.4.9 @@ -150,18 +203,6 @@ ${java-string-similarity.version} - - org.apache.logging.log4j - log4j-core - ${log4j.version} - - - - org.apache.logging.log4j - log4j-api - ${log4j.version} - - org.checkerframework checker-qual @@ -232,6 +273,17 @@ galen-core 2.4.4 jar + + + com.squareup.okhttp3 + okhttp + + + + + com.squareup.okhttp3 + okhttp + 5.0.0 ru.yandex.qatools.ashot @@ -239,11 +291,22 @@ 1.5.4 jar + + org.yaml + snakeyaml + 2.0 + com.github.javafaker javafaker ${javafaker.version} - + + + org.yaml + snakeyaml + + + com.ibm.mq @@ -257,6 +320,11 @@ ${appium.version} jar + + com.microsoft.sqlserver + mssql-jdbc + 12.10.0.jre11 + com.mysql mysql-connector-j diff --git a/Engine/src/main/java/com/ing/engine/commands/browser/Command.java b/Engine/src/main/java/com/ing/engine/commands/browser/Command.java index a5a2cdfe..52f9d0bb 100644 --- a/Engine/src/main/java/com/ing/engine/commands/browser/Command.java +++ b/Engine/src/main/java/com/ing/engine/commands/browser/Command.java @@ -35,15 +35,14 @@ import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; -/** Kafka Imports -import org.apache.kafka.common.header.Header; -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericRecord; -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerRecord; -*/ +/** Kafka Imports */ +// import org.apache.kafka.common.header.Header; +// import org.apache.avro.Schema; +// import org.apache.avro.generic.GenericRecord; +// import org.apache.kafka.clients.consumer.ConsumerRecord; +// import org.apache.kafka.clients.consumer.KafkaConsumer; +// import org.apache.kafka.clients.producer.KafkaProducer; +// import org.apache.kafka.clients.producer.ProducerRecord; public class Command { @@ -89,6 +88,9 @@ public class Command { static public Map before = new HashMap<>(); static public Map after = new HashMap<>(); static public Map duration = new HashMap<>(); + static public HashMap headerMap = new HashMap<>(); + static public Map> headerKeyValueMap = new HashMap<>(); + public String key; static public String basicAuthorization; /** @@ -143,46 +145,44 @@ public class Command { /** * *** Kafka Parameters **** */ - - /** Kafka Parameters - static public Map> kafkaHeaders = new HashMap<>(); - static public Map kafkaProducerTopic = new HashMap<>(); - static public Map kafkaConsumerTopic = new HashMap<>(); - static public Map kafkaConsumerGroupId = new HashMap<>(); - static public Map kafkaServers = new HashMap<>(); - static public Map kafkaSchemaRegistryURL = new HashMap<>(); - static public Map kafkaPartition = new HashMap<>(); - static public Map kafkaTimeStamp = new HashMap<>(); - static public Map kafkaKey = new HashMap<>(); - static public Map kafkaKeySerializer = new HashMap<>(); - static public Map kafkaKeyDeserializer = new HashMap<>(); - static public Map kafkaValue = new HashMap<>(); - static public Map kafkaValueSerializer = new HashMap<>(); - static public Map kafkaValueDeserializer = new HashMap<>(); - static public Map kafkaConsumerPollRetries = new HashMap<>(); - static public Map kafkaConsumerPollDuration = new HashMap<>(); - static public Map kafkaAvroSchema =new HashMap<>(); - static public Map> kafkaGenericRecord =new HashMap<>(); - static public Map kafkaGenericRecordValue =new HashMap<>(); - static public Map> kafkaAvroProducer =new HashMap<>(); - static public Map> kafkaConfigs = new HashMap<>(); - static public Map kafkaProducersslConfigs = new HashMap<>(); - static public Map kafkaConsumersslConfigs = new HashMap<>(); - static public Map kafkaAvroCompatibleMessage = new HashMap<>(); - static public Map kafkaConsumeRecordCount = new HashMap<>(); - static public Map kafkaConsumeRecordValue = new HashMap<>(); - static public Map kafkaSharedSecret = new HashMap<>(); - static public Map>> kafkaConsumerRecords = new HashMap<>(); - static public Map> kafkaConsumerPollRecord = new HashMap<>(); - static public Map kafkaRecordIdentifierValue = new HashMap<>(); - static public Map kafkaRecordIdentifierPath = new HashMap<>(); - static public Map kafkaConsumerMaxPollRecords = new HashMap<>(); - static public Map kafkaAutoRegisterSchemas = new HashMap<>(); - static public Map kafkaProducerRecord = new HashMap<>(); - static public Map kafkaConsumerRecord = new HashMap<>(); - static public Map kafkaProducer = new HashMap<>(); - static public Map kafkaConsumer = new HashMap<>(); - */ + // static public Map> kafkaHeaders = new HashMap<>(); + // static public Map kafkaProducerTopic = new HashMap<>(); + // static public Map kafkaConsumerTopic = new HashMap<>(); + // static public Map kafkaConsumerGroupId = new HashMap<>(); + // static public Map kafkaServers = new HashMap<>(); + // static public Map kafkaSchemaRegistryURL = new HashMap<>(); + // static public Map kafkaPartition = new HashMap<>(); + // static public Map kafkaTimeStamp = new HashMap<>(); + // static public Map kafkaKey = new HashMap<>(); + // static public Map kafkaKeySerializer = new HashMap<>(); + // static public Map kafkaKeyDeserializer = new HashMap<>(); + // static public Map kafkaValue = new HashMap<>(); + // static public Map kafkaValueSerializer = new HashMap<>(); + // static public Map kafkaValueDeserializer = new HashMap<>(); + // static public Map kafkaConsumerPollRetries = new HashMap<>(); + // static public Map kafkaConsumerPollDuration = new HashMap<>(); + // static public Map kafkaAvroSchema =new HashMap<>(); + // static public Map> kafkaGenericRecord =new HashMap<>(); + // static public Map kafkaGenericRecordValue =new HashMap<>(); + // static public Map> kafkaAvroProducer =new HashMap<>(); + // static public Map> kafkaConfigs = new HashMap<>(); + // static public Map kafkaProducersslConfigs = new HashMap<>(); + // static public Map kafkaConsumersslConfigs = new HashMap<>(); + // static public Map kafkaAvroCompatibleMessage = new HashMap<>(); + // static public Map kafkaConsumeRecordCount = new HashMap<>(); + // static public Map kafkaConsumeRecordValue = new HashMap<>(); + // static public Map kafkaSharedSecret = new HashMap<>(); + // static public Map>> kafkaConsumerRecords = new HashMap<>(); + // static public Map> kafkaConsumerPollRecord = new HashMap<>(); + // static public Map kafkaRecordIdentifierValue = new HashMap<>(); + // static public Map kafkaRecordIdentifierPath = new HashMap<>(); + // static public Map kafkaConsumerMaxPollRecords = new HashMap<>(); + // static public Map kafkaAutoRegisterSchemas = new HashMap<>(); + // static public Map kafkaProducerRecord = new HashMap<>(); + // static public Map kafkaConsumerRecord = new HashMap<>(); + // static public Map kafkaProducer = new HashMap<>(); + // static public Map kafkaConsumer = new HashMap<>(); + // static public Map>> kafkaRecordIdentifier = new HashMap<>(); public Command(CommandControl cc) { Commander = cc; diff --git a/Engine/src/main/java/com/ing/engine/commands/browser/DynamicObject.java b/Engine/src/main/java/com/ing/engine/commands/browser/DynamicObject.java index 5bdf8069..0d0160be 100644 --- a/Engine/src/main/java/com/ing/engine/commands/browser/DynamicObject.java +++ b/Engine/src/main/java/com/ing/engine/commands/browser/DynamicObject.java @@ -3,16 +3,21 @@ import com.ing.engine.core.CommandControl; import com.ing.engine.drivers.AutomationObject; +import com.ing.engine.reporting.impl.html.bdd.Report; +import com.ing.engine.reporting.util.RDS; import com.ing.engine.support.Status; +import com.ing.engine.support.Step; import com.ing.engine.support.methodInf.Action; import com.ing.engine.support.methodInf.InputType; import com.ing.engine.support.methodInf.ObjectType; + +import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * - * + * */ public class DynamicObject extends Command { @@ -74,4 +79,55 @@ private void setProperty(String key, String value) { AutomationObject.dynamicValue.get(Reference).get(ObjectName).put(key, value); } } + + @Action(object = ObjectType.PLAYWRIGHT, desc = "Set filter `Has Text` for the locator", input = InputType.YES, condition = InputType.NO) + public void setFilterHasText() { + if (!Data.isEmpty()) { + AutomationObject.locatorFiltersMap.computeIfAbsent(Reference+ObjectName, k -> new ArrayList<>()).add("setHasText: "+ Data); + String text = String.format("Setting Filter 'Has Text' with '%s' for Object [%s - %s]", + Data, Reference, ObjectName); + Report.updateTestLog(Action, text, Status.DONE); + } else { + Report.updateTestLog(Action, "Input should not be empty", Status.FAILNS); + } + } + + @Action(object = ObjectType.PLAYWRIGHT, desc = "Set filter `Has Not Text` for the locator", input = InputType.YES, condition = InputType.NO) + public void setFilterHasNotText() { + if (!Data.isEmpty()) { + AutomationObject.locatorFiltersMap.computeIfAbsent(Reference+ObjectName, k -> new ArrayList<>()).add("setHasNotText: "+ Data); + String text = String.format("Setting Filter 'Has Not Text' with '%s' for Object [%s - %s]", + Data, Reference, ObjectName); + Report.updateTestLog(Action, text, Status.DONE); + } else { + Report.updateTestLog(Action, "Input should not be empty", Status.FAILNS); + } + } + + @Action(object = ObjectType.PLAYWRIGHT, desc = "Set filter `Visible` for the locator", input = InputType.YES, condition = InputType.NO) + public void setFilterIsVisible() { + if (!Data.isEmpty()) { + AutomationObject.locatorFiltersMap.computeIfAbsent(Reference+ObjectName, k -> new ArrayList<>()).add("setVisible: "+ Data); + String text = String.format("Setting Filter 'Visible' with '%s' for Object [%s - %s]", + Data, Reference, ObjectName); + Report.updateTestLog(Action, text, Status.DONE); + } else { + Report.updateTestLog(Action, "Input should not be empty", Status.FAILNS); + } + } + + @Action(object = ObjectType.PLAYWRIGHT, desc = "Set filter `Index` for the locator", input = InputType.YES, condition = InputType.NO) + public void setFilterIndex() { + if (!Data.isEmpty()) { + AutomationObject.locatorFiltersMap.computeIfAbsent(Reference+ObjectName, k -> new ArrayList<>()).add("setIndex: "+ Data); + String text = String.format("Setting Filter 'Index' with '%s' for Object [%s - %s]", + Data, Reference, ObjectName); + Report.updateTestLog(Action, text, Status.DONE); + } else { + Report.updateTestLog(Action, "Input should not be empty", Status.FAILNS); + } + } + + + } diff --git a/Engine/src/main/java/com/ing/engine/commands/database/Database.java b/Engine/src/main/java/com/ing/engine/commands/database/Database.java index a833af0d..bf240c92 100644 --- a/Engine/src/main/java/com/ing/engine/commands/database/Database.java +++ b/Engine/src/main/java/com/ing/engine/commands/database/Database.java @@ -12,15 +12,24 @@ import java.util.List; /** - * - * + * Provides database-specific command implementations for executing queries, asserting results, + * storing values, and managing database connections. Extends General for common database utilities. */ public class Database extends General { + /** + * Constructs a Database command handler with the given command control. + * + * @param cc the command control context + */ public Database(CommandControl cc) { super(cc); } + /** + * Initiates the database connection using the input database name. + * Updates the test log with connection status and metadata. + */ @Action(object = ObjectType.DATABASE, desc = "Initiate the DB transaction", input = InputType.YES) public void initDBConnection() { try { @@ -45,6 +54,9 @@ public void initDBConnection() { } } + /** + * Executes a SELECT query and updates the test log with the result. + */ @Action(object = ObjectType.DATABASE, desc = "Execute the Query in []", input = InputType.YES) public void executeSelectQuery() { try { @@ -56,13 +68,17 @@ public void executeSelectQuery() { } } + /** + * Executes a DML query (INSERT, UPDATE, DELETE) and updates the test log with the result and query used. + */ @Action(object = ObjectType.DATABASE, desc = "Execute the Query in []", input = InputType.YES) public void executeDMLQuery() { try { - if (executeDML()) { - Report.updateTestLog(Action, " Table updated by using " + Data, Status.PASSNS); + DMLResult result = executeDML(); + if (result.success) { + Report.updateTestLog(Action, "Table updated by using query: " + result.query, Status.PASSNS); } else { - Report.updateTestLog(Action, " Table not updated by using " + Data, Status.FAILNS); + Report.updateTestLog(Action, "Table not updated by using query: " + result.query, Status.FAILNS); } } catch (SQLException ex) { Report.updateTestLog(Action, "Error executing the SQL Query: " + ex.getMessage(), @@ -70,6 +86,10 @@ public void executeDMLQuery() { } } + /** + * Asserts that the value in Data exists in the specified column (Condition) of the database. + * Updates the test log with the assertion result. + */ @Action(object = ObjectType.DATABASE, desc = "Assert the value [] exist in the column [] ", input = InputType.YES, condition = InputType.YES) public void assertDBResult() { if (assertDB(Condition, Data)) { @@ -79,6 +99,10 @@ public void assertDBResult() { } } + /** + * Stores the value from the specified DB column (Condition) in a global variable (Input). + * Updates the test log with the storage result. + */ @Action(object = ObjectType.DATABASE, desc = "Store it in Global variable from the DB column [] ", input = InputType.YES, condition = InputType.YES) public void storeValueInGlobalVariable() { storeValue(Input, Condition, true); @@ -89,6 +113,10 @@ public void storeValueInGlobalVariable() { } } + /** + * Stores the value from the specified DB column (Condition) in a local variable (Input). + * Updates the test log with the storage result. + */ @Action(object = ObjectType.DATABASE, desc = "Store it in the variable from the DB column [] ", input = InputType.YES, condition = InputType.YES) public void storeValueInVariable() { storeValue(Input, Condition, false); @@ -99,6 +127,10 @@ public void storeValueInVariable() { } } + /** + * Stores the value from the specified DB column (Condition) in the test data sheet (Input). + * Updates the test log with the storage result. + */ @Action(object = ObjectType.DATABASE, desc = "Save DB value in Test Data Sheet", input = InputType.YES, condition = InputType.YES) public void storeDBValueinDataSheet() { try { @@ -134,6 +166,9 @@ public void storeDBValueinDataSheet() { } } + /** + * Closes the database connection and updates the test log with the result. + */ @Action(object = ObjectType.DATABASE, desc = "Close the DB Connection") public void closeDBConnection() { try { @@ -148,6 +183,9 @@ public void closeDBConnection() { } } + /** + * Verifies table values against the test data sheet and updates the test log with the result. + */ @Action(object = ObjectType.DATABASE, desc = "Verify Table values with the Test Data sheet ", input = InputType.YES) public void verifyWithDataSheet() { String sheetName = Data; @@ -171,8 +209,8 @@ public void verifyWithDataSheet() { } /** - * Under the assumption that 1. User executed only SELECT Query 2. Returns a - * column with one or more rows + * Stores the result of a SELECT query in runtime variable(s) based on the specified condition. + * Assumes the query returns one or more rows in a column. */ @Action(object = ObjectType.DATABASE, desc = "Query and save the result in variable(s) ", input = InputType.YES, condition = InputType.YES) public void storeResultInVariable() { @@ -205,7 +243,8 @@ public void storeResultInVariable() { } /** - * Under the assumption that 1. User executed only SELECT Query + * Stores the result of a SELECT query in the datasheet based on the specified condition. + * Assumes the query returns one or more rows. */ @Action(object = ObjectType.DATABASE, desc = "Query and save the result in Datasheet ", input = InputType.YES, condition = InputType.YES) public void storeResultInDataSheet() { diff --git a/Engine/src/main/java/com/ing/engine/commands/database/General.java b/Engine/src/main/java/com/ing/engine/commands/database/General.java index 546832e5..7eab1892 100644 --- a/Engine/src/main/java/com/ing/engine/commands/database/General.java +++ b/Engine/src/main/java/com/ing/engine/commands/database/General.java @@ -19,8 +19,9 @@ import java.util.regex.Pattern; /** - * - * + * Provides database command utilities for executing SQL queries, managing connections, + * handling variable resolution, and storing results. This class is intended to be extended + * for specific database operations and supports both DML and SELECT queries. */ public class General extends Command { @@ -39,10 +40,23 @@ public class General extends Command { static final Pattern INPUTS = Pattern.compile("([^{]+?)(?=\\})"); static List colNames = new ArrayList<>(); + /** + * Constructs a General database command handler with the given command control. + * + * @param cc the command control context + */ public General(CommandControl cc) { super(cc); } + /** + * Verifies and establishes a database connection using the specified database name. + * + * @param dbName the name or alias of the database + * @return true if the connection is established successfully, false otherwise + * @throws ClassNotFoundException if the database driver class is not found + * @throws SQLException if a database access error occurs + */ public boolean verifyDbConnection(String dbName) throws ClassNotFoundException, SQLException { if (getDBFile(dbName).exists()) { Properties dbDetails = getDBDetails(dbName); @@ -95,32 +109,69 @@ private String resolveAllVariables(String str) { return str; } + /** + * Executes a SELECT SQL query after resolving variables and stores the result set. + * + * @throws SQLException if a database access error occurs + */ public void executeSelect() throws SQLException { String query = Data; query = handleDataSheetVariables(query); - query = handleuserDefinedVariables(query); + query = handleUserDefinedVariables(query); System.out.println("Query :" + query); result = statement.executeQuery(query); resultData = result.getMetaData(); populateColumnNames(); } - public boolean executeDML() throws SQLException { + /** + * Represents the result of a DML operation, including success status and the executed query. + */ + public static class DMLResult { + public final boolean success; + public final String query; + public DMLResult(boolean success, String query) { + this.success = success; + this.query = query; + } + } + + /** + * Executes a DML SQL query (INSERT, UPDATE, DELETE) after resolving variables. + * + * @return a DMLResult containing the success status and the executed query + * @throws SQLException if a database access error occurs + */ + public DMLResult executeDML() throws SQLException { String query = Data; - query = handleDataSheetVariables(query); - query = handleuserDefinedVariables(query); - System.out.println("Query :" + query); - return (statement.executeUpdate(query) >= 0); + query = handleDataSheetVariables(query); + query = handleUserDefinedVariables(query); + System.out.println("Executing DML query: :" + query); + boolean result = (statement.executeUpdate(query) >= 0); + return new DMLResult(result, query); } + /** + * Initializes the database connection, statement, and variable resolution. + * + * @param commit whether to use auto-commit mode + * @param timeout the query timeout in seconds + * @throws SQLException if a database access error occurs + */ private void initialize(Boolean commit,int timeout) throws SQLException { colNames.clear(); dbconnection.setAutoCommit(commit); - statement = dbconnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); + statement = dbconnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); statement.setQueryTimeout(timeout); resolveVars(); } + /** + * Closes the database connection, statement, and result set. + * + * @return true if all resources are closed successfully, false otherwise + * @throws SQLException if a database access error occurs + */ public boolean closeConnection() throws SQLException { if (dbconnection != null && statement != null && result != null) { dbconnection.close(); @@ -131,6 +182,13 @@ public boolean closeConnection() throws SQLException { return true; } + /** + * Asserts that a value exists in the specified column of the result set. + * + * @param columnName the column to check + * @param condition the value to assert + * @return true if the value exists, false otherwise + */ public boolean assertDB(String columnName, String condition) { boolean isExist = false; try { @@ -152,6 +210,13 @@ public boolean assertDB(String columnName, String condition) { return isExist; } + /** + * Stores a value from the result set in a variable or global variable. + * + * @param input the variable name + * @param condition the column and row specification + * @param isGlobal true to store as a global variable, false for local + */ public void storeValue(String input, String condition, boolean isGlobal) { String value; int rowIndex = 1; @@ -182,6 +247,9 @@ public void storeValue(String input, String condition, boolean isGlobal) { } } + /** + * Resolves variables in the Data string and replaces them with their values. + */ private void resolveVars() { Matcher matcher = INPUTS.matcher(Data); Set listMatches = new HashSet<>(); @@ -203,10 +271,21 @@ private void resolveVars() { } + /** + * Retrieves database properties for the specified database name. + * + * @param dbName the database name or alias + * @return the database properties + */ public Properties getDBDetails(String dbName) { return getDataBaseData(dbName); } + /** + * Populates the column names from the result set metadata. + * + * @throws SQLException if a database access error occurs + */ private void populateColumnNames() throws SQLException { int count = resultData.getColumnCount(); for (int index = 1; index <= count; index++) { @@ -214,10 +293,22 @@ private void populateColumnNames() throws SQLException { } } + /** + * Gets the index of the specified column name in the column list. + * + * @param columnName the column name to search for + * @return the index of the column, or -1 if not found + */ public int getColumnIndex(String columnName) { return colNames.indexOf(columnName); } + /** + * Resolves datasheet variables in the query string. + * + * @param query the SQL query string + * @return the query with datasheet variables replaced + */ private String handleDataSheetVariables(String query) { List sheetlist = Control.getCurrentProject().getTestData().getTestDataFor(Control.exe.runEnv()) .getTestDataNames(); @@ -237,7 +328,13 @@ private String handleDataSheetVariables(String query) { return query; } - private String handleuserDefinedVariables(String query) { + /** + * Resolves user-defined variables in the query string. + * + * @param query the SQL query string + * @return the query with user-defined variables replaced + */ + private String handleUserDefinedVariables(String query) { Collection valuelist = Control.getCurrentProject().getProjectSettings().getUserDefinedSettings() .values(); for (Object prop : valuelist) { diff --git a/Engine/src/main/java/com/ing/engine/commands/general/GeneralOperations.java b/Engine/src/main/java/com/ing/engine/commands/general/GeneralOperations.java index 2a6a9c6b..365ba704 100644 --- a/Engine/src/main/java/com/ing/engine/commands/general/GeneralOperations.java +++ b/Engine/src/main/java/com/ing/engine/commands/general/GeneralOperations.java @@ -376,7 +376,7 @@ public void storeDataFromPreviousTestCaseData() { *
  • {@code %PreviousSubIteration%}
  • * */ - @Action(object = ObjectType.GENERAL, desc = "Rest Required Variables for storeDataFromPreviousTestCaseData action", input = InputType.OPTIONAL) + @Action(object = ObjectType.GENERAL, desc = "Reset Required Variables for storeDataFromPreviousTestCaseData action", input = InputType.OPTIONAL) public void resetPreviousTestCaseDataVariables() { // Reset Variables addVar("%PreviousScenario%", null); diff --git a/Engine/src/main/java/com/ing/engine/commands/kafka/KafkaOperations.java b/Engine/src/main/java/com/ing/engine/commands/kafka/KafkaOperations.java index b4924e8f..a21a6270 100644 --- a/Engine/src/main/java/com/ing/engine/commands/kafka/KafkaOperations.java +++ b/Engine/src/main/java/com/ing/engine/commands/kafka/KafkaOperations.java @@ -1,1127 +1,1255 @@ -/** Kafka Operations related commands - -package com.ing.engine.commands.kafka; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.NullNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fasterxml.jackson.databind.node.TextNode; -import com.ing.engine.commands.browser.General; -import com.ing.engine.core.CommandControl; -import com.ing.engine.core.Control; -import com.ing.engine.support.Status; -import com.ing.engine.support.methodInf.Action; -import com.ing.engine.support.methodInf.InputType; -import com.ing.engine.support.methodInf.ObjectType; -import com.jayway.jsonpath.JsonPath; -import io.confluent.kafka.serializers.KafkaAvroDeserializer; -import io.confluent.kafka.serializers.KafkaAvroDeserializerConfig; -import io.confluent.kafka.serializers.KafkaAvroSerializer; -import java.io.ByteArrayInputStream; -import java.io.File; - -import java.time.Duration; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.Instant; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericDatumReader; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.Decoder; -import org.apache.avro.io.DecoderFactory; -import org.apache.kafka.common.errors.SerializationException; -import org.apache.kafka.clients.consumer.*; -import org.apache.kafka.clients.producer.KafkaProducer; -import org.apache.kafka.clients.producer.ProducerConfig; -import org.apache.kafka.clients.producer.ProducerRecord; -import org.apache.kafka.clients.producer.RecordMetadata; -import org.apache.kafka.common.config.SslConfigs; -import org.apache.kafka.common.header.Header; -import org.apache.kafka.common.header.internals.RecordHeader; -import org.apache.kafka.common.serialization.ByteArrayDeserializer; -import org.apache.kafka.common.serialization.ByteArraySerializer; -import org.apache.kafka.common.serialization.StringDeserializer; -import org.apache.kafka.common.serialization.StringSerializer; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public class KafkaOperations extends General { - -private final static ObjectMapper mapper = new ObjectMapper(); - - public KafkaOperations(CommandControl cc) { - super(cc); - } - - @Action(object = ObjectType.KAFKA, desc = "Add Kafka Header", input = InputType.YES) - public void addKafkaHeader() { - try { - - List sheetlist = Control.getCurrentProject().getTestData().getTestDataFor(Control.exe.runEnv()) - .getTestDataNames(); - for (int sheet = 0; sheet < sheetlist.size(); sheet++) { - if (Data.contains("{" + sheetlist.get(sheet) + ":")) { - com.ing.datalib.testdata.model.TestDataModel tdModel = Control.getCurrentProject().getTestData() - .getTestDataByName(sheetlist.get(sheet)); - List columns = tdModel.getColumns(); - for (int col = 0; col < columns.size(); col++) { - if (Data.contains("{" + sheetlist.get(sheet) + ":" + columns.get(col) + "}")) { - Data = Data.replace("{" + sheetlist.get(sheet) + ":" + columns.get(col) + "}", - userData.getData(sheetlist.get(sheet), columns.get(col))); - } - } - } - } - - Collection valuelist = Control.getCurrentProject().getProjectSettings().getUserDefinedSettings() - .values(); - for (Object prop : valuelist) { - if (Data.contains("{" + prop + "}")) { - Data = Data.replace("{" + prop + "}", prop.toString()); - } - } - String headerKey = Data.split("=", 2)[0]; - String headerValue = Data.split("=", 2)[1]; - - if (kafkaHeaders.containsKey(key)) { - kafkaHeaders.get(key).add(new RecordHeader(headerKey, headerValue.getBytes())); - } else { - ArrayList
    toBeAdded = new ArrayList
    (); - toBeAdded.add(new RecordHeader(headerKey, headerValue.getBytes())); - kafkaHeaders.put(key, toBeAdded); - } - - Report.updateTestLog(Action, "Header added " + Data, Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error adding Header :" + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Producer Topic", input = InputType.YES, condition = InputType.NO) - public void setProducerTopic() { - try { - kafkaProducerTopic.put(key, Data); - Report.updateTestLog(Action, "Topic has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Topic setup", ex); - Report.updateTestLog(Action, "Error in setting Topic: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Auto Register Schemas", input = InputType.YES, condition = InputType.NO) - public void setAutoRegisterSchemas() { - try { - kafkaAutoRegisterSchemas.put(key, Boolean.valueOf(Data.toLowerCase().trim())); - Report.updateTestLog(Action, "Auto Register Schemas has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception Max Poll Record setup", ex); - Report.updateTestLog(Action, "Error in Auto Register Schemas: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Consumer Topic", input = InputType.YES, condition = InputType.NO) - public void setConsumerTopic() { - try { - kafkaConsumerTopic.put(key, Data); - Report.updateTestLog(Action, "Topic has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Topic setup", ex); - Report.updateTestLog(Action, "Error in setting Topic: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Consumer Retries", input = InputType.YES, condition = InputType.NO) - public void setConsumerPollRetries() { - try { - kafkaConsumerPollRetries.put(key, Integer.parseInt(Data)); - Report.updateTestLog(Action, "Poll Retries has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Poll Retries setup", ex); - Report.updateTestLog(Action, "Error in setting Poll Retries: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Consumer Retries", input = InputType.YES, condition = InputType.NO) - public void setConsumerPollInterval() { - try { - kafkaConsumerPollDuration.put(key, Long.valueOf(Data)); - Report.updateTestLog(Action, "Poll interval has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Poll interval setup", ex); - Report.updateTestLog(Action, "Error in setting Poll interval: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Consumer Max Poll Records", input = InputType.YES, condition = InputType.NO) - public void setConsumerMaxPollRecords() { - try { - kafkaConsumerMaxPollRecords.put(key, Integer.valueOf(Data)); - Report.updateTestLog(Action, "Max Poll Records has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception Max Poll Record setup", ex); - Report.updateTestLog(Action, "Error in setting Max Poll Records: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Bootstrap Servers", input = InputType.YES, condition = InputType.NO) - public void setBootstrapServers() { - try { - kafkaServers.put(key, Data); - Report.updateTestLog(Action, "Bootstrap Servers have been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Bootstrap Servers setup", - ex); - Report.updateTestLog(Action, "Error in setting Bootstrap Servers: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Schema Registry URL", input = InputType.YES, condition = InputType.NO) - public void setSchemaRegistryURL() { - try { - kafkaSchemaRegistryURL.put(key, Data); - Report.updateTestLog(Action, "Schema Registry URL has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Schema Registry URL setup", - ex); - Report.updateTestLog(Action, "Error in setting Schema Registry URL: " + "\n" + ex.getMessage(), - Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Shared Secret", input = InputType.YES, condition = InputType.NO) - public void setSharedSecret() { - try { - kafkaSharedSecret.put(key, Data); - Report.updateTestLog(Action, "Shared Secret set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Shared Secret setup", ex); - Report.updateTestLog(Action, "Error in setting Shared Secret: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Key", input = InputType.YES, condition = InputType.NO) - public void setKey() { - try { - kafkaKey.put(key, Data); - Report.updateTestLog(Action, "Key has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Key setup", ex); - Report.updateTestLog(Action, "Error in setting Key: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Consumer GroupId", input = InputType.YES, condition = InputType.NO) - public void setConsumerGroupId() { - try { - kafkaConsumerGroupId.put(key, Data); - Report.updateTestLog(Action, "Consumer GroupId has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Consumer GroupId setup", - ex); - Report.updateTestLog(Action, "Error in setting Consumer GroupId: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Partition", input = InputType.YES, condition = InputType.NO) - public void setPartition() { - try { - if (Data.toLowerCase().equals("null")) { - kafkaPartition.put(key, null); - } else { - kafkaPartition.put(key, Integer.valueOf(Data)); - } - Report.updateTestLog(Action, "Partition has been set successfully", Status.DONE); - } catch (NumberFormatException ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Partition setup", ex); - Report.updateTestLog(Action, "Error in setting Partition: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set TimeStamp", input = InputType.NO, condition = InputType.NO) - public void setTimeStamp() { - try { - kafkaTimeStamp.put(key, System.currentTimeMillis()); - Report.updateTestLog(Action, "Time Stamp has been set successfully", Status.DONE); - } catch (NumberFormatException ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Time Stamp setup", ex); - Report.updateTestLog(Action, "Error in setting Time Stamp: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Key Serializer", input = InputType.YES, condition = InputType.NO) - public void setKeySerializer() { - try { - kafkaKeySerializer.put(key, Data); - Report.updateTestLog(Action, "Key Serializer has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Key Serializer setup", ex); - Report.updateTestLog(Action, "Error in setting Key Serializer: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Value Serializer", input = InputType.YES, condition = InputType.NO) - public void setValueSerializer() { - try { - kafkaValueSerializer.put(key, Data); - Report.updateTestLog(Action, "Value Serializer has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Value Serializer setup", - ex); - Report.updateTestLog(Action, "Error in setting Value Serializer: " + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Set Value Deserializer", input = InputType.YES, condition = InputType.NO) - public void setValueDeserializer() { - try { - kafkaValueDeserializer.put(key, Data); - Report.updateTestLog(Action, "Value Deserializer has been set successfully", Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Value Deserializer setup", - ex); - Report.updateTestLog(Action, "Error in setting Value Deserializer: " + "\n" + ex.getMessage(), - Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Add Avro Schema", input = InputType.YES, condition = InputType.NO) - public void addSchema() throws IOException { - try { - Schema mainSchema = null; - Schema.Parser parser = new Schema.Parser(); - if (Data.contains(";")) { - String[] paths = Data.split(";"); - for (int i = 0; i < paths.length - 1; i++) { - - parser.parse(new File(Paths.get(paths[i]).toString())); - } - mainSchema = parser.parse(new File(Paths.get(paths[paths.length - 1]).toString())); - - } else { - // Only one schema, no dependencies - mainSchema = new Schema.Parser().parse(new File(Paths.get(Data).toString())); - } - kafkaAvroSchema.put(key, mainSchema); - Report.updateTestLog(Action, "Schema added successfully", Status.DONE); - } catch (Exception e) { - Report.updateTestLog(Action, " Unable to add Schema : " + e.getMessage(), Status.FAIL); - } - - } - - @Action(object = ObjectType.KAFKA, desc = "Produce Kafka Message", input = InputType.YES, condition = InputType.NO) - public void produceMessage() { - try { - String value = Data; - value = handleDataSheetVariables(value); - value = handleuserDefinedVariables(value); - System.out.println("\n Generated Record is : \n " + value + "\n"); - kafkaValue.put(key, value); - if (kafkaValueSerializer.get(key).equals("avro")) { - getAvroCompatibleMessage(); - kafkaValue.put(key, kafkaAvroCompatibleMessage.get(key)); - produceGenericRecord(kafkaValue.get(key)); - } - if (kafkaHeaders.get(key) != null && kafkaTimeStamp.get(key) != null) { - produceMessage(kafkaProducerTopic.get(key), kafkaPartition.get(key), kafkaTimeStamp.get(key), - kafkaKey.get(key), kafkaValue.get(key), kafkaHeaders.get(key)); - } else if (kafkaHeaders.get(key) != null) { - produceMessage(kafkaProducerTopic.get(key), kafkaPartition.get(key), kafkaKey.get(key), - kafkaValue.get(key), kafkaHeaders.get(key)); - } else if (kafkaTimeStamp.get(key) != null) { - produceMessage(kafkaProducerTopic.get(key), kafkaPartition.get(key), kafkaTimeStamp.get(key), - kafkaKey.get(key), kafkaValue.get(key)); - } else if (kafkaPartition.containsKey(key)) { - produceMessage(kafkaProducerTopic.get(key), kafkaPartition.get(key), kafkaKey.get(key), - kafkaValue.get(key)); - } else if (kafkaKey.get(key) != null) { - produceMessage(kafkaProducerTopic.get(key), kafkaKey.get(key), kafkaValue.get(key)); - } else { - produceMessage(kafkaProducerTopic.get(key), kafkaValue.get(key)); - } - - Report.updateTestLog(Action, "Message has been produced. ", Status.DONE); - - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Something went wrong in producing the message" + "\n" + ex.getMessage(), - Status.FAILNS); - ex.printStackTrace(); - } - } - - public void produceGenericRecord(Object message) { - try { - InputStream input = new ByteArrayInputStream(((String) message).getBytes()); - Decoder decoder = DecoderFactory.get().jsonDecoder(kafkaAvroSchema.get(key), input); - GenericDatumReader reader = new GenericDatumReader<>(kafkaAvroSchema.get(key)); - GenericRecord record = reader.read(null, decoder); - kafkaValue.put(key, record); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - @Action(object = ObjectType.KAFKA, desc = "Send Message", input = InputType.NO, condition = InputType.NO) - public void sendKafkaMessage() { - try { - createProducer(kafkaValueSerializer.get(key)); - - kafkaProducer.get(key).send(kafkaProducerRecord.get(key), - (RecordMetadata metadata, Exception exception) -> { - if (exception != null) { - Report.updateTestLog(Action, "Error in sending record : " + exception.getMessage(), - Status.FAIL); - } else { - Report.updateTestLog(Action, - "Record sent to [topic: " + metadata.topic() + ", partition: " - + metadata.partition() + ", offset: " + metadata.offset() + ", timestamp: " - + metadata.timestamp() + "]", - Status.DONE); - } - }); - - kafkaProducer.get(key).close(); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception while sending record", ex); - Report.updateTestLog(Action, "Error in sending record: " + "\n" + ex.getMessage(), Status.DEBUG); - } finally { - clearProducerDetails(); - } - } - - private void createProducer(String serializer) { -// getProducersslConfigurations(); - Properties props = new Properties(); - if (isProducersslEnabled()) { - props = getProducersslConfigurations(props); - props.put("security.protocol", "SSL"); - } - props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers.get(key)); - if (kafkaConfigs.containsKey(key)) { - props = addConfigProps(props); - } - if (serializer.toLowerCase().contains("string")) { - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); - } else if (serializer.toLowerCase().contains("bytearray")) { - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); - } else if (serializer.toLowerCase().contains("avro")) { - props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName()); - props.put("schema.registry.url", kafkaSchemaRegistryURL.get(key)); - if (kafkaAutoRegisterSchemas.get(key) != null) { - props.put("auto.register.schemas", kafkaAutoRegisterSchemas.get(key)); - } - - } else { - throw new IllegalArgumentException("Unsupported value type"); - } - - props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); - kafkaProducer.put(key, new KafkaProducer<>(props)); - } - - private void produceMessage(String topic, Object value) { - kafkaProducerRecord.put(key, new ProducerRecord<>(topic, value)); - } - - private void produceMessage(String topic, String kafkaKey, Object value) { - kafkaProducerRecord.put(key, new ProducerRecord<>(topic, kafkaKey, value)); - } - - private void produceMessage(String topic, Integer partition, String kafkaKey, Object value) { - kafkaProducerRecord.put(key, new ProducerRecord<>(topic, partition, kafkaKey, value)); - } - - private void produceMessage(String topic, Integer partition, long timestamp, String kafkaKey, Object value) { - kafkaProducerRecord.put(key, new ProducerRecord<>(topic, partition, timestamp, kafkaKey, value)); - } - - private void produceMessage(String topic, Integer partition, String kafkaKey, Object value, List
    headers) { - kafkaProducerRecord.put(key, new ProducerRecord<>(topic, partition, kafkaKey, value, headers)); - } - - private void produceMessage(String topic, Integer partition, long timestamp, String kafkaKey, Object value, - List
    headers) { - kafkaProducerRecord.put(key, new ProducerRecord<>(topic, partition, timestamp, kafkaKey, value, headers)); - } - - private String handleDataSheetVariables(String payloadstring) { - List sheetlist = Control.getCurrentProject().getTestData().getTestDataFor(Control.exe.runEnv()) - .getTestDataNames(); - for (int sheet = 0; sheet < sheetlist.size(); sheet++) { - if (payloadstring.contains("{" + sheetlist.get(sheet) + ":")) { - com.ing.datalib.testdata.model.TestDataModel tdModel = Control.getCurrentProject().getTestData() - .getTestDataByName(sheetlist.get(sheet)); - List columns = tdModel.getColumns(); - for (int col = 0; col < columns.size(); col++) { - if (payloadstring.contains("{" + sheetlist.get(sheet) + ":" + columns.get(col) + "}")) { - payloadstring = payloadstring.replace("{" + sheetlist.get(sheet) + ":" + columns.get(col) + "}", - userData.getData(sheetlist.get(sheet), columns.get(col))); - } - } - } - } - return payloadstring; - } - - private String handleuserDefinedVariables(String payloadstring) { - Collection valuelist = Control.getCurrentProject().getProjectSettings().getUserDefinedSettings() - .values(); - for (Object prop : valuelist) { - if (payloadstring.contains("{" + prop + "}")) { - payloadstring = payloadstring.replace("{" + prop + "}", prop.toString()); - } - } - return payloadstring; - } - - private void clearProducerDetails() { - kafkaKey.clear(); - kafkaHeaders.clear(); - kafkaProducerTopic.clear(); - kafkaPartition.clear(); - kafkaTimeStamp.clear(); - kafkaKeySerializer.clear(); - kafkaValue.clear(); - kafkaValueSerializer.clear(); - kafkaProducer.clear(); - kafkaProducerRecord.clear(); - kafkaAvroSchema.clear(); - kafkaGenericRecord.clear(); - kafkaAvroProducer.clear(); - kafkaConfigs.clear(); - kafkaProducersslConfigs.clear(); - kafkaAvroCompatibleMessage.clear(); - kafkaSharedSecret.clear(); - kafkaAutoRegisterSchemas.clear(); - } - - public void createConsumer(String deserializer) { - try { - Properties props = new Properties(); - if (isConsumersslEnabled()) { - props = getConsumersslConfigurations(props); - props.put("security.protocol", "SSL"); - } - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers.get(key)); - props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConsumerGroupId.get(key)); - if (kafkaConsumerMaxPollRecords.get(key) != null) { - props.put("max.poll.records", kafkaConsumerMaxPollRecords.get(key)); - } - if (deserializer.toLowerCase().contains("string")) { - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); - } else if (deserializer.toLowerCase().contains("bytearray")) { - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); - } else if (deserializer.toLowerCase().contains("avro")) { - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class.getName()); - props.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, "false"); - props.put("schema.registry.url", kafkaSchemaRegistryURL.get(key)); - - } else { - throw new IllegalArgumentException("Unsupported value type"); - } - - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); - props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - - kafkaConsumer.put(key, new KafkaConsumer<>(props)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Consume Kafka Message", input = InputType.NO) - public void consumeKafkaMessage() { - try { - createConsumer(kafkaValueDeserializer.get(key)); - kafkaConsumer.get(key).subscribe(Arrays.asList(kafkaConsumerTopic.get(key))); - ConsumerRecords record = pollKafkaConsumer(); - if (record != null && kafkaConsumeRecordValue.containsKey(key)) { - Report.updateTestLog(Action, "Kafka messages consumed successfully and Target message found.", - Status.DONE); - } else if (record != null && !kafkaConsumeRecordValue.containsKey(key) - && kafkaConsumerPollRecord.containsKey(key)) { - Report.updateTestLog(Action, "Kafka messages consumed successfully but target message not found.", - Status.FAILNS); - } else { - Report.updateTestLog(Action, "Kafka message not received.", Status.FAIL); - } - } catch (Exception e) { - e.printStackTrace(); - Report.updateTestLog(Action, "Error while consuming Kafka message: " + e.getMessage(), Status.FAIL); - } finally { - kafkaConsumer.get(key).close(); - } - } - - private ConsumerRecords pollKafkaConsumer() throws SerializationException { - int maxRetries = kafkaConsumerPollRetries.get(key); - int attempt = 1; - boolean matchRecordFound = false; - List> allRecords = new ArrayList<>(); - - while (attempt <= maxRetries) { - try { - ConsumerRecords pollRecords = kafkaConsumer.get(key) - .poll(Duration.ofMillis(kafkaConsumerPollDuration.get(key))); - if (!pollRecords.isEmpty()) { - for (ConsumerRecord record : pollRecords) { - kafkaConsumerPollRecord.put(key, record); - allRecords.add(record); - if (findAndSetTargetRecordForAssertion()) { - matchRecordFound = true; - break; - } - } - if (matchRecordFound) { - System.out.println("Record consumed in attempt " + attempt + " are " + pollRecords.count() - + " and Record found with unique identifier."); - System.out.println("Details of record found with unique idetifier are as follows : "); - System.out.println("Key : " + kafkaConsumerPollRecord.get(key).key()); - System.out.println("Partition : " + kafkaConsumerPollRecord.get(key).partition()); - System.out.println("Offset : " + kafkaConsumerPollRecord.get(key).offset()); - System.out.println("Value : " + kafkaConsumerPollRecord.get(key).value()); - return pollRecords; - } else { - System.out.println("Record consumed in attempt " + attempt + " are " + pollRecords.count() - + ". But, no Record found with unique identifier."); - } - attempt++; - } else { - System.out.println("Record consumed in attempt " + attempt + " are " + pollRecords.count() + "."); - attempt++; - } - - } catch (Exception e) { - System.out.println("Error in polling records : " + e.getMessage()); - attempt++; - } - } - return null; - } - - @Action(object = ObjectType.KAFKA, desc = "Identify target message", input = InputType.YES, condition = InputType.YES) - public void identifyTargetMessage() { - try { - kafkaRecordIdentifierValue.put(key, Data); - kafkaRecordIdentifierPath.put(key, Condition); - Report.updateTestLog(Action, - "Target message set with tag value as [" + Data + "] and tag path as [" + Condition + "].", - Status.DONE); - } catch (Exception e) { - Report.updateTestLog(Action, "Error in target message setup : " + e.getMessage(), Status.FAIL); - } - } - - public boolean findAndSetTargetRecordForAssertion() { // identifyTargetMessage - boolean matchFound = false; - try { - if (kafkaConsumerPollRecord.get(key).value() != null) { - String recordValue = kafkaConsumerPollRecord.get(key).value().toString(); - boolean isJson = Pattern.matches("^\\s*(\\{.*\\}|\\[.*\\])\\s*$", recordValue); - boolean isXml = Pattern.matches("^\\s*<\\?*xml*.*>.*<.*>.*\\s*$", recordValue); - - if (isJson) { - if (getJSONRecordForAssertion(recordValue)) { - matchFound = true; - } - - } else if (isXml) { - if (getXMLRecordForAssertion(recordValue)) { - matchFound = true; - } - } else { - System.out.println("Unknown format"); - } - } - } catch (Exception e) { - System.out.println("Error in find and set target record for assertion : " + e.getMessage()); - } - return matchFound; - } - - public boolean getJSONRecordForAssertion(String JSONMessage) { - try { - String jsonpath = kafkaRecordIdentifierPath.get(key); - String value = JsonPath.read(JSONMessage, jsonpath).toString(); - if (value.equals(kafkaRecordIdentifierValue.get(key))) { - kafkaConsumeRecordValue.put(key, JSONMessage); - return true; - } - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error in validating JSON element :" + "\n" + ex.getMessage(), Status.DEBUG); - } - return false; - } - - public boolean getXMLRecordForAssertion(String XMLMessage) { - try { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dBuilder; - InputSource inputSource = new InputSource(); - inputSource.setCharacterStream(new StringReader(XMLMessage)); - dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(inputSource); - doc.getDocumentElement().normalize(); - XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = kafkaRecordIdentifierPath.get(key); - String value = (String) xPath.compile(expression).evaluate(doc); - if (value.equals(kafkaRecordIdentifierValue.get(key))) { - kafkaConsumeRecordValue.put(key, XMLMessage); - return true; - } - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error in validating XML element :" + "\n" + ex.getMessage(), Status.DEBUG); - } - return false; - } - - @Action(object = ObjectType.KAFKA, desc = "Close Consumer", input = InputType.NO, condition = InputType.NO) - public void closeConsumer() { - try { - kafkaConsumerRecords.remove(key); - kafkaConsumerRecord.remove(key); - kafkaConsumeRecordValue.remove(key); - kafkaConsumerPollDuration.remove(key); - kafkaConsumerPollRetries.remove(key); - kafkaConsumerTopic.remove(key); - kafkaValueDeserializer.remove(key); - kafkaSchemaRegistryURL.remove(key); - kafkaSharedSecret.remove(key); - kafkaConsumerGroupId.remove(key); - kafkaConsumerPollRecord.remove(key); - kafkaRecordIdentifierValue.remove(key); - kafkaRecordIdentifierPath.remove(key); - Report.updateTestLog(Action, "Consumer closed successfully", Status.DONE); - } catch (Exception ex) { - Report.updateTestLog(Action, "Error in closing Consumer.", Status.DEBUG); - } - - } - - @Action(object = ObjectType.KAFKA, desc = "Store XML tag In DataSheet ", input = InputType.YES, condition = InputType.NO) - public void storeKafkaXMLtagInDataSheet() { - - try { - String strObj = Input; - if (strObj.matches(".*:.*")) { - try { - System.out.println("Updating value in SubIteration " + userData.getSubIteration()); - String sheetName = strObj.split(":", 2)[0]; - String columnName = strObj.split(":", 2)[1]; - String xmlText = kafkaConsumeRecordValue.get(key); - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dBuilder; - InputSource inputSource = new InputSource(); - inputSource.setCharacterStream(new StringReader(xmlText)); - dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(inputSource); - doc.getDocumentElement().normalize(); - XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = Condition; - String value = (String) xPath.compile(expression).evaluate(doc); - userData.putData(sheetName, columnName, value); - Report.updateTestLog(Action, "Element text [" + value + "] is stored in " + strObj, Status.DONE); - } catch (IOException | ParserConfigurationException | XPathExpressionException | DOMException - | SAXException ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, ex.getMessage(), ex); - Report.updateTestLog(Action, "Error Storing XML element in datasheet :" + "\n" + ex.getMessage(), - Status.DEBUG); - } - } else { - Report.updateTestLog(Action, - "Given input [" + Input + "] format is invalid. It should be [sheetName:ColumnName]", - Status.DEBUG); - } - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error Storing XML element in datasheet :" + "\n" + ex.getMessage(), - Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Assert XML Tag Equals ", input = InputType.YES, condition = InputType.YES) - public void assertKafkaXMLtagEquals() { - try { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dBuilder; - InputSource inputSource = new InputSource(); - inputSource.setCharacterStream(new StringReader(kafkaConsumeRecordValue.get(key))); - dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(inputSource); - doc.getDocumentElement().normalize(); - XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = Condition; - String value = (String) xPath.compile(expression).evaluate(doc); - if (value.equals(Data)) { - Report.updateTestLog(Action, "Element text [" + value + "] is as expected", Status.PASSNS); - } else { - Report.updateTestLog(Action, "Element text [" + value + "] is not as expected", Status.FAILNS); - } - } catch (IOException | ParserConfigurationException | XPathExpressionException | DOMException - | SAXException ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error validating XML element :" + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Assert XML Tag Contains ", input = InputType.YES, condition = InputType.YES) - public void assertKafkaXMLtagContains() { - try { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder dBuilder; - InputSource inputSource = new InputSource(); - inputSource.setCharacterStream(new StringReader(kafkaConsumeRecordValue.get(key))); - dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(inputSource); - doc.getDocumentElement().normalize(); - XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = Condition; - String value = (String) xPath.compile(expression).evaluate(doc); - if (value.contains(Data)) { - Report.updateTestLog(Action, "Element text contains [" + Data + "] is as expected", Status.PASSNS); - } else { - Report.updateTestLog(Action, "Element text [" + value + "] does not contain [" + Data + "]", - Status.FAILNS); - } - } catch (IOException | ParserConfigurationException | XPathExpressionException | DOMException - | SAXException ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error validating XML element :" + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Assert Response Message contains ", input = InputType.YES) - public void assertKafkaResponseMessageContains() { - try { - if (kafkaConsumeRecordValue.get(key).contains(Data)) { - Report.updateTestLog(Action, "Response Message contains : " + Data, Status.PASSNS); - } else { - Report.updateTestLog(Action, "Response Message does not contain : " + Data, Status.FAILNS); - } - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error in validating response body :" + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Assert JSON Tag Equals ", input = InputType.YES, condition = InputType.YES) - public void assertKafkaJSONtagEquals() { - try { - String response = kafkaConsumeRecordValue.get(key); - String jsonpath = Condition; - String value = JsonPath.read(response, jsonpath).toString(); - if (value.equals(Data)) { - Report.updateTestLog(Action, "Element text [" + value + "] is as expected", Status.PASSNS); - } else { - Report.updateTestLog(Action, "Element text is [" + value + "] but is expected to be [" + Data + "]", - Status.FAILNS); - } - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error in validating JSON element :" + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Assert JSON Tag Contains ", input = InputType.YES, condition = InputType.YES) - public void assertKafkaJSONtagContains() { - try { - String response = kafkaConsumeRecordValue.get(key); - String jsonpath = Condition; - String value = JsonPath.read(response, jsonpath).toString(); - if (value.contains(Data)) { - Report.updateTestLog(Action, "Element text contains [" + Data + "] is as expected", Status.PASSNS); - } else { - Report.updateTestLog(Action, "Element text [" + value + "] does not contain [" + Data + "]", - Status.FAILNS); - } - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error in validating JSON element :" + "\n" + ex.getMessage(), Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Store JSON Tag In DataSheet ", input = InputType.YES, condition = InputType.YES) - public void storeKafkaJSONtagInDataSheet() { - - try { - String strObj = Input; - if (strObj.matches(".*:.*")) { - try { - System.out.println("Updating value in SubIteration " + userData.getSubIteration()); - String sheetName = strObj.split(":", 2)[0]; - String columnName = strObj.split(":", 2)[1]; - String response = kafkaConsumeRecordValue.get(key); - String jsonpath = Condition; - String value = JsonPath.read(response, jsonpath).toString(); - userData.putData(sheetName, columnName, value); - Report.updateTestLog(Action, "Element text [" + value + "] is stored in " + strObj, Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, ex.getMessage(), ex); - Report.updateTestLog(Action, "Error Storing JSON element in datasheet :" + "\n" + ex.getMessage(), - Status.DEBUG); - } - } else { - Report.updateTestLog(Action, - "Given input [" + Input + "] format is invalid. It should be [sheetName:ColumnName]", - Status.DEBUG); - } - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error Storing JSON element in datasheet :" + "\n" + ex.getMessage(), - Status.DEBUG); - } - } - - @Action(object = ObjectType.KAFKA, desc = "Store Response In DataSheet ", input = InputType.YES, condition = InputType.NO) - public void storeKafkaResponseInDataSheet() { - - try { - String strObj = Input; - if (strObj.matches(".*:.*")) { - try { - System.out.println("Updating value in SubIteration " + userData.getSubIteration()); - String sheetName = strObj.split(":", 2)[0]; - String columnName = strObj.split(":", 2)[1]; - String response = kafkaConsumeRecordValue.get(key); - userData.putData(sheetName, columnName, response); - Report.updateTestLog(Action, "Response is stored in " + strObj, Status.DONE); - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, ex.getMessage(), ex); - Report.updateTestLog(Action, "Error storing Response in datasheet :" + "\n" + ex.getMessage(), - Status.DEBUG); - } - } else { - Report.updateTestLog(Action, - "Given input [" + Input + "] format is invalid. It should be [sheetName:ColumnName]", - Status.DEBUG); - } - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - Report.updateTestLog(Action, "Error storing Response in datasheet :" + "\n" + ex.getMessage(), - Status.DEBUG); - } - } - - // to add Configs in props - public Properties addConfigProps(Properties props) { - for (String config : kafkaConfigs.get(key)) { - String[] keyValue = config.split("=", 2); - if (keyValue.length == 2) { - props.put(keyValue[0], keyValue[1]); - } - } - return props; - } - - public Properties getProducersslConfigurations(Properties prop) { - Properties sslProp = Control.getCurrentProject().getProjectSettings().getKafkaSSLConfigurations(); - Set keys = sslProp.stringPropertyNames(); - for (String key : keys) { - String value = sslProp.getProperty(key); - value = handleDataSheetVariables(value); - value = handleuserDefinedVariables(value); - switch (key) { - case "Producer_ssl_Enabled": - Boolean.valueOf(value); - break; - case "Producer_Truststore_Location": - String producertrustStroreLocation = Paths.get(value).toAbsolutePath().toString(); - prop.put("ssl.truststore.location", producertrustStroreLocation); - break; - case "Producer_Truststore_Password": - prop.put("ssl.truststore.password", value); - break; - case "Producer_Keystore_Location": - String producerKeyStroreLocation = Paths.get(value).toAbsolutePath().toString(); - prop.put("ssl.keystore.location", producerKeyStroreLocation); - break; - case "Producer_Keystore_Password": - prop.put("ssl.keystore.password", value); - break; - case "Producer_Key_Password": - prop.put("ssl.key.password", value); - break; - } - } - return prop; - } - - public Properties getConsumersslConfigurations(Properties prop) { - Properties sslProp = Control.getCurrentProject().getProjectSettings().getKafkaSSLConfigurations(); - Set keys = sslProp.stringPropertyNames(); - for (String key : keys) { - String value = sslProp.getProperty(key); - value = handleDataSheetVariables(value); - value = handleuserDefinedVariables(value); - switch (key) { - case "Consumer_ssl_Enabled": - break; - case "Consumer_Truststore_Location": - String trustStroreLocation = Paths.get(value).toAbsolutePath().toString(); - prop.put("ssl.truststore.location", trustStroreLocation); - break; - case "Consumer_Truststore_Password": - prop.put("ssl.truststore.password", value); - break; - case "Consumer_Keystore_Location": - String consumerKeyStroreLocation = Paths.get(value).toAbsolutePath().toString(); - prop.put("ssl.keystore.location", consumerKeyStroreLocation); - break; - case "Consumer_Keystore_Password": - prop.put("ssl.keystore.password", value); - break; - case "Consumer_Key_Password": - prop.put("ssl.key.password", value); - break; - } - } - return prop; - } - - public boolean isProducersslEnabled() { - Properties prop = Control.getCurrentProject().getProjectSettings().getKafkaSSLConfigurations(); - String value = prop.getProperty("Producer_ssl_Enabled"); - value = handleRuntimeValues(value); - return "true".equalsIgnoreCase(value); - - } - - public String handleRuntimeValues(String value) { - value = handleDataSheetVariables(value); - value = handleuserDefinedVariables(value); - return value; - } - - public boolean isConsumersslEnabled() { - Properties prop = Control.getCurrentProject().getProjectSettings().getKafkaSSLConfigurations(); - String value = prop.getProperty("Consumer_ssl_Enabled"); - value = handleRuntimeValues(value); - return "true".equalsIgnoreCase(value); - } - - // Added to create avro compatible message - public void getAvroCompatibleMessage() { - String jsonAvroMessage = ""; - try { - ObjectMapper stringMapper = new ObjectMapper(); - JsonNode inputJson = mapper.readTree(kafkaValue.get(key).toString()); -// JsonNode inputJson = stringMapper.readTree((String) kafkaValue.get(key)); - JsonNode avroCompatibleJson = convertNode(inputJson, kafkaAvroSchema.get(key)); - jsonAvroMessage = stringMapper.writerWithDefaultPrettyPrinter().writeValueAsString(avroCompatibleJson); - kafkaAvroCompatibleMessage.put(key, jsonAvroMessage); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private static JsonNode convertNode(JsonNode input, Schema schema) { - switch (schema.getType()) { - case RECORD: - ObjectNode recordNode = mapper.createObjectNode(); - for (Schema.Field field : schema.getFields()) { - JsonNode value = input.get(field.name()); - recordNode.set(field.name(), convertNode(value, field.schema())); - } - return recordNode; - - case ARRAY: - ArrayNode arrayNode = mapper.createArrayNode(); - for (JsonNode item : input) { - arrayNode.add(convertNode(item, schema.getElementType())); - } - return arrayNode; - - case MAP: - ObjectNode mapNode = mapper.createObjectNode(); - for (Iterator> it = input.fields(); it.hasNext();) { - Map.Entry entry = it.next(); - mapNode.set(entry.getKey(), convertNode(entry.getValue(), schema.getValueType())); - } - return mapNode; - - case UNION: - for (Schema subSchema : schema.getTypes()) { - if (subSchema.getType() == Schema.Type.NULL && (input == null || input.isNull())) { - return NullNode.getInstance(); - } - - if (isCompatible(input, subSchema)) { - JsonNode wrapped = convertNode(input, subSchema); - ObjectNode unionNode = mapper.createObjectNode(); - - // ✅ Use fully qualified name for ENUM and RECORD - String typeName = (subSchema.getType() == Schema.Type.RECORD - || subSchema.getType() == Schema.Type.ENUM) ? subSchema.getFullName() - : subSchema.getType().getName(); - - unionNode.set(typeName, wrapped); - return unionNode; - } - } - - System.err.println("❌ No matching type in union for value: " + input); - System.err.println("Schema: " + schema.toString(true)); - throw new IllegalArgumentException("No matching type in union for value: " + input); - - case ENUM: - return new TextNode(input.textValue()); - - default: - return input; - } - } - - private static boolean isCompatible(JsonNode value, Schema schema) { - switch (schema.getType()) { - case STRING: - return value.isTextual(); - case INT: - return value.isInt(); - case LONG: - return value.isLong() || value.isInt(); - case FLOAT: - return value.isFloat() || value.isDouble(); - case DOUBLE: - return value.isDouble() || value.isFloat(); - case BOOLEAN: - return value.isBoolean(); - case NULL: - return value == null || value.isNull(); - case RECORD: - return value.isObject(); - case ARRAY: - return value.isArray(); - case MAP: - return value.isObject(); - case ENUM: - return value.isTextual() && schema.getEnumSymbols().contains(value.textValue()); - default: - return false; - } - } -} - -*/ \ No newline at end of file +// /** Kafka Operations related commands */ + +// package com.ing.engine.commands.kafka; + +// import com.fasterxml.jackson.core.JsonParser; +// import com.fasterxml.jackson.databind.JsonNode; +// import com.fasterxml.jackson.databind.ObjectMapper; +// import com.fasterxml.jackson.databind.node.ArrayNode; +// import com.fasterxml.jackson.databind.node.NullNode; +// import com.fasterxml.jackson.databind.node.ObjectNode; +// import com.fasterxml.jackson.databind.node.TextNode; +// import com.ing.engine.commands.browser.General; +// import com.ing.engine.core.CommandControl; +// import com.ing.engine.core.Control; +// import com.ing.engine.support.Status; +// import com.ing.engine.support.methodInf.Action; +// import com.ing.engine.support.methodInf.InputType; +// import com.ing.engine.support.methodInf.ObjectType; +// import com.jayway.jsonpath.JsonPath; +// import io.confluent.kafka.serializers.KafkaAvroDeserializer; +// import io.confluent.kafka.serializers.KafkaAvroDeserializerConfig; +// import io.confluent.kafka.serializers.KafkaAvroSerializer; +// import java.io.ByteArrayInputStream; +// import java.io.File; + +// import java.time.Duration; +// import java.util.*; +// import java.util.logging.Level; +// import java.util.logging.Logger; +// import java.util.regex.Pattern; +// import java.io.IOException; +// import java.io.InputStream; +// import java.io.StringReader; +// import java.nio.file.Path; +// import java.nio.file.Paths; +// import java.time.Instant; +// import javax.xml.parsers.DocumentBuilder; +// import javax.xml.parsers.DocumentBuilderFactory; +// import javax.xml.parsers.ParserConfigurationException; +// import javax.xml.xpath.XPath; +// import javax.xml.xpath.XPathExpressionException; +// import javax.xml.xpath.XPathFactory; +// import org.apache.avro.Schema; +// import org.apache.avro.generic.GenericDatumReader; +// import org.apache.avro.generic.GenericRecord; +// import org.apache.avro.io.Decoder; +// import org.apache.avro.io.DecoderFactory; +// import org.apache.kafka.common.errors.SerializationException; +// import org.apache.kafka.clients.consumer.*; +// import org.apache.kafka.clients.producer.KafkaProducer; +// import org.apache.kafka.clients.producer.ProducerConfig; +// import org.apache.kafka.clients.producer.ProducerRecord; +// import org.apache.kafka.clients.producer.RecordMetadata; +// import org.apache.kafka.common.config.SslConfigs; +// import org.apache.kafka.common.header.Header; +// import org.apache.kafka.common.header.internals.RecordHeader; +// import org.apache.kafka.common.serialization.ByteArrayDeserializer; +// import org.apache.kafka.common.serialization.ByteArraySerializer; +// import org.apache.kafka.common.serialization.StringDeserializer; +// import org.apache.kafka.common.serialization.StringSerializer; +// import org.w3c.dom.DOMException; +// import org.w3c.dom.Document; +// import org.xml.sax.InputSource; +// import org.xml.sax.SAXException; + +// /** +// * Provides end‑to‑end Kafka producer and consumer utilities for the test framework, including +// * topic setup, SSL/Schema Registry configuration, message production (String/byte[]/Avro), +// * and consumption with retry-based polling. Also supports JSONPath/XPath assertions to +// * identify a target record and store or validate fields from consumed messages. +// * +// *

    State is maintained per framework {@code key}, allowing multiple independent Kafka +// * operations. Not thread‑safe. +// */ +// public class KafkaOperations extends General { + +// private final static ObjectMapper mapper = new ObjectMapper(); + +// public KafkaOperations(CommandControl cc) { +// super(cc); +// } + +// @Action(object = ObjectType.KAFKA, desc = "Add Kafka Header", input = InputType.YES) +// public void addKafkaHeader() { +// try { + +// List sheetlist = Control.getCurrentProject().getTestData().getTestDataFor(Control.exe.runEnv()) +// .getTestDataNames(); +// for (int sheet = 0; sheet < sheetlist.size(); sheet++) { +// if (Data.contains("{" + sheetlist.get(sheet) + ":")) { +// com.ing.datalib.testdata.model.TestDataModel tdModel = Control.getCurrentProject().getTestData() +// .getTestDataByName(sheetlist.get(sheet)); +// List columns = tdModel.getColumns(); +// for (int col = 0; col < columns.size(); col++) { +// if (Data.contains("{" + sheetlist.get(sheet) + ":" + columns.get(col) + "}")) { +// Data = Data.replace("{" + sheetlist.get(sheet) + ":" + columns.get(col) + "}", +// userData.getData(sheetlist.get(sheet), columns.get(col))); +// } +// } +// } +// } + +// Collection valuelist = Control.getCurrentProject().getProjectSettings().getUserDefinedSettings() +// .values(); +// for (Object prop : valuelist) { +// if (Data.contains("{" + prop + "}")) { +// Data = Data.replace("{" + prop + "}", prop.toString()); +// } +// } +// String headerKey = Data.split("=", 2)[0]; +// String headerValue = Data.split("=", 2)[1]; + +// if (kafkaHeaders.containsKey(key)) { +// kafkaHeaders.get(key).add(new RecordHeader(headerKey, headerValue.getBytes())); +// } else { +// ArrayList
    toBeAdded = new ArrayList
    (); +// toBeAdded.add(new RecordHeader(headerKey, headerValue.getBytes())); +// kafkaHeaders.put(key, toBeAdded); +// } + +// Report.updateTestLog(Action, "Header added " + Data, Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error adding Header :" + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Producer Topic", input = InputType.YES, condition = InputType.NO) +// public void setProducerTopic() { +// try { +// kafkaProducerTopic.put(key, Data); +// Report.updateTestLog(Action, "Topic has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Topic setup", ex); +// Report.updateTestLog(Action, "Error in setting Topic: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Auto Register Schemas", input = InputType.YES, condition = InputType.NO) +// public void setAutoRegisterSchemas() { +// try { +// kafkaAutoRegisterSchemas.put(key, Boolean.valueOf(Data.toLowerCase().trim())); +// Report.updateTestLog(Action, "Auto Register Schemas has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception Max Poll Record setup", ex); +// Report.updateTestLog(Action, "Error in Auto Register Schemas: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Consumer Topic", input = InputType.YES, condition = InputType.NO) +// public void setConsumerTopic() { +// try { +// kafkaConsumerTopic.put(key, Data); +// Report.updateTestLog(Action, "Topic has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Topic setup", ex); +// Report.updateTestLog(Action, "Error in setting Topic: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Consumer Retries", input = InputType.YES, condition = InputType.NO) +// public void setConsumerPollRetries() { +// try { +// kafkaConsumerPollRetries.put(key, Integer.parseInt(Data)); +// Report.updateTestLog(Action, "Poll Retries has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Poll Retries setup", ex); +// Report.updateTestLog(Action, "Error in setting Poll Retries: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Consumer Retries", input = InputType.YES, condition = InputType.NO) +// public void setConsumerPollInterval() { +// try { +// kafkaConsumerPollDuration.put(key, Long.valueOf(Data)); +// Report.updateTestLog(Action, "Poll interval has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Poll interval setup", ex); +// Report.updateTestLog(Action, "Error in setting Poll interval: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Consumer Max Poll Records", input = InputType.YES, condition = InputType.NO) +// public void setConsumerMaxPollRecords() { +// try { +// kafkaConsumerMaxPollRecords.put(key, Integer.valueOf(Data)); +// Report.updateTestLog(Action, "Max Poll Records has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception Max Poll Record setup", ex); +// Report.updateTestLog(Action, "Error in setting Max Poll Records: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Bootstrap Servers", input = InputType.YES, condition = InputType.NO) +// public void setBootstrapServers() { +// try { +// kafkaServers.put(key, Data); +// Report.updateTestLog(Action, "Bootstrap Servers have been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Bootstrap Servers setup", +// ex); +// Report.updateTestLog(Action, "Error in setting Bootstrap Servers: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Schema Registry URL", input = InputType.YES, condition = InputType.NO) +// public void setSchemaRegistryURL() { +// try { +// kafkaSchemaRegistryURL.put(key, Data); +// Report.updateTestLog(Action, "Schema Registry URL has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Schema Registry URL setup", +// ex); +// Report.updateTestLog(Action, "Error in setting Schema Registry URL: " + "\n" + ex.getMessage(), +// Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Shared Secret", input = InputType.YES, condition = InputType.NO) +// public void setSharedSecret() { +// try { +// kafkaSharedSecret.put(key, Data); +// Report.updateTestLog(Action, "Shared Secret set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Shared Secret setup", ex); +// Report.updateTestLog(Action, "Error in setting Shared Secret: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Key", input = InputType.YES, condition = InputType.NO) +// public void setKey() { +// try { +// kafkaKey.put(key, Data); +// Report.updateTestLog(Action, "Key has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Key setup", ex); +// Report.updateTestLog(Action, "Error in setting Key: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Consumer GroupId", input = InputType.YES, condition = InputType.NO) +// public void setConsumerGroupId() { +// try { +// kafkaConsumerGroupId.put(key, Data); +// Report.updateTestLog(Action, "Consumer GroupId has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Consumer GroupId setup", +// ex); +// Report.updateTestLog(Action, "Error in setting Consumer GroupId: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Partition", input = InputType.YES, condition = InputType.NO) +// public void setPartition() { +// try { +// if (Data.toLowerCase().equals("null")) { +// kafkaPartition.put(key, null); +// } else { +// kafkaPartition.put(key, Integer.valueOf(Data)); +// } +// Report.updateTestLog(Action, "Partition has been set successfully", Status.DONE); +// } catch (NumberFormatException ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Partition setup", ex); +// Report.updateTestLog(Action, "Error in setting Partition: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set TimeStamp", input = InputType.NO, condition = InputType.NO) +// public void setTimeStamp() { +// try { +// kafkaTimeStamp.put(key, System.currentTimeMillis()); +// Report.updateTestLog(Action, "Time Stamp has been set successfully", Status.DONE); +// } catch (NumberFormatException ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Time Stamp setup", ex); +// Report.updateTestLog(Action, "Error in setting Time Stamp: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Key Serializer", input = InputType.YES, condition = InputType.NO) +// public void setKeySerializer() { +// try { +// kafkaKeySerializer.put(key, Data); +// Report.updateTestLog(Action, "Key Serializer has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Key Serializer setup", ex); +// Report.updateTestLog(Action, "Error in setting Key Serializer: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Value Serializer", input = InputType.YES, condition = InputType.NO) +// public void setValueSerializer() { +// try { +// kafkaValueSerializer.put(key, Data); +// Report.updateTestLog(Action, "Value Serializer has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Value Serializer setup", +// ex); +// Report.updateTestLog(Action, "Error in setting Value Serializer: " + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Set Value Deserializer", input = InputType.YES, condition = InputType.NO) +// public void setValueDeserializer() { +// try { +// kafkaValueDeserializer.put(key, Data); +// Report.updateTestLog(Action, "Value Deserializer has been set successfully", Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception during Value Deserializer setup", +// ex); +// Report.updateTestLog(Action, "Error in setting Value Deserializer: " + "\n" + ex.getMessage(), +// Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Add Avro Schema", input = InputType.YES, condition = InputType.NO) +// public void addSchema() throws IOException { +// try { +// Schema mainSchema = null; +// Schema.Parser parser = new Schema.Parser(); +// if (Data.contains(";")) { +// String[] paths = Data.split(";"); +// for (int i = 0; i < paths.length - 1; i++) { + +// parser.parse(new File(Paths.get(paths[i]).toString())); +// } +// mainSchema = parser.parse(new File(Paths.get(paths[paths.length - 1]).toString())); + +// } else { +// // Only one schema, no dependencies +// mainSchema = new Schema.Parser().parse(new File(Paths.get(Data).toString())); +// } +// kafkaAvroSchema.put(key, mainSchema); +// Report.updateTestLog(Action, "Schema added successfully", Status.DONE); +// } catch (Exception e) { +// Report.updateTestLog(Action, " Unable to add Schema : " + e.getMessage(), Status.FAIL); +// } + +// } + +// @Action(object = ObjectType.KAFKA, desc = "Produce Kafka Message", input = InputType.YES, condition = InputType.NO) +// public void produceMessage() { +// try { +// String value = Data; +// value = handleDataSheetVariables(value); +// value = handleuserDefinedVariables(value); +// System.out.println("\n Generated Record is : \n " + value + "\n"); +// kafkaValue.put(key, value); +// if (kafkaValueSerializer.get(key).equals("avro")) { +// getAvroCompatibleMessage(); +// kafkaValue.put(key, kafkaAvroCompatibleMessage.get(key)); +// produceGenericRecord(kafkaValue.get(key)); +// } +// if (kafkaHeaders.get(key) != null && kafkaTimeStamp.get(key) != null) { +// produceMessage(kafkaProducerTopic.get(key), kafkaPartition.get(key), kafkaTimeStamp.get(key), +// kafkaKey.get(key), kafkaValue.get(key), kafkaHeaders.get(key)); +// } else if (kafkaHeaders.get(key) != null) { +// produceMessage(kafkaProducerTopic.get(key), kafkaPartition.get(key), kafkaKey.get(key), +// kafkaValue.get(key), kafkaHeaders.get(key)); +// } else if (kafkaTimeStamp.get(key) != null) { +// produceMessage(kafkaProducerTopic.get(key), kafkaPartition.get(key), kafkaTimeStamp.get(key), +// kafkaKey.get(key), kafkaValue.get(key)); +// } else if (kafkaPartition.containsKey(key)) { +// produceMessage(kafkaProducerTopic.get(key), kafkaPartition.get(key), kafkaKey.get(key), +// kafkaValue.get(key)); +// } else if (kafkaKey.get(key) != null) { +// produceMessage(kafkaProducerTopic.get(key), kafkaKey.get(key), kafkaValue.get(key)); +// } else { +// produceMessage(kafkaProducerTopic.get(key), kafkaValue.get(key)); +// } + +// Report.updateTestLog(Action, "Message has been produced. ", Status.DONE); + +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Something went wrong in producing the message" + "\n" + ex.getMessage(), +// Status.FAILNS); +// ex.printStackTrace(); +// } +// } + +// public void produceGenericRecord(Object message) { +// try { +// InputStream input = new ByteArrayInputStream(((String) message).getBytes()); +// Decoder decoder = DecoderFactory.get().jsonDecoder(kafkaAvroSchema.get(key), input); +// GenericDatumReader reader = new GenericDatumReader<>(kafkaAvroSchema.get(key)); +// GenericRecord record = reader.read(null, decoder); +// kafkaValue.put(key, record); +// } catch (Exception e) { +// e.printStackTrace(); +// } + +// } + +// @Action(object = ObjectType.KAFKA, desc = "Send Message", input = InputType.NO, condition = InputType.NO) +// public void sendKafkaMessage() { +// try { +// createProducer(kafkaValueSerializer.get(key)); + +// kafkaProducer.get(key).send(kafkaProducerRecord.get(key), +// (RecordMetadata metadata, Exception exception) -> { +// if (exception != null) { +// Report.updateTestLog(Action, "Error in sending record : " + exception.getMessage(), +// Status.FAIL); +// } else { +// Report.updateTestLog(Action, +// "Record sent to [topic: " + metadata.topic() + ", partition: " +// + metadata.partition() + ", offset: " + metadata.offset() + ", timestamp: " +// + metadata.timestamp() + "]", +// Status.DONE); +// } +// }); + +// kafkaProducer.get(key).close(); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Exception while sending record", ex); +// Report.updateTestLog(Action, "Error in sending record: " + "\n" + ex.getMessage(), Status.DEBUG); +// } finally { +// clearProducerDetails(); +// } +// } + +// private void createProducer(String serializer) { +// // getProducersslConfigurations(); +// Properties props = new Properties(); +// if (isProducersslEnabled()) { +// props = getProducersslConfigurations(props); +// props.put("security.protocol", "SSL"); +// } +// props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers.get(key)); +// if (kafkaConfigs.containsKey(key)) { +// props = addConfigProps(props); +// } +// if (serializer.toLowerCase().contains("string")) { +// props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); +// } else if (serializer.toLowerCase().contains("bytearray")) { +// props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class.getName()); +// } else if (serializer.toLowerCase().contains("avro")) { +// props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaAvroSerializer.class.getName()); +// props.put("schema.registry.url", kafkaSchemaRegistryURL.get(key)); +// if (kafkaAutoRegisterSchemas.get(key) != null) { +// props.put("auto.register.schemas", kafkaAutoRegisterSchemas.get(key)); +// } + +// } else { +// throw new IllegalArgumentException("Unsupported value type"); +// } + +// props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); +// kafkaProducer.put(key, new KafkaProducer<>(props)); +// } + +// private void produceMessage(String topic, Object value) { +// kafkaProducerRecord.put(key, new ProducerRecord<>(topic, value)); +// } + +// private void produceMessage(String topic, String kafkaKey, Object value) { +// kafkaProducerRecord.put(key, new ProducerRecord<>(topic, kafkaKey, value)); +// } + +// private void produceMessage(String topic, Integer partition, String kafkaKey, Object value) { +// kafkaProducerRecord.put(key, new ProducerRecord<>(topic, partition, kafkaKey, value)); +// } + +// private void produceMessage(String topic, Integer partition, long timestamp, String kafkaKey, Object value) { +// kafkaProducerRecord.put(key, new ProducerRecord<>(topic, partition, timestamp, kafkaKey, value)); +// } + +// private void produceMessage(String topic, Integer partition, String kafkaKey, Object value, List
    headers) { +// kafkaProducerRecord.put(key, new ProducerRecord<>(topic, partition, kafkaKey, value, headers)); +// } + +// private void produceMessage(String topic, Integer partition, long timestamp, String kafkaKey, Object value, +// List
    headers) { +// kafkaProducerRecord.put(key, new ProducerRecord<>(topic, partition, timestamp, kafkaKey, value, headers)); +// } + +// private String handleDataSheetVariables(String payloadstring) { +// List sheetlist = Control.getCurrentProject().getTestData().getTestDataFor(Control.exe.runEnv()) +// .getTestDataNames(); +// for (int sheet = 0; sheet < sheetlist.size(); sheet++) { +// if (payloadstring.contains("{" + sheetlist.get(sheet) + ":")) { +// com.ing.datalib.testdata.model.TestDataModel tdModel = Control.getCurrentProject().getTestData() +// .getTestDataByName(sheetlist.get(sheet)); +// List columns = tdModel.getColumns(); +// for (int col = 0; col < columns.size(); col++) { +// if (payloadstring.contains("{" + sheetlist.get(sheet) + ":" + columns.get(col) + "}")) { +// payloadstring = payloadstring.replace("{" + sheetlist.get(sheet) + ":" + columns.get(col) + "}", +// userData.getData(sheetlist.get(sheet), columns.get(col))); +// } +// } +// } +// } +// return payloadstring; +// } + +// private String handleuserDefinedVariables(String payloadstring) { +// Collection valuelist = Control.getCurrentProject().getProjectSettings().getUserDefinedSettings() +// .values(); +// for (Object prop : valuelist) { +// if (payloadstring.contains("{" + prop + "}")) { +// payloadstring = payloadstring.replace("{" + prop + "}", prop.toString()); +// } +// } +// return payloadstring; +// } + +// private void clearProducerDetails() { +// kafkaKey.clear(); +// kafkaHeaders.clear(); +// kafkaProducerTopic.clear(); +// kafkaPartition.clear(); +// kafkaTimeStamp.clear(); +// kafkaKeySerializer.clear(); +// kafkaValue.clear(); +// kafkaValueSerializer.clear(); +// kafkaProducer.clear(); +// kafkaProducerRecord.clear(); +// kafkaAvroSchema.clear(); +// kafkaGenericRecord.clear(); +// kafkaAvroProducer.clear(); +// kafkaConfigs.clear(); +// kafkaProducersslConfigs.clear(); +// kafkaAvroCompatibleMessage.clear(); +// kafkaSharedSecret.clear(); +// kafkaAutoRegisterSchemas.clear(); +// } + +// public void createConsumer(String deserializer) { +// try { +// Properties props = new Properties(); +// if (isConsumersslEnabled()) { +// props = getConsumersslConfigurations(props); +// props.put("security.protocol", "SSL"); +// } +// props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers.get(key)); +// props.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConsumerGroupId.get(key)); +// if (kafkaConsumerMaxPollRecords.get(key) != null) { +// props.put("max.poll.records", kafkaConsumerMaxPollRecords.get(key)); +// } +// if (deserializer.toLowerCase().contains("string")) { +// props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); +// } else if (deserializer.toLowerCase().contains("bytearray")) { +// props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); +// } else if (deserializer.toLowerCase().contains("avro")) { +// props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class.getName()); +// props.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, "false"); +// props.put("schema.registry.url", kafkaSchemaRegistryURL.get(key)); + +// } else { +// throw new IllegalArgumentException("Unsupported value type"); +// } + +// props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); +// props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + +// kafkaConsumer.put(key, new KafkaConsumer<>(props)); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Consume Kafka Message", input = InputType.NO) +// public void consumeKafkaMessage() { +// try { +// createConsumer(kafkaValueDeserializer.get(key)); +// kafkaConsumer.get(key).subscribe(Arrays.asList(kafkaConsumerTopic.get(key))); +// ConsumerRecords record = pollKafkaConsumer(); +// if (record != null && kafkaConsumeRecordValue.containsKey(key)) { +// Report.updateTestLog(Action, "Kafka messages consumed successfully and Target message found.", +// Status.DONE); +// } else if (record != null && !kafkaConsumeRecordValue.containsKey(key) +// && kafkaConsumerPollRecord.containsKey(key)) { +// Report.updateTestLog(Action, "Kafka messages consumed successfully but target message not found.", +// Status.FAILNS); +// } else { +// Report.updateTestLog(Action, "Kafka message not received.", Status.FAIL); +// } +// } catch (Exception e) { +// e.printStackTrace(); +// Report.updateTestLog(Action, "Error while consuming Kafka message: " + e.getMessage(), Status.FAIL); +// } finally { +// kafkaConsumer.get(key).close(); +// } +// } + +// /** +// * Polls the Kafka consumer for the configured number of retries and returns the +// * polled batch that contains a record matching the assertion criteria. +// * Each attempt polls using the duration configured for {@code key}. +// *

    +// * Side effects: Updates {@code kafkaConsumerPollRecord} and logs to stdout. +// * +// * @return the {@link ConsumerRecords} containing the matched record, or {@code null} +// * if no matching record is found after all retries +// * @throws SerializationException if a deserialization error occurs during polling +// */ +// private ConsumerRecords pollKafkaConsumer() throws SerializationException { +// int maxRetries = kafkaConsumerPollRetries.get(key); +// int attempt = 1; +// boolean matchRecordFound = false; +// List> allRecords = new ArrayList<>(); + +// while (attempt <= maxRetries) { +// try { +// ConsumerRecords pollRecords = kafkaConsumer.get(key) +// .poll(Duration.ofMillis(kafkaConsumerPollDuration.get(key))); +// if (!pollRecords.isEmpty()) { +// for (ConsumerRecord record : pollRecords) { +// kafkaConsumerPollRecord.put(key, record); +// allRecords.add(record); +// if (findAndSetTargetRecordForAssertion()) { +// matchRecordFound = true; +// break; +// } +// } +// if (matchRecordFound) { +// System.out.println("Record consumed in attempt " + attempt + " are " + pollRecords.count() +// + " and Record found with unique identifier."); +// System.out.println("Details of record found with unique idetifier are as follows : "); +// System.out.println("Key : " + kafkaConsumerPollRecord.get(key).key()); +// System.out.println("Partition : " + kafkaConsumerPollRecord.get(key).partition()); +// System.out.println("Offset : " + kafkaConsumerPollRecord.get(key).offset()); +// System.out.println("Value : " + kafkaConsumerPollRecord.get(key).value()); +// return pollRecords; +// } else { +// System.out.println("Record consumed in attempt " + attempt + " are " + pollRecords.count() +// + ". But, no Record found with unique identifier."); +// } +// attempt++; +// } else { +// System.out.println("Record consumed in attempt " + attempt + " are " + pollRecords.count() + "."); +// attempt++; +// } + +// } catch (Exception e) { +// System.out.println("Error in polling records : " + e.getMessage()); +// attempt++; +// } +// } +// return null; +// } + +// @Action(object = ObjectType.KAFKA, desc = "Identify target message", input = InputType.YES, condition = InputType.YES) +// public void identifyTargetMessage() { +// try { +// // --- Multi-condition support: append (path -> value) per key --- +// final String path = Condition; +// final String value = Data; + +// // Create a single-condition map (path -> value) +// HashMap identifyValuePath = new HashMap<>(); +// identifyValuePath.put(path, value); + +// // Get or create the list for this key, then add the condition map +// List> conditionsForKey = +// kafkaRecordIdentifier.computeIfAbsent(key, k -> new ArrayList<>()); +// conditionsForKey.add(identifyValuePath); +// Report.updateTestLog( +// Action, +// "Added target identifier: [path=" + path + " , value=" + value + "] for key [" + key + "]. " +// + "Total conditions for key now: " + conditionsForKey.size(), +// Status.DONE +// ); +// } catch (Exception e) { +// Report.updateTestLog(Action, "Error in target message setup : " + e.getMessage(), Status.FAIL); +// } +// } + +// public boolean findAndSetTargetRecordForAssertion() { // identifyTargetMessage +// boolean matchFound = false; +// try { +// if (kafkaConsumerPollRecord.get(key).value() != null) { +// String recordValue = kafkaConsumerPollRecord.get(key).value().toString(); +// boolean isJson = Pattern.matches("^\\s*(\\{.*\\}|\\[.*\\])\\s*$", recordValue); +// boolean isXml = Pattern.matches("^\\s*<\\?*xml*.*>.*<.*>.*\\s*$", recordValue); + +// if (isJson) { +// if (getJSONRecordForAssertion(recordValue)) { +// matchFound = true; +// } + +// } else if (isXml) { +// if (getXMLRecordForAssertion(recordValue)) { +// matchFound = true; +// } +// } else { +// System.out.println("Unknown format"); +// } +// } +// } catch (Exception e) { +// System.out.println("Error in find and set target record for assertion : " + e.getMessage()); +// } +// return matchFound; +// } + +// /** +// * Validates a JSON message against all JSONPath conditions associated with {@code key}. +// * Each condition consists of one JSONPath expression mapped to an expected value. +// * Returns {@code true} only if every condition matches; otherwise {@code false}. +// *

    +// * Side effect: On success, stores the JSON message in {@code kafkaConsumeRecordValue.put(key, JSONMessage)}. +// * Any JSON parsing or evaluation error is logged and results in {@code false}. +// * +// * @param JSONMessage the JSON payload to evaluate +// * @return {@code true} if all JSONPath -> expectedValue conditions for {@code key} match; +// * {@code false} if none exist, a mismatch occurs, or an exception is thrown +// */ +// public boolean getJSONRecordForAssertion(String JSONMessage) { +// try { +// // Prefer multi-condition evaluation if present +// List> conditions = kafkaRecordIdentifier.get(key); + +// if (conditions != null && !conditions.isEmpty()) { +// // ALL conditions must match +// for (HashMap cond : conditions) { +// // Each cond map contains exactly one entry: path -> expectedValue +// Map.Entry entry = cond.entrySet().iterator().next(); +// String path = entry.getKey(); +// String expected = entry.getValue(); + +// // Object actualObj = com.jayway.jsonpath.JsonPath.read(JSONMessage, path); +// Object actualObj = JsonPath.read(JSONMessage, path); +// String actual = (actualObj == null) ? null : String.valueOf(actualObj); + +// // if (!java.util.Objects.equals(actual, expected)) { +// if (!Objects.equals(actual, expected)) { +// // Early exit on first mismatch +// return false; +// } +// } +// // All matched → set the matched message and return true +// kafkaConsumeRecordValue.put(key, JSONMessage); +// return true; +// } + +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error in validating JSON element :" + "\n" + ex.getMessage(), Status.DEBUG); +// } +// return false; +// } + +// /** +// * Parses the given XML string and validates it against XPath conditions linked to {@code key}. +// * Returns {@code true} only if all conditions match; otherwise {@code false}. +// *

    +// * Side effect: On success, stores the original XML in {@code kafkaConsumeRecordValue.put(key, XMLMessage)}. +// * Any parsing/XPath error is logged and results in {@code false}. +// * +// * @param XMLMessage well-formed XML payload to evaluate +// * @return {@code true} if all XPath -> expectedValue conditions for {@code key} match; +// * {@code false} if none exist, any mismatch occurs, or an error is thrown +// */ +// public boolean getXMLRecordForAssertion(String XMLMessage) { +// try { +// DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); +// DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); +// InputSource inputSource = new org.xml.sax.InputSource(new java.io.StringReader(XMLMessage)); +// Document doc = dBuilder.parse(inputSource); +// doc.getDocumentElement().normalize(); + +// XPath xPath = XPathFactory.newInstance().newXPath(); + +// // Get the list of (path -> expectedValue) condition maps for this key +// List> conditions = kafkaRecordIdentifier.get(key); +// if (conditions == null || conditions.isEmpty()) { +// // No conditions defined for this key +// return false; +// } + +// // ALL conditions must match +// for (HashMap cond : conditions) { +// Map.Entry entry = cond.entrySet().iterator().next(); +// String path = entry.getKey(); +// String expected = entry.getValue(); + +// String actual = xPath.compile(path).evaluate(doc); + +// if (!java.util.Objects.equals(actual, expected)) { +// // Early exit on first mismatch +// return false; +// } +// } + +// // All matched → record the matched message +// kafkaConsumeRecordValue.put(key, XMLMessage); +// return true; + +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error in validating XML element :" + "\n" + ex.getMessage(), Status.DEBUG); +// return false; +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Close Consumer", input = InputType.NO, condition = InputType.NO) +// public void closeConsumer() { +// try { +// kafkaConsumerRecords.remove(key); +// kafkaConsumerRecord.remove(key); +// kafkaConsumeRecordValue.remove(key); +// kafkaConsumerPollDuration.remove(key); +// kafkaConsumerPollRetries.remove(key); +// kafkaConsumerTopic.remove(key); +// kafkaValueDeserializer.remove(key); +// kafkaSchemaRegistryURL.remove(key); +// kafkaSharedSecret.remove(key); +// kafkaConsumerGroupId.remove(key); +// kafkaConsumerPollRecord.remove(key); +// kafkaRecordIdentifierValue.remove(key); +// kafkaRecordIdentifierPath.remove(key); +// kafkaRecordIdentifier.remove(key); +// Report.updateTestLog(Action, "Consumer closed successfully", Status.DONE); +// } catch (Exception ex) { +// Report.updateTestLog(Action, "Error in closing Consumer.", Status.DEBUG); +// } + +// } + +// @Action(object = ObjectType.KAFKA, desc = "Store XML tag In DataSheet ", input = InputType.YES, condition = InputType.NO) +// public void storeKafkaXMLtagInDataSheet() { + +// try { +// String strObj = Input; +// if (strObj.matches(".*:.*")) { +// try { +// System.out.println("Updating value in SubIteration " + userData.getSubIteration()); +// String sheetName = strObj.split(":", 2)[0]; +// String columnName = strObj.split(":", 2)[1]; +// String xmlText = kafkaConsumeRecordValue.get(key); +// DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); +// DocumentBuilder dBuilder; +// InputSource inputSource = new InputSource(); +// inputSource.setCharacterStream(new StringReader(xmlText)); +// dBuilder = dbFactory.newDocumentBuilder(); +// Document doc = dBuilder.parse(inputSource); +// doc.getDocumentElement().normalize(); +// XPath xPath = XPathFactory.newInstance().newXPath(); +// String expression = Condition; +// String value = (String) xPath.compile(expression).evaluate(doc); +// userData.putData(sheetName, columnName, value); +// Report.updateTestLog(Action, "Element text [" + value + "] is stored in " + strObj, Status.DONE); +// } catch (IOException | ParserConfigurationException | XPathExpressionException | DOMException +// | SAXException ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, ex.getMessage(), ex); +// Report.updateTestLog(Action, "Error Storing XML element in datasheet :" + "\n" + ex.getMessage(), +// Status.DEBUG); +// } +// } else { +// Report.updateTestLog(Action, +// "Given input [" + Input + "] format is invalid. It should be [sheetName:ColumnName]", +// Status.DEBUG); +// } +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error Storing XML element in datasheet :" + "\n" + ex.getMessage(), +// Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Assert XML Tag Equals ", input = InputType.YES, condition = InputType.YES) +// public void assertKafkaXMLtagEquals() { +// try { +// DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); +// DocumentBuilder dBuilder; +// InputSource inputSource = new InputSource(); +// inputSource.setCharacterStream(new StringReader(kafkaConsumeRecordValue.get(key))); +// dBuilder = dbFactory.newDocumentBuilder(); +// Document doc = dBuilder.parse(inputSource); +// doc.getDocumentElement().normalize(); +// XPath xPath = XPathFactory.newInstance().newXPath(); +// String expression = Condition; +// String value = (String) xPath.compile(expression).evaluate(doc); +// if (value.equals(Data)) { +// Report.updateTestLog(Action, "Element text [" + value + "] is as expected", Status.PASSNS); +// } else { +// Report.updateTestLog(Action, "Element text [" + value + "] is not as expected", Status.FAILNS); +// } +// } catch (IOException | ParserConfigurationException | XPathExpressionException | DOMException +// | SAXException ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error validating XML element :" + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Assert XML Tag Contains ", input = InputType.YES, condition = InputType.YES) +// public void assertKafkaXMLtagContains() { +// try { +// DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); +// DocumentBuilder dBuilder; +// InputSource inputSource = new InputSource(); +// inputSource.setCharacterStream(new StringReader(kafkaConsumeRecordValue.get(key))); +// dBuilder = dbFactory.newDocumentBuilder(); +// Document doc = dBuilder.parse(inputSource); +// doc.getDocumentElement().normalize(); +// XPath xPath = XPathFactory.newInstance().newXPath(); +// String expression = Condition; +// String value = (String) xPath.compile(expression).evaluate(doc); +// if (value.contains(Data)) { +// Report.updateTestLog(Action, "Element text contains [" + Data + "] is as expected", Status.PASSNS); +// } else { +// Report.updateTestLog(Action, "Element text [" + value + "] does not contain [" + Data + "]", +// Status.FAILNS); +// } +// } catch (IOException | ParserConfigurationException | XPathExpressionException | DOMException +// | SAXException ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error validating XML element :" + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Assert Response Message contains ", input = InputType.YES) +// public void assertKafkaResponseMessageContains() { +// try { +// if (kafkaConsumeRecordValue.get(key).contains(Data)) { +// Report.updateTestLog(Action, "Response Message contains : " + Data, Status.PASSNS); +// } else { +// Report.updateTestLog(Action, "Response Message does not contain : " + Data, Status.FAILNS); +// } +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error in validating response body :" + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Assert JSON Tag Equals ", input = InputType.YES, condition = InputType.YES) +// public void assertKafkaJSONtagEquals() { +// try { +// String response = kafkaConsumeRecordValue.get(key); +// String jsonpath = Condition; +// String value = JsonPath.read(response, jsonpath).toString(); +// if (value.equals(Data)) { +// Report.updateTestLog(Action, "Element text [" + value + "] is as expected", Status.PASSNS); +// } else { +// Report.updateTestLog(Action, "Element text is [" + value + "] but is expected to be [" + Data + "]", +// Status.FAILNS); +// } +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error in validating JSON element :" + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Assert JSON Tag Contains ", input = InputType.YES, condition = InputType.YES) +// public void assertKafkaJSONtagContains() { +// try { +// String response = kafkaConsumeRecordValue.get(key); +// String jsonpath = Condition; +// String value = JsonPath.read(response, jsonpath).toString(); +// if (value.contains(Data)) { +// Report.updateTestLog(Action, "Element text contains [" + Data + "] is as expected", Status.PASSNS); +// } else { +// Report.updateTestLog(Action, "Element text [" + value + "] does not contain [" + Data + "]", +// Status.FAILNS); +// } +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error in validating JSON element :" + "\n" + ex.getMessage(), Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Store JSON Tag In DataSheet ", input = InputType.YES, condition = InputType.YES) +// public void storeKafkaJSONtagInDataSheet() { + +// try { +// String strObj = Input; +// if (strObj.matches(".*:.*")) { +// try { +// System.out.println("Updating value in SubIteration " + userData.getSubIteration()); +// String sheetName = strObj.split(":", 2)[0]; +// String columnName = strObj.split(":", 2)[1]; +// String response = kafkaConsumeRecordValue.get(key); +// String jsonpath = Condition; +// String value = JsonPath.read(response, jsonpath).toString(); +// userData.putData(sheetName, columnName, value); +// Report.updateTestLog(Action, "Element text [" + value + "] is stored in " + strObj, Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, ex.getMessage(), ex); +// Report.updateTestLog(Action, "Error Storing JSON element in datasheet :" + "\n" + ex.getMessage(), +// Status.DEBUG); +// } +// } else { +// Report.updateTestLog(Action, +// "Given input [" + Input + "] format is invalid. It should be [sheetName:ColumnName]", +// Status.DEBUG); +// } +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error Storing JSON element in datasheet :" + "\n" + ex.getMessage(), +// Status.DEBUG); +// } +// } + +// @Action(object = ObjectType.KAFKA, desc = "Store Response In DataSheet ", input = InputType.YES, condition = InputType.NO) +// public void storeKafkaResponseInDataSheet() { + +// try { +// String strObj = Input; +// if (strObj.matches(".*:.*")) { +// try { +// System.out.println("Updating value in SubIteration " + userData.getSubIteration()); +// String sheetName = strObj.split(":", 2)[0]; +// String columnName = strObj.split(":", 2)[1]; +// String response = kafkaConsumeRecordValue.get(key); +// userData.putData(sheetName, columnName, response); +// Report.updateTestLog(Action, "Response is stored in " + strObj, Status.DONE); +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, ex.getMessage(), ex); +// Report.updateTestLog(Action, "Error storing Response in datasheet :" + "\n" + ex.getMessage(), +// Status.DEBUG); +// } +// } else { +// Report.updateTestLog(Action, +// "Given input [" + Input + "] format is invalid. It should be [sheetName:ColumnName]", +// Status.DEBUG); +// } +// } catch (Exception ex) { +// Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); +// Report.updateTestLog(Action, "Error storing Response in datasheet :" + "\n" + ex.getMessage(), +// Status.DEBUG); +// } +// } + +// // to add Configs in props +// public Properties addConfigProps(Properties props) { +// for (String config : kafkaConfigs.get(key)) { +// String[] keyValue = config.split("=", 2); +// if (keyValue.length == 2) { +// props.put(keyValue[0], keyValue[1]); +// } +// } +// return props; +// } + +// public Properties getProducersslConfigurations(Properties prop) { +// Properties sslProp = Control.getCurrentProject().getProjectSettings().getKafkaSSLConfigurations(); +// Set keys = sslProp.stringPropertyNames(); +// for (String key : keys) { +// String value = sslProp.getProperty(key); +// value = handleDataSheetVariables(value); +// value = handleuserDefinedVariables(value); +// switch (key) { +// case "Producer_ssl_Enabled": +// Boolean.valueOf(value); +// break; +// case "Producer_Truststore_Location": +// String producertrustStroreLocation = Paths.get(value).toAbsolutePath().toString(); +// prop.put("ssl.truststore.location", producertrustStroreLocation); +// break; +// case "Producer_Truststore_Password": +// prop.put("ssl.truststore.password", value); +// break; +// case "Producer_Keystore_Location": +// String producerKeyStroreLocation = Paths.get(value).toAbsolutePath().toString(); +// prop.put("ssl.keystore.location", producerKeyStroreLocation); +// break; +// case "Producer_Keystore_Password": +// prop.put("ssl.keystore.password", value); +// break; +// case "Producer_Key_Password": +// prop.put("ssl.key.password", value); +// break; +// case "Schema_Registry_Truststore_Location": +// String producerSchemaTrustStroreLocation = Paths.get(value).toAbsolutePath().toString(); +// prop.put("schema.registry.ssl.truststore.location", producerSchemaTrustStroreLocation); +// break; +// case "Schema_Registry_Truststore_Password": +// prop.put("schema.registry.ssl.truststore.password", value); +// break; +// case "Schema_Registry_Keystore_Location": +// String producerSchemaKeyStroreLocation = Paths.get(value).toAbsolutePath().toString(); +// prop.put("schema.registry.ssl.keystore.location", producerSchemaKeyStroreLocation); +// break; +// case "Schema_Registry_Keystore_Password": +// prop.put("schema.registry.ssl.keystore.password", value); +// break; +// case "Schema_Registry_Key_Password": +// prop.put("schema.registry.ssl.key.password", value); +// break; +// } +// } +// return prop; +// } + +// public Properties getConsumersslConfigurations(Properties prop) { +// Properties sslProp = Control.getCurrentProject().getProjectSettings().getKafkaSSLConfigurations(); +// Set keys = sslProp.stringPropertyNames(); +// for (String key : keys) { +// String value = sslProp.getProperty(key); +// value = handleDataSheetVariables(value); +// value = handleuserDefinedVariables(value); +// switch (key) { +// case "Consumer_ssl_Enabled": +// break; +// case "Consumer_Truststore_Location": +// String trustStroreLocation = Paths.get(value).toAbsolutePath().toString(); +// prop.put("ssl.truststore.location", trustStroreLocation); +// break; +// case "Consumer_Truststore_Password": +// prop.put("ssl.truststore.password", value); +// break; +// case "Consumer_Keystore_Location": +// String consumerKeyStroreLocation = Paths.get(value).toAbsolutePath().toString(); +// prop.put("ssl.keystore.location", consumerKeyStroreLocation); +// break; +// case "Consumer_Keystore_Password": +// prop.put("ssl.keystore.password", value); +// break; +// case "Consumer_Key_Password": +// prop.put("ssl.key.password", value); +// break; +// case "Schema_Registry_Truststore_Location": +// String consumerSchemaTrustStroreLocation = Paths.get(value).toAbsolutePath().toString(); +// prop.put("schema.registry.ssl.truststore.location", consumerSchemaTrustStroreLocation); +// break; +// case "Schema_Registry_Truststore_Password": +// prop.put("schema.registry.ssl.truststore.password", value); +// break; +// case "Schema_Registry_Keystore_Location": +// String consumerSchemaKeyStroreLocation = Paths.get(value).toAbsolutePath().toString(); +// prop.put("schema.registry.ssl.keystore.location", consumerSchemaKeyStroreLocation); +// break; +// case "Schema_Registry_Keystore_Password": +// prop.put("schema.registry.ssl.keystore.password", value); +// break; +// case "Schema_Registry_Key_Password": +// prop.put("schema.registry.ssl.key.password", value); +// break; +// } +// } +// return prop; +// } + +// public boolean isProducersslEnabled() { +// Properties prop = Control.getCurrentProject().getProjectSettings().getKafkaSSLConfigurations(); +// String value = prop.getProperty("Producer_ssl_Enabled"); +// value = handleRuntimeValues(value); +// return "true".equalsIgnoreCase(value); + +// } + +// public String handleRuntimeValues(String value) { +// value = handleDataSheetVariables(value); +// value = handleuserDefinedVariables(value); +// return value; +// } + +// public boolean isConsumersslEnabled() { +// Properties prop = Control.getCurrentProject().getProjectSettings().getKafkaSSLConfigurations(); +// String value = prop.getProperty("Consumer_ssl_Enabled"); +// value = handleRuntimeValues(value); +// return "true".equalsIgnoreCase(value); +// } + +// // Added to create avro compatible message +// public void getAvroCompatibleMessage() { +// String jsonAvroMessage = ""; +// try { +// ObjectMapper stringMapper = new ObjectMapper(); +// JsonNode inputJson = mapper.readTree(kafkaValue.get(key).toString()); +// // JsonNode inputJson = stringMapper.readTree((String) kafkaValue.get(key)); +// JsonNode avroCompatibleJson = convertNode(inputJson, kafkaAvroSchema.get(key)); +// jsonAvroMessage = stringMapper.writerWithDefaultPrettyPrinter().writeValueAsString(avroCompatibleJson); +// kafkaAvroCompatibleMessage.put(key, jsonAvroMessage); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } + +// private static JsonNode convertNode(JsonNode input, Schema schema) { +// switch (schema.getType()) { +// case RECORD: +// ObjectNode recordNode = mapper.createObjectNode(); +// for (Schema.Field field : schema.getFields()) { +// JsonNode value = input.get(field.name()); +// recordNode.set(field.name(), convertNode(value, field.schema())); +// } +// return recordNode; + +// case ARRAY: +// ArrayNode arrayNode = mapper.createArrayNode(); +// for (JsonNode item : input) { +// arrayNode.add(convertNode(item, schema.getElementType())); +// } +// return arrayNode; + +// case MAP: +// ObjectNode mapNode = mapper.createObjectNode(); +// for (Iterator> it = input.fields(); it.hasNext();) { +// Map.Entry entry = it.next(); +// mapNode.set(entry.getKey(), convertNode(entry.getValue(), schema.getValueType())); +// } +// return mapNode; + +// case UNION: +// for (Schema subSchema : schema.getTypes()) { +// if (subSchema.getType() == Schema.Type.NULL && (input == null || input.isNull())) { +// return NullNode.getInstance(); +// } + +// if (isCompatible(input, subSchema)) { +// JsonNode wrapped = convertNode(input, subSchema); +// ObjectNode unionNode = mapper.createObjectNode(); + +// // ✅ Use fully qualified name for ENUM and RECORD +// String typeName = (subSchema.getType() == Schema.Type.RECORD +// || subSchema.getType() == Schema.Type.ENUM) ? subSchema.getFullName() +// : subSchema.getType().getName(); + +// unionNode.set(typeName, wrapped); +// return unionNode; +// } +// } + +// System.err.println("❌ No matching type in union for value: " + input); +// System.err.println("Schema: " + schema.toString(true)); +// throw new IllegalArgumentException("No matching type in union for value: " + input); + +// case ENUM: +// return new TextNode(input.textValue()); + +// default: +// return input; +// } +// } + +// private static boolean isCompatible(JsonNode value, Schema schema) { +// switch (schema.getType()) { +// case STRING: +// return value.isTextual(); +// case INT: +// return value.isInt(); +// case LONG: +// return value.isLong() || value.isInt(); +// case FLOAT: +// return value.isFloat() || value.isDouble(); +// case DOUBLE: +// return value.isDouble() || value.isFloat(); +// case BOOLEAN: +// return value.isBoolean(); +// case NULL: +// return value == null || value.isNull(); +// case RECORD: +// return value.isObject(); +// case ARRAY: +// return value.isArray(); +// case MAP: +// return value.isObject(); +// case ENUM: +// return value.isTextual() && schema.getEnumSymbols().contains(value.textValue()); +// default: +// return false; +// } +// } +// } diff --git a/Engine/src/main/java/com/ing/engine/commands/mobile/AppiumDeviceCommands.java b/Engine/src/main/java/com/ing/engine/commands/mobile/AppiumDeviceCommands.java index 42369a81..54ca6bc3 100644 --- a/Engine/src/main/java/com/ing/engine/commands/mobile/AppiumDeviceCommands.java +++ b/Engine/src/main/java/com/ing/engine/commands/mobile/AppiumDeviceCommands.java @@ -2,6 +2,7 @@ import java.time.Duration; import java.util.Arrays; +import java.util.Map; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.Rectangle; @@ -344,6 +345,21 @@ public void hideKeyboard() { } } + @Action(object = ObjectType.MOBILE, desc = "Go to homescreen", input = InputType.NO, condition = InputType.NO) + public void goToHomescreen() { + try { + if (mDriver instanceof AndroidDriver) { + ((AndroidDriver) mDriver).executeScript("mobile: pressKey", Map.of("keycode", 3)); + } else if (mDriver instanceof IOSDriver) { + ((IOSDriver) mDriver).executeScript("mobile: pressButton", Map.of("name", "home")); + } + Report.updateTestLog(Action, "Performed go to Homescreen operation", Status.DONE); + } catch (Exception e) { + Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, e); + Report.updateTestLog(Action, "Unable to perform homescreen operation, Error: " + e.getMessage(), Status.FAIL); + } + } + @Action(object = ObjectType.MOBILE, desc = "Pinch and Zoom", input = InputType.YES, condition = InputType.NO) public void pinchAndZoomScreen() throws InterruptedException { try { diff --git a/Engine/src/main/java/com/ing/engine/commands/stringOperations/StringOperations.java b/Engine/src/main/java/com/ing/engine/commands/stringOperations/StringOperations.java index 21662a68..5bbe72ee 100644 --- a/Engine/src/main/java/com/ing/engine/commands/stringOperations/StringOperations.java +++ b/Engine/src/main/java/com/ing/engine/commands/stringOperations/StringOperations.java @@ -14,7 +14,11 @@ import java.util.List; /** - * + * Provides string manipulation operations for test automation. + * This class extends General and offers various string operations such as concatenation, + * trimming, substring extraction, replacement, case conversion, splitting, and more. + * All operations store their results in variables that can be referenced in test cases. + * * @author Julie Ann Ayap */ public class StringOperations extends General { @@ -26,10 +30,25 @@ public class StringOperations extends General { private List getSplitList = new ArrayList(); private List getOccurenceList = new ArrayList(); + /** + * Constructs a new StringOperations instance with the specified CommandControl. + * + * @param cc the CommandControl instance for managing test execution commands + */ public StringOperations(CommandControl cc) { super(cc); } + /** + * Retrieves the value of a string argument based on its format. + * Supports three formats: + * - Variables: %variableName% + * - Datasheet references: {sheet:column} + * - String literals: "text" + * + * @param strArg the string argument to process + * @return the resolved value of the argument, or empty string if format is invalid + */ private String getVarValue(String strArg){ if (strArg.matches("%.*%")) return getVar(strArg); @@ -41,6 +60,12 @@ else if (strArg.matches("\".*\"")) return ""; } + /** + * Checks if a string represents a valid numeric value. + * + * @param str the string to check + * @return true if the string is a valid number, false otherwise + */ private static boolean isNumeric(String str) { if (str == null || str.isEmpty()) { return false; @@ -53,6 +78,13 @@ private static boolean isNumeric(String str) { } } + /** + * Counts the number of occurrences of a specific character in a text string. + * + * @param text the text to search in + * @param targetChar the character to count + * @return the number of times the target character appears in the text + */ public static int countCharOccurrences(String text, char targetChar) { int count = 0; for (int i = 0; i < text.length(); i++) { @@ -63,6 +95,20 @@ public static int countCharOccurrences(String text, char targetChar) { return count; } + /** + * Concatenates multiple string inputs and stores the result in a variable. + * Accepts up to 5 string inputs separated by commas. + * Supports variables (%var%), datasheet references ({sheet:column}), and string literals ("text"). + * The concatenated result is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: "Hello",%text%,{data:greeting}
    • + *
    • Condition: %result%
    • + *
    + * + * @throws ForcedException if input exceeds the limit of 5 strings or contains invalid format + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Concats String inputs within testcase []", input = InputType.YES, condition = InputType.YES) public void Concat() { if(!Condition.isBlank()){ @@ -98,6 +144,20 @@ public void Concat() { } } + /** + * Removes leading and trailing whitespace from a string input. + * Supports variables (%var%), datasheet references ({sheet:column}), and string literals ("text"). + * The trimmed result is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: " Hello World " or %text% or {data:greeting}
    • + *
    • Condition: %trimmedText%
    • + *
    • Result: "Hello World"
    • + *
    + * + * @throws ForcedException if input format is invalid or no variable name is assigned + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Trim white spaces of String input within testcase", input = InputType.YES, condition = InputType.YES) public void Trim() { if(!Condition.isBlank()){ @@ -121,6 +181,23 @@ public void Trim() { } } + /** + * Extracts a substring from a string based on start and end indices. + * Accepts 2 or 3 parameters: string, startIndex, and optionally endIndex. + * If endIndex is not provided, extracts until the end of the string. + * Supports variables (%var%), datasheet references ({sheet:column}), and string literals ("text"). + * The substring result is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: "Hello World", 0, 5 (extracts "Hello")
    • + *
    • Input: %text%, 6 (extracts from index 6 to end from ther )
    • + *
    • Input: {data:greeting}, 6 (extracts from index 6 to end)
    • + *
    • Condition: %result%
    • + *
    + * + * @throws ForcedException if indices are not numeric, out of bounds, or input format is invalid + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Substring String input within testcase", input = InputType.YES, condition = InputType.YES) public void Substring() { if(!Condition.isBlank()){ @@ -131,7 +208,7 @@ public void Substring() { if(subStringList.size() == 2 || subStringList.size() == 3){ s = getVarValue(subStringList.get(0)); String s2 = getVarValue(subStringList.get(1).trim()) ; - String s3 = subStringList.size() == 3 ? getVarValue(subStringList.get(2).trim()) : String.valueOf(s.length() -1); + String s3 = subStringList.size() == 3 ? getVarValue(subStringList.get(2).trim()) : String.valueOf(s.length()); if (isNumeric(s2) && isNumeric(s3)){ int firstIndex = Integer.parseInt(s2); int secondIndex = Integer.parseInt(s3); @@ -160,6 +237,24 @@ public void Substring() { } } + /** + * Replaces occurrences of a substring within a string. + * Accepts 3 or 4 parameters: string, searchText, replacementText, and optionally replaceType. + * ReplaceType can be "first" (replace first occurrence) or "all" (replace all occurrences). + * If replaceType is not provided, it must be explicitly specified. + * Supports variables (%var%), datasheet references ({sheet:column}), and string literals ("text"). + * The result is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: "Hello World", "World", "Universe", "first"
    • + *
    • Input: %text%, "old", "new", "all"
    • + *
    • Input: {data:greeting}, "old", "new", "all"
    • + *
    • Condition: %result%
    • + *
    + * + * @throws ForcedException if replaceType is not "first" or "all", or input format is invalid + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Replace String input within testcase", input = InputType.YES, condition = InputType.YES) public void Replace() { if(!Condition.isBlank()){ @@ -207,6 +302,20 @@ public void Replace() { } } + /** + * Converts a string input to lowercase. + * Supports variables (%var%), datasheet references ({sheet:column}), and string literals ("text"). + * The lowercase result is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: "HELLO WORLD" or %text% or {data:greeting}
    • + *
    • Condition: %lowerText%
    • + *
    • Result: "hello world"
    • + *
    + * + * @throws ForcedException if input format is invalid or no variable name is assigned + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Converts String input to lower case within testcase", input = InputType.YES, condition = InputType.YES) public void ToLower() { if(!Condition.isBlank()){ @@ -230,6 +339,20 @@ public void ToLower() { } } + /** + * Converts a string input to uppercase. + * Supports variables (%var%), datasheet references ({sheet:column}), and string literals ("text"). + * The uppercase result is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: "hello world" or %text% or {data:greeting}
    • + *
    • Condition: %upperText%
    • + *
    • Result: "HELLO WORLD"
    • + *
    + * + * @throws ForcedException if input format is invalid or no variable name is assigned + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Converts String input to upper case within testcase", input = InputType.YES, condition = InputType.YES) public void ToUpper() { if(!Condition.isBlank()){ @@ -253,6 +376,23 @@ public void ToUpper() { } } + /** + * Splits a string by a delimiter and retrieves a specific element from the result. + * Supports variables (%var%), datasheet references ({sheet:column}), and string literals ("text"). + * Accepts 3 or 4 parameters: string, delimiter, index, and optionally limit. + * The limit parameter controls the maximum number of splits (-1 for unlimited). + * The element at the specified index is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: "one,two,three", ",", 1 (returns "two")
    • + *
    • Input: %text%, ",", 1 (returns "two")
    • + *
    • Input: {data:string_value}, ",", 1 (returns "two")
    • + *
    • Condition: %result%
    • + *
    + * + * @throws ForcedException if index/limit are not numeric, index is out of bounds, or input format is invalid + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Split String input within testcase", input = InputType.YES, condition = InputType.YES) public void Split() { if(!Condition.isBlank()){ @@ -299,6 +439,22 @@ public void Split() { } } + /** + * Counts the number of occurrences of a specific character in a string. + * Accepts 2 parameters: string and character (must be a single character). + * Supports variables (%var%), datasheet references ({sheet:column}), and string literals ("text"). + * The count is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: "Hello World", "l" (returns 3)
    • + *
    • Input: %text%, "a"
    • + *
    • Input: {data:greeting}, "a"
    • + *
    • Condition: %count%
    • + *
    + * + * @throws ForcedException if second parameter is not a single character or input format is invalid + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Get occurence of String input within testcase", input = InputType.YES, condition = InputType.YES) public void GetOccurence() { if(!Condition.isBlank()){ @@ -337,6 +493,18 @@ public void GetOccurence() { } } + /** + * Calculates the length of a string input. + * The length is stored in the variable specified in the Condition field. + * + *

    Example usage: + *

      + *
    • Input: "Hello World" or %text% or {data:greeting}
    • + *
    • Condition: %length%
    • + *
    + * + * @throws ForcedException if input format is invalid or no variable name is assigned + */ @Action(object = ObjectType.STRINGOPERATIONS, desc = "Get length of String input within testcase", input = InputType.YES, condition = InputType.YES) public void GetLength() { if(!Condition.isBlank()){ diff --git a/Engine/src/main/java/com/ing/engine/commands/webservice/Webservice.java b/Engine/src/main/java/com/ing/engine/commands/webservice/Webservice.java index 98efb2e2..890c9377 100644 --- a/Engine/src/main/java/com/ing/engine/commands/webservice/Webservice.java +++ b/Engine/src/main/java/com/ing/engine/commands/webservice/Webservice.java @@ -5,6 +5,7 @@ import com.ing.engine.constants.FilePath; import com.ing.engine.core.CommandControl; import com.ing.engine.core.Control; +import com.ing.engine.execution.exception.ActionException; import com.ing.engine.support.Status; import com.ing.engine.support.methodInf.Action; import com.ing.engine.support.methodInf.InputType; @@ -35,6 +36,8 @@ import java.io.StringReader; import java.net.URLEncoder; import java.net.http.HttpClient; +import java.net.http.HttpClient.Redirect; +import java.net.http.HttpHeaders; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublisher; import java.net.http.HttpResponse; @@ -84,9 +87,10 @@ public enum RequestMethod { public void putRestRequest() { try { createhttpRequest(RequestMethod.PUT); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (Exception e) { + Report.updateTestLog(Action, + "An unexpected error occurred while executing the request : " + "\n" + e.getMessage(), + Status.FAIL); } } @@ -94,8 +98,10 @@ public void putRestRequest() { public void postRestRequest() { try { createhttpRequest(RequestMethod.POST); - } catch (InterruptedException e) { - e.printStackTrace(); + } catch (Exception e) { + Report.updateTestLog(Action, + "An unexpected error occurred while executing the request : " + "\n" + e.getMessage(), + Status.FAIL); } } @@ -103,9 +109,10 @@ public void postRestRequest() { public void postSoapRequest() { try { createhttpRequest(RequestMethod.POST); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (Exception e) { + Report.updateTestLog(Action, + "An unexpected error occurred while executing the request : " + "\n" + e.getMessage(), + Status.FAIL); } } @@ -113,9 +120,10 @@ public void postSoapRequest() { public void patchRestRequest() { try { createhttpRequest(RequestMethod.PATCH); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (Exception e) { + Report.updateTestLog(Action, + "An unexpected error occurred while executing the request : " + "\n" + e.getMessage(), + Status.FAIL); } } @@ -123,9 +131,10 @@ public void patchRestRequest() { public void getRestRequest() { try { createhttpRequest(RequestMethod.GET); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (Exception e) { + Report.updateTestLog(Action, + "An unexpected error occurred while executing the request : " + "\n" + e.getMessage(), + Status.FAIL); } } @@ -133,9 +142,10 @@ public void getRestRequest() { public void deleteRestRequest() { try { createhttpRequest(RequestMethod.DELETE); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (Exception e) { + Report.updateTestLog(Action, + "An unexpected error occurred while executing the request : " + "\n" + e.getMessage(), + Status.FAIL); } } @@ -143,9 +153,10 @@ public void deleteRestRequest() { public void deleteWithPayload() { try { createhttpRequest(RequestMethod.DELETEWITHPAYLOAD); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } catch (Exception e) { + Report.updateTestLog(Action, + "An unexpected error occurred while executing the request : " + "\n" + e.getMessage(), + Status.FAIL); } } @@ -453,7 +464,7 @@ private void returnResponseDetails() throws IOException, InterruptedException { /** * *** need to add timeout,version****** */ - httpClient.put(key, httpClientBuilder.get(key).build()); + httpClient.put(key, httpClientBuilder.get(key).followRedirects(getRedirectPolicy()).build()); httpRequest.put(key, httpRequestBuilder.get(key).build()); response.put(key, httpClient.get(key).send(httpRequest.get(key), HttpResponse.BodyHandlers.ofString())); @@ -673,6 +684,233 @@ public void addURLParam() { } + /** + * Stores the value of a header by name in a variable. + *

    + * The header value is retrieved for the current scenario/test case and stored in a variable if the variable format is correct. + *

      + *
    • Condition: Variable name (e.g., %Variable Name%)
    • + *
    • Data: Header name (e.g., "Content-Type")
    • + *
    + */ + @Action(object = ObjectType.WEBSERVICE, desc = "Store Header Element in Variable", input = InputType.YES, condition = InputType.YES) + public void storeHeaderByNameInVariable() { + try { + String variableName = Condition; // e.g., %Variable Name% + String headerName = Data; // e.g., "Content-Type" + + // storeAllHeadersInMap() will populate headerKeyValueMap with headers for the current scenario/test case (key) + storeAllHeadersInMap(); + + // Check if headers exist for this key + if (!headerKeyValueMap.containsKey(key) || headerKeyValueMap.get(key).isEmpty()) { + Report.updateTestLog(Action, "No headers found for scenario: [" + userData.getScenario() + "] and test case: [" + userData.getTestCase() + "]", Status.DEBUG); + return; + } + + // Get headers for this scenario + Map currentHeaders = headerKeyValueMap.get(key); + + // Check if requested header exists + if (!currentHeaders.containsKey(headerName)) { + Report.updateTestLog(Action, "Header '" + headerName + "' does not exist in available headers for scenario: [" + userData.getScenario() + "] and test case: [" + userData.getTestCase() + "]", Status.DEBUG); + return; + } + + // Validate variable format + if (variableName.matches("%.*%")) { + String headerValue = currentHeaders.get(headerName); + addVar(variableName, headerValue); + Report.updateTestLog(Action, "Header '" + headerName + "' stored in variable '" + variableName + "' with value: " + headerValue, Status.DONE); + } else { + Report.updateTestLog(Action, "Variable format is not correct", Status.DEBUG); + } + + } catch (Exception ex) { + Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); + Report.updateTestLog(Action, "Error storing header value: " + ex.getMessage(), Status.DEBUG); + } + } + + /** + * Stores the value of a header by name in a datasheet column. + *

    + * The header value is retrieved for the current scenario/test case and stored in the specified datasheet column. + *

      + *
    • Condition: Header name (e.g., "Content-Type")
    • + *
    • Input: sheetName:ColumnName
    • + *
    + */ + @Action(object = ObjectType.WEBSERVICE, desc = "Store Header value in Datasheet", input = InputType.YES, condition = InputType.YES) + public void storeHeaderByNameInDatasheet() { + try { + String headerName = Condition; // e.g., "Content-Type" + + // First, populate maps for this scenario/test case + storeAllHeadersInMap(); + + // Check if headers exist for this key + if (!headerKeyValueMap.containsKey(key) || headerKeyValueMap.get(key).isEmpty()) { + Report.updateTestLog(Action, "No headers found for scenario: [" + userData.getScenario() + "] and test case: [" + userData.getTestCase() + "]", Status.DEBUG); + return; + } + + // Get headers for this scenario + Map currentHeaders = headerKeyValueMap.get(key); + + // Check if requested header exists + if (!currentHeaders.containsKey(headerName)) { + Report.updateTestLog(Action, "Header '" + headerName + "' does not exist in available headers for scenario: [" + userData.getScenario() + "] and test case: [" + userData.getTestCase() + "]", Status.DEBUG); + return; + } + + // Early return if input format is invalid + if (!Input.matches(".*:.*")) { + Report.updateTestLog(Action, "Invalid input format [" + Input + "]. Expected format: sheetName:ColumnName", Status.DEBUG); + return; + } + + try { + String sheetName = Input.split(":", 2)[0]; + String columnName = Input.split(":", 2)[1]; + String headerValue = currentHeaders.get(headerName); + + // Store header value in datasheet + userData.putData(sheetName, columnName, headerValue); + + Report.updateTestLog(Action, "Header value [" + headerValue + "] stored in datasheet [" + sheetName + ":" + columnName + "]", Status.DONE); + } catch (Exception ex) { + Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex); + Report.updateTestLog(Action, "Error storing header value in datasheet: " + ex.getMessage(), Status.DEBUG); + } + + } catch (Exception ex) { + Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); + Report.updateTestLog(Action, "Error storing header value in datasheet: " + ex.getMessage(), Status.DEBUG); + } + } + + /** + * Asserts that the value of a header contains the expected text. + *

    + * The header value is checked for the current scenario/test case. + *

      + *
    • Condition: Header name (e.g., "Content-Type")
    • + *
    • Data: Expected substring
    • + *
    + */ + @Action(object = ObjectType.WEBSERVICE, desc = "Assert header", input = InputType.YES, condition = InputType.YES) + public void assertHeaderValueContains() { + try { + String headerName = Condition; // e.g., "Content-Type" + + // First, populate maps for this scenario/test case + storeAllHeadersInMap(); + + // Check if headers exist for this key + if (!headerKeyValueMap.containsKey(key) || headerKeyValueMap.get(key).isEmpty()) { + Report.updateTestLog(Action, "No headers found for scenario: [" + userData.getScenario() + "] and test case: [" + userData.getTestCase() + "]", Status.FAILNS); + return; + } + + // Get headers for this scenario + Map currentHeaders = headerKeyValueMap.get(key); + + // Check if requested header exists + if (!currentHeaders.containsKey(headerName)) { + Report.updateTestLog(Action, "Header '" + headerName + "' does not exist in available headers.", Status.FAILNS); + return; + } + + String headerValue = headerKeyValueMap.get(key).get(headerName); + if (headerValue.contains(Data)) { + Report.updateTestLog(Action, "Header value [" + headerValue + "] contains expected text [" + Data + "]", Status.PASSNS); + } else { + Report.updateTestLog(Action, "Header value [" + headerValue + "] does not contain expected text [" + Data + "]", Status.FAILNS); + } + + } catch (Exception ex) { + Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); + Report.updateTestLog(Action, "Error to assert header value : " + ex.getMessage(), Status.FAILNS); + } + } + + /** + * Asserts that the value of a header equals the expected text. + *

    + * The header value is checked for the current scenario/test case. + *

      + *
    • Condition: Header name (e.g., "Content-Type")
    • + *
    • Data: Expected value
    • + *
    + */ + @Action(object = ObjectType.WEBSERVICE, desc = "Assert header", input = InputType.YES, condition = InputType.YES) + public void assertHeaderValueEquals() { + try { + String headerName = Condition; // e.g., "Content-Type" + + // First, populate maps for this scenario/test case + storeAllHeadersInMap(); + + // Check if headers exist for this key + if (!headerKeyValueMap.containsKey(key) || headerKeyValueMap.get(key).isEmpty()) { + Report.updateTestLog(Action, "No headers found for scenario: [" + userData.getScenario() + "] and test case: [" + userData.getTestCase() + "]", Status.FAILNS); + return; + } + + // Get headers for this scenario + Map currentHeaders = headerKeyValueMap.get(key); + + // Check if requested header exists + if (!currentHeaders.containsKey(headerName)) { + Report.updateTestLog(Action, "Header '" + headerName + "' does not exist in available headers.", Status.FAILNS); + return; + } + + String headerValue = headerKeyValueMap.get(key).get(headerName); + if (headerValue.equals(Data)) { + Report.updateTestLog(Action, "Header value [" + headerValue + "] equals expected text [" + Data + "]", Status.PASSNS); + } else { + Report.updateTestLog(Action, "Header value [" + headerValue + "] does not equal expected text [" + Data + "]", Status.FAILNS); + } + + } catch (Exception ex) { + Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); + Report.updateTestLog(Action, "Error to assert header value : " + ex.getMessage(), Status.FAILNS); + } + } + + /** + * Populates the headerKeyValueMap with all headers for the current scenario/test case. + *

    + * Combines header values and tags them with the scenario/test case key. + */ + private void storeAllHeadersInMap() { + try { + Map> headersMap = response.get(key).headers().map(); + + // If headers are missing, just return + if (headersMap == null || headersMap.isEmpty()) { + return; + } + + // Clear previous headerMap for this run + headerMap.clear(); + + // Populate headerMap with combined values + headersMap.forEach((headerName, values) -> { + String combinedValues = String.join(", ", values); // Append all values + headerMap.put(headerName, combinedValues); + }); + + // Tag this headerMap with scenario/test case key + headerKeyValueMap.put(key, new HashMap<>(headerMap)); + + } catch (Exception ex) { + Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); + } + } + private boolean isformUrlencoded() { if (headers.containsKey(key)) { ArrayList headerlist = headers.get(key); @@ -917,7 +1155,7 @@ private void setRequestMethod(RequestMethod requestmethod) throws FileNotFoundEx } } - private void createhttpRequest(RequestMethod requestmethod) throws InterruptedException { + private void createhttpRequest(RequestMethod requestmethod) throws InterruptedException, Exception { try { setheaders(); setRequestMethod(requestmethod); @@ -965,6 +1203,9 @@ private void createhttpRequest(RequestMethod requestmethod) throws InterruptedEx "Error in executing " + requestmethod.toString() + " request : " + "\n" + ex.getMessage(), Status.DEBUG); } + } catch (InterruptedException e) { + e.printStackTrace(); + throw new ActionException(e); } } @@ -1030,8 +1271,8 @@ public void checkServerTrusted(X509Certificate[] certs, String authType) { }}; private KeyManager[] loadKeyStore() { - String keystorePath = Control.getCurrentProject().getProjectSettings().getDriverSettings().getProperty("keyStorePath"); - String keystorePassword = Control.getCurrentProject().getProjectSettings().getDriverSettings().getProperty("keyStorePassword"); + String keystorePath = Control.getCurrentProject().getProjectSettings().getDriverSettings().getKeyStorePath(); + String keystorePassword = Control.getCurrentProject().getProjectSettings().getDriverSettings().getKeyStorePassword(); KeyStore keyStore; KeyManagerFactory kmf = null; try { @@ -1071,4 +1312,108 @@ private Boolean isSelfSigned() { return Control.getCurrentProject().getProjectSettings().getDriverSettings().selfSigned(); } + + /** + * Retrieves the HTTP redirect policy configured for the current API driver settings. + *

    + * The logic follows three strict rules: + *

      + *
    • If no value is configured (i.e., the property is {@code null} or blank), the method defaults to + * {@link Redirect#NEVER}.
    • + *
    • If a valid redirect policy is provided (one of {@code NEVER}, {@code NORMAL}, or {@code ALWAYS}, + * case-insensitive), the corresponding {@link Redirect} enum is returned.
    • + *
    • If a value is provided but does not match any {@link Redirect} enum constant, the method throws an + * {@link IllegalArgumentException} to indicate a configuration error.
    • + *
    + *

    + * + * @return the resolved {@link Redirect} policy to be applied when building the {@link java.net.http.HttpClient} + * @throws IllegalArgumentException if a non-blank but invalid redirect value is configured + */ + private Redirect getRedirectPolicy() { + String httpClientRedirect = Control.getCurrentProject().getProjectSettings().getDriverSettings().getHttpClientRedirect(); + + if (httpClientRedirect == null || httpClientRedirect.trim().isEmpty()) { + return Redirect.NEVER; + } + + try { + return Redirect.valueOf(httpClientRedirect.trim().toUpperCase()); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Invalid httpClientRedirect value: '" + httpClientRedirect + "'. Allowed values: NEVER, NORMAL, ALWAYS."); + } + } + + /** + * Extracts a cookie value from the HTTP response headers and stores it in a variable. + *

    + * This method searches for the cookie with the name specified by {@code Data} in the response headers. + * The cookie value is then stored in a variable whose name is specified by {@code Condition} (must be in the format %variableName%). + * The header name search for "Set-Cookie" is case-insensitive and will match any casing. + *

      + *
    • If the variable name format is invalid, a debug message is logged and the method returns.
    • + *
    • If the cookie is found, its value is stored in the variable and a DONE status is logged.
    • + *
    • If no cookies are found, a FAIL status is logged.
    • + *
    • If an error occurs, a FAIL status is logged and the stack trace is printed.
    • + *
    + * + * @see #addVar(String, String) + */ + @Action(object = ObjectType.WEBSERVICE, desc = "Store Cookies In Variable ", input = InputType.YES, condition = InputType.YES) + public void storeResponseCookiesInVariable() { + try { + String cookieKey = Data; + String variableName = Condition; + + if (!variableName.matches("%.*%")) { + Report.updateTestLog(Action, "Variable format is not correct. Should be %variableName%", Status.DEBUG); + return; + } + + variableName = variableName.substring(1, variableName.length() - 1); + + if (!response.containsKey(key) && response.get(key) == null) { + Report.updateTestLog(Action, "Response did not contain a valid HttpResponse for key [" + key + "]", Status.FAIL); + return; + } + + HttpResponse httpResponse = response.get(key); + HttpHeaders responseHeaders = httpResponse.headers(); + + List cookieHeaders = !responseHeaders.allValues("set-cookie").isEmpty() ? responseHeaders.allValues("set-cookie") : responseHeaders.allValues("Set-Cookie"); + + if (cookieHeaders.isEmpty()) { + Report.updateTestLog(Action, "No cookies were retrieved from the endpoint", Status.FAIL); + return; + } + + for (String cookieHeader : cookieHeaders) { + if (cookieHeader == null || cookieHeader.isEmpty()) continue; + + String[] cookieParts = cookieHeader.split(";"); + if (cookieParts.length == 0) continue; + + String[] keyValue = cookieParts[0].trim().split("=", 2); + if (keyValue.length != 2) continue; + + String cookieName = keyValue[0].trim(); + String cookieValue = keyValue[1].trim(); + + if (cookieName.equals(cookieKey)) { + addVar(variableName, cookieValue); + Report.updateTestLog( + Action, + "Cookies with name [" + cookieKey + "] has been added in variable [" + + variableName + "] with value [" + cookieValue + "] ", + Status.DONE + ); + return; // early exit on success + } + } + } catch (Exception ex) { + Report.updateTestLog(Action, "Error in storing cookies with name in variable :"+ex.getMessage(), Status.FAIL); + ex.printStackTrace(); + } + } + } diff --git a/Engine/src/main/java/com/ing/engine/core/Task.java b/Engine/src/main/java/com/ing/engine/core/Task.java index 8c09bcf9..8ce74a0b 100644 --- a/Engine/src/main/java/com/ing/engine/core/Task.java +++ b/Engine/src/main/java/com/ing/engine/core/Task.java @@ -23,6 +23,7 @@ import java.util.logging.Logger; import com.ing.engine.drivers.WebDriverCreation; +import com.ing.engine.execution.exception.data.DataNotFoundException; import java.util.Locale; import org.openqa.selenium.JavascriptExecutor; @@ -146,6 +147,11 @@ public boolean runIteration(int iter) { SystemDefaults.stopCurrentIteration.set(false); runner.run(createControl(), iter); success = true; + } catch (DataNotFoundException ex) { + if (!ex.cause.isEndData()){ + LOG.log(Level.SEVERE, ex.getMessage(), ex); + report.updateTestLog("DataNotFoundException", ex.getMessage(), Status.DEBUG); + } } catch (DriverClosedException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); report.updateTestLog("DriverClosedException", ex.getMessage(), Status.FAILNS); diff --git a/Engine/src/main/java/com/ing/engine/drivers/AutomationObject.java b/Engine/src/main/java/com/ing/engine/drivers/AutomationObject.java index 0bd8d710..39630c82 100644 --- a/Engine/src/main/java/com/ing/engine/drivers/AutomationObject.java +++ b/Engine/src/main/java/com/ing/engine/drivers/AutomationObject.java @@ -3,39 +3,28 @@ import com.ing.datalib.or.ObjectRepository; import com.ing.datalib.or.common.ORAttribute; import com.ing.datalib.or.common.ObjectGroup; -import com.ing.datalib.or.image.ImageORObject; import com.ing.datalib.or.mobile.MobileORObject; import com.ing.datalib.or.mobile.MobileORPage; +import com.ing.datalib.or.mobile.ResolvedMobileObject; import com.ing.datalib.or.web.WebORObject; import com.ing.datalib.or.web.WebORPage; +import com.ing.datalib.or.web.ResolvedWebObject; import com.ing.engine.constants.SystemDefaults; import com.ing.engine.core.Control; import com.ing.engine.core.CommandControl; -import com.ing.engine.reporting.intf.Report; -import com.ing.engine.support.Status; import com.microsoft.playwright.BrowserContext; import com.microsoft.playwright.FrameLocator; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; -import com.microsoft.playwright.Page.GetByAltTextOptions; -import com.microsoft.playwright.Page.GetByLabelOptions; -import com.microsoft.playwright.Page.GetByPlaceholderOptions; -import com.microsoft.playwright.Page.GetByRoleOptions; -import com.microsoft.playwright.Page.GetByTextOptions; -import com.microsoft.playwright.Page.GetByTitleOptions; import com.microsoft.playwright.options.AriaRole; import java.time.Duration; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.apache.http.client.methods.RequestBuilder.options; public class AutomationObject { @@ -63,6 +52,7 @@ public void setPage(Page page) { public static HashMap globalDynamicValue = new HashMap<>(); public static String Action = ""; static HashMap chainLocatorMaping = new HashMap(); + public static final Map> locatorFiltersMap = new HashMap<>(); public enum FindType { GLOBAL_OBJECT, DEFAULT; @@ -140,7 +130,8 @@ public List findElements(String objectKey, String pageKey, String Attri } public List findElements(String objectKey, String pageKey, FindType condition) { - return findElements(objectKey, pageKey, condition); + //return findElements(objectKey, pageKey, condition); + return findElements(objectKey, pageKey, null, condition); } public List findElements(String objectKey, String pageKey, String Attribute, FindType condition) { @@ -154,10 +145,28 @@ private Locator getElementFromList(List elements) { public ObjectGroup getORObject(String page, String object) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); - if (objRep.getWebOR().getPageByName(page) != null) { + try { + ResolvedWebObject.PageRef wref = ResolvedWebObject.PageRef.parse(page); + ResolvedWebObject wresolved = objRep.resolveWebObject(wref, object); + if (wresolved != null && wresolved.getGroup() != null) { + return wresolved.getGroup(); + } + } catch (Exception ignore) { } + try { + ResolvedMobileObject.PageRef mref = ResolvedMobileObject.PageRef.parse(page); + ResolvedMobileObject mresolved = objRep.resolveMobileObject(mref, object); + if (mresolved != null && mresolved.getGroup() != null) { + return mresolved.getGroup(); + } + } catch (Exception ignore) { } + if (objRep.getWebOR() != null && objRep.getWebOR().getPageByName(page) != null) { return objRep.getWebOR().getPageByName(page).getObjectGroupByName(object); - } else if (objRep.getMobileOR().getPageByName(page) != null) { + } else if (objRep.getWebSharedOR() != null && objRep.getWebSharedOR().getPageByName(page) != null) { + return objRep.getWebSharedOR().getPageByName(page).getObjectGroupByName(object); + } else if (objRep.getMobileOR() != null && objRep.getMobileOR().getPageByName(page) != null) { return objRep.getMobileOR().getPageByName(page).getObjectGroupByName(object); + } else if (objRep.getMobileSharedOR() != null && objRep.getMobileSharedOR().getPageByName(page) != null) { + return objRep.getMobileSharedOR().getPageByName(page).getObjectGroupByName(object); } return null; } @@ -165,35 +174,49 @@ public ObjectGroup getORObject(String page, String object) { public String getObjectProperty(String pageName, String objectName, String propertyName) { return getWebObject(pageName, objectName).getAttributeByName(propertyName); } - + public ObjectGroup getWebObjects(String page, String object) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); - if (objRep.getWebOR().getPageByName(page) != null) { + + try { + ResolvedWebObject.PageRef ref = ResolvedWebObject.PageRef.parse(page); + ResolvedWebObject resolved = objRep.resolveWebObject(ref, object); + if (resolved != null && resolved.getGroup() != null) { + return (ObjectGroup) resolved.getGroup(); + } + } catch (Exception ignore) { } + if (objRep.getWebOR() != null && objRep.getWebOR().getPageByName(page) != null) { return objRep.getWebOR().getPageByName(page).getObjectGroupByName(object); + } else if (objRep.getWebSharedOR() != null && objRep.getWebSharedOR().getPageByName(page) != null) { + return objRep.getWebSharedOR().getPageByName(page).getObjectGroupByName(object); } return null; } public WebORObject getWebObject(String page, String object) { - ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); - if (objRep.getWebOR().getPageByName(page) != null) { - return objRep.getWebOR().getPageByName(page).getObjectGroupByName(object).getObjects().get(0); + ObjectGroup group = getWebObjects(page, object); + if (group != null && group.getObjects() != null && !group.getObjects().isEmpty()) { + return group.getObjects().get(0); } return null; } public ObjectGroup getMobileObjects(String page, String object) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); - if (objRep.getMobileOR().getPageByName(page) != null) { + if (objRep.getMobileOR() != null && objRep.getMobileOR().getPageByName(page) != null) { return objRep.getMobileOR().getPageByName(page).getObjectGroupByName(object); + } else if (objRep.getMobileSharedOR() != null && objRep.getMobileSharedOR().getPageByName(page) != null) { + return objRep.getMobileSharedOR().getPageByName(page).getObjectGroupByName(object); } return null; } public MobileORObject getMobileObject(String page, String object) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); - if (objRep.getMobileOR().getPageByName(page) != null) { + if (objRep.getMobileOR() != null && objRep.getMobileOR().getPageByName(page) != null) { return objRep.getMobileOR().getPageByName(page).getObjectGroupByName(object).getObjects().get(0); + } else if (objRep.getMobileSharedOR() != null && objRep.getMobileSharedOR().getPageByName(page) != null) { + return objRep.getMobileSharedOR().getPageByName(page).getObjectGroupByName(object).getObjects().get(0); } return null; } @@ -251,229 +274,93 @@ private String notFoundIn(ObjectGroup objectGroup) { } private List getElements(final List attributes) { - try { - - String tag = ""; - String value = ""; - List elements = new ArrayList(); - Locator e = null; - //elements = null; - for (ORAttribute attr : attributes) { - if (!attr.getValue().trim().isEmpty()) { - tag = attr.getName(); - value = getRuntimeValue(attr.getValue()); - - switch (tag) { - case "Text": - System.out.println(foundElementBy("Text", value)); - GetByTextOptions textOptions = new Page.GetByTextOptions(); - if (value.toLowerCase().contains(";exact")) { - textOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(this.getPage().getByText(value, textOptions)); - break; - case "Label": - System.out.println(foundElementBy("Label", value)); - GetByLabelOptions labelOptions = new Page.GetByLabelOptions(); - if (value.toLowerCase().contains(";exact")) { - labelOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(this.getPage().getByLabel(value, labelOptions)); - break; - case "Placeholder": - System.out.println(foundElementBy("Placeholder", value)); - GetByPlaceholderOptions placeholderOptions = new Page.GetByPlaceholderOptions(); - if (value.toLowerCase().contains(";exact")) { - placeholderOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(this.getPage().getByPlaceholder(value, placeholderOptions)); - break; - case "AltText": - System.out.println(foundElementBy("AltText", value)); - GetByAltTextOptions altTextOptions = new Page.GetByAltTextOptions(); - if (value.toLowerCase().contains(";exact")) { - altTextOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(this.getPage().getByAltText(value, altTextOptions)); - break; - case "Title": - System.out.println(foundElementBy("Title", value)); - GetByTitleOptions titleOptions = new Page.GetByTitleOptions(); - if (value.toLowerCase().contains(";exact")) { - titleOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(this.getPage().getByTitle(value, titleOptions)); - break; - case "TestId": - System.out.println(foundElementBy("TestId", value)); - elements.add(this.getPage().getByTestId(value)); - break; - case "css": - System.out.println(foundElementBy("CSS", value)); - elements.add(this.getPage().locator("css=" + value).first()); - break; - case "xpath": - System.out.println(foundElementBy("Xpath", value)); - elements.add(this.getPage().locator("xpath=" + value)); - break; - case "Role": - System.out.println(foundElementBy("Role", value)); - String roleType; - String name; - if (value.contains(";")) { - roleType = value.split(";")[0].toUpperCase(); - GetByRoleOptions roleOptions = new Page.GetByRoleOptions(); - if (value.toLowerCase().contains(";exact")) { - roleOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - name = value.split(";")[1]; - roleOptions.setName(name); - - elements.add(this.getPage().getByRole(AriaRole.valueOf(roleType), roleOptions)); - } else { - elements.add(this.getPage().getByRole(AriaRole.valueOf(value.toUpperCase()))); - } - case "ChainedLocator": - - List selectors = new ArrayList<>(); - selectors = Arrays.asList(value.split(";")); - Locator locator = null; - for (int i = 0; i < selectors.size(); i++) { - locator = chainLocators(selectors.get(i), i, this.getPage(), locator); - } - //System.out.println(foundElementBy("Chained Locators", value)); - elements.add(locator); - break; - } - - return elements; - } - + return getElementsInternal(attributes, (tag, value, options) -> { + Locator locator = null; + switch (tag) { + case "Text": + locator = this.page.getByText(value, (Page.GetByTextOptions) options); + break; + case "Label": + locator = this.page.getByLabel(value, (Page.GetByLabelOptions) options); + break; + case "Placeholder": + locator = this.page.getByPlaceholder(value, (Page.GetByPlaceholderOptions) options); + break; + case "AltText": + locator = this.page.getByAltText(value, (Page.GetByAltTextOptions) options); + break; + case "Title": + locator = this.page.getByTitle(value, (Page.GetByTitleOptions) options); + break; + case "TestId": + locator = this.page.getByTestId(value); + break; + case "css": + locator = this.page.locator("css=" + value); + break; + case "xpath": + locator = this.page.locator("xpath=" + value); + break; + case "Role": + locator = createRoleLocator(value, this.page); + break; + case "ChainedLocator": + locator = createChainedLocator(value, this.page); + break; + default: + locator = null; } - return null; - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - return null; - } + // Apply filter if required + if (locator != null) { + locator = setFilter(locator); + } + return locator; + }); } private List getElements(FrameLocator framelocator, final List attributes) { - try { - String tag = ""; - String value = ""; - List elements = new ArrayList(); - Locator e = null; - //elements = null; - for (ORAttribute attr : attributes) { - if (!attr.getValue().trim().isEmpty()) { - tag = attr.getName(); - value = getRuntimeValue(attr.getValue()); - //value = attr.getValue(); - - switch (tag) { - case "Text": - System.out.println(foundElementBy("Text", value)); - FrameLocator.GetByTextOptions textOptions = new FrameLocator.GetByTextOptions(); - if (value.toLowerCase().contains(";exact")) { - textOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(framelocator.getByText(value, textOptions)); - break; - case "Label": - System.out.println(foundElementBy("Label", value)); - FrameLocator.GetByLabelOptions labelOptions = new FrameLocator.GetByLabelOptions(); - if (value.toLowerCase().contains(";exact")) { - labelOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(framelocator.getByLabel(value, labelOptions)); - break; - case "Placeholder": - System.out.println(foundElementBy("Placeholder", value)); - FrameLocator.GetByPlaceholderOptions placeholderOptions = new FrameLocator.GetByPlaceholderOptions(); - if (value.toLowerCase().contains(";exact")) { - placeholderOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(framelocator.getByPlaceholder(value, placeholderOptions)); - break; - case "AltText": - System.out.println(foundElementBy("AltText", value)); - FrameLocator.GetByAltTextOptions altTextOptions = new FrameLocator.GetByAltTextOptions(); - if (value.toLowerCase().contains(";exact")) { - altTextOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(framelocator.getByAltText(value, altTextOptions)); - break; - case "Title": - System.out.println(foundElementBy("Title", value)); - FrameLocator.GetByTitleOptions titleOptions = new FrameLocator.GetByTitleOptions(); - if (value.toLowerCase().contains(";exact")) { - titleOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - elements.add(framelocator.getByTitle(value, titleOptions)); - break; - case "TestId": - System.out.println(foundElementBy("TestId", value)); - elements.add(framelocator.getByTestId(value)); - break; - case "css": - System.out.println(foundElementBy("CSS", value)); - elements.add(framelocator.locator("css=" + value).first()); - break; - case "xpath": - System.out.println(foundElementBy("Xpath", value)); - elements.add(framelocator.locator("xpath=" + value)); - break; - case "Role": - System.out.println(foundElementBy("Role", value)); - String roleType; - String name; - if (value.contains(";")) { - roleType = value.split(";")[0].toUpperCase(); - FrameLocator.GetByRoleOptions roleOptions = new FrameLocator.GetByRoleOptions(); - if (value.toLowerCase().contains(";exact")) { - roleOptions.setExact(true); - value = value.replace(";exact", "").trim(); - } - name = value.split(";")[1]; - roleOptions.setName(name); - - elements.add(framelocator.getByRole(AriaRole.valueOf(roleType), roleOptions)); - } else { - elements.add(framelocator.getByRole(AriaRole.valueOf(value.toUpperCase()))); - } - case "ChainedLocator": - - List selectors = new ArrayList<>(); - selectors = Arrays.asList(value.split(";")); - Locator locator = null; - for (int i = 0; i < selectors.size(); i++) { - locator = chainLocators(selectors.get(i), i, framelocator, locator); - } - //System.out.println(foundElementBy("Chained Locators", value)); - elements.add(locator); - break; - } - - return elements; - } - + return getElementsInternal(attributes, (tag, value, options) -> { + Locator locator = null; + switch (tag) { + case "Text": + locator = framelocator.getByText(value, (FrameLocator.GetByTextOptions) options); + break; + case "Label": + locator = framelocator.getByLabel(value, (FrameLocator.GetByLabelOptions) options); + break; + case "Placeholder": + locator = framelocator.getByPlaceholder(value, (FrameLocator.GetByPlaceholderOptions) options); + break; + case "AltText": + locator = framelocator.getByAltText(value, (FrameLocator.GetByAltTextOptions) options); + break; + case "Title": + locator = framelocator.getByTitle(value, (FrameLocator.GetByTitleOptions) options); + break; + case "TestId": + locator = framelocator.getByTestId(value); + break; + case "css": + locator = framelocator.locator("css=" + value).first(); + break; + case "xpath": + locator = framelocator.locator("xpath=" + value); + break; + case "Role": + locator = createRoleLocator(value, framelocator); + break; + case "ChainedLocator": + locator = createChainedLocator(value, framelocator); + break; + default: + locator = null; } - return null; - } catch (Exception ex) { - Logger.getLogger(this.getClass().getName()).log(Level.OFF, null, ex); - return null; - } + // Apply filter if required + if (locator != null) { + locator = setFilter(locator); + } + return locator; + }); } private static Locator chainLocators(String selector, int index, Page page, Locator locator) { @@ -583,9 +470,12 @@ private static Locator chainLocators(String selector, int index, Page page, Loca } - if (selector.matches("first()")) { + if (selector.matches("first\\(\\)")) { locator = locator.first(); } + if (selector.matches("last\\(\\)")) { + locator = locator.last(); + } if (selector.matches("nth\\((\\d+)\\)")) { pattern = Pattern.compile("nth\\((\\d+)\\)"); matcher = pattern.matcher(selector); @@ -705,9 +595,12 @@ private static Locator chainLocators(String selector, int index, FrameLocator fr } - if (selector.matches("first()")) { + if (selector.matches("first\\(\\)")) { locator = locator.first(); } + if (selector.matches("last\\(\\)")) { + locator = locator.last(); + } if (selector.matches("nth\\((\\d+)\\)")) { pattern = Pattern.compile("nth\\((\\d+)\\)"); matcher = pattern.matcher(selector); @@ -834,6 +727,12 @@ public void setDriver(Page page) { } + private String stripScope(String pageKey) { + if (pageKey == null) return null; + int at = pageKey.lastIndexOf('@'); + return (at > 0) ? pageKey.substring(0, at) : pageKey; + } + public List getObjectList(String page, String regexObject) { if (page == null || page.trim().isEmpty()) { throw new RuntimeException("Page Name is empty please give a valid pageName"); @@ -841,11 +740,32 @@ public List getObjectList(String page, String regexObject) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); WebORPage wPage = null; MobileORPage mPage = null; - if (objRep.getWebOR().getPageByName(page) != null) { + try { + ResolvedWebObject.PageRef ref = ResolvedWebObject.PageRef.parse(page); + + if (ref != null && ref.scope != null) { + // Scoped: pick only the specified OR + if (ref.scope.name().equals("SHARED")) { + wPage = objRep.getWebSharedOR().getPageByName(ref.name); + } else { + wPage = objRep.getWebOR().getPageByName(ref.name); + } + } else { + // Unscoped: project-first then shared + wPage = objRep.getWebOR().getPageByName(ref.name); + if (wPage == null) wPage = objRep.getWebSharedOR().getPageByName(ref.name); + } + + } catch (Exception ignore) { + // If parsing fails, treat as plain page name wPage = objRep.getWebOR().getPageByName(page); - } else if (objRep.getMobileOR().getPageByName(page) != null) { - mPage = objRep.getMobileOR().getPageByName(page); + if (wPage == null) wPage = objRep.getWebSharedOR().getPageByName(page); } + + if (wPage == null && objRep.getMobileOR().getPageByName(stripScope(page)) != null) { + mPage = objRep.getMobileOR().getPageByName(stripScope(page)); + } + if (wPage == null && mPage == null) { throw new RuntimeException("Page [" + page + "] is not available in ObjectRepository"); } @@ -909,4 +829,147 @@ private int getMinKey(Map map, Object... object) { return minKey; } -} + @FunctionalInterface + private interface LocatorFactory { + Locator create(String tag, String value, Object options); + } + + private List getElementsInternal(final List attributes, LocatorFactory factory) { + if (attributes == null || attributes.isEmpty()) return null; + List elements = new ArrayList<>(); + for (ORAttribute attr : attributes) { + String value = getRuntimeValue(attr.getValue() != null ? attr.getValue() : ""); + if (value.trim().isEmpty()) continue; + String tag = attr.getName(); + Object options = getOptions(tag, value); + value = value.replace(";exact", "").trim(); + Locator locator = factory.create(tag, value, options); + if (locator != null) { + elements.add(locator); + break; // Only first valid locator + } + } + return elements.isEmpty() ? null : elements; + } + + private Object getOptions(String tag, String value) { + switch (tag) { + case "Text": + Page.GetByTextOptions textOptions = new Page.GetByTextOptions(); + if (value.toLowerCase().contains(";exact")) { + textOptions.setExact(true); + } + System.out.println("textOptions : " + textOptions); + return textOptions; + case "Label": + Page.GetByLabelOptions labelOptions = new Page.GetByLabelOptions(); + if (value.toLowerCase().contains(";exact")) { + labelOptions.setExact(true); + } + return labelOptions; + case "Placeholder": + Page.GetByPlaceholderOptions placeholderOptions = new Page.GetByPlaceholderOptions(); + if (value.toLowerCase().contains(";exact")) { + placeholderOptions.setExact(true); + } + return placeholderOptions; + case "AltText": + Page.GetByAltTextOptions altTextOptions = new Page.GetByAltTextOptions(); + if (value.toLowerCase().contains(";exact")) { + altTextOptions.setExact(true); + } + return altTextOptions; + case "Title": + Page.GetByTitleOptions titleOptions = new Page.GetByTitleOptions(); + if (value.toLowerCase().contains(";exact")) { + titleOptions.setExact(true); + } + return titleOptions; + default: + return null; + } + } + + private Locator createRoleLocator(String value, Page page) { + if (value.contains(";")) { + String[] parts = value.split(";"); + String roleType = parts[0].toUpperCase(); + Page.GetByRoleOptions roleOptions = new Page.GetByRoleOptions(); + if (value.toLowerCase().contains(";exact")) { + roleOptions.setExact(true); + } + if (parts.length > 1) { + roleOptions.setName(parts[1]); + } + return page.getByRole(AriaRole.valueOf(roleType), roleOptions); + } else { + return page.getByRole(AriaRole.valueOf(value.toUpperCase())); + } + } + + private Locator createRoleLocator(String value, FrameLocator framelocator) { + if (value.contains(";")) { + String[] parts = value.split(";"); + String roleType = parts[0].toUpperCase(); + FrameLocator.GetByRoleOptions roleOptions = new FrameLocator.GetByRoleOptions(); + if (value.toLowerCase().contains(";exact")) { + roleOptions.setExact(true); + } + if (parts.length > 1) { + roleOptions.setName(parts[1]); + } + return framelocator.getByRole(AriaRole.valueOf(roleType), roleOptions); + } else { + return framelocator.getByRole(AriaRole.valueOf(value.toUpperCase())); + } + } + + private Locator createChainedLocator(String value, Page page) { + List selectors = Arrays.asList(value.split(";")); + Locator locator = null; + for (int i = 0; i < selectors.size(); i++) { + locator = chainLocators(selectors.get(i), i, page, locator); + } + return locator; + } + + private Locator createChainedLocator(String value, FrameLocator framelocator) { + List selectors = Arrays.asList(value.split(";")); + Locator locator = null; + for (int i = 0; i < selectors.size(); i++) { + locator = chainLocators(selectors.get(i), i, framelocator, locator); + } + return locator; + } + + public void addFilter(String locatorKey, String filter) { + locatorFiltersMap.computeIfAbsent(locatorKey, k -> new ArrayList<>()).add(filter); + } + + private Locator setFilter(Locator locator) { + List filters = locatorFiltersMap.get(pageName + objectName); + if (filters != null) { + for (String value : filters) { + Locator.FilterOptions options = new Locator.FilterOptions(); + if (value.startsWith("setHasText: ")) { + options.setHasText(value.replace("setHasText: ", "")); + } else if (value.startsWith("setHasNotText: ")) { + options.setHasNotText(value.replace("setHasNotText: ", "")); + } else if (value.startsWith("setVisible: ")) { + options.setVisible(Boolean.parseBoolean(value.replace("setVisible: ", ""))); + } + locator = locator.filter(options); + if (value.startsWith("setIndex: ")) { + locator = locator.nth(Integer.parseInt(value.replace("setIndex: ", ""))); + } + } + if(!Action.contains("setFilter")) { + locatorFiltersMap.remove(pageName + objectName); // Clear only for this locator + } + + } + + return locator; + } + +} \ No newline at end of file diff --git a/Engine/src/main/java/com/ing/engine/drivers/MobileObject.java b/Engine/src/main/java/com/ing/engine/drivers/MobileObject.java index d6d598ce..0937cfcf 100644 --- a/Engine/src/main/java/com/ing/engine/drivers/MobileObject.java +++ b/Engine/src/main/java/com/ing/engine/drivers/MobileObject.java @@ -6,6 +6,7 @@ import com.ing.datalib.or.image.ImageORObject; import com.ing.datalib.or.mobile.MobileORObject; import com.ing.datalib.or.mobile.MobileORPage; +import com.ing.datalib.or.mobile.ResolvedMobileObject; import com.ing.datalib.or.web.WebORObject; import com.ing.datalib.or.web.WebORPage; import com.ing.engine.constants.SystemDefaults; @@ -174,10 +175,22 @@ private WebElement getElementFromList(List elements) { public ObjectGroup getORObject(String page, String object) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); - if (objRep.getWebOR().getPageByName(page) != null) { + try { + com.ing.datalib.or.mobile.ResolvedMobileObject.PageRef mref = com.ing.datalib.or.mobile.ResolvedMobileObject.PageRef.parse(page); + com.ing.datalib.or.mobile.ResolvedMobileObject mresolved = objRep.resolveMobileObject(mref, object); + if (mresolved != null && mresolved.getGroup() != null) { + return mresolved.getGroup(); + } + } catch (Exception ignore) { + } + if (objRep.getWebSharedOR().getPageByName(page) != null) { + return objRep.getWebSharedOR().getPageByName(page).getObjectGroupByName(object); + } else if (objRep.getWebOR().getPageByName(page) != null) { return objRep.getWebOR().getPageByName(page).getObjectGroupByName(object); } else if (objRep.getMobileOR().getPageByName(page) != null) { return objRep.getMobileOR().getPageByName(page).getObjectGroupByName(object); + } else if (objRep.getMobileSharedOR() != null && objRep.getMobileSharedOR().getPageByName(page) != null) { + return objRep.getMobileSharedOR().getPageByName(page).getObjectGroupByName(object); } return null; } @@ -188,7 +201,9 @@ public String getObjectProperty(String pageName, String objectName, String prope public ObjectGroup getWebObjects(String page, String object) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); - if (objRep.getWebOR().getPageByName(page) != null) { + if (objRep.getWebSharedOR().getPageByName(page) != null) { + return objRep.getWebSharedOR().getPageByName(page).getObjectGroupByName(object); + } else if (objRep.getWebOR().getPageByName(page) != null) { return objRep.getWebOR().getPageByName(page).getObjectGroupByName(object); } return null; @@ -196,7 +211,9 @@ public ObjectGroup getWebObjects(String page, String object) { public WebORObject getWebObject(String page, String object) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); - if (objRep.getWebOR().getPageByName(page) != null) { + if (objRep.getWebSharedOR().getPageByName(page) != null) { + return objRep.getWebSharedOR().getPageByName(page).getObjectGroupByName(object).getObjects().get(0); + } else if (objRep.getWebOR().getPageByName(page) != null) { return objRep.getWebOR().getPageByName(page).getObjectGroupByName(object).getObjects().get(0); } return null; @@ -206,6 +223,8 @@ public ObjectGroup getMobileObjects(String page, String object) ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); if (objRep.getMobileOR().getPageByName(page) != null) { return objRep.getMobileOR().getPageByName(page).getObjectGroupByName(object); + } else if (objRep.getMobileSharedOR() != null && objRep.getMobileSharedOR().getPageByName(page) != null) { + return objRep.getMobileSharedOR().getPageByName(page).getObjectGroupByName(object); } return null; } @@ -214,6 +233,8 @@ public MobileORObject getMobileObject(String page, String object) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); if (objRep.getMobileOR().getPageByName(page) != null) { return objRep.getMobileOR().getPageByName(page).getObjectGroupByName(object).getObjects().get(0); + } else if (objRep.getMobileSharedOR() != null && objRep.getMobileSharedOR().getPageByName(page) != null) { + return objRep.getMobileSharedOR().getPageByName(page).getObjectGroupByName(object).getObjects().get(0); } return null; } @@ -413,7 +434,9 @@ public Map findElementsByRegex(String regexObject, String pa ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); WebORPage wPage = null; MobileORPage mPage = null; - if (objRep.getWebOR().getPageByName(page) != null) { + if (objRep.getWebSharedOR().getPageByName(page) != null) { + wPage = objRep.getWebSharedOR().getPageByName(page); + } else if (objRep.getWebOR().getPageByName(page) != null) { wPage = objRep.getWebOR().getPageByName(page); } else if (objRep.getMobileOR().getPageByName(page) != null) { mPage = objRep.getMobileOR().getPageByName(page); @@ -451,7 +474,9 @@ public List getObjectList(String page, String regexObject) { ObjectRepository objRep = Control.getCurrentProject().getObjectRepository(); WebORPage wPage = null; MobileORPage mPage = null; - if (objRep.getWebOR().getPageByName(page) != null) { + if (objRep.getWebSharedOR().getPageByName(page) != null) { + wPage = objRep.getWebSharedOR().getPageByName(page); + } else if (objRep.getWebOR().getPageByName(page) != null) { wPage = objRep.getWebOR().getPageByName(page); } else if (objRep.getMobileOR().getPageByName(page) != null) { mPage = objRep.getMobileOR().getPageByName(page); @@ -712,5 +737,4 @@ private int getMinKey(Map map, Object... object) { } return minKey; } - -} +} \ No newline at end of file diff --git a/Engine/src/main/java/com/ing/engine/drivers/PlaywrightDriverFactory.java b/Engine/src/main/java/com/ing/engine/drivers/PlaywrightDriverFactory.java index b67c18cc..23d3411a 100644 --- a/Engine/src/main/java/com/ing/engine/drivers/PlaywrightDriverFactory.java +++ b/Engine/src/main/java/com/ing/engine/drivers/PlaywrightDriverFactory.java @@ -144,8 +144,8 @@ private static LaunchOptions addLaunchOptions(LaunchOptions launchOptions, List< if (!value.trim().equals("")) launchOptions.setChromiumSandbox((boolean) getPropertyValueAsDesiredType(value)); } else if (key.toLowerCase().contains("setdevtools")) { - if (!value.trim().equals("")) - launchOptions.setDevtools((boolean) getPropertyValueAsDesiredType(value)); + if (!value.trim().equals("")) {} + // launchOptions.setDevtools((boolean) getPropertyValueAsDesiredType(value)); } else if (key.toLowerCase().contains("setdownloadspath")) { if (!value.trim().equals("")) launchOptions.setDownloadsPath(Paths.get((String) getPropertyValueAsDesiredType(value))); diff --git a/Engine/src/main/java/com/ing/engine/execution/data/DataAccess.java b/Engine/src/main/java/com/ing/engine/execution/data/DataAccess.java index c3b42436..708086b3 100644 --- a/Engine/src/main/java/com/ing/engine/execution/data/DataAccess.java +++ b/Engine/src/main/java/com/ing/engine/execution/data/DataAccess.java @@ -58,6 +58,37 @@ public static String getData(TestCaseRunner context, String sheet, String field, } return DataProcessor.resolve(val, context, field); } + + /** + * Get the test data for the next iteration from the test data sheet + * as specified sheet data that mathces the provided field, iteration and subiteration. + * + * @param context the context(environment,testcase,reusable and iteration) + * which the data + * @param sheet data sheet name + * @param field the field name + * @param iter the iteration + * @param subIter the sub iteration for the data + * @return - the test data + * @throws DataNotFoundException if the data not present + */ + public static String getNextData(TestCaseRunner context, String sheet, String field, String iter, String subIter) + throws DataNotFoundException { + String subIteration = (Integer.parseInt(subIter) + 1) + ""; + Object val; + TestDataModel env; + TestDataModel def = getDefModel(context, sheet); + if (validEnv(context)) { + env = getModel(context, sheet); + val = getData(context, env, def, field, iter, subIteration); + } else { + val = getData(context, def, field, iter, subIteration); + } + if (val == null) { + return null; + } + return DataProcessor.resolve(val, context, field); + } /** * if the environment in the context is valid, then update data to @@ -218,6 +249,7 @@ public static void putGlobalData(TestCaseRunner context, String gid, String fiel } else if (isNull(env)) { throw new GlobalDataNotFoundException(context, gid, field); } + env.load(); env.setValueAt(value, env.getRecordIndexByKey(gid), env.findColumn(field)); env.saveChanges(); } diff --git a/Engine/src/main/java/com/ing/engine/execution/data/DataAccessInternal.java b/Engine/src/main/java/com/ing/engine/execution/data/DataAccessInternal.java index dbfc39db..8195a05a 100644 --- a/Engine/src/main/java/com/ing/engine/execution/data/DataAccessInternal.java +++ b/Engine/src/main/java/com/ing/engine/execution/data/DataAccessInternal.java @@ -3,6 +3,7 @@ import com.ing.datalib.testdata.model.GlobalDataModel; import com.ing.datalib.testdata.model.TestDataModel; +import com.ing.engine.execution.exception.data.DataNotFoundException; import com.ing.engine.execution.exception.data.DataNotFoundException.Cause; import com.ing.engine.execution.exception.data.TestDataNotFoundException; import com.ing.engine.execution.run.TestCaseRunner; @@ -267,15 +268,17 @@ protected static Set getSubIter(TestCaseRunner context, TestDataModel de * @throws TestDataNotFoundException detailed exception with cause */ protected static void throwErrorWithCause(TestCaseRunner context, - String sheet, String field, String subIter) throws TestDataNotFoundException { + String sheet, String field, String subIter) throws TestDataNotFoundException, DataNotFoundException { Set iterSet = getIterations(context, sheet); if (isNull(iterSet) || !iterSet.contains(context.iteration())) { throw new TestDataNotFoundException(context, sheet, field, Cause.Iteration, context.iteration()); } else { Set subIterSet = getSubIterations(context, sheet); if (isNull(subIterSet) || !subIterSet.contains(subIter)) { - throw new TestDataNotFoundException(context, sheet, field, Cause.SubIteration, - String.format("%s:%s", context.iteration(), subIter)); + DataNotFoundException dnfe = new DataNotFoundException("Reached the end of data sheet."); + DataNotFoundException.CauseInfo causeInfo = dnfe.new CauseInfo(Cause.EndOfDataSheet, "Reached the end of data sheet."); + dnfe.cause = causeInfo; + throw dnfe; } else { throw new TestDataNotFoundException(context, sheet, field, Cause.Data, field); } diff --git a/Engine/src/main/java/com/ing/engine/execution/exception/data/DataNotFoundException.java b/Engine/src/main/java/com/ing/engine/execution/exception/data/DataNotFoundException.java index 5dbf1965..4c655bb8 100644 --- a/Engine/src/main/java/com/ing/engine/execution/exception/data/DataNotFoundException.java +++ b/Engine/src/main/java/com/ing/engine/execution/exception/data/DataNotFoundException.java @@ -18,7 +18,7 @@ public class DataNotFoundException extends RuntimeException { public String field; public CauseInfo cause; - protected DataNotFoundException(String name) { + public DataNotFoundException(String name) { super(name); } @@ -32,7 +32,7 @@ public static String getTemplate(Boolean isReusable) { } public enum Cause { - Data, Iteration, SubIteration + Data, Iteration, SubIteration, EndOfDataSheet } public class CauseInfo { @@ -52,6 +52,10 @@ public boolean isIter() { public boolean isSubIter() { return type == Cause.SubIteration; } + + public boolean isEndData() { + return type == Cause.EndOfDataSheet; + } } diff --git a/Engine/src/main/java/com/ing/engine/execution/run/TestCaseRunner.java b/Engine/src/main/java/com/ing/engine/execution/run/TestCaseRunner.java index e9cc94fd..f2df38b9 100644 --- a/Engine/src/main/java/com/ing/engine/execution/run/TestCaseRunner.java +++ b/Engine/src/main/java/com/ing/engine/execution/run/TestCaseRunner.java @@ -3,9 +3,12 @@ import com.ing.datalib.component.Project; import com.ing.datalib.component.TestCase; import com.ing.datalib.component.TestStep; +import com.ing.datalib.testdata.model.TestDataModel; import com.ing.engine.constants.SystemDefaults; import com.ing.engine.core.CommandControl; +import com.ing.engine.execution.data.DataAccess; import com.ing.engine.execution.data.DataIterator; +import com.ing.engine.execution.data.DataProcessor; import com.ing.engine.execution.data.Parameter; import com.ing.engine.execution.data.StepSet; import com.ing.engine.execution.exception.DriverClosedException; @@ -15,12 +18,15 @@ import com.ing.engine.execution.exception.AppiumDriverException; import com.ing.engine.execution.exception.UnCaughtException; import com.ing.engine.execution.exception.data.DataNotFoundException; +import com.ing.engine.execution.exception.data.DataNotFoundException.Cause; +import com.ing.engine.execution.exception.data.DataNotFoundException.CauseInfo; import com.ing.engine.execution.exception.data.GlobalDataNotFoundException; import com.ing.engine.execution.exception.data.TestDataNotFoundException; import com.ing.engine.execution.exception.element.ElementException; import com.ing.engine.reporting.TestCaseReport; import com.ing.engine.support.Status; import com.ing.engine.support.Step; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -38,8 +44,8 @@ public class TestCaseRunner { private static final Logger LOG = Logger.getLogger(TestCaseRunner.class.getName()); - private TestCase testcase; - private String scenario, testCase; + private TestCase testCase; + private String scenario, testCaseName; private final Stack stepStack = new Stack<>(); @@ -53,34 +59,35 @@ public class TestCaseRunner { private CommandControl control; private int currentSubIteration = -1; + private boolean breakSubIterationFlag = false; // public TestCaseRunner(ProjectRunner exe, String scenario, String testCase) { this(exe, null, null, new Parameter()); iterater = exe.getIterater(scenario, testCase); this.scenario = scenario; - this.testCase = testCase; + this.testCaseName = testCase; } - public TestCaseRunner(ProjectRunner exe, TestCase testcase) { - this(exe, null, testcase, new Parameter()); - iterater = exe.getIterater(testcase); + public TestCaseRunner(ProjectRunner exe, TestCase testCase) { + this(exe, null, testCase, new Parameter()); + iterater = exe.getIterater(testCase); } - public TestCaseRunner(TestCaseRunner parent, TestCase testcase) { - this(parent.exe, parent, testcase, new Parameter()); + public TestCaseRunner(TestCaseRunner parent, TestCase testCase) { + this(parent.exe, parent, testCase, new Parameter()); } - public TestCaseRunner(TestCaseRunner parent, TestCase testcase, + public TestCaseRunner(TestCaseRunner parent, TestCase testCase, Parameter parameter) { - this(parent.exe, parent, testcase, parameter); + this(parent.exe, parent, testCase, parameter); } - private TestCaseRunner(TestRunner exe, TestCaseRunner parent, TestCase testcase, + private TestCaseRunner(TestRunner exe, TestCaseRunner parent, TestCase testCase, Parameter parameter) { this.exe = exe; this.context = parent; - this.testcase = testcase; + this.testCase = testCase; this.parameter = parameter; } // @@ -109,18 +116,18 @@ public Project project() { } public String scenario() { - if (testcase != null) { - return testcase.getScenario().getName(); + if (testCase != null) { + return testCase.getScenario().getName(); } else { return scenario; } } public String testcase() { - if (testcase != null) { - return testcase.getName(); + if (testCase != null) { + return testCase.getName(); } else { - return testCase; + return testCaseName; } } @@ -185,13 +192,13 @@ public boolean isReusable() { } public TestCase getTestCase() { - return testcase; + return testCase; } // // private boolean canRunStep(int currStep) { - return currStep < testcase.getTestSteps().size() && canRun(); + return currStep < testCase.getTestSteps().size() && canRun(); } private boolean canRun() { @@ -210,6 +217,54 @@ private void checkForStartLoop(TestStep testStep, int currStep) { } } } + + /*** + * Check for end of loops to set breakSubIterationFlag to true. + * Applies to dynamic Start Param - End Param blocks. + * Execution is based on the occurence of the next data in the test sheet. + * This method flags that the last data in the data sheet has been reached. + * + * @param testStep + * @param currStep + * @return + * true - Reached the last subiteration within a Start Param - End Param pair + * false - Allows the loop to iterate one more time + */ + private boolean checkIfLastData(TestStep testStep, int currStep){ + //check the next step if it is the end of a loop + try { + // Read next data if step with data access + String data = ""; + String testInput = testStep.getInput(); + if(!testInput.startsWith("@") && DataProcessor.isInputPatternDataSheet(testInput)) { + String sheet = testStep.getInput().split(":")[0]; + String dataCol = testStep.getInput().split(":")[1]; + + data = DataAccess.getNextData(this, sheet, dataCol, parameter.getIteration()+"", (this.currentSubIteration)+""); + } else { + // Step does not access data sheet + return false; + } + if (data==null) { + // Execution has reached end of the test data sheet + this.breakSubIterationFlag = true; + } + + if (this.breakSubIterationFlag) { + // Delay breaking until last step of component + if (testCase.getTestSteps().size() <= currStep+1) { + return true; + } + } + } catch (Exception ex){ + // Exceptions are not applicable since this is a checker method. + System.out.println(ex.getMessage()); + } catch (Throwable ex) { + System.out.println(ex.getMessage()); + } + + return false; + } private int checkForEndLoop(TestStep testStep, int currStep) { if (Parameter.endParamRLoop(testStep.getCondition())) { @@ -225,7 +280,7 @@ private int checkForEndLoop(TestStep testStep, int currStep) { stepStack.peek().next(); } } - } + } return currStep; } @@ -264,15 +319,19 @@ public String getCurrentSubIteration() { // private void onError(Throwable ex) { - if (!ex.getMessage().contains("ActionException")) - reportOnError(getStepName(), ex.getMessage(), Status.DEBUG); - if (exe.isContinueOnError()) { - LOG.log(Level.SEVERE, ex.getMessage(), Optional.ofNullable(ex.getCause()).orElse(ex)); + if (ex.getMessage().contains("Reached the end of data sheet.")){ + // Do nothing } else { - if (ex instanceof RuntimeException) { - throw new TestFailedException(scenario(), testcase(), ex); - } - throw new UnCaughtException(ex); + if (!ex.getMessage().contains("ActionException")) + reportOnError(getStepName(), ex.getMessage(), Status.DEBUG); + if (exe.isContinueOnError()) { + LOG.log(Level.SEVERE, ex.getMessage(), Optional.ofNullable(ex.getCause()).orElse(ex)); + } else { + if (ex instanceof RuntimeException) { + throw new TestFailedException(scenario(), testcase(), ex); + } + throw new UnCaughtException(ex); + } } } @@ -305,6 +364,12 @@ private void onDataNotFoundException(DataNotFoundException ex) throws TestFailed System.out.println(ex.toString() + ", Breaking subIteration!!"); reportOnError("DataNotFound", ex.toString(), Status.DEBUG); LOG.log(Level.SEVERE, ex.getMessage(), ex); + } else if (ex.cause.isEndData()) { + /** + * its a dynamic sub-iteration(number of sub-iterations is not + * known in script) and at the end of data so break from it + */ + System.out.println("Breaking subIteration, End Of Input!!"); } else { /** * its a dynamic sub-iteration(number of sub-iterations is not @@ -330,17 +395,23 @@ public void run(CommandControl cc, int iter) throws DriverClosedException, TestFailedException { parameter.setIteration(iter); setControl(cc); - if (testcase != null) { - testcase.loadTableModel(); + if (testCase != null) { + testCase.loadTableModel(); /* * caution: breaking the loop will stop the iteration */ + boolean isLastData = false; for (int currStep = 0; canRunStep(currStep); currStep++) { - TestStep testStep = testcase.getTestSteps().get(currStep); + TestStep testStep = testCase.getTestSteps().get(currStep); + + int testCaseSize = testStep.getTestCase().getTestSteps().size(); + boolean isLastStep = (testCaseSize <= currStep+1); + if (!testStep.isCommented()) { checkForStartLoop(testStep, currStep); try { runStep(testStep); + isLastData = checkIfLastData(testStep, currStep); } catch (DriverClosedException | TestFailedException | UnCaughtException ex) { throw ex; } catch (DataNotFoundException ex) { @@ -356,7 +427,11 @@ public void run(CommandControl cc, int iter) /** * error while breaking the execution */ - throw new TestFailedException(scenario(), testcase(), ex); + if (ex.cause.isEndData()){ + throw new DataNotFoundException("End SubIteration"); + } else { + throw new TestFailedException(scenario(), testcase(), ex); + } } } catch (ForcedException | ElementException ex) { onRuntimeException(ex); @@ -365,7 +440,21 @@ public void run(CommandControl cc, int iter) } catch (Throwable ex) { onError(ex); } - currStep = checkForEndLoop(testStep, currStep); + + if (isLastStep && this.breakSubIterationFlag){ + DataNotFoundException dnfe = new DataNotFoundException("Reached the end of data sheet."); + CauseInfo causeInfo = dnfe.new CauseInfo(Cause.EndOfDataSheet, "Reached the end of data sheet."); + dnfe.cause = causeInfo; + this.breakSubIterationFlag = false; + if (this.stepStack.empty()){ + // Normal flow + currStep = checkForEndLoop(testStep, currStep); + continue; + } + throw dnfe; + } else { + currStep = checkForEndLoop(testStep, currStep); + } } } } @@ -382,19 +471,19 @@ private int breakSubIteration() { return -1; } - public void run() throws DataNotFoundException, DriverClosedException { + public void run() throws DriverClosedException { run(createControl(this), parameter.getIteration()); } - public void run(CommandControl cc) throws DataNotFoundException, DriverClosedException { + public void run(CommandControl cc) throws DriverClosedException { run(cc, parameter.getIteration()); } - private void runStep(TestStep testStep) throws DataNotFoundException, DriverClosedException, Throwable { - new TestStepRunner(testStep, resolveParam()).run(this); - } + private void runStep(TestStep testStep) throws DriverClosedException, Throwable { + new TestStepRunner(testStep, resolveParam()).run(this); + } - public void runStep(Step step, int subIter) throws DataNotFoundException, DriverClosedException { + public void runStep(Step step, int subIter) throws DriverClosedException { Parameter param = new Parameter(); param.setIteration(this.parameter.getIteration()); param.setSubIteration(subIter); @@ -452,7 +541,7 @@ public DataIterator getRootIterator() { // @Override public String toString() { - return String.format("[%s:%s] [%s] [%s]", testcase.getScenario(), testcase, + return String.format("[%s:%s] [%s] [%s]", testCase.getScenario(), testCase, parameter, getRoot().iterater); } diff --git a/Engine/src/main/java/com/ing/engine/reporting/impl/azure/AzureTestCaseHandler.java b/Engine/src/main/java/com/ing/engine/reporting/impl/azure/AzureTestCaseHandler.java index 8e1cbfe8..eed1e0e9 100644 --- a/Engine/src/main/java/com/ing/engine/reporting/impl/azure/AzureTestCaseHandler.java +++ b/Engine/src/main/java/com/ing/engine/reporting/impl/azure/AzureTestCaseHandler.java @@ -228,8 +228,8 @@ public void startComponent(String component, String desc) { public void endComponent(String string) { reusable.put(RDS.Step.END_TIME, DateTimeUtils.DateTimeNow()); if (reusable.get(TestCase.STATUS).equals("")) { - /* status not is updated set it to FAIL */ - reusable.put(TestCase.STATUS, "FAIL"); + /* status not is updated set it to PASS */ + reusable.put(TestCase.STATUS, "PASS"); } /* diff --git a/Engine/src/main/java/com/ing/engine/reporting/impl/excel/ExcelTestCaseHandler.java b/Engine/src/main/java/com/ing/engine/reporting/impl/excel/ExcelTestCaseHandler.java index cf7a680c..ecc1b2cd 100644 --- a/Engine/src/main/java/com/ing/engine/reporting/impl/excel/ExcelTestCaseHandler.java +++ b/Engine/src/main/java/com/ing/engine/reporting/impl/excel/ExcelTestCaseHandler.java @@ -149,9 +149,9 @@ public void endComponent(String string) { reusable.put(RDS.Step.END_TIME, DateTimeUtils.DateTimeNow()); if (reusable.get(TestCase.STATUS).equals("")) { /* - * status not is updated set it to FAIL + * status not is updated set it to PASS */ - reusable.put(TestCase.STATUS, "FAIL"); + reusable.put(TestCase.STATUS, "PASS"); } /* * remove the reusable from the stack then fall back to iteration diff --git a/Engine/src/main/java/com/ing/engine/reporting/impl/extent/ExtentTestCaseHandler.java b/Engine/src/main/java/com/ing/engine/reporting/impl/extent/ExtentTestCaseHandler.java index 2ba52205..b56e0ac1 100644 --- a/Engine/src/main/java/com/ing/engine/reporting/impl/extent/ExtentTestCaseHandler.java +++ b/Engine/src/main/java/com/ing/engine/reporting/impl/extent/ExtentTestCaseHandler.java @@ -224,8 +224,8 @@ public void startComponent(String component, String desc) { public void endComponent(String string) { reusable.put(RDS.Step.END_TIME, DateTimeUtils.DateTimeNow()); if (reusable.get(TestCase.STATUS).equals("")) { - /* status not is updated set it to FAIL */ - reusable.put(TestCase.STATUS, "FAIL"); + /* status not is updated set it to PASS */ + reusable.put(TestCase.STATUS, "PASS"); } this.test.info(MarkupHelper.createLabel("Reusable Component : [" + this.CurrentComponent + "] ends here", ExtentColor.GREY)); /* diff --git a/Engine/src/main/java/com/ing/engine/reporting/impl/html/HtmlSummaryHandler.java b/Engine/src/main/java/com/ing/engine/reporting/impl/html/HtmlSummaryHandler.java index d6a700bf..075f4a9c 100644 --- a/Engine/src/main/java/com/ing/engine/reporting/impl/html/HtmlSummaryHandler.java +++ b/Engine/src/main/java/com/ing/engine/reporting/impl/html/HtmlSummaryHandler.java @@ -32,8 +32,8 @@ import org.json.simple.JSONObject; /** - * - * + * Handles the creation and management of HTML summary reports for test executions. + * Supports BDD, performance, and history reporting, and integrates with CucumberReport. */ @SuppressWarnings("rawtypes") public class HtmlSummaryHandler extends SummaryHandler implements PrimaryHandler { @@ -49,15 +49,25 @@ public class HtmlSummaryHandler extends SummaryHandler implements PrimaryHandler DateTimeUtils RunTime; public PerformanceReport perf; + /** + * Constructs a new HtmlSummaryHandler for the given SummaryReport. + * Initializes performance reporting if enabled. + * @param report The summary report instance + */ public HtmlSummaryHandler(SummaryReport report) { super(report); if (Control.exe.getExecSettings().getRunSettings().isPerformanceLogEnabled()) { perf = new PerformanceReport(); } createReportIfNotExists(FilePath.getResultsPath()); - } + /** + * Adds HAR (HTTP Archive) data to the performance report. + * @param h HAR log + * @param report Test case report + * @param pageName Name of the page + */ @Override public void addHar(Har h, TestCaseReport report, String pageName) { if (perf != null) { @@ -65,6 +75,10 @@ public void addHar(Har h, TestCaseReport report, String pageNam } } + /** + * Creates the report directory and copies media resources if not already present. + * @param path Path to the results directory + */ private void createReportIfNotExists(String path) { File file = new File(path + File.separator + "media"); if (!file.exists()) { @@ -119,7 +133,14 @@ public synchronized void createReport(String runTime, int size) { */ @SuppressWarnings("unchecked") @Override - public synchronized void updateTestCaseResults(RunContext runContext, TestCaseReport report, Status state, + /** + * Updates the result of each test case execution. + * @param runContext Run context + * @param report Test case report + * @param state Test case status + * @param executionTime Execution time + */ + public synchronized void updateTestCaseResults(RunContext runContext, TestCaseReport report, Status state, String executionTime) { executions.add(report.getData()); @@ -166,7 +187,7 @@ public synchronized void updateResults() { } /** - * finalize the summary report creation + * Finalizes the summary report creation. */ @Override public synchronized void finalizeReport() { @@ -191,6 +212,10 @@ public synchronized void finalizeReport() { launchResultSummary(); } + /** + * Copies summary, detailed, and performance HTML files to the results directory. + * @throws IOException if file operations fail + */ private void createHtmls() throws IOException { FileUtils.copyFileToDirectory(new File(FilePath.getSummaryHTMLPath()), new File(FilePath.getCurrentResultsPath())); @@ -207,6 +232,10 @@ private void createHtmls() throws IOException { } } + /** + * Creates standalone HTML reports and replaces media paths. + * @throws IOException if file operations fail + */ private void createStandaloneHtmls() throws IOException { createReportIfNotExists(FilePath.getCurrentResultsPath()); @@ -228,12 +257,20 @@ private void createStandaloneHtmls() throws IOException { } } + /** + * Generates the BDD report if enabled in run settings. + * @throws Exception if report generation fails + */ private void createBddReport() throws Exception { if (Control.exe.getExecSettings().getRunSettings().isBddReportEnabled()) { CucumberReport.get().ifPresent(this::createCucumberBddReport); } } + /** + * Generates the Cucumber BDD report using the provided reporter. + * @param reporter CucumberReport instance + */ private void createCucumberBddReport(CucumberReport reporter) { try { System.out.print("Generating BDD-Report..."); @@ -245,6 +282,9 @@ private void createCucumberBddReport(CucumberReport reporter) { } } + /** + * Copies the current results to the latest results location. + */ private synchronized void createLatest() { try { File latestResult = new File(FilePath.getLatestResultsLocation()); @@ -258,6 +298,10 @@ private synchronized void createLatest() { } } + /** + * Checks if Extent reporting is enabled for the current project and test run. + * @return true if enabled, false otherwise + */ public boolean isExtentEnabled() { if (!RunManager.getGlobalSettings().isTestRun()) { return Control.getCurrentProject().getProjectSettings() @@ -268,7 +312,7 @@ public boolean isExtentEnabled() { } /** - * open the summary report when execution is finished + * Opens the summary report in the desktop browser if allowed and Extent is not enabled. */ public synchronized void launchResultSummary() { if (!isExtentEnabled()) { @@ -279,7 +323,7 @@ public synchronized void launchResultSummary() { } /** - * updates the history of execution report + * Updates the history of execution reports by appending the current run data. */ @SuppressWarnings("unchecked") private void updateReportHistoryData() { @@ -308,8 +352,8 @@ private void updateReportHistoryData() { } /** - * - * @return the test set result details + * Returns the test set result details as a map. + * @return Map of report data */ private Map getReportData() { Map reportMap = new HashMap<>(); @@ -322,6 +366,9 @@ private Map getReportData() { return reportMap; } + /** + * Prints the summary of the test execution to the console. + */ private void printReport() { System.out.println("-----------------------------------------------------"); print("ExecutionDate", FilePath.getDate() + " " + FilePath.getTime()); @@ -333,21 +380,25 @@ private void printReport() { System.out.println("-----------------------------------------------------"); } + /** + * Prints a key-value pair to the console in formatted style. + * @param key Key string + * @param val Value object + */ private void print(String key, Object val) { System.out.println(String.format("%-20s : %s", key, val)); } /** - * update the result when any error in execution - * - * @param testScenario - * @param testCase - * @param Iteration - * @param testDescription - * @param executionTime - * @param fileName - * @param state - * @param Browser + * Updates the result when any error occurs in execution. + * @param testScenario Scenario name + * @param testCase Test case name + * @param Iteration Iteration info + * @param testDescription Description + * @param executionTime Execution time + * @param fileName File name + * @param state Test case status + * @param Browser Browser info */ @Override public void updateTestCaseResults(String testScenario, String testCase, String Iteration, String testDescription, @@ -361,16 +412,28 @@ public void updateTestCaseResults(String testScenario, String testCase, String I } } + /** + * Returns the test set data JSON object. + * @return testSetData JSON object + */ @Override public Object getData() { return testSetData; } + /** + * Returns the summary HTML file. + * @return File object for summary HTML + */ @Override public File getFile() { return new File(FilePath.getCurrentSummaryHTMLPath()); } + /** + * Returns the current status of the test run. + * @return Status enum (PASS or FAIL) + */ @Override public Status getCurrentStatus() { if (FailedTestCases > 0 || PassedTestCases == 0) { diff --git a/Engine/src/main/java/com/ing/engine/reporting/impl/html/HtmlTestCaseHandler.java b/Engine/src/main/java/com/ing/engine/reporting/impl/html/HtmlTestCaseHandler.java index 358e2c7e..01b1d2b6 100644 --- a/Engine/src/main/java/com/ing/engine/reporting/impl/html/HtmlTestCaseHandler.java +++ b/Engine/src/main/java/com/ing/engine/reporting/impl/html/HtmlTestCaseHandler.java @@ -177,9 +177,9 @@ public void endComponent(String string) { reusable.put(RDS.Step.END_TIME, DateTimeUtils.DateTimeNow()); if (reusable.get(TestCase.STATUS).equals("")) { /* - * status not is updated set it to FAIL + * status not is updated set it to PASS */ - reusable.put(TestCase.STATUS, "FAIL"); + reusable.put(TestCase.STATUS, "PASS"); } /* * remove the reusable from the stack then fall back to iteration diff --git a/Engine/src/main/java/com/ing/engine/reporting/impl/html/bdd/CucumberReport.java b/Engine/src/main/java/com/ing/engine/reporting/impl/html/bdd/CucumberReport.java index bfe646cb..3f115235 100644 --- a/Engine/src/main/java/com/ing/engine/reporting/impl/html/bdd/CucumberReport.java +++ b/Engine/src/main/java/com/ing/engine/reporting/impl/html/bdd/CucumberReport.java @@ -28,12 +28,29 @@ import static java.util.stream.Collectors.toList; import java.util.stream.Stream; +/** + * CucumberReport is responsible for generating Cucumber-compatible JSON and HTML reports + * from test execution data. It parses report data, groups executions by scenario, and + * transforms them into Cucumber FeatureReport objects. It also provides methods to save + * reports to files and convert between formats. + * + *

    Usage:

    + *
      + *
    • Use {@link #toCucumberReport(String, File)} to generate a Cucumber JSON report from a JSON string.
    • + *
    • Use {@link #toCucumberReport(File, File)} to generate a Cucumber JSON report from a file.
    • + *
    • Use {@link #get()} to obtain the singleton instance.
    • + *
    + */ public class CucumberReport { private static final CucumberReport INS = new CucumberReport(); private File bddReport; + /** + * Returns the singleton instance of CucumberReport wrapped in an Optional. + * @return Optional containing the singleton CucumberReport instance + */ public static Optional get() { return Optional.of(INS); } @@ -45,7 +62,6 @@ public static Optional get() { * @param project project name */ private void toCucumberHtmlReport(File cucumberJson, String project) { - //TO-DO: add your html implementation } @@ -84,6 +100,11 @@ public void toCucumberReport(File report, File bddReport) throws Exception { toCucumberReport(parseReport(report), bddReport); } + /** + * Saves the Cucumber JSON report string to a file. + * @param res Destination file + * @param cucumberReport Cucumber JSON report string + */ private void saveAs(File res, String cucumberReport) { try (PrintWriter pw = new PrintWriter(new FileWriter(res));) { pw.print(cucumberReport); @@ -92,38 +113,88 @@ private void saveAs(File res, String cucumberReport) { } } + /** + * Converts parsed report data to a Cucumber JSON string. + * @param reportData Parsed report data + * @return Cucumber JSON string + * @throws Exception if conversion fails + */ private String convert(Report reportData) throws Exception { return gson().toJson(toCucumberReport(reportData)); } + /** + * Returns a Gson instance with pretty printing enabled. + * @return Gson instance + */ private static Gson gson() { return new com.google.gson.GsonBuilder().setPrettyPrinting().create(); } + /** + * Parses a report file into a Report object. + * @param jsonFile Source report file + * @return Parsed Report object + * @throws Exception if parsing fails + */ private Report parseReport(File jsonFile) throws Exception { return gson().fromJson(new FileReader(jsonFile), Report.class); } + /** + * Parses a JSON string into a Report object. + * @param report JSON string + * @return Parsed Report object + * @throws Exception if parsing fails + */ private Report parseReport(String report) throws Exception { return gson().fromJson(report, Report.class); } + /** + * Groups executions by scenario and converts them to FeatureReport objects. + * @param reportData Parsed report data + * @return List of FeatureReport objects + */ private List toCucumberReport(Report reportData) { return reportData.getEXECUTIONS().stream().collect(groupingBy(Report.Execution::getScenarioName)) .entrySet().stream().map(To::FeatureReport).collect(toList()); } + /** + * Static helper class for transforming report data into FeatureReport and related objects. + */ private static class To { + /** + * Converts a scenario entry to a FeatureReport object. + * @param story Entry containing scenario name and executions + * @return FeatureReport object + */ private static FeatureReport FeatureReport(Entry> story) { - return new FeatureReport(story.getKey(), story.getKey(), - project().findScenario(story.getKey()).get().getDesc(), - String.format("//TestPlan/%s.feature", story.getKey()), - getLine(project().findScenario(story.getKey()).get().getAttributes(), "feature.line"), - story.getValue().stream().map(To::Element).collect(toList()), - getTags(story.getKey())); - } - + // Safely handle missing scenario + Optional scenarioOpt = project().findScenario(story.getKey()); + String desc = scenarioOpt.map(Meta::getDesc).orElse("No description available"); + int featureLine = -1; + if (scenarioOpt.isPresent()) { + featureLine = getLine(scenarioOpt.get().getAttributes(), "feature.line"); + } + return new FeatureReport( + story.getKey(), + story.getKey(), + desc, + String.format("//TestPlan/%s.feature", story.getKey()), + featureLine, + story.getValue().stream().map(To::Element).collect(toList()), + getTags(story.getKey()) + ); + } + + /** + * Converts an execution to a FeatureReport.Element object. + * @param exe Report.Execution object + * @return FeatureReport.Element object + */ private static FeatureReport.Element Element(Report.Execution exe) { return new FeatureReport.Element(getKeyword(exe), getName(exe.description, exe.testcaseName), exe.description, @@ -131,41 +202,88 @@ private static FeatureReport.Element Element(Report.Execution exe) { getSteps(exe), getTags(exe.testcaseName, exe.scenarioName)); } + /** + * Retrieves the keyword for a scenario step. + * @param exe Report.Execution object + * @return Step keyword + */ private static String getKeyword(Report.Execution exe) { return findTC(exe.testcaseName, exe.scenarioName) .getAttributes().find("feature.children.keyword").orElse(Attribute.create("#", "Scenario")) .getValue(); } + /** + * Retrieves the line number for a feature or step. + * @param attrs Attributes object + * @param key Attribute key + * @return Line number + */ private static int getLine(Attributes attrs, String key) { return Integer.valueOf(attrs.find(key).orElse(Attribute.create("", "-1")).getValue()); } + /** + * Retrieves reusable steps from an execution. + * @param exe Report.Execution object + * @return List of FeatureReport.Step objects + */ private static List getSteps(Report.Execution exe) { return exe.getIterData().get(0).getSteps().stream() .filter(By::Reusable).map(To::Step).collect(toList()); } + /** + * Retrieves tags for a scenario. + * @param scn Scenario name + * @return List of FeatureReport.Tag objects + */ private static List getTags(String scn) { return findScn(scn).getTags().stream().map(To::Tag).collect(toList()); } + /** + * Finds scenario metadata by name. + * @param scn Scenario name + * @return Meta object for the scenario + */ private static Meta findScn(String scn) { return project().findScenario(scn).orElse(Meta.scenario()); } + /** + * Retrieves tags for a test case and scenario. + * @param tc Test case name + * @param scn Scenario name + * @return List of FeatureReport.Tag objects + */ private static List getTags(String tc, String scn) { return findTC(tc, scn).getTags().stream().map(To::Tag).collect(toList()); } + /** + * Finds test case data by test case and scenario name. + * @param tc Test case name + * @param scn Scenario name + * @return DataItem object for the test case + */ private static DataItem findTC(String tc, String scn) { return project().getData().find(tc, scn).orElse(DataItem.create(tc)); } + /** + * Retrieves the current project info. + * @return ProjectInfo object + */ private static ProjectInfo project() { return Control.exe.getProject().getInfo(); } + /** + * Converts a Report.Step to a FeatureReport.Step object. + * @param r Report.Step object + * @return FeatureReport.Step object + */ private static FeatureReport.Step Step(Report.Step r) { return new FeatureReport.Step(getName(r.description, RC(r.name)[1]), Result(r), @@ -174,12 +292,22 @@ private static FeatureReport.Step Step(Report.Step r) { .addEmbeddings(getDesc(r.data)).addEmbeddings(getImages(r.data)); } + /** + * Converts description data to text embeddings for Cucumber report. + * @param data Step data object + * @return List of text FeatureReport.Embedding objects + */ private static List getDesc(Object data) { return dataStream(data).map(Report.Data::getDescription).map(To::Pure) .map(String::getBytes).map(To::Base64).map(To::TxtEmbedding) .collect(toList()); } + /** + * Converts image data to image embeddings for Cucumber report. + * @param data Step data object + * @return List of image FeatureReport.Embedding objects + */ private static List getImages(Object data) { return dataStream(data).filter(By::Image) .map(Report.Data::getLink).map(To::File).map(To::Byte) @@ -187,10 +315,20 @@ private static List getImages(Object data) { .collect(toList()); } + /** + * Flattens a list of step data objects into a stream of Report.Data. + * @param o List of step data objects + * @return Stream of Report.Data + */ private static Stream dataStream(Object o) { return ((List) o).stream().flatMap(To::Data); } + /** + * Converts a step data object to a stream of Report.Data. + * @param o Step data object + * @return Stream of Report.Data + */ private static Stream Data(Object o) { Object data = ((Map) o).get("data"); if (data instanceof List) { @@ -200,34 +338,74 @@ private static Stream Data(Object o) { } } + /** + * Converts a Tag object to a FeatureReport.Tag. + * @param t Tag object + * @return FeatureReport.Tag object + */ private static FeatureReport.Tag Tag(Tag t) { return new FeatureReport.Tag(t.getValue()); } + /** + * Converts a Report.Step to a FeatureReport.Result. + * @param s Report.Step object + * @return FeatureReport.Result object + */ private static FeatureReport.Result Result(Report.Step s) { return new FeatureReport.Result(milliToNano() * getDuration(s), Status(s.getStatus())); } + /** + * Creates a text embedding from a string. + * @param s Text string + * @return FeatureReport.Embedding object + */ public static FeatureReport.Embedding TxtEmbedding(String s) { return new FeatureReport.Embedding("text/html", s); } + /** + * Creates an image embedding from a string (base64 encoded image). + * @param s Base64 encoded image string + * @return FeatureReport.Embedding object + */ public static FeatureReport.Embedding PngEmbedding(String s) { return new FeatureReport.Embedding("image/jpeg", s); } + /** + * Splits a string by the first colon. + * @param s Input string + * @return Array of two strings + */ public static String[] RC(String s) { return s.split(":", 2); } + /** + * Cleans a string for embedding, removing special tags. + * @param s Input string + * @return Cleaned string + */ public static String Pure(String s) { return Objects.toString(s, "").replace("#CTAG", ""); } + /** + * Encodes a byte array to a Base64 string. + * @param d Byte array + * @return Base64 encoded string + */ public static String Base64(byte[] d) { return java.util.Base64.getEncoder().encodeToString(d); } + /** + * Reads a file and returns its bytes. + * @param f File object + * @return Byte array of file contents + */ public static byte[] Byte(File f) { try { return Files.readAllBytes(f.toPath()); @@ -236,22 +414,47 @@ public static byte[] Byte(File f) { } } + /** + * Resolves a file path relative to the report directory. + * @param f File name + * @return File object + */ private static File File(String f) { return new File(INS.bddReport.getParentFile(), f); } + /** + * Converts a step status string to Cucumber status. + * @param status Step status string + * @return "passed" or "failed" + */ private static String Status(String status) { return Objects.nonNull(status) && status.toLowerCase().startsWith("pass") ? "passed" : "failed"; } + /** + * Determines the step name, preferring description if available. + * @param desc Step description + * @param name Step name + * @return Step name or description + */ private static String getName(String desc, String name) { return Objects.nonNull(desc) && !desc.isEmpty() && !desc.equals("Test Run") ? desc : name; } + /** + * Returns the conversion factor from milliseconds to nanoseconds. + * @return 1000000 + */ private static int milliToNano() { return 1000000; } + /** + * Calculates the duration of a step in milliseconds. + * @param s Report.Step object + * @return Duration in milliseconds + */ private static long getDuration(Report.Step s) { try { if (s.startTime != null && s.endTime != null) { @@ -264,6 +467,12 @@ private static long getDuration(Report.Step s) { } } + /** + * Calculates the duration of a step from its data. + * @param step Report.Step object + * @return Duration in milliseconds + * @throws Exception if parsing fails + */ @SuppressWarnings("unchecked") private static long calcDuration(Report.Step step) throws Exception { List> data = (List>) step.data; @@ -275,23 +484,48 @@ private static long calcDuration(Report.Step step) throws Exception { } } + /** + * Extracts the timestamp from a step data map. + * @param step Step data map + * @return Timestamp in milliseconds + * @throws ParseException if parsing fails + */ private static long getTime(Map step) throws ParseException { return parseTime(((Map) step.get("data")) .get(Report.Step.StepInfo.tStamp.name())); } + /** + * Parses a timestamp string to milliseconds. + * @param val Timestamp string + * @return Time in milliseconds + * @throws ParseException if parsing fails + */ private static long parseTime(String val) throws ParseException { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.sss").parse(val).getTime(); } } + /** + * Utility class for filtering and identifying reusable steps and image data in report processing. + */ private static class By { + /** + * Checks if a step is marked as reusable. + * @param s Report.Step object + * @return true if step type is "reusable", false otherwise + */ private static boolean Reusable(Report.Step s) { return "reusable".equals(s.type); } + /** + * Checks if a data object contains an image link. + * @param d Report.Data object + * @return true if link is not null, false otherwise + */ private static boolean Image(Report.Data d) { return d.link != null; } diff --git a/Engine/src/main/java/com/ing/engine/reporting/impl/rp/RPTestCaseHandler.java b/Engine/src/main/java/com/ing/engine/reporting/impl/rp/RPTestCaseHandler.java index 3a47f205..09a47b3f 100644 --- a/Engine/src/main/java/com/ing/engine/reporting/impl/rp/RPTestCaseHandler.java +++ b/Engine/src/main/java/com/ing/engine/reporting/impl/rp/RPTestCaseHandler.java @@ -222,8 +222,8 @@ public void startComponent(String component, String desc) { public void endComponent(String string) { reusable.put(RDS.Step.END_TIME, DateTimeUtils.DateTimeNow()); if (reusable.get(TestCase.STATUS).equals("")) { - /* status not is updated set it to FAIL */ - reusable.put(TestCase.STATUS, "FAIL"); + /* status not is updated set it to PASS */ + reusable.put(TestCase.STATUS, "PASS"); } /* remove the reusable from the stack then fall back to iteration diff --git a/IDE/pom.xml b/IDE/pom.xml index 7950cb78..46b55ef3 100644 --- a/IDE/pom.xml +++ b/IDE/pom.xml @@ -4,7 +4,7 @@ com.ing ingenious-playwright - 2.3.1 + 2.4 ingenious-ide jar @@ -207,7 +207,7 @@ ${javafx.version} ${mac.version} - + @@ -228,6 +228,7 @@ org.apache.maven.plugins maven-dependency-plugin + 3.9.0 install diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/AppActionListener.java b/IDE/src/main/java/com/ing/ide/main/mainui/AppActionListener.java index 6c7a85fc..410c6fcc 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/AppActionListener.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/AppActionListener.java @@ -25,6 +25,9 @@ import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Comparator; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JToggleButton; @@ -220,22 +223,23 @@ public void actionPerformed(ActionEvent ae) { PlaywrightRecordingParser playwrightRecordingParser = new PlaywrightRecordingParser(sMainFrame); String ProjectLocation = sMainFrame.getProject().getLocation(); sMainFrame.loadProject(ProjectLocation); - File originalFile = new File(ProjectLocation + File.separator + "Recording" + File.separator + "recording.txt"); - File renamedFile = new File(ProjectLocation + File.separator + "Recording" + File.separator + ScenarioName + ".txt"); - - if (originalFile.exists()) { - boolean success = originalFile.renameTo(renamedFile); - if (success) { - Notification.show("Recorded steps saved as " + renamedFile.getAbsolutePath()); - } else { - Notification.show("Failed to save recorded steps."); + File recordingDir = new File(ProjectLocation + File.separator + "Recording"); + File[] recordingFiles = recordingDir.listFiles((dir, name) -> name.startsWith("recording_") && name.endsWith(".txt")); + if (recordingFiles != null && recordingFiles.length > 0) { + Arrays.sort(recordingFiles, Comparator.comparingLong(File::lastModified).reversed()); + File latestFile = recordingFiles[0]; + File duplicateFile = new File(recordingDir, ScenarioName + ".txt"); + try { + Files.copy(latestFile.toPath(), duplicateFile.toPath()); + } catch (IOException e) { + e.printStackTrace(); } + + playwrightRecordingParser.playwrightParser(duplicateFile); + sMainFrame.loadProject(ProjectLocation); } else { - Notification.show("Original file does not exist."); - } - - playwrightRecordingParser.playwrightParser(renamedFile); - sMainFrame.loadProject(ProjectLocation); + System.out.println("No recording file found."); + } } catch (Exception ex) { Logger.getLogger(AppActionListener.class.getName()).log(Level.SEVERE, null, ex); } diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/AppMainFrame.java b/IDE/src/main/java/com/ing/ide/main/mainui/AppMainFrame.java index efb991d7..84244e2e 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/AppMainFrame.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/AppMainFrame.java @@ -89,7 +89,7 @@ public class AppMainFrame extends JFrame { private final LoaderScreen loader; private QUIT_TYPE quitType = QUIT_TYPE.NORMAL; - + private enum QUIT_TYPE { NORMAL, FORCE, diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectPopupMenu.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectPopupMenu.java index 661cfeb8..189c3613 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectPopupMenu.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectPopupMenu.java @@ -17,8 +17,19 @@ import javax.swing.TransferHandler; /** + * Context (right-click) popup menu for Object Repository (OR) tree nodes in the Test Design UI. + *

    + * This menu provides OR maintenance actions such as adding/renaming/deleting pages, object groups, + * and objects, plus utilities like removing unused objects, copying items to Shared OR, opening page dumps, + * and running impact analysis. It also includes standard clipboard operations (cut/copy/paste) using + * Swing transfer actions. + *

    * - * + *

    + * The available actions are dynamically enabled/disabled based on the type of the current selection + * (root, page, group, or object) and whether the selected item belongs to a Shared repository + * (e.g., disabling actions that should not modify shared content). + *

    */ public class ObjectPopupMenu extends JPopupMenu { @@ -31,6 +42,7 @@ public class ObjectPopupMenu extends JPopupMenu { private JMenuItem renameObject; private JMenuItem deleteObject; private JMenuItem removeUnusedObject; + private JMenuItem copyToShared; private JMenuItem openPageDump; @@ -61,8 +73,10 @@ private void init() { add(deleteObject = create("Delete Object", Keystroke.DELETE)); add(removeUnusedObject = create("Remove Unused Object",Keystroke.REMOVE_OBJECT)); addSeparator(); + copyToShared = create("Copy to Shared", null); + add(copyToShared); + - add(openPageDump = create("Open Page Dump", null)); add(impactAnalysis = create("Get Impacted TestCases", null)); @@ -75,8 +89,11 @@ private void init() { } public void togglePopupMenu(Object selected) { + copyToShared.setEnabled(false); + if (selected instanceof ORRootInf) { forRoot(); + return; } else if (selected instanceof ORPageInf) { forPage(); } else if (selected instanceof ObjectGroup) { @@ -84,6 +101,8 @@ public void togglePopupMenu(Object selected) { } else if (selected instanceof ORObjectInf) { forObject(); } + copyToShared.setEnabled(!isSharedSelection(selected)); + removeUnusedObject.setEnabled(!isSharedSelection(selected)); } private void forPage() { @@ -205,4 +224,23 @@ private void setCCP() { add(paste); } -} + private boolean isSharedSelection(Object selected) { + ORPageInf page = null; + if (selected instanceof ORPageInf) { + page = (ORPageInf) selected; + } else if (selected instanceof ORObjectInf) { + page = ((ORObjectInf) selected).getPage(); + } else if (selected instanceof ObjectGroup) { + page = ((ObjectGroup) selected).getParent(); + } + if (page != null && page.getRoot() instanceof com.ing.datalib.or.web.WebOR) { + com.ing.datalib.or.web.WebOR root = (com.ing.datalib.or.web.WebOR) page.getRoot(); + return root.isShared(); + } + if (page != null && page.getRoot() instanceof com.ing.datalib.or.mobile.MobileOR) { + com.ing.datalib.or.mobile.MobileOR root = (com.ing.datalib.or.mobile.MobileOR) page.getRoot(); + return root.isShared(); + } + return false; + } +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectRepDnD.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectRepDnD.java index ffb8a69a..e2ffb5b7 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectRepDnD.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectRepDnD.java @@ -8,8 +8,17 @@ import java.util.List; /** + * Helper model for Object Repository drag-and-drop (DnD) operations in the Test Design UI. + *

    + * {@code ObjectRepDnD} captures the type of items being dragged (pages, object groups, or objects), + * stores both the original components and their encoded string representations, and provides + * convenience methods to extract page/object identifiers from the encoded values. + *

    * - * + *

    + * Drag payload values are encoded using a fixed separator and include page scope information + * (e.g., Project vs Shared) to preserve context across DnD operations. + *

    */ public class ObjectRepDnD { @@ -18,6 +27,7 @@ public class ObjectRepDnD { Boolean isObject = false; List values = new ArrayList<>(); List components = new ArrayList<>(); + private static final String SEP = "###"; public Boolean isPage() { return isPage; @@ -42,7 +52,7 @@ public List getComponents() { public ObjectRepDnD withPages(List pages) { isPage = true; for (ORPageInf page : pages) { - values.add(page.getName()); + values.add(pageToken(page)); components.add(page); } return this; @@ -51,10 +61,8 @@ public ObjectRepDnD withPages(List pages) { public ObjectRepDnD withObjectGroups(List groups) { isGroup = true; for (ObjectGroup group : groups) { - values.add( - group.getName() - + "###" - + group.getParent().getName()); + ORPageInf parent = (ORPageInf) group.getParent(); + values.add(group.getName() + SEP + pageToken(parent)); components.add(group); } return this; @@ -63,13 +71,8 @@ public ObjectRepDnD withObjectGroups(List groups) { public ObjectRepDnD withObjects(List objects) { isObject = true; for (ORObjectInf object : objects) { - values.add( - object.getName() - + "###" - + object.getParent().toString() - + "###" - + object.getPage().getName() - ); + ORPageInf page = object.getPage(); + values.add(object.getName() + SEP + object.getParent().toString() + SEP + pageToken(page)); components.add(object); } return this; @@ -80,10 +83,10 @@ public String getPageName(String value) { return value; } if (isGroup()) { - return value.split("###")[1]; + return value.split(SEP)[1]; } if (isObject()) { - return value.split("###")[2]; + return value.split(SEP)[2]; } return null; } @@ -97,4 +100,22 @@ public String getObjectName(String value) { } return null; } -} + + private String scopeOf(ORPageInf page) { + try { + var m = page.getClass().getMethod("getSource"); + Object src = m.invoke(page); + if (src != null && src.toString().equalsIgnoreCase("SHARED")) return "SHARED"; + } catch (Exception ignore) { } + return "PROJECT"; + } + + private String pageToken(ORPageInf page) { + String scope = scopeOf(page); + if ("SHARED".equalsIgnoreCase(scope)) { + return "[Shared] " + page.getName(); + } else { + return "[Project] " + page.getName(); + } + } +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectRepo.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectRepo.java index d6c09d3b..8510fda3 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectRepo.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectRepo.java @@ -22,8 +22,20 @@ import javax.swing.UIManager; /** + * Main UI container for managing the Object Repository within Test Design. + *

    + * The {@code ObjectRepo} panel provides a unified interface for switching between + * Web and Mobile Object Repository views. It embeds both {@link WebORPanel} and + * {@link MobileORPanel} inside a card-based layout and exposes high-level actions + * such as loading repository data, adjusting UI layout, and navigating directly to + * specific OR objects. + *

    * - * + *

    + * A toggle-based toolbar allows the user to switch between repository types, and + * the component ensures the correct panel is shown and updated when selections occur. + * This class acts as the entry point for OR maintenance within the Test Design module. + *

    */ public class ObjectRepo extends JPanel implements ItemListener { @@ -35,7 +47,6 @@ public class ObjectRepo extends JPanel implements ItemListener { private final WebORPanel webOR; - private final MobileORPanel mobileOR; public ObjectRepo(TestDesign testDesign) { @@ -83,7 +94,6 @@ public WebORPanel getWebOR() { return webOR; } - public MobileORPanel getMobileOR() { return mobileOR; } @@ -148,4 +158,4 @@ private JToggleButton create(String text) { return togg; } } -} +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectTree.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectTree.java index 7bce0755..c568bd1e 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectTree.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/ObjectTree.java @@ -3,10 +3,13 @@ import com.ing.datalib.component.Project; import com.ing.datalib.component.TestCase; +import com.ing.datalib.or.ObjectRepository; import com.ing.datalib.or.common.ORObjectInf; import com.ing.datalib.or.common.ORPageInf; import com.ing.datalib.or.common.ORRootInf; import com.ing.datalib.or.common.ObjectGroup; +import com.ing.datalib.or.web.ResolvedWebObject; +import com.ing.datalib.or.web.WebOR; import com.ing.ide.main.help.Help; import com.ing.ide.main.utils.keys.Keystroke; @@ -28,6 +31,7 @@ import java.util.Map; import java.util.Set; import com.ing.ide.main.mainui.AppMainFrame; +import com.ing.ide.main.mainui.components.testdesign.or.web.WebObjectTree; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.util.List; @@ -64,9 +68,34 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; + /** + * Base abstract class representing a fully interactive Object Repository (OR) tree. + *

    + * {@code ObjectTree} provides a complete UI framework for browsing, editing, and + * maintaining Object Repository structures including pages, object groups, and + * objects. It manages a {@link JTree} with support for inline editing, drag‑and‑drop, + * contextual popup menus, keyboard shortcuts, custom icons, and dynamic selection + * handling. + *

    + * + *

    + * The class defines core behaviors such as: + *

      + *
    • Loading repository structures into the tree.
    • + *
    • Renaming, adding, sorting, and deleting OR nodes.
    • + *
    • Project‑synchronized updates (save, refresh, rename validations).
    • + *
    • Shared vs. project‑scoped OR safeguards (shared rename checks, shared copy restrictions).
    • + *
    • Finding and selecting OR objects and scrolling them into view.
    • + *
    • Right‑click context menu actions through {@link ObjectPopupMenu}.
    • + *
    • Coordination with table panels via {@code loadTableModelForSelection()}.
    • + *
    + *

    * - * + *

    + * Subclasses must implement methods for loading table models, accessing the active + * project instance, retrieving the OR root, and showing impacted test cases. + *

    */ public abstract class ObjectTree implements ActionListener { @@ -250,6 +279,9 @@ public void actionPerformed(ActionEvent ae) { case "Open Page Dump": openPageDump(); break; + case "Copy to Shared": + copyToShared(); + break; default: throw new UnsupportedOperationException(); } @@ -260,19 +292,26 @@ private Boolean checkAndRename() { if (Validator.isValidName(name)) { ORPageInf page = getSelectedPage(); if (page != null && !page.getName().equals(name)) { + if (!confirmSharedRename("Page", page.getName(), name)) { + return false; + } if (page.rename(name)) { nodeRenamed(page); + getProject().save(); return true; } else { Notification.show("Page " + name + " Already present"); return false; } } - ObjectGroup group = getSelectedObjectGroup(); if (group != null && !group.getName().equals(name)) { + if (!confirmSharedRename("Object Group", group.getName(), name)) { + return false; + } if (group.rename(name)) { nodeRenamed(group); + getProject().save(); return true; } else { Notification.show("Object " + name + " Already present"); @@ -282,8 +321,12 @@ private Boolean checkAndRename() { ORObjectInf obj = getSelectedObject(); if (obj != null && !obj.getName().equals(name)) { + if (!confirmSharedRename("Object", obj.getName(), name)) { + return false; + } if (obj.rename(name)) { nodeRenamed(obj); + getProject().save(); return true; } else { Notification.show("Object " + name + " Already present"); @@ -388,13 +431,17 @@ private void addPage() { private void deleteObjects() { List objects = getSelectedObjects(); if (!objects.isEmpty()) { - int option = JOptionPane.showConfirmDialog(null, - "

    " - + "Are you sure want to delete the following Objects?
    " - + objects - + "

    ", - "Delete Object", - JOptionPane.YES_NO_OPTION); + String extra = isSharedScope() ? sharedProjectsInfo() : ""; + int option = JOptionPane.showConfirmDialog( + null, + "

    " + + "Are you sure you want to delete the following Objects?
    " + + objects + + extra + + "

    ", + isSharedScope() ? "Delete SHARED Object" : "Delete Object", + JOptionPane.YES_NO_OPTION + ); if (option == JOptionPane.YES_OPTION) { for (ORObjectInf object : objects) { objectRemoved(object); @@ -632,17 +679,21 @@ public void deleteUnusedObject(String page, String object) { e.printStackTrace(); } } - + private void deleteObjectGroups() { List objects = getSelectedObjectGroups(); if (!objects.isEmpty()) { - int option = JOptionPane.showConfirmDialog(null, - "

    " - + "Are you sure want to delete the following ObjectGroups?
    " - + objects - + "

    ", - "Delete ObjectGroup", - JOptionPane.YES_NO_OPTION); + String extra = isSharedScope() ? sharedProjectsInfo() : ""; + int option = JOptionPane.showConfirmDialog( + null, + "

    " + + "Are you sure you want to delete the following ObjectGroups?
    " + + objects + + extra + + "

    ", + isSharedScope() ? "Delete SHARED ObjectGroup" : "Delete ObjectGroup", + JOptionPane.YES_NO_OPTION + ); if (option == JOptionPane.YES_OPTION) { for (ObjectGroup object : objects) { objectGroupRemoved(object); @@ -655,13 +706,17 @@ private void deleteObjectGroups() { private void deletePages() { List pages = getSelectedPages(); if (!pages.isEmpty()) { - int option = JOptionPane.showConfirmDialog(null, - "

    " - + "Are you sure want to delete the following Pages?
    " - + pages - + "

    ", - "Delete Page", - JOptionPane.YES_NO_OPTION); + String extra = isSharedScope() ? sharedProjectsInfo() : ""; + int option = JOptionPane.showConfirmDialog( + null, + "

    " + + "Are you sure you want to delete the following Pages?
    " + + pages + + extra + + "

    ", + isSharedScope() ? "Delete SHARED Page" : "Delete Page", + JOptionPane.YES_NO_OPTION + ); if (option == JOptionPane.YES_OPTION) { for (ORPageInf page : pages) { pageRemoved(page); @@ -670,7 +725,7 @@ private void deletePages() { } } } - + private void getImpactedTestCases() { ObjectGroup group = getSelectedObjectGroup(); if (group == null) { @@ -683,10 +738,14 @@ private void getImpactedTestCases() { } String pageName = group.getParent().getName(); String objectName = group.getName(); - showImpactedTestCases( - getProject().getImpactedObjectTestCases(pageName, objectName), - pageName, - objectName); + WebOR.ORScope scope = isSharedScope() + ? WebOR.ORScope.SHARED + : WebOR.ORScope.PROJECT; + + List impacted = getProject() + .getImpactedObjectTestCases(scope, pageName, objectName); + + showImpactedTestCases(impacted, pageName, objectName); } public abstract void showImpactedTestCases( @@ -741,6 +800,124 @@ public void openPageDump() { } } + private void copyToShared() { + ORObjectInf obj = getSelectedObject(); + ObjectGroup group = getSelectedObjectGroup(); + ORPageInf selectedPage = getSelectedPage(); + + if (obj == null && group == null && selectedPage == null) { + com.ing.ide.util.Notification.show("Select an Object, Object Group, or Page."); + return; + } + + ORPageInf page = (obj != null) ? obj.getPage() + : (group != null) ? group.getParent() + : selectedPage; + + ObjectRepository repo = getProject().getObjectRepository(); + + ORRootInf root = getOR(); + boolean isWeb = (root instanceof com.ing.datalib.or.web.WebOR); + boolean isMobile = (root instanceof com.ing.datalib.or.mobile.MobileOR); + + if (obj == null && group == null && selectedPage != null) { + if (isWeb) { + String newName = repo.copyWebPage(page.getName(), page.getName()); + if (newName != null) { + com.ing.ide.util.Notification.show("Copied Page '" + page.getName() + "' to Shared Web Object successfully as '" + newName + "'."); + } else { + com.ing.ide.util.Notification.show("Copy failed. Could not copy Page '" + page.getName() + "' to Shared Web Objects."); + } + if (newName != null) { + if (this instanceof com.ing.ide.main.mainui.components.testdesign.or.web.WebObjectTree) { + com.ing.ide.main.mainui.components.testdesign.or.web.WebORPanel panel = + ((com.ing.ide.main.mainui.components.testdesign.or.web.WebObjectTree) this).getORPanel(); + panel.getSharedTree().load(); + } else { + reload(); + } + } + return; + } else if (isMobile) { + String newName = repo.copyMobilePage(page.getName(), page.getName()); + if (newName != null) { + com.ing.ide.util.Notification.show("Copied Page '" + page.getName() + "' to Shared Mobile Object successfully as '" + newName + "'."); + } else { + com.ing.ide.util.Notification.show("Copy failed. Could not copy Page '" + page.getName() + "' to Shared Mobile Objects."); + } + if (newName != null) { + if (this instanceof com.ing.ide.main.mainui.components.testdesign.or.mobile.MobileObjectTree) { + com.ing.ide.main.mainui.components.testdesign.or.mobile.MobileORPanel panel = + ((com.ing.ide.main.mainui.components.testdesign.or.mobile.MobileObjectTree) this).getORPanel(); + panel.getSharedTree().load(); + } else { + reload(); + } + } + return; + } + } + + String objectName = (obj != null) ? obj.getName() : group.getName(); + + if (isWeb) { + ResolvedWebObject resolved = + repo.resolveWebObject( + new ResolvedWebObject.PageRef(page.getName(), com.ing.datalib.or.web.WebOR.ORScope.PROJECT), + objectName + ); + if (resolved == null) { + com.ing.ide.util.Notification.show("Object '" + objectName + "' not found in Project OR (Page '" + page.getName() + "')."); + return; + } + + String copiedName = repo.copyWebObject(resolved, page.getName()); + if (copiedName != null) { + com.ing.ide.util.Notification.show("Copied Object '" + copiedName + "' from Page '" + page.getName() + "' to Shared Web Object successfully."); + } else { + com.ing.ide.util.Notification.show("Copy failed. Could not copy Object '" + objectName + "' to Shared Web Object (Page '" + page.getName() + "')."); + } + if (copiedName != null) { + if (this instanceof com.ing.ide.main.mainui.components.testdesign.or.web.WebObjectTree) { + com.ing.ide.main.mainui.components.testdesign.or.web.WebORPanel panel = + ((com.ing.ide.main.mainui.components.testdesign.or.web.WebObjectTree) this).getORPanel(); + panel.getSharedTree().load(); + } else { + reload(); + } + } + } else if (isMobile) { + com.ing.datalib.or.mobile.ResolvedMobileObject mresolved = + repo.resolveMobileObject( + new com.ing.datalib.or.mobile.ResolvedMobileObject.PageRef( + page.getName(), + com.ing.datalib.or.web.WebOR.ORScope.PROJECT + ), + objectName + ); + if (mresolved == null) { + com.ing.ide.util.Notification.show("Object '" + objectName + "' not found in Project Mobile OR (Page '" + page.getName() + "')."); + return; + } + + String copiedName = repo.copyMobileObject(mresolved, page.getName()); + if (copiedName != null) { + com.ing.ide.util.Notification.show("Copied Object '" + copiedName + "' from Page '" + page.getName() + "' to Shared Mobile Object successfully."); + } else { + com.ing.ide.util.Notification.show("Copy failed. Could not copy Object '" + objectName + "' to Shared Mobile Object (Page '" + page.getName() + "')."); + } + if (copiedName != null) { + if (this instanceof com.ing.ide.main.mainui.components.testdesign.or.mobile.MobileObjectTree) { + com.ing.ide.main.mainui.components.testdesign.or.mobile.MobileORPanel panel = + ((com.ing.ide.main.mainui.components.testdesign.or.mobile.MobileObjectTree) this).getORPanel(); + panel.getSharedTree().load(); + } else { + reload(); + } + } + } + } + public Boolean navigateToObject(String objectName, String pageName) { ORPageInf page = getOR().getPageByName(pageName); if (page != null) { @@ -784,11 +961,14 @@ public void run() { } private void nodeRenamed(final TreeNode node) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - ((DefaultTreeModel) tree.getModel()).nodeChanged(node); + SwingUtilities.invokeLater(() -> { + DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); + model.nodeChanged(node); + TreeNode parent = node.getParent(); + if (parent != null) { + model.nodeStructureChanged(parent); } + tree.repaint(); }); } @@ -843,7 +1023,6 @@ public void run() { } private void alterDefaultKeyBindings() { - int menuShortcutKeyMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx(); tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_X, menuShortcutKeyMask), "none"); tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, menuShortcutKeyMask), "none"); @@ -851,9 +1030,70 @@ private void alterDefaultKeyBindings() { tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_X, menuShortcutKeyMask), "cut"); tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, menuShortcutKeyMask), "copy"); - tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, menuShortcutKeyMask), "paste"); - - + tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, menuShortcutKeyMask), "paste"); + } + + private boolean isSharedScope() { + ORRootInf root = getOR(); + if (root instanceof com.ing.datalib.or.web.WebOR) { + return ((com.ing.datalib.or.web.WebOR) root).isShared(); + } + if (root instanceof com.ing.datalib.or.mobile.MobileOR) { + return ((com.ing.datalib.or.mobile.MobileOR) root).isShared(); + } + return false; } -} + private boolean confirmSharedRename(String entityLabel, String currentName, String newName) { + if (!isSharedScope()) return true; + ORRootInf root = getOR(); + java.util.List projects = null; + + if (root instanceof com.ing.datalib.or.web.WebOR) { + projects = ((com.ing.datalib.or.web.WebOR) root).getProjects(); + } else if (root instanceof com.ing.datalib.or.mobile.MobileOR) { + projects = ((com.ing.datalib.or.mobile.MobileOR) root).getProjects(); + } + + if (projects == null || projects.isEmpty()) { + return true; + } + + String extra = sharedProjectsInfo(); + if (extra == null) extra = ""; + + String message = + "

    " + + "You are about to rename the SHARED " + entityLabel + " " + + "" + currentName + " to " + newName + ".

    " + + "Other projects that use Shared " + (root instanceof com.ing.datalib.or.mobile.MobileOR ? "Mobile" : "Web") + + " Objects still reference the old name in their test steps." + + extra + + ""; + + int option = javax.swing.JOptionPane.showConfirmDialog( + null, + message, + "Confirm Shared Rename", + javax.swing.JOptionPane.YES_NO_OPTION + ); + return option == javax.swing.JOptionPane.YES_OPTION; + } + + private String sharedProjectsInfo() { + ORRootInf root = getOR(); + java.util.List projects = null; + + if (root instanceof com.ing.datalib.or.web.WebOR) { + projects = ((com.ing.datalib.or.web.WebOR) root).getProjects(); + } else if (root instanceof com.ing.datalib.or.mobile.MobileOR) { + projects = ((com.ing.datalib.or.mobile.MobileOR) root).getProjects(); + } + + if (projects != null && !projects.isEmpty()) { + return "

    Before proceeding, please verify whether this page/object is being used by the following project(s):
    " + + String.join(", ", projects); + } + return ""; + } +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileORPanel.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileORPanel.java index f254ccba..3e81d38d 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileORPanel.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileORPanel.java @@ -1,4 +1,3 @@ - package com.ing.ide.main.mainui.components.testdesign.or.mobile; import com.ing.datalib.component.Project; @@ -7,39 +6,116 @@ import com.ing.ide.main.mainui.components.testdesign.TestDesign; import com.ing.ide.main.utils.tree.TreeSearch; import java.awt.BorderLayout; +import java.util.List; +import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JSplitPane; +import javax.swing.JTabbedPane; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.tree.TreePath; /** - * - * + * Main panel for the Mobile Object Repository (OR) UI, containing: + *

      + *
    • Project and Shared OR trees (with search support)
    • + *
    • A properties table for displaying and modifying object attributes
    • + *
    + *

    + * This panel manages tree–table interaction, updates the table based on the + * active tab, and provides navigation utilities for locating specific OR objects. + * It serves as the central coordinator for loading, displaying, and interacting + * with mobile OR data in Test Design. */ public class MobileORPanel extends JPanel { - private final MobileObjectTree objectTree; + private final MobileObjectTree projectTree; + private final MobileObjectTree sharedTree; private final MobileORTable objectTable; - private final TestDesign testDesign; private JSplitPane splitPane; + private JTabbedPane tabs; public MobileORPanel(TestDesign testDesign) { this.testDesign = testDesign; - this.objectTree = new MobileObjectTree(this); + this.projectTree = new MobileObjectTree(this, MobileObjectTree.ORSource.PROJECT); + this.sharedTree = new MobileObjectTree(this, MobileObjectTree.ORSource.SHARED); this.objectTable = new MobileORTable(this); init(); } private void init() { setLayout(new BorderLayout()); + + tabs = new JTabbedPane(); + + JComponent projectTreeWithSearch = TreeSearch.installForOR(projectTree.getTree()); + tabs.addTab("Project", projectTreeWithSearch); + + JComponent sharedTreeWithSearch = TreeSearch.installForOR(sharedTree.getTree()); + tabs.addTab("Shared", sharedTreeWithSearch); + + tabs.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + updateTableForCurrentSelection(); + } + }); + splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setOneTouchExpandable(true); + splitPane.setTopComponent(tabs); splitPane.setBottomComponent(objectTable); - TreeSearch tSearch = TreeSearch.installForOR(objectTree.getTree()); - splitPane.setTopComponent(tSearch); - splitPane.setResizeWeight(.5); - splitPane.setDividerLocation(.5); - add(splitPane); + splitPane.setResizeWeight(0.5); + + add(splitPane, BorderLayout.CENTER); + + javax.swing.SwingUtilities.invokeLater(() -> { + splitPane.setDividerLocation(0.5); + }); + + hookSelectionToTable(projectTree); + hookSelectionToTable(sharedTree); + } + + private void hookSelectionToTable(MobileObjectTree tree) { + tree.getTree().addTreeSelectionListener(e -> { + if (isTreeOnCurrentTab(tree)) { + loadTableModelForSelection(getSelectedNodeUserObject(tree)); + } + }); + } + + private boolean isTreeOnCurrentTab(MobileObjectTree tree) { + int idx = tabs.getSelectedIndex(); + String title = (idx >= 0) ? tabs.getTitleAt(idx) : ""; + return (tree == projectTree && "Project".equals(title)) + || (tree == sharedTree && "Shared".equals(title)); + } + + private Object getSelectedNodeUserObject(MobileObjectTree tree) { + TreePath path = tree.getTree().getSelectionPath(); + if (path == null) return null; + + Object node = path.getLastPathComponent(); + if (node instanceof javax.swing.tree.DefaultMutableTreeNode) { + return ((javax.swing.tree.DefaultMutableTreeNode) node).getUserObject(); + } + return node; + } + + private void updateTableForCurrentSelection() { + MobileObjectTree activeTree = getActiveTree(); + Object selected = (activeTree != null) ? getSelectedNodeUserObject(activeTree) : null; + loadTableModelForSelection(selected); + } + + public MobileObjectTree getActiveTree() { + int idx = tabs.getSelectedIndex(); + if (idx == 0) return projectTree; + if (idx == 1) return sharedTree; + return null; } void loadTableModelForSelection(Object object) { @@ -52,34 +128,41 @@ void loadTableModelForSelection(Object object) { } } - public MobileObjectTree getObjectTree() { - return objectTree; - } - - public TestDesign getTestDesign() { - return testDesign; - } - - public Project getProject() { - return testDesign.getProject(); - } + public TestDesign getTestDesign() { return testDesign; } + public Project getProject() { return testDesign.getProject(); } public void load() { objectTable.reset(); - objectTree.load(); - splitPane.setDividerLocation(.5); + sharedTree.load(); + projectTree.load(); } public void adjustUI() { - splitPane.setDividerLocation(0.5); } public Boolean navigateToObject(String objectName, String pageName) { - return objectTree.navigateToObject(objectName, pageName); + MobileObjectTree active = getActiveTree(); + if (active != null && Boolean.TRUE.equals(active.navigateToObject(objectName, pageName))) return true; + + MobileObjectTree other = (active == projectTree) ? sharedTree : projectTree; + return (other != null) ? other.navigateToObject(objectName, pageName) : false; } - public MobileORTable getObjectTable() { - return objectTable; + public MobileORTable getObjectTable() { + return objectTable; } -} + public MobileObjectTree getProjectTree() { + return projectTree; + } + + public MobileObjectTree getSharedTree() { + return sharedTree; + } + + public List getSelectedObjectsFromActiveTab() { + MobileObjectTree active = getActiveTree(); + return (active != null) ? active.getSelectedObjects() + : java.util.Collections.emptyList(); + } +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileORTable.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileORTable.java index 0cbc634e..d7e93f13 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileORTable.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileORTable.java @@ -23,6 +23,18 @@ import javax.swing.JToolBar; import javax.swing.table.DefaultTableModel; +/** + * Displays and edits properties of a selected {@link MobileORObject} in table form. + *

    + * Supports a wide range of attribute operations, including: + *

      + *
    • adding, removing, and clearing attributes
    • + *
    • bulk operations across pages or selected objects
    • + *
    • reordering attributes and setting priority
    • + *
    • context menu and toolbar actions
    • + *
    + * This component acts as the editable detail view within the Mobile OR panel. + */ public class MobileORTable extends JPanel implements ActionListener { private final XTable table; @@ -54,10 +66,13 @@ public XTable getTable() { public void loadObject(MobileORObject object) { table.setModel(object); + String source = object.getPage().getRoot().isShared() ? "Shared" : "Project"; + toolBar.setTitleSuffix("[" + source + "]"); } public void reset() { table.setModel(new DefaultTableModel()); + toolBar.setTitleSuffix(""); } @Override @@ -161,17 +176,15 @@ private void moveDown() { } } - private List getSelectedObjects() { - return mobileOR.getObjectTree().getSelectedObjects(); - } - private void clearFromSelected() { if (table.getSelectedRowCount() > 0) { String[] attrs = getSelectedAttrs(); - for (String attr : attrs) { - getSelectedObjects().stream().forEach((object) -> { - ((MobileORObject) object).setAttributeByName(attr, ""); - }); + for (ORObjectInf object : mobileOR.getSelectedObjectsFromActiveTab()) { + for (String attr : attrs) { + if (object instanceof MobileORObject) { + ((MobileORObject) object).setAttributeByName(attr, ""); + } + } } } } @@ -213,11 +226,16 @@ private void removeFromAll() { private void removeFromSelected() { if (table.getSelectedRowCount() > 0) { String[] attrs = getSelectedAttrs(); - for (String attr : attrs) { - getSelectedObjects().stream().forEach((object) -> { - ((MobileORObject) object).removeAttribute(attr); - }); + List selected = mobileOR.getSelectedObjectsFromActiveTab(); + for (ORObjectInf object : selected) { + for (String attr : attrs) { + if (object instanceof MobileORObject) { + ((MobileORObject) object).removeAttribute(attr); + } + } } + mobileOR.getObjectTable().revalidate(); + mobileOR.getObjectTable().repaint(); } } @@ -240,11 +258,16 @@ private void removeFromPage(MobileORPage page, String[] attrs) { private void addToSelected() { if (table.getSelectedRowCount() > 0) { String[] attrs = getSelectedAttrs(); - for (String attr : attrs) { - getSelectedObjects().stream().forEach((object) -> { - ((MobileORObject) object).addNewAttribute(attr); - }); + List selected = mobileOR.getSelectedObjectsFromActiveTab(); + for (ORObjectInf object : selected) { + for (String attr : attrs) { + if (object instanceof MobileORObject) { + ((MobileORObject) object).addNewAttribute(attr); + } + } } + mobileOR.getObjectTable().revalidate(); + mobileOR.getObjectTable().repaint(); } } @@ -284,9 +307,17 @@ private void setPriorityToAll() { private void setPriorityToSelected() { stopCellEditing(); MobileORObject currObj = getObject(); - getSelectedObjects().stream().forEach((object) -> { - reorderAttributes(currObj.getAttributes(), ((MobileORObject) object).getAttributes()); - }); + List selected = mobileOR.getSelectedObjectsFromActiveTab(); + for (ORObjectInf object : selected) { + if (object instanceof MobileORObject) { + if (currObj != null) { + reorderAttributes(currObj.getAttributes(), + ((MobileORObject) object).getAttributes()); + } + } + } + mobileOR.getObjectTable().revalidate(); + mobileOR.getObjectTable().repaint(); } private void setPriorityToPage() { @@ -329,6 +360,8 @@ public MobileORObject getObject() { } class ToolBar extends JToolBar { + + private JLabel titleLabel; public ToolBar() { init(); @@ -342,9 +375,9 @@ private void init() { add(new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767))); - JLabel label = new JLabel("Properties"); - label.setFont(new Font("Default", Font.BOLD, 12)); - add(label); + titleLabel = new JLabel("Properties"); + titleLabel.setFont(new Font("Default", Font.BOLD, 12)); + add(titleLabel); add(new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767))); @@ -354,6 +387,10 @@ private void init() { add(Utils.createButton("Move Rows Up", "up", "Ctrl+Up", MobileORTable.this)); add(Utils.createButton("Move Rows Down", "down", "Ctrl+Down", MobileORTable.this)); } + + public void setTitleSuffix(String suffix) { + titleLabel.setText("Properties " + suffix); + } } @@ -388,4 +425,4 @@ private void init() { } } -} +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileObjectTree.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileObjectTree.java index 6849a455..4657cf8b 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileObjectTree.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/mobile/MobileObjectTree.java @@ -1,8 +1,8 @@ - package com.ing.ide.main.mainui.components.testdesign.or.mobile; import com.ing.datalib.component.Project; import com.ing.datalib.component.TestCase; +import com.ing.datalib.or.ObjectRepository; import com.ing.datalib.or.common.ORObjectInf; import com.ing.datalib.or.common.ORRootInf; import com.ing.datalib.or.mobile.MobileORObject; @@ -11,15 +11,25 @@ import javax.swing.tree.TreePath; /** - * - * + * Represents the tree UI component for displaying Mobile Object Repository (OR) items. + *

    + * This class links the object tree with the {@link MobileORPanel}, enabling: + *

      + *
    • loading object details into the properties table
    • + *
    • retrieving the appropriate OR source (Project or Shared)
    • + *
    • handling impacted test case display
    • + *
    • resetting the table when selected objects are removed
    • + *
    + * It acts as the controller between tree selections and OR object presentation. */ public class MobileObjectTree extends ObjectTree { private final MobileORPanel oRPanel; + private final ORSource source; - public MobileObjectTree(MobileORPanel sProxy) { - this.oRPanel = sProxy; + public MobileObjectTree(MobileORPanel panel, ORSource source) { + this.oRPanel = panel; + this.source = source; } @Override @@ -42,13 +52,14 @@ public void showImpactedTestCases(List testcases, String pageName, Str @Override public ORRootInf getOR() { - return oRPanel.getProject().getObjectRepository().getMobileOR(); + ObjectRepository repo = oRPanel.getProject().getObjectRepository(); + return (source == ORSource.SHARED) ? repo.getMobileSharedOR() : repo.getMobileOR(); } @Override protected void objectRemoved(ORObjectInf object) { - if (getLoadedObject() != null - && getLoadedObject().equals(object)) { + ORObjectInf loaded = getLoadedObject(); + if (loaded != null && loaded.equals(object)) { oRPanel.getObjectTable().reset(); } super.objectRemoved(object); @@ -58,5 +69,15 @@ public MobileORObject getLoadedObject() { return oRPanel.getObjectTable().getObject(); } + public enum ORSource { + PROJECT, SHARED + } + + public ORSource getSource() { + return source; + } -} + public MobileORPanel getORPanel() { + return oRPanel; + } +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebORPanel.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebORPanel.java index efcdf75a..65ce98db 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebORPanel.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebORPanel.java @@ -2,48 +2,130 @@ package com.ing.ide.main.mainui.components.testdesign.or.web; import com.ing.datalib.component.Project; +import com.ing.datalib.or.common.ORObjectInf; import com.ing.datalib.or.common.ObjectGroup; import com.ing.datalib.or.web.WebORObject; import com.ing.ide.main.mainui.components.testdesign.TestDesign; +import com.ing.ide.main.mainui.components.testdesign.or.web.WebObjectTree.ORSource; import com.ing.ide.main.utils.tree.TreeSearch; import java.awt.BorderLayout; import java.awt.Toolkit; import java.awt.event.KeyEvent; +import java.util.List; +import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JSplitPane; +import javax.swing.JTabbedPane; import javax.swing.KeyStroke; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.tree.TreePath; /** + * Main UI panel for managing Web Object Repository (OR) entries in Test Design. + *

    + * This panel provides two tabbed OR trees (Project and Shared) and a details table below. + * It synchronizes tree selection with the {@link WebORTable} so that selecting an OR node + * loads the corresponding {@link WebORObject} into the table, and switching tabs refreshes + * the table based on the active tree selection. + *

    * - * + *

    Key Features

    + *
      + *
    • Tabbed OR Trees: Displays {@link WebObjectTree} instances for project and shared repositories.
    • + *
    • Search Integration: Installs tree search UI on each OR tree.
    • + *
    • Selection → Details: Loads/reset the {@link WebORTable} depending on what is selected.
    • + *
    • Navigation: Can navigate to an object/page in the active tree, falling back to the other tree.
    • + *
    • Delegation: Exposes access to {@link TestDesign} and {@link Project} for child components.
    • + *
    */ public class WebORPanel extends JPanel { - - private final WebObjectTree objectTree; + private final WebObjectTree projectTree; + private final WebObjectTree sharedTree; private final WebORTable objectTable; - private final TestDesign testDesign; - private JSplitPane splitPane; + private JTabbedPane tabs; public WebORPanel(TestDesign testDesign) { this.testDesign = testDesign; - this.objectTree = new WebObjectTree(this); + this.projectTree = new WebObjectTree(this, ORSource.PROJECT); + this.sharedTree = new WebObjectTree(this, ORSource.SHARED); this.objectTable = new WebORTable(this); init(); } private void init() { setLayout(new BorderLayout()); + tabs = new JTabbedPane(); + + JComponent projectTreeWithSearch = TreeSearch.installForOR(projectTree.getTree()); + tabs.addTab("Project", projectTreeWithSearch); + + JComponent sharedTreeWithSearch = TreeSearch.installForOR(sharedTree.getTree()); + tabs.addTab("Shared", sharedTreeWithSearch); + + tabs.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + updateTableForCurrentSelection(); + } + }); + splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setOneTouchExpandable(true); + splitPane.setTopComponent(tabs); splitPane.setBottomComponent(objectTable); - TreeSearch tSearch = TreeSearch.installForOR(objectTree.getTree()); - splitPane.setTopComponent(tSearch); - splitPane.setResizeWeight(.5); - splitPane.setDividerLocation(.5); - add(splitPane); - + splitPane.setResizeWeight(0.5); + add(splitPane, BorderLayout.CENTER); + + javax.swing.SwingUtilities.invokeLater(() -> { + splitPane.setDividerLocation(0.5); + }); + + hookSelectionToTable(projectTree); + hookSelectionToTable(sharedTree); + } + + private void hookSelectionToTable(WebObjectTree tree) { + tree.getTree().addTreeSelectionListener(e -> { + if (isTreeOnCurrentTab(tree)) { + loadTableModelForSelection(getSelectedNodeUserObject(tree)); + } + }); + } + + private boolean isTreeOnCurrentTab(WebObjectTree tree) { + int idx = tabs.getSelectedIndex(); + String title = (idx >= 0) ? tabs.getTitleAt(idx) : ""; + return (tree == projectTree && "Project".equals(title)) + || (tree == sharedTree && "Shared".equals(title)); + } + + private Object getSelectedNodeUserObject(WebObjectTree tree) { + TreePath path = tree.getTree().getSelectionPath(); + if (path == null) return null; + Object node = path.getLastPathComponent(); + if (node instanceof javax.swing.tree.DefaultMutableTreeNode) { + return ((javax.swing.tree.DefaultMutableTreeNode) node).getUserObject(); + } + return node; + } + + private void updateTableForCurrentSelection() { + WebObjectTree activeTree = getActiveTree(); + Object selected = (activeTree != null) ? getSelectedNodeUserObject(activeTree) : null; + loadTableModelForSelection(selected); + } + + public WebObjectTree getActiveTree() { + int idx = tabs.getSelectedIndex(); + if (idx == 0) { + return projectTree; + } else if (idx == 1) { + return sharedTree; + } + return null; } void loadTableModelForSelection(Object object) { @@ -57,7 +139,10 @@ void loadTableModelForSelection(Object object) { } void changeFrameData(String frameText) { - objectTree.changeFrameData(frameText); + WebObjectTree activeTree = getActiveTree(); + if (activeTree != null) { + activeTree.changeFrameData(frameText); + } } public TestDesign getTestDesign() { @@ -70,26 +155,37 @@ public Project getProject() { public void load() { objectTable.reset(); - objectTree.load(); - splitPane.setDividerLocation(.5); + sharedTree.load(); + projectTree.load(); } public void adjustUI() { - splitPane.setDividerLocation(0.5); } public Boolean navigateToObject(String objectName, String pageName) { - return objectTree.navigateToObject(objectName, pageName); + WebObjectTree active = getActiveTree(); + if (active != null && Boolean.TRUE.equals(active.navigateToObject(objectName, pageName))) { + return true; + } + WebObjectTree other = (active == projectTree) ? sharedTree : projectTree; + return (other != null) ? other.navigateToObject(objectName, pageName) : false; } - public WebObjectTree getObjectTree() { - return objectTree; + public WebObjectTree getProjectTree() { + return projectTree; + } + + public WebObjectTree getSharedTree() { + return sharedTree; } public WebORTable getObjectTable() { return objectTable; } - - -} + public List getSelectedObjectsFromActiveTab() { + WebObjectTree active = getActiveTree(); + return (active != null) ? active.getSelectedObjects() + : java.util.Collections.emptyList(); + } +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebORTable.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebORTable.java index 5ede10f6..6ba20357 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebORTable.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebORTable.java @@ -6,6 +6,7 @@ import com.ing.datalib.or.common.ObjectGroup; import com.ing.datalib.or.web.WebORObject; import com.ing.datalib.or.web.WebORPage; +import com.ing.ide.main.mainui.components.testdesign.or.web.WebObjectTree.ORSource; import com.ing.ide.main.utils.Utils; import com.ing.ide.main.utils.table.XTable; import java.awt.BorderLayout; @@ -33,19 +34,29 @@ import javax.swing.table.DefaultTableModel; /** + * UI component for viewing and editing Web Object Repository (WebOR) object properties. + *

    + * The {@code WebORTable} displays a {@link WebORObject}'s attributes in a table and provides + * tools for adding, removing, reordering, and bulk-modifying properties across pages or selected items. + * It integrates with {@link WebORPanel} and responds to tree selections, context menu actions, + * and toolbar commands. Frame values can also be viewed and edited using a dedicated frame toolbar. + *

    * - * + *

    + * Core features include: + *

      + *
    • Loading and displaying OR attributes for the selected {@code WebORObject}.
    • + *
    • Editing operations such as add/delete property, reorder rows, and bulk updates across pages.
    • + *
    • Frame metadata editing with automatic propagation to selected or related objects.
    • + *
    • Context menu and toolbar integration for fast OR maintenance actions.
    • + *
    + *

    */ public class WebORTable extends JPanel implements ActionListener, ItemListener { - private final XTable table; - private final FrameToolBar frameToolbar; - private final ToolBar toolBar; - private final PopupMenu popupMenu; - private final WebORPanel webOR; private Boolean monitorFrameChange = true; @@ -80,6 +91,8 @@ public void loadObject(WebORObject object) { frameToolbar.frameText.setText(object.getFrame()); toolBar.frameToggle.setSelected(!frameToolbar.frameText.getText().isEmpty()); monitorFrameChange = true; + String source = object.getPage().getRoot().isShared() ? "Shared" : "Project"; + toolBar.setTitleSuffix("[" + source + "]"); } private void changeFrameText() { @@ -152,6 +165,7 @@ public void actionPerformed(ActionEvent ae) { break; case "From Selected": clearFrameFromSelected(); + break; } } } @@ -201,13 +215,9 @@ private void moveDown() { } } - private List getSelectedObjects() { - return webOR.getObjectTree().getSelectedObjects(); - } - private void clearFrameFromSelected() { frameToolbar.frameText.setText(""); - getSelectedObjects().stream().forEach((object) -> { + webOR.getSelectedObjectsFromActiveTab().stream().forEach((object) -> { ((WebORObject) object).setFrame(""); }); } @@ -235,10 +245,12 @@ private void clearFrameFromPage(WebORPage page) { private void clearFromSelected() { if (table.getSelectedRowCount() > 0) { String[] attrs = getSelectedAttrs(); - for (String attr : attrs) { - getSelectedObjects().stream().forEach((object) -> { - ((WebORObject) object).setAttributeByName(attr, ""); - }); + for (ORObjectInf object : webOR.getSelectedObjectsFromActiveTab()) { + for (String attr : attrs) { + if (object instanceof WebORObject) { + ((WebORObject) object).setAttributeByName(attr, ""); + } + } } } } @@ -271,11 +283,16 @@ private void clearFromPage(WebORPage page, String[] attrs) { private void removeFromSelected() { if (table.getSelectedRowCount() > 0) { String[] attrs = getSelectedAttrs(); - for (String attr : attrs) { - getSelectedObjects().stream().forEach((object) -> { - ((WebORObject) object).removeAttribute(attr); - }); + List selected = webOR.getSelectedObjectsFromActiveTab(); + for (ORObjectInf object : selected) { + for (String attr : attrs) { + if (object instanceof WebORObject) { + ((WebORObject) object).removeAttribute(attr); + } + } } + webOR.getObjectTable().revalidate(); + webOR.getObjectTable().repaint(); } } @@ -307,11 +324,16 @@ private void removeFromPage(WebORPage page, String[] attrs) { private void addToSelected() { if (table.getSelectedRowCount() > 0) { String[] attrs = getSelectedAttrs(); - for (String attr : attrs) { - getSelectedObjects().stream().forEach((object) -> { - ((WebORObject) object).addNewAttribute(attr); - }); + List selected = webOR.getSelectedObjectsFromActiveTab(); + for (ORObjectInf object : selected) { + for (String attr : attrs) { + if (object instanceof WebORObject) { + ((WebORObject) object).addNewAttribute(attr); + } + } } + webOR.getObjectTable().revalidate(); + webOR.getObjectTable().repaint(); } } @@ -343,9 +365,17 @@ private void addToPage(WebORPage page, String[] attrs) { private void setPriorityToSelected() { stopCellEditing(); WebORObject currObj = getObject(); - getSelectedObjects().stream().forEach((object) -> { - reorderAttributes(currObj.getAttributes(), ((WebORObject) object).getAttributes()); - }); + List selected = webOR.getSelectedObjectsFromActiveTab(); + for (ORObjectInf object : selected) { + if (object instanceof WebORObject) { + if (currObj != null) { + reorderAttributes(currObj.getAttributes(), + ((WebORObject) object).getAttributes()); + } + } + } + webOR.getObjectTable().revalidate(); + webOR.getObjectTable().repaint(); } private void setPriorityToAll() { @@ -401,7 +431,6 @@ public void itemStateChanged(ItemEvent ie) { } class FrameToolBar extends JToolBar implements DocumentListener { - private JTextField frameText; public FrameToolBar() { @@ -416,29 +445,22 @@ private void init() { add(new JLabel("Frame")); add(new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767))); add(frameText); - frameText.getDocument().addDocumentListener(this); } @Override - public void insertUpdate(DocumentEvent de) { - changeFrameText(); - } + public void insertUpdate(DocumentEvent de) { changeFrameText(); } @Override - public void removeUpdate(DocumentEvent de) { - changeFrameText(); - } + public void removeUpdate(DocumentEvent de) { changeFrameText(); } @Override - public void changedUpdate(DocumentEvent de) { - changeFrameText(); - } + public void changedUpdate(DocumentEvent de) { changeFrameText(); } } class ToolBar extends JToolBar { - JToggleButton frameToggle; + private JLabel titleLabel; public ToolBar() { init(); @@ -448,21 +470,16 @@ public ToolBar() { private void init() { setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.X_AXIS)); setFloatable(false); - - add(new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), - new java.awt.Dimension(10, 0), - new java.awt.Dimension(10, 32767))); - JLabel label = new JLabel("Properties"); - label.setFont(new Font("Default", Font.BOLD, 12)); - add(label); - + add(new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767))); + titleLabel = new JLabel("Properties"); + titleLabel.setFont(new Font("Default", Font.BOLD, 12)); + add(titleLabel); add(new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 32767))); - - add(Utils.createLRButton("Add Row", "add", WebORTable.this)); - add(Utils.createLRButton("Delete Rows", "remove", WebORTable.this)); + add(Utils.createLRButton("Add Row", "add", WebORTable.this)); + add(Utils.createLRButton("Delete Rows", "remove", WebORTable.this)); addSeparator(); - add(Utils.createLRButton("Move Rows Up", "up", WebORTable.this)); - add(Utils.createLRButton("Move Rows Down", "down", WebORTable.this)); + add(Utils.createLRButton("Move Rows Up", "up", WebORTable.this)); + add(Utils.createLRButton("Move Rows Down", "down", WebORTable.this)); addSeparator(); frameToggle = new JToggleButton(Utils.getIconByResourceName("/ui/resources/or/web/propViewer")); frameToggle.addItemListener(WebORTable.this); @@ -470,11 +487,13 @@ private void init() { frameToggle.setActionCommand("Toggle Frame"); add(frameToggle); } - + + public void setTitleSuffix(String suffix) { + titleLabel.setText("Properties " + suffix); + } } class PopupMenu extends JPopupMenu { - public PopupMenu() { init(); } @@ -490,25 +509,28 @@ private void init() { setPriority.add(Utils.createMenuItem("Set Priority to All", WebORTable.this)); setPriority.add(Utils.createMenuItem("Set Priority to Selected", WebORTable.this)); add(setPriority); + clearProp.add(Utils.createMenuItem("Clear from Page", WebORTable.this)); clearProp.add(Utils.createMenuItem("Clear from All", WebORTable.this)); clearProp.add(Utils.createMenuItem("Clear from Selected", WebORTable.this)); add(clearProp); + deleteProp.add(Utils.createMenuItem("Remove from Page", WebORTable.this)); deleteProp.add(Utils.createMenuItem("Remove from All", WebORTable.this)); deleteProp.add(Utils.createMenuItem("Remove from Selected", WebORTable.this)); add(deleteProp); + addProp.add(Utils.createMenuItem("Add to Page", WebORTable.this)); addProp.add(Utils.createMenuItem("Add to All", WebORTable.this)); addProp.add(Utils.createMenuItem("Add to Selected", WebORTable.this)); add(addProp); + addSeparator(); + clearFrame.add(Utils.createMenuItem("From Page", WebORTable.this)); clearFrame.add(Utils.createMenuItem("From All", WebORTable.this)); clearFrame.add(Utils.createMenuItem("From Selected", WebORTable.this)); add(clearFrame); } - } - -} +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebObjectTree.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebObjectTree.java index 032aa365..33956a1a 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebObjectTree.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/or/web/WebObjectTree.java @@ -3,6 +3,7 @@ import com.ing.datalib.component.Project; import com.ing.datalib.component.TestCase; +import com.ing.datalib.or.ObjectRepository; import com.ing.datalib.or.common.ORObjectInf; import com.ing.datalib.or.common.ORRootInf; import com.ing.datalib.or.web.WebORObject; @@ -11,15 +12,29 @@ import javax.swing.tree.TreePath; /** + * Swing tree component for browsing and editing Web Object Repository (OR) entries in the Test Design UI. + *

    + * {@code WebObjectTree} extends {@link ObjectTree} and delegates most UI actions to the owning + * {@link WebORPanel}. It loads the object details table based on the current tree selection, + * routes "impacted test cases" requests to the Impact UI, and resolves the correct Web OR root + * (project OR vs shared OR) based on {@link ORSource}. + *

    * - * + *

    Key Behaviors

    + *
      + *
    • Selection → Table: On selection change, loads the object attributes into the OR table model.
    • + *
    • Repository Source: Returns either the project Web OR or shared Web OR depending on {@link ORSource}.
    • + *
    • Frame Editing: Updates the selected {@link WebORObject}'s frame metadata.
    • + *
    • Removal Handling: If the removed object is currently loaded in the table, resets the table before removal completes.
    • + *
    */ public class WebObjectTree extends ObjectTree { - private final WebORPanel oRPanel; + private final ORSource source; - public WebObjectTree(WebORPanel sProxy) { - this.oRPanel = sProxy; + public WebObjectTree(WebORPanel panel, ORSource source) { + this.oRPanel = panel; + this.source = source; } @Override @@ -49,13 +64,16 @@ public void showImpactedTestCases(List testcases, String pageName, Str @Override public ORRootInf getOR() { - return oRPanel.getProject().getObjectRepository().getWebOR(); + ObjectRepository repo = oRPanel.getProject().getObjectRepository(); + return (source == ORSource.SHARED) + ? repo.getWebSharedOR() + : repo.getWebOR(); } @Override protected void objectRemoved(ORObjectInf object) { - if (getLoadedObject() != null - && getLoadedObject().equals(object)) { + ORObjectInf loaded = getAnyLoadedObject(); + if (loaded != null && loaded.equals(object)) { oRPanel.getObjectTable().reset(); } super.objectRemoved(object); @@ -65,4 +83,16 @@ public WebORObject getLoadedObject() { return oRPanel.getObjectTable().getObject(); } -} + private ORObjectInf getAnyLoadedObject() { + return getLoadedObject(); + } + + public enum ORSource { + PROJECT, + SHARED + } + + public WebORPanel getORPanel() { + return oRPanel; + } +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseAutoSuggest.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseAutoSuggest.java index c61f8cd2..93e290a0 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseAutoSuggest.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseAutoSuggest.java @@ -5,13 +5,15 @@ import com.ing.datalib.component.TestCase; import com.ing.datalib.component.TestData; import com.ing.datalib.component.TestStep; + import static com.ing.datalib.component.TestStep.HEADERS.Action; import static com.ing.datalib.component.TestStep.HEADERS.Condition; import static com.ing.datalib.component.TestStep.HEADERS.Description; import static com.ing.datalib.component.TestStep.HEADERS.Input; import static com.ing.datalib.component.TestStep.HEADERS.ObjectName; import static com.ing.datalib.component.TestStep.HEADERS.Reference; -import com.ing.datalib.or.common.ORPageInf; +import com.ing.datalib.or.mobile.ResolvedMobileObject; +import com.ing.datalib.or.web.ResolvedWebObject; import com.ing.datalib.testdata.model.Record; import com.ing.datalib.testdata.model.TestDataModel; import com.ing.engine.support.methodInf.MethodInfoManager; @@ -26,6 +28,7 @@ import com.ing.ide.main.utils.table.autosuggest.AutoSuggestCellEditor; import com.ing.ide.main.utils.table.autosuggest.InputAutoSuggestCellEditor; import com.ing.ide.main.utils.table.autosuggest.ComboSeparatorsRenderer; + import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; @@ -48,11 +51,13 @@ import javax.swing.Timer; /** + * Auto-suggest controller for the Test Case table, providing intelligent + * suggestions for Object, Action, Condition, and Input columns. * - * + * Updated to support Mobile OR separation (Project + Shared) and scoped + * reference tokens ("[Project]" / "[Shared]") when detecting object type. */ public class TestCaseAutoSuggest { - private final Project sProject; final JTable table; @@ -71,19 +76,22 @@ public TestCaseAutoSuggest(Project sProject, JTable table) { private void initAutoSuggest() { objAutoSuggest = new AutoSuggest().withSearchList(getObjectList()) .withOnHide(stopEditingOnFocusLost()); + conditionAutoSuggest = (ConditionAutoSuggest) new ConditionAutoSuggest() .withOnHide(stopEditingOnFocusLost()); conditionAutoSuggest.setRenderer( new ComboSeparatorsRenderer(conditionAutoSuggest.getRenderer()) { - @Override - protected boolean addSeparatorAfter(JList list, Object value, int index) { - return "End Param:@n".equals(value) - || "End Loop:@n".equals(value) - || "GlobalObject".equals(value); - } - }); + @Override + protected boolean addSeparatorAfter(JList list, Object value, int index) { + return "End Param:@n".equals(value) + || "End Loop:@n".equals(value) + || "GlobalObject".equals(value); + } + }); + actionAutoSuggest = new ActionAutoSuggest() .withOnHide(stopEditingOnFocusLost()); + inputAutoSuggest = (InputAutoSuggest) new InputAutoSuggest() .withOnHide(stopEditingOnFocusLost()); } @@ -91,14 +99,11 @@ protected boolean addSeparatorAfter(JList list, Object value, int index) { private boolean isStringOpsEditor(){ int row = table.getSelectedRow(); String value = ""; - if(row >= 0) - value = table.getModel().getValueAt(row, 1).toString(); - if(!value.matches("String Operations")) - return false; - - return true; + if(row >= 0) value = table.getModel().getValueAt(row, 1).toString(); + if(!value.matches("String Operations")) return false; + return true; } - + private Action stopEditingOnFocusLost() { return new AbstractAction() { @Override @@ -118,8 +123,8 @@ public void installForTestCase() { table.getColumnModel().getColumn(Input.getIndex()).setCellEditor(new InputAutoSuggestCellEditor(inputAutoSuggest)); } - private List getObjectList() { - List objectList = new ArrayList<>(); + private List getObjectList() { + List objectList = new ArrayList<>(); objectList.add("Browser"); objectList.add("Mobile"); objectList.add("Webservice"); @@ -134,41 +139,39 @@ private List getObjectList() { return objectList; } - public List getContextAliasList() { - List values = sProject.getProjectSettings().getContextSettings().getContextList(); - List newList = new ArrayList<>(); - for (String string : values) { + public List getContextAliasList() { + List values = sProject.getProjectSettings().getContextSettings().getContextList(); + List newList = new ArrayList<>(); + for (Object string : values) { newList.add("#"+string); } return newList; } - public List getDatabaseAliasList() { - List values = sProject.getProjectSettings().getDatabaseSettings().getDbList(); - List newList = new ArrayList<>(); - for (String string : values) { + public List getDatabaseAliasList() { + List values = sProject.getProjectSettings().getDatabaseSettings().getDbList(); + List newList = new ArrayList<>(); + for (Object string : values) { newList.add("#"+string); } return newList; } - - public List getAPIAliasList() { - List values = sProject.getProjectSettings().getDriverSettings().getAPIList(); - List newList = new ArrayList<>(); - for (String string : values) { + + public List getAPIAliasList() { + List values = sProject.getProjectSettings().getDriverSettings().getAPIList(); + List newList = new ArrayList<>(); + for (Object string : values) { newList.add("#"+string); } return newList; } - private void startEditing(final AutoSuggest suggest) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!table.isEditing()) { table.editCellAt(table.getSelectedRow(), table.getSelectedColumn()); - boolean isStringOpsEditor = isStringOpsEditor(); if(!isStringOpsEditor){ suggest.getTextField().setText(suggest.getText() + ":"); @@ -179,14 +182,13 @@ public void run() { } }); } - + private void startEditing(final InputMainAutoSuggest suggest) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!table.isEditing()) { table.editCellAt(table.getSelectedRow(), table.getSelectedColumn()); - boolean isStringOpsEditor = isStringOpsEditor(); if(!isStringOpsEditor){ suggest.getTextField().setText(suggest.getText() + ":"); @@ -211,56 +213,53 @@ private TestCase getTestCase(JTable table) { } private boolean isDataBaseQueryStep(TestStep step) { - return step != null && step.isDatabaseStep() - && (step.getAction().contains("execute") || step.getAction().contains("storeResult")); + return step != null && step.isDatabaseStep() && (step.getAction().contains("execute") + || step.getAction().contains("storeResult")); } private boolean isProtractorjsStep(TestStep step) { - return step != null - && (step.getAction().contains("protractor_customSpec")); + return step != null && (step.getAction().contains("protractor_customSpec")); } private boolean isRestWebservicePostStep(TestStep step) { - return step != null && step.isWebserviceStep() - && (step.getAction().contains("postRest") || step.getAction().contains("putRest") || step.getAction().contains("patchRest") || step.getAction().contains("deleteWithPayload")); + return step != null && step.isWebserviceStep() && (step.getAction().contains("postRest") + || step.getAction().contains("putRest") + || step.getAction().contains("patchRest") + || step.getAction().contains("deleteWithPayload")); } private boolean isSetEndPointStep(TestStep step) { - return step != null && step.isWebserviceStep() - && (step.getAction().contains("setEndPoint")); + return step != null && step.isWebserviceStep() && (step.getAction().contains("setEndPoint")); } private boolean isSOAPWebservicePostStep(TestStep step) { - return step != null && step.isWebserviceStep() - && step.getAction().contains("postSoap"); + return step != null && step.isWebserviceStep() && step.getAction().contains("postSoap"); } private boolean isFileStep(TestStep step) { - return step != null && step.isFileStep() - && step.getAction().contains("populateData"); + return step != null && step.isFileStep() && step.getAction().contains("populateData"); } - + private boolean isMessageStep(TestStep step) { - return step != null && step.isMessageStep() - && (step.getAction().contains("setText")|| step.getAction().contains("produceMessage")); + return step != null && step.isMessageStep() && (step.getAction().contains("setText") + || step.getAction().contains("produceMessage")); } private boolean isRouteFulfillEndpointStep(TestStep step) { - return step != null && step.isBrowserStep() - && (step.getAction().contains("RouteFulfillEndpoint")); + return step != null && step.isBrowserStep() && (step.getAction().contains("RouteFulfillEndpoint")); } private boolean isRouteFulfillSetBodyStep(TestStep step) { - return step != null && step.isBrowserStep() - && step.getAction().contains("RouteFulfillSetBody"); + return step != null && step.isBrowserStep() && step.getAction().contains("RouteFulfillSetBody"); } - + private boolean isStringOperationsStep(TestStep step) { return step != null && step.isStringOperationsStep(); } class ConditionAutoSuggest extends AutoSuggest { - private List getConditionBasedOnText(String value) { + + private List getConditionBasedOnText(String value) { String objectName = Objects.toString(table.getValueAt( table.getSelectedRow(), ObjectName.getIndex()), ""); if ("Webservice".equals(objectName)){ @@ -268,9 +267,8 @@ private List getConditionBasedOnText(String value) { } else { return getContextAliasList(); } - } - + @Override public void beforeSearch(String text) { if (text.isEmpty()) { @@ -281,8 +279,9 @@ public void beforeSearch(String text) { } } } - private List getConditionList() { - List conditionList = new ArrayList<>(); + + private List getConditionList() { + List conditionList = new ArrayList<>(); conditionList.add("Start Param"); conditionList.add("End Param"); conditionList.add("End Param:@n"); @@ -297,10 +296,10 @@ private List getConditionList() { class ActionAutoSuggest extends AutoSuggest { - private List getActionBasedOnObject() { + private List getActionBasedOnObject() { String objectName = Objects.toString(table.getValueAt( table.getSelectedRow(), ObjectName.getIndex()), ""); - String pageName = Objects.toString(table.getValueAt( + String pageToken = Objects.toString(table.getValueAt( table.getSelectedRow(), Reference.getIndex()), ""); switch (objectName) { @@ -317,29 +316,29 @@ private List getActionBasedOnObject() { case "Webservice": return MethodInfoManager.getMethodListFor(ObjectType.WEBSERVICE, ObjectType.WEBSERVICE); case "Synthetic Data": - return MethodInfoManager.getMethodListFor(ObjectType.DATA, ObjectType.DATA); + return MethodInfoManager.getMethodListFor(ObjectType.DATA, ObjectType.DATA); case "Queue": - return MethodInfoManager.getMethodListFor(ObjectType.QUEUE, ObjectType.QUEUE); + return MethodInfoManager.getMethodListFor(ObjectType.QUEUE, ObjectType.QUEUE); case "Kafka": - return MethodInfoManager.getMethodListFor(ObjectType.KAFKA, ObjectType.KAFKA); + return MethodInfoManager.getMethodListFor(ObjectType.KAFKA, ObjectType.KAFKA); case "File": return MethodInfoManager.getMethodListFor(ObjectType.FILE, ObjectType.FILE); case "General": - return MethodInfoManager.getMethodListFor(ObjectType.GENERAL, ObjectType.GENERAL); + return MethodInfoManager.getMethodListFor(ObjectType.GENERAL, ObjectType.GENERAL); case "String Operations": - return MethodInfoManager.getMethodListFor(ObjectType.STRINGOPERATIONS, ObjectType.STRINGOPERATIONS); + return MethodInfoManager.getMethodListFor(ObjectType.STRINGOPERATIONS, ObjectType.STRINGOPERATIONS); default: - if (isWebObject(objectName, pageName)) { + if (isWebObject(objectName, pageToken)) { return MethodInfoManager.getMethodListFor(ObjectType.PLAYWRIGHT, ObjectType.WEB, ObjectType.ANY); - } else if (isMobileObject(objectName, pageName)) { + } else if (isMobileObject(objectName, pageToken)) { return MethodInfoManager.getMethodListFor(ObjectType.APP); } } return new ArrayList<>(); } - private List getReusables() { - List reusableList = new ArrayList<>(); + private List getReusables() { + List reusableList = new ArrayList<>(); for (Scenario scenario : sProject.getScenarios()) { int rcount = scenario.getReusableCount(); for (int i = 0; i < rcount; i++) { @@ -349,15 +348,38 @@ private List getReusables() { return reusableList; } - - private boolean isWebObject(String objectName, String pageName) { - ORPageInf page = sProject.getObjectRepository().getWebOR().getPageByName(pageName); - return page != null && page.getObjectGroupByName(objectName) != null; + private boolean isWebObject(String objectName, String pageToken) { + if (pageToken == null + || pageToken.isBlank() + || objectName == null + || objectName.isBlank()) { + return false; + } + var repo = sProject.getObjectRepository(); + ResolvedWebObject.PageRef ref = ResolvedWebObject.PageRef.parse(pageToken); + ResolvedWebObject r = (ref != null && ref.name != null && ref.scope != null) + ? repo.resolveWebObject(ref, objectName) + : repo.resolveWebObjectWithScope(pageToken, objectName); + return r != null && r.isPresent(); } - private boolean isMobileObject(String objectName, String pageName) { - ORPageInf page = sProject.getObjectRepository().getMobileOR().getPageByName(pageName); - return page != null && page.getObjectGroupByName(objectName) != null; + /** + * Detect Mobile objects via Mobile resolver (supports scoped refs + shared) + * instead of directly accessing getMobileOR()/pages. + */ + private boolean isMobileObject(String objectName, String pageToken) { + if (pageToken == null + || pageToken.isBlank() + || objectName == null + || objectName.isBlank()) { + return false; + } + var repo = sProject.getObjectRepository(); + ResolvedMobileObject.PageRef ref = ResolvedMobileObject.PageRef.parse(pageToken); + ResolvedMobileObject r = (ref != null && ref.name != null && ref.scope != null) + ? repo.resolveMobileObject(ref, objectName) + : repo.resolveMobileObjectWithScope(pageToken, objectName); + return r != null && r.isPresent(); } @Override @@ -374,52 +396,49 @@ public void afterReset() { table.setValueAt(desc, table.getSelectedRow(), Description.getIndex()); } } - } class InputAutoSuggest extends InputMainAutoSuggest { - Boolean isPending = false; - private String prevText; - + public InputAutoSuggest(){ - super.setTable(TestCaseAutoSuggest.this.table); + super.setTable(TestCaseAutoSuggest.this.table); } - private List getInputBasedOnText(String value) { + private List getInputBasedOnText(String value) { if (value.startsWith("%")) { return getUserDefinedList(); } else if (value.startsWith("=")) { return getFunctionList(); - }else if(value.startsWith("#")) { + } else if(value.startsWith("#")) { return getDatabaseAliasList(); } return setupTestData(value); } - public List getUserDefinedList() { - Set udSet = sProject.getProjectSettings().getUserDefinedSettings().stringPropertyNames(); - List values = new ArrayList<>(); - for (String string : udSet) { - values.add("%".concat(string).concat("%")); + public List getUserDefinedList() { + Set udSet = sProject.getProjectSettings().getUserDefinedSettings().stringPropertyNames(); + List values = new ArrayList<>(); + for (Object string : udSet) { + values.add("%".concat((String) string).concat("%")); } return values; } - private List getFunctionList() { - List newFList = new ArrayList<>(); + private List getFunctionList() { + List newFList = new ArrayList<>(); for (String function : FParser.getFuncList()) { newFList.add("=" + function); } return newFList; } - private List setupTestData(String value) { + private List setupTestData(String value) { if (value != null && value.contains(":")) { prevText = value.substring(0, value.indexOf(':')); isPending = true; - Set colList = new LinkedHashSet<>(); + Set colList = new LinkedHashSet<>(); String tdName = value.substring(0, value.indexOf(':')); for (TestData sTestData : sProject.getTestData().getAllEnvironments()) { for (TestDataModel stdList : sTestData.getTestDataList()) { @@ -431,7 +450,7 @@ private List setupTestData(String value) { colList.removeAll(Arrays.asList(Record.HEADERS)); return new ArrayList<>(colList); } else { - Set tdList = new LinkedHashSet<>(); + Set tdList = new LinkedHashSet<>(); for (TestData sTestData : sProject.getTestData().getAllEnvironments()) { for (TestDataModel stdList : sTestData.getTestDataList()) { tdList.add(stdList.getName()); @@ -441,16 +460,16 @@ private List setupTestData(String value) { } } - public List getTestData() { - List retList = new ArrayList<>(); - Set tdList = new LinkedHashSet<>(); + public List getTestData() { + List retList = new ArrayList<>(); + Set tdList = new LinkedHashSet<>(); sProject.getTestData().getAllEnvironments().stream().forEach((sTestData) -> { for (TestDataModel stdList : sTestData.getTestDataList()) { tdList.add(stdList.getName()); } }); tdList.stream().forEach((string) -> { - List tdCols = setupTestData(string + ":"); + List tdCols = setupTestData(string + ":"); tdCols.stream().forEach((tdCol) -> { retList.add(string + ":" + tdCol); }); @@ -460,14 +479,11 @@ public List getTestData() { @Override public void setSelectedItem(Object o) { - boolean isStringOpsEditor = isStringOpsEditor(); - if (o != null - && !o.toString().matches("(@.+)|(=.+)|(%.+%)") - && !o.toString().contains(":")) { + if (o != null && !o.toString().matches("(@.+)\n(=.+)\n(%.+%)") && !o.toString().contains(":")) { if (isPending && prevText != null && !isStringOpsEditor) { o = prevText + ":" + o.toString(); - } else if (isPending && prevText != null && isStringOpsEditor) { + } else if (isPending && prevText != null && isStringOpsEditor) { o = prevText + o.toString(); } } @@ -476,8 +492,7 @@ public void setSelectedItem(Object o) { @Override public String preReset(String val) { - if (!val.isEmpty() && !val.equals(getText()) - && !val.contains(":")) { + if (!val.isEmpty() && !val.equals(getText()) && !val.contains(":")) { val = getText().split(":")[0] + ":" + val; table.setValueAt(val, table.getSelectedRow(), table.getSelectedColumn()); return val; @@ -500,7 +515,7 @@ public void beforeSearch(String text) { public void afterReset() { prevText = null; isPending = false; - if (!getText().isEmpty() && !getText().matches("^[\\%|\\@].*") && !getText().contains(":")) { + if (!getText().isEmpty() && !getText().matches("^[\\%\\@].*") && !getText().contains(":")) { startEditing(this); } } @@ -512,7 +527,7 @@ public void setPrevText(String prevText) { @Override public void beforeShow() { String val = Objects.toString(getSelectedItem(), ""); - if (!val.isEmpty() && !val.matches("(@.+)|(=.+)|(%.+%)") && val.contains(":")) { + if (!val.isEmpty() && !val.matches("(@.+)\n(=.+)\n(%.+%)") && val.contains(":")) { setPrevText(val.substring(0, val.indexOf(':'))); isPending = true; } @@ -526,18 +541,17 @@ public String getSearchString() { } return text; } - } class MouseAdapterImpl extends MouseAdapter { - @Override public void mouseClicked(MouseEvent me) { boolean isInputclicked = table.columnAtPoint(me.getPoint()) == Input.getIndex(); if (me.isAltDown()) { if (table.rowAtPoint(me.getPoint()) != -1 && getTestCase(table) != null) { TestStep step = getTestCase(table).getTestSteps().get(table.rowAtPoint(me.getPoint())); - if ((isDataBaseQueryStep(step) && table.columnAtPoint(me.getPoint()) == Input.getIndex()) || (isProtractorjsStep(step) && table.columnAtPoint(me.getPoint()) == Input.getIndex())) { + if ((isDataBaseQueryStep(step) && table.columnAtPoint(me.getPoint()) == Input.getIndex()) + || (isProtractorjsStep(step) && table.columnAtPoint(me.getPoint()) == Input.getIndex())) { new SQLTextArea(null, step, getInputs()); } if ((isRestWebservicePostStep(step) && isInputclicked)) { @@ -569,8 +583,8 @@ public void mouseClicked(MouseEvent me) { } } - public List getInputs() { - List auto = inputAutoSuggest.getUserDefinedList(); + public List getInputs() { + List auto = inputAutoSuggest.getUserDefinedList(); auto.addAll(inputAutoSuggest.getTestData()); return auto; } @@ -584,12 +598,14 @@ class MouseMotionAdapterImpl extends MouseMotionAdapter { Timer showTimerf; Timer showTimerm; Timer showTimers; + Timer disposeTimerp; Timer disposeTimerd; Timer disposeTimerw; Timer disposeTimerf; Timer disposeTimerm; Timer disposeTimers; + JPopupMenu popupp; JPopupMenu popupd; JPopupMenu popupw; @@ -606,6 +622,7 @@ public MouseMotionAdapterImpl() { popupf = new JPopupMenu(); popupm = new JPopupMenu(); popups = new JPopupMenu(); + final JMenuItem jMenuItemp = new JMenuItem("Click to open ProtractorJS command editor"); final JMenuItem jMenuItemd = new JMenuItem("Click to Open SQL Query Editor "); final JMenuItem jMenuItemw = new JMenuItem("Click to Open Webservice Editor "); @@ -631,6 +648,7 @@ public MouseMotionAdapterImpl() { new SQLTextArea(null, step, getInputs()); } }); + jMenuItemw.addActionListener((ActionEvent ae) -> { if (step.isWebserviceStep() && step.getAction().contains("postSoap")) { new WebservicePayloadArea(null, step, "SOAP", getInputs()); @@ -654,13 +672,13 @@ public MouseMotionAdapterImpl() { new WebservicePayloadArea(null, step, "SOAP", getInputs()); } }); - + jMenuItemm.addActionListener((ActionEvent ae) -> { if (step != null && (isMessageStep(step))) { new WebservicePayloadArea(null, step, "SOAP", getInputs()); } }); - + jMenuItems.addActionListener((ActionEvent ae) -> { if (step != null && (isStringOperationsStep(step))) { new StringOperationsPayloadArea(null, step, getInputs()); @@ -681,7 +699,6 @@ public MouseMotionAdapterImpl() { }); showTimerp.setRepeats(false); showTimerp.setCoalesce(true); - disposeTimerp = new Timer(2000, (ActionEvent ae) -> { popupp.setVisible(false); }); @@ -693,7 +710,6 @@ public MouseMotionAdapterImpl() { if (hintCell != null) { disposeTimerd.stop(); popupd.setVisible(false); - Rectangle bounds = table.getCellRect(hintCell.y, hintCell.x, true); int x = bounds.x; int y = bounds.y + bounds.height; @@ -703,7 +719,6 @@ public MouseMotionAdapterImpl() { }); showTimerd.setRepeats(false); showTimerd.setCoalesce(true); - disposeTimerd = new Timer(2000, (ActionEvent ae) -> { popupd.setVisible(false); }); @@ -715,7 +730,6 @@ public MouseMotionAdapterImpl() { if (hintCell != null) { disposeTimerw.stop(); popupw.setVisible(false); - Rectangle bounds = table.getCellRect(hintCell.y, hintCell.x, true); int x = bounds.x; int y = bounds.y + bounds.height; @@ -725,7 +739,6 @@ public MouseMotionAdapterImpl() { }); showTimerw.setRepeats(false); showTimerw.setCoalesce(true); - disposeTimerw = new Timer(2000, (ActionEvent ae) -> { popupw.setVisible(false); }); @@ -737,7 +750,6 @@ public MouseMotionAdapterImpl() { if (hintCell != null) { disposeTimerf.stop(); popupf.setVisible(false); - Rectangle bounds = table.getCellRect(hintCell.y, hintCell.x, true); int x = bounds.x; int y = bounds.y + bounds.height; @@ -747,19 +759,17 @@ public MouseMotionAdapterImpl() { }); showTimerf.setRepeats(false); showTimerf.setCoalesce(true); - disposeTimerf = new Timer(2000, (ActionEvent ae) -> { popupf.setVisible(false); }); disposeTimerf.setRepeats(false); disposeTimerf.setCoalesce(true); - + //Timer m showTimerm = new Timer(1000, (ActionEvent ae) -> { if (hintCell != null) { disposeTimerm.stop(); popupm.setVisible(false); - Rectangle bounds = table.getCellRect(hintCell.y, hintCell.x, true); int x = bounds.x; int y = bounds.y + bounds.height; @@ -769,19 +779,17 @@ public MouseMotionAdapterImpl() { }); showTimerm.setRepeats(false); showTimerm.setCoalesce(true); - disposeTimerm = new Timer(2000, (ActionEvent ae) -> { popupm.setVisible(false); }); disposeTimerm.setRepeats(false); disposeTimerm.setCoalesce(true); - + //Timer s showTimers = new Timer(1000, (ActionEvent ae) -> { if (hintCell != null) { disposeTimers.stop(); popups.setVisible(false); - Rectangle bounds = table.getCellRect(hintCell.y, hintCell.x, true); int x = bounds.x; int y = bounds.y + bounds.height; @@ -791,14 +799,11 @@ public MouseMotionAdapterImpl() { }); showTimers.setRepeats(false); showTimers.setCoalesce(true); - disposeTimers = new Timer(2000, (ActionEvent ae) -> { popups.setVisible(false); }); disposeTimers.setRepeats(false); disposeTimers.setCoalesce(true); - - } @Override @@ -809,56 +814,77 @@ public void mouseMoved(MouseEvent e) { if (row != -1 && getTestCase(table) != null) { step = getTestCase(table).getTestSteps().get(row); if (isDataBaseQueryStep(step) && col == Input.getIndex()) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); showTimerd.restart(); } } else if (isProtractorjsStep(step) && col == Input.getIndex()) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); - //System.out.println("inside P + before restart" +popup.isVisible()); showTimerp.restart(); - //System.out.println("inside P + after restart" +popup.isVisible()); } - } else if ((isSOAPWebservicePostStep(step) && col == Input.getIndex()) || (isRestWebservicePostStep(step) && col == Input.getIndex())) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + } else if ((isSOAPWebservicePostStep(step) && col == Input.getIndex()) + || (isRestWebservicePostStep(step) && col == Input.getIndex())) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); showTimerw.restart(); } } else if ((isSetEndPointStep(step) && col == Input.getIndex())) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); showTimerw.restart(); } } else if ((isFileStep(step) && col == Input.getIndex())) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); showTimerf.restart(); } } else if ((isRouteFulfillEndpointStep(step) && col == Input.getIndex())) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); showTimerw.restart(); } } else if ((isRouteFulfillSetBodyStep(step) && col == Input.getIndex())) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); showTimerw.restart(); - } - } - else if ((isMessageStep(step) && col == Input.getIndex())) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + } + } else if ((isMessageStep(step) && col == Input.getIndex())) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); showTimerm.restart(); } } else if ((isStringOperationsStep(step) && col == Input.getIndex())) { - if (hintCell == null || (hintCell.x != col || hintCell.y != row)) { + if (hintCell == null + || (hintCell.x != col + || hintCell.y != row)) { hintCell = new Point(col, row); showTimers.restart(); } } else { hintCell = null; - if (popupp.isVisible() || popupd.isVisible() || popupw.isVisible() || popupf.isVisible()|| popupm.isVisible()|| popups.isVisible()) { + if (popupp.isVisible() + || popupd.isVisible() + || popupw.isVisible() + || popupf.isVisible() + || popupm.isVisible() + || popups.isVisible()) { popupp.setVisible(false); popupd.setVisible(false); popupw.setVisible(false); @@ -866,9 +892,8 @@ else if ((isMessageStep(step) && col == Input.getIndex())) { popupm.setVisible(false); popups.setVisible(false); } - } } } } -} +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseComponent.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseComponent.java index 2d5ad020..62a819f1 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseComponent.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseComponent.java @@ -4,6 +4,7 @@ import com.ing.datalib.component.Scenario; import com.ing.datalib.component.TestCase; import com.ing.datalib.component.TestStep; +import com.ing.datalib.component.TestStep.HEADERS; import static com.ing.datalib.component.TestStep.HEADERS.Description; import com.ing.datalib.component.utils.SaveListener; import com.ing.engine.constants.SystemDefaults; @@ -24,6 +25,7 @@ import com.ing.ide.util.Notification; import com.ing.ide.util.WindowMover; import java.awt.BorderLayout; +import java.awt.Component; import java.awt.Cursor; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; @@ -41,12 +43,15 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.util.Arrays; +import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.stream.Collectors; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; @@ -57,14 +62,32 @@ import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; +import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.SwingUtilities; +import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableCellRenderer; /** + * Main UI component for creating, editing, validating, and executing + * test cases within the Test Design module. + *

    + * {@code TestCaseComponent} manages the test case table, toolbars, + * popup menus, auto‑suggest systems, validations, breakpoints, comment + * toggling, and history tracking. It also integrates execution and debug + * workflows, invokes Playwright recording, handles table actions such as + * insert/delete/move/replicate steps, supports reusable creation, and + * synchronizes navigation to objects and test data. + *

    * - * + *

    + * The component orchestrates multiple sub‑dialogs (console, debugger, + * recorder), manages runner threads, ensures save lifecycle handling, + * and provides a unified environment for building and running automated + * test cases. + *

    */ public class TestCaseComponent extends JPanel implements ActionListener { @@ -97,6 +120,10 @@ public class TestCaseComponent extends JPanel implements ActionListener { private final AppMainFrame sMainFrame; private ClipboardMonitor monitor; + + private CompletableFuture launchPlaywrightTask; + + public static long INSTANCE_START_TIME; public TestCaseComponent(TestDesign testDesign, AppMainFrame sMainFrame) { this.testDesign = testDesign; @@ -283,7 +310,6 @@ public void onSave(Boolean bln) { }; testCaseTable.setTransferHandler(new TestCaseTableDnD()); - testCaseTable.addMouseListener(new MouseAdapter() { @Override @@ -398,7 +424,7 @@ public void actionPerformed(ActionEvent ae) { case "Toggle Validation": validator.toggleValidation(); break; - case "Paramterize": + case "Parameterize": parameterizeSelectedSteps(); break; case "Up One Level": @@ -417,26 +443,38 @@ public TestCase getCurrentTestCase() { } public void record() throws IOException { - String ProjectLocation = sMainFrame.getProject().getLocation(); - File recordedFile = new File(ProjectLocation + File.separator + "Recording" + File.separator + "recording.txt"); - if (recordedFile.exists()) { - boolean deleted = recordedFile.delete(); - if (deleted) { - System.out.println("Existing recording.txt deleted."); - } + String projectLocation = sMainFrame.getProject().getLocation(); + INSTANCE_START_TIME = System.currentTimeMillis(); + if (launchPlaywrightTask == null || launchPlaywrightTask.isDone()) { + PlaywrightSpinner playwrightSpinnerGUI = new PlaywrightSpinner(); + + launchPlaywrightTask = CompletableFuture.runAsync(() -> { + try { + launchPlaywright(playwrightSpinnerGUI); + } catch (IOException ex) { + Logger.getLogger(TestCaseComponent.class.getName()).log(Level.SEVERE, "Error launching Playwright", ex); + } + }); + + CompletableFuture playwrightLoading = CompletableFuture.runAsync(() -> { + try { + playwrightLoading(playwrightSpinnerGUI); + } catch (Exception ex) { + Logger.getLogger(TestCaseComponent.class.getName()).log(Level.WARNING, "Error in playwright loading UI", ex); + } + }); + CompletableFuture.allOf(launchPlaywrightTask, playwrightLoading) + .whenComplete((result, throwable) -> { + if (throwable != null) { + Logger.getLogger(TestCaseComponent.class.getName()).log(Level.SEVERE, "Playwright tasks failed", throwable); + } + SwingUtilities.invokeLater(() -> toolBar.enableRecordButton()); + }); + + } else { + System.out.println("Playwright is already running. Skipping duplicate launch."); + SwingUtilities.invokeLater(() -> toolBar.enableRecordButton()); } - PlaywrightSpinner playwrightSpinnerGUI = new PlaywrightSpinner(); - CompletableFuture launchPlaywright = CompletableFuture.runAsync(() -> { - try { - launchPlaywright(playwrightSpinnerGUI); - } catch (IOException ex) { - Logger.getLogger(TestCaseComponent.class.getName()).log(Level.SEVERE, null, ex); - } - }); - CompletableFuture playwrightLoading = CompletableFuture.runAsync(() -> { - playwrightLoading(playwrightSpinnerGUI); - }); - CompletableFuture playwright = CompletableFuture.allOf(launchPlaywright, playwrightLoading); } public Process startPlaywrightProcess(String processName, PlaywrightSpinner playwrightSpinnerGUI) { @@ -484,26 +522,37 @@ public Process startPlaywrightProcess(String processName, PlaywrightSpinner play return null; } +// public void initialization(PlaywrightSpinner playwrightSpinnerGUI){ +// try{ +// String[] command = new String[0]; +// String osName = System.getProperty("os.name").toLowerCase(); +// if (osName.contains("windows")) { +// // Windows command +// +// command = new String[]{"cmd", "/c", "mvn initialize -f engine/pom.xml"}; +// } else if (osName.contains("mac")) { +// // Mac command +// command = new String[]{"bash", "-l", "-c", "mvn initialize -f engine/pom.xml"}; +// } +// Runtime.getRuntime().exec(command); +// }catch (Exception ex){ +// System.out.println(ex.getMessage()); +// //playwrightSpinnerGUI.appendLog(ex.getMessage()); +// } +// } - public void initialization(PlaywrightSpinner playwrightSpinnerGUI){ - try{ - String[] command = new String[0]; - String osName = System.getProperty("os.name").toLowerCase(); - if (osName.contains("windows")) { - // Windows command - - command = new String[]{"cmd", "/c", "mvn initialize -f engine/pom.xml"}; - } else if (osName.contains("mac")) { - // Mac command - command = new String[]{"bash", "-l", "-c", "mvn initialize -f engine/pom.xml"}; - } - Runtime.getRuntime().exec(command); - }catch (Exception ex){ - System.out.println(ex.getMessage()); - //playwrightSpinnerGUI.appendLog(ex.getMessage()); - } - } - + /** + * Launches the Playwright codegen process and handles the recording workflow. + *

    + * Displays an informational dialog, starts clipboard monitoring, and executes + * the Playwright codegen process. If required, triggers Playwright installation. + * After recording, attempts to import the latest recorded steps and notifies the user + * if no recording is available. + *

    + * + * @param playwrightSpinnerGUI the spinner GUI component for Playwright status updates + * @throws IOException if an I/O error occurs during process execution + */ public void launchPlaywright(PlaywrightSpinner playwrightSpinnerGUI) throws IOException { System.out.println("============================== Playwright Log Started =============================="); //playwrightSpinnerGUI.appendLog("============================== Playwright Log Started =============================="); @@ -557,15 +606,31 @@ public void launchPlaywright(PlaywrightSpinner playwrightSpinnerGUI) throws IOEx System.out.println("============================== Playwright Log Ended =============================="); //playwrightSpinnerGUI.appendLog("============================== Playwright Log Ended =============================="); - new Thread(() -> { + + new Thread(() -> { try { String projectLocation = sMainFrame.getProject().getLocation(); launchRecorder.waitFor(); - File recordedFile = new File(projectLocation + File.separator + "Recording" + File.separator + "recording.txt"); + File recordingDir = new File(projectLocation + File.separator + "Recording"); + File[] recordingFiles = recordingDir.listFiles((dir, name) -> name.startsWith("recording_") && name.endsWith(".txt")); + + File latestFile = null; + if (recordingFiles != null && recordingFiles.length > 0) { + List filteredFiles = Arrays.stream(recordingFiles) + .filter(file -> file.lastModified() >= INSTANCE_START_TIME) + .sorted(Comparator.comparingLong(File::lastModified).reversed()) + .collect(Collectors.toList()); + + if (!filteredFiles.isEmpty()) { + latestFile = filteredFiles.get(0); + } + } + + final File recordedFile = latestFile; SwingUtilities.invokeLater(() -> { - if (recordedFile.exists()) { + if (recordedFile != null && recordedFile.exists()) { RecordedStepsImportDialog window = new RecordedStepsImportDialog(sMainFrame); window.setLocationRelativeTo(null); window.setVisible(true); @@ -579,11 +644,11 @@ public void launchPlaywright(PlaywrightSpinner playwrightSpinnerGUI) throws IOEx } monitor.stopMonitoring(); }); - - } catch (InterruptedException e) { + } catch (InterruptedException e) { e.printStackTrace(); - } - }).start(); + } + }).start(); + } public void playwrightLoading(PlaywrightSpinner playwrightSpinnerGUI) { @@ -1096,5 +1161,4 @@ public void actionPerformed(ActionEvent ae) { loadTableModelForSelection(visit()); } } - -} +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCasePopupMenu.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCasePopupMenu.java index 5ab8b3bb..354ee00e 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCasePopupMenu.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCasePopupMenu.java @@ -53,7 +53,7 @@ private void init() { goToMenu.add(Utils.createMenuItem("Go To Object", actionListener)); goToMenu.add(Utils.createMenuItem("Go To TestData", actionListener)); add(goToMenu); - add(Utils.createMenuItem("Paramterize", actionListener)); + add(Utils.createMenuItem("Parameterize", actionListener)); addSeparator(); JRadioButtonMenuItem toggleValidation = new JRadioButtonMenuItem("Toggle Validation", true); diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseTableDnD.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseTableDnD.java index 3e2c3736..68d9fde0 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseTableDnD.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseTableDnD.java @@ -19,8 +19,16 @@ import javax.swing.TransferHandler; /** - * - * + * Drag‑and‑drop handler for the Test Case table, enabling users to drop + * Object Repository items, Test Data references, or reusable test cases + * directly into step rows. + *

    + * The handler interprets dropped payloads from multiple DnD flavors + * (objects, test data, test cases) and updates the appropriate TestStep + * fields such as Object, Reference, Input, or Reusable. It also supports + * expanding page-level drops into multiple steps and correctly manages + * grouped edits within a TestCase model. + *

    */ public class TestCaseTableDnD extends TransferHandler { @@ -129,8 +137,14 @@ private void putRelativeObject(JTable table, int row) { } } + private String basePage(String pageToken) { + int at = pageToken.lastIndexOf('@'); + return (at > 0) ? pageToken.substring(0, at) : pageToken; + } + private void putInput(JTable table, int row) { - table.setValueAt("@" + ((ObjectRepDnD) dropObject).getPageName(((ObjectRepDnD) dropObject).getValues().get(0)), row, inputColumn); + String token = ((ObjectRepDnD) dropObject).getPageName(((ObjectRepDnD) dropObject).getValues().get(0)); + table.setValueAt("@" + basePage(token), row, inputColumn); } private void putReusables(JTable table, int row) { @@ -160,4 +174,4 @@ private void putTestData(JTable table, int row) { } testCase.stopGroupEdit(); } -} +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseToolBar.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseToolBar.java index aee20728..3a16cef5 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseToolBar.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/TestCaseToolBar.java @@ -38,6 +38,8 @@ public class TestCaseToolBar extends JToolBar { private JPopupMenu browsersMenu; private ButtonGroup browserSelectButtonGroup; + + private boolean isRecording = false; public TestCaseToolBar(TestCaseComponent testCaseComp) { this.testCaseComp = testCaseComp; @@ -65,11 +67,15 @@ private void init() { addSeparator(); add(consoleButton = Utils.createButton("Console", "console", null, testCaseComp)); - add(record = Utils.createButton("Record", testCaseComp)); + + record = Utils.createButton("Record", testCaseComp); record.setText(null); - record.setToolTipText("Start/Stop Recording"); + record.setToolTipText("Start Recording"); record.setIcon(IconSettings.getIconSettings().getRecordStartIcon()); + record.addActionListener(e -> toggleRecording()); + add(record); + add(runButton = Utils.createButton("Run", "run", "F6", testCaseComp)); add(debugButton = Utils.createButton("Debug", "debug", "Ctrl+F6", testCaseComp)); @@ -186,4 +192,14 @@ void stopMode() { runButton.setActionCommand("StopRun"); runButton.setIcon(Utils.getIconByResourceName("/ui/resources/stop")); } + + void toggleRecording() { + record.setEnabled(false); + } + + public void enableRecordButton() { + record.setEnabled(true); + record.setToolTipText("Start Recording"); + } + } diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ActionRenderer.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ActionRenderer.java index 7842ad29..31fdfd0e 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ActionRenderer.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ActionRenderer.java @@ -2,16 +2,19 @@ import com.ing.datalib.component.Scenario; import com.ing.datalib.component.TestStep; -import com.ing.datalib.or.common.ORPageInf; +import com.ing.datalib.or.web.ResolvedWebObject; +import com.ing.datalib.or.mobile.ResolvedMobileObject; import com.ing.engine.support.methodInf.MethodInfoManager; import com.ing.engine.support.methodInf.ObjectType; + import java.awt.Color; import java.awt.Font; import java.util.Objects; import javax.swing.JComponent; /** - * + * Renderer for the “Action” column of a test step, validating actions and + * reusable-step references while applying appropriate visual feedback in the UI. * */ public class ActionRenderer extends AbstractRenderer { @@ -66,8 +69,7 @@ private Boolean isReusablePresent(TestStep step) { } private String getDesc(Object value) { - String val = MethodInfoManager.getDescriptionFor( - value.toString()); + String val = MethodInfoManager.getDescriptionFor(value.toString()); return val.isEmpty() ? null : val; } @@ -81,49 +83,38 @@ private Boolean isActionValid(TestStep step, Object value) { valid = true; break; case "Browser": - valid = MethodInfoManager.getMethodListFor(ObjectType.BROWSER) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.BROWSER).contains(action); break; case "Mobile": - valid = MethodInfoManager.getMethodListFor(ObjectType.MOBILE) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.MOBILE).contains(action); break; case "Database": - valid = MethodInfoManager.getMethodListFor(ObjectType.DATABASE) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.DATABASE).contains(action); break; case "ProtractorJS": - valid = MethodInfoManager.getMethodListFor(ObjectType.PROTRACTORJS) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.PROTRACTORJS).contains(action); break; case "Webservice": - valid = MethodInfoManager.getMethodListFor(ObjectType.WEBSERVICE) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.WEBSERVICE).contains(action); break; case "File": - valid = MethodInfoManager.getMethodListFor(ObjectType.FILE) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.FILE).contains(action); break; case "Synthetic Data": - valid = MethodInfoManager.getMethodListFor(ObjectType.DATA) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.DATA).contains(action); break; case "Queue": - valid = MethodInfoManager.getMethodListFor(ObjectType.QUEUE) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.QUEUE).contains(action); break; case "Kafka": - valid = MethodInfoManager.getMethodListFor(ObjectType.KAFKA) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.KAFKA).contains(action); break; case "General": - valid = MethodInfoManager.getMethodListFor(ObjectType.GENERAL) - .contains(action); - break; + valid = MethodInfoManager.getMethodListFor(ObjectType.GENERAL).contains(action); + break; case "String Operations": - valid = MethodInfoManager.getMethodListFor(ObjectType.STRINGOPERATIONS) - .contains(action); - break; + valid = MethodInfoManager.getMethodListFor(ObjectType.STRINGOPERATIONS).contains(action); + break; default: if (isWebObject(step)) { valid = MethodInfoManager.getMethodListFor(ObjectType.PLAYWRIGHT, ObjectType.WEB).contains(action); @@ -134,21 +125,33 @@ private Boolean isActionValid(TestStep step, Object value) { } if (!valid) { - valid = MethodInfoManager.getMethodListFor(ObjectType.ANY) - .contains(action); + valid = MethodInfoManager.getMethodListFor(ObjectType.ANY).contains(action); } return valid; } private boolean isWebObject(TestStep step) { - ORPageInf page = step.getProject(). - getObjectRepository().getWebOR().getPageByName(step.getReference()); - return page != null && page.getObjectGroupByName(step.getObject()) != null; + var repo = step.getProject().getObjectRepository(); + String pageToken = step.getReference(); + String objectName = step.getObject(); + + ResolvedWebObject.PageRef ref = ResolvedWebObject.PageRef.parse(pageToken); + ResolvedWebObject r = (ref != null && ref.name != null && ref.scope != null) + ? repo.resolveWebObject(ref, objectName) + : repo.resolveWebObjectWithScope(pageToken, objectName); + return r != null && r.isPresent(); } private boolean isMobileObject(TestStep step) { - ORPageInf page = step.getProject(). - getObjectRepository().getMobileOR().getPageByName(step.getReference()); - return page != null && page.getObjectGroupByName(step.getObject()) != null; + var repo = step.getProject().getObjectRepository(); + String pageToken = step.getReference(); + String objectName = step.getObject(); + + ResolvedMobileObject.PageRef ref = ResolvedMobileObject.PageRef.parse(pageToken); + ResolvedMobileObject r = (ref != null && ref.name != null && ref.scope != null) + ? repo.resolveMobileObject(ref, objectName) + : repo.resolveMobileObjectWithScope(pageToken, objectName); + + return r != null && r.isPresent(); } -} +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ObjectRenderer.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ObjectRenderer.java index f14051fd..28a9768c 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ObjectRenderer.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ObjectRenderer.java @@ -1,18 +1,19 @@ - package com.ing.ide.main.mainui.components.testdesign.testcase.validation; import com.ing.datalib.component.TestStep; +import com.ing.datalib.or.web.ResolvedWebObject; +import com.ing.datalib.or.mobile.ResolvedMobileObject; + import java.awt.Color; import java.awt.Font; -import java.util.Objects; import javax.swing.JComponent; /** + * Renderer responsible for validating and visually marking the “Object” column + * of a test step within the Test Design UI. * - * */ public class ObjectRenderer extends AbstractRenderer { - String objNotPresent = "Object is not present in the Object Repository"; public ObjectRenderer() { @@ -42,28 +43,27 @@ public void render(JComponent comp, TestStep step, Object value) { } } - private Color getColor(Object value) { - String val = Objects.toString(value, "").trim(); - switch (val) { - case "Execute": - return Color.BLUE;//.darker(); - case "Mobile": - return Color.CYAN;//.darker(); - case "Browser": - return Color.RED;//.darker(); - default: - return new Color(204, 0, 255); - } - } - private Boolean isObjectPresent(TestStep step) { - return step.getProject().getObjectRepository() - .isObjectPresent(step.getReference(), step.getObject()); + var repo = step.getProject().getObjectRepository(); + String pageToken = step.getReference(); + String objectName = step.getObject(); + ResolvedWebObject.PageRef wref = ResolvedWebObject.PageRef.parse(pageToken); + if (wref != null && wref.name != null && wref.scope != null) { + if (repo.resolveWebObject(wref, objectName) != null) { + return true; + } + } else if (repo.resolveWebObjectWithScope(pageToken, objectName) != null) { + return true; + } + ResolvedMobileObject.PageRef mref = ResolvedMobileObject.PageRef.parse(pageToken); + if (mref != null && mref.name != null && mref.scope != null) { + return repo.resolveMobileObject(mref, objectName) != null; + } + return repo.resolveMobileObjectWithScope(pageToken, objectName) != null; } private Boolean isValidObject(Object value) { - return Objects.toString(value, "").trim() - .matches("Execute|Mobile|Browser|Database|Webservice|Kafka|Synthetic Data|Queue|File|General|String Operations"); + String v = java.util.Objects.toString(value, "").trim(); + return v.matches("^(Execute|App|Browser|Database|Webservice|Kafka|Synthetic Data|Queue|File|General|String Operations|Mobile)$"); } - -} +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ReferenceRenderer.java b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ReferenceRenderer.java index e72acbbf..50b62ddd 100644 --- a/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ReferenceRenderer.java +++ b/IDE/src/main/java/com/ing/ide/main/mainui/components/testdesign/testcase/validation/ReferenceRenderer.java @@ -1,39 +1,89 @@ - package com.ing.ide.main.mainui.components.testdesign.testcase.validation; import com.ing.datalib.component.TestStep; +import com.ing.datalib.or.web.ResolvedWebObject; +import com.ing.datalib.or.mobile.ResolvedMobileObject; + import java.awt.Color; import java.awt.Font; -import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; import javax.swing.JComponent; /** + * Renderer for the “Reference” column of a test step, responsible for validating + * and decorating page references used in object-based steps. * - * */ public class ReferenceRenderer extends AbstractRenderer { + private static final Set CATEGORY_OBJECTS = Set.of( + "Execute", + "App", + "Browser", + "Mobile", + "Database", + "Webservice", + "Kafka", + "Synthetic Data", + "Queue", + "File", + "General", + "String Operations" + ); + String objNotPresent = "Object is not present in the Object Repository"; public ReferenceRenderer() { - super("Reference Shouldn't be empty, except if Object is one of [Execute,App,Browser]"); + super(buildEmptyRefMessage()); + } + + private static String buildEmptyRefMessage() { + String allowed = CATEGORY_OBJECTS.stream().collect(Collectors.joining(",")); + return "Reference Shouldn't be empty, except if Object is one of [" + allowed + "]"; } @Override public void render(JComponent comp, TestStep step, Object value) { + String ref = step.getReference(); + String decorated = ref; + var repo = step.getProject().getObjectRepository(); + + var wref = ResolvedWebObject.PageRef.parse(ref); + var wres = repo.resolveWebObject(wref, step.getObject()); + + if (wres == null) { + var mref = ResolvedMobileObject.PageRef.parse(ref); + var mres = repo.resolveMobileObject(mref, step.getObject()); + if (mres != null) { + if (mres.isFromShared()) { + decorated = "[Shared] " + mres.getPageName(); + } else if (mres.isFromProject()) { + decorated = "[Project] " + mres.getPageName(); + } + } else { + decorated = ref; + } + } else { + if (wres.isFromShared()) { + decorated = "[Shared] " + wres.getPageName(); + } else if (wres.isFromProject()) { + decorated = "[Project] " + wres.getPageName(); + } + } + + if (comp instanceof javax.swing.JLabel) { + javax.swing.JLabel lbl = (javax.swing.JLabel) comp; + lbl.setText(decorated); + } + if (!step.isCommented()) { if (isEmpty(value)) { - if (isOptional(step)) { - setDefault(comp); - } else { - setEmpty(comp); - } + if (isOptional(step)) setDefault(comp); + else setEmpty(comp); } else if (step.isPageObjectStep()) { - if (isObjectPresent(step)) { - setDefault(comp); - } else { - setNotPresent(comp, objNotPresent); - } + if (isObjectPresent(step)) setDefault(comp); + else setNotPresent(comp, objNotPresent); } else { setDefault(comp); } @@ -43,28 +93,30 @@ public void render(JComponent comp, TestStep step, Object value) { comp.setFont(new Font("Default", Font.ITALIC, 11)); } } - - private Color getColor(Object value) { - String val = Objects.toString(value, "").trim(); - switch (val) { - case "Execute": - return Color.BLUE;//.darker(); - case "Mobile": - return Color.CYAN;//.darker(); - case "Browser": - return Color.RED;//.darker(); - default: - return new Color(204, 0, 255); - } - } private Boolean isOptional(TestStep step) { - return step.getObject().matches("Execute|Mobile|Browser|Database|Webservice|Kafka|Synthetic Data|Queue|File|General|String Operations"); + String obj = String.valueOf(step.getObject()).trim(); + return CATEGORY_OBJECTS.contains(obj); } private Boolean isObjectPresent(TestStep step) { - return step.getProject().getObjectRepository() - .isObjectPresent(step.getReference(), step.getObject()); - } + var repo = step.getProject().getObjectRepository(); + String pageToken = step.getReference(); + String objectName = step.getObject(); + + ResolvedWebObject.PageRef wref = ResolvedWebObject.PageRef.parse(pageToken); + if (wref != null && wref.name != null && wref.scope != null) { + if (repo.resolveWebObject(wref, objectName) != null) { + return true; + } + } else if (repo.resolveWebObjectWithScope(pageToken, objectName) != null) { + return true; + } -} + ResolvedMobileObject.PageRef mref = ResolvedMobileObject.PageRef.parse(pageToken); + if (mref != null && mref.name != null && mref.scope != null) { + return repo.resolveMobileObject(mref, objectName) != null; + } + return repo.resolveMobileObjectWithScope(pageToken, objectName) != null; + } +} \ No newline at end of file diff --git a/IDE/src/main/java/com/ing/ide/main/playwrightrecording/ClipboardMonitor.java b/IDE/src/main/java/com/ing/ide/main/playwrightrecording/ClipboardMonitor.java index 2e21c3ef..a61890c5 100644 --- a/IDE/src/main/java/com/ing/ide/main/playwrightrecording/ClipboardMonitor.java +++ b/IDE/src/main/java/com/ing/ide/main/playwrightrecording/ClipboardMonitor.java @@ -2,10 +2,18 @@ import com.ing.ide.main.mainui.AppMainFrame; import com.ing.ide.util.Notification; -import java.awt.*; -import java.awt.datatransfer.*; -import java.io.*; -import java.nio.file.*; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.Transferable; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.logging.Level; import java.util.logging.Logger; @@ -52,11 +60,14 @@ public void startMonitoring() { Transferable contents = clipboard.getContents(null); if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { String currentContent = (String) contents.getTransferData(DataFlavor.stringFlavor); + String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")); if (!currentContent.equals(lastContent) && !currentContent.trim().isEmpty()) { - lastContent = currentContent; - Path filePath = recordingsDir.resolve("recording.txt"); - Files.writeString(filePath, currentContent, StandardOpenOption.CREATE); - Notification.show("Saved recorded steps to temporary file: " + filePath); + if (currentContent.contains("import com.microsoft.playwright.*;")) { + lastContent = currentContent; + Path filePath = recordingsDir.resolve("recording_" + timestamp + ".txt"); + Files.writeString(filePath, currentContent, StandardOpenOption.CREATE); + Notification.show("Saved recorded steps to temporary file: " + filePath); + } } } Thread.sleep(250); diff --git a/IDE/src/main/java/com/ing/ide/main/ui/NewProject.form b/IDE/src/main/java/com/ing/ide/main/ui/NewProject.form index ce0a6e46..d4f6d930 100644 --- a/IDE/src/main/java/com/ing/ide/main/ui/NewProject.form +++ b/IDE/src/main/java/com/ing/ide/main/ui/NewProject.form @@ -1,6 +1,6 @@ -
    + @@ -31,8 +31,14 @@ - + + + + + + + @@ -48,96 +54,188 @@ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - + - - - - - - - - - - - - - - - - - - - + + + + + + + + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + - - + + + + + + + + + + + + + + + + + + diff --git a/IDE/src/main/java/com/ing/ide/main/ui/NewProject.java b/IDE/src/main/java/com/ing/ide/main/ui/NewProject.java index 878ee982..6d4c0a01 100644 --- a/IDE/src/main/java/com/ing/ide/main/ui/NewProject.java +++ b/IDE/src/main/java/com/ing/ide/main/ui/NewProject.java @@ -53,12 +53,20 @@ private void initComponents() { fileChooser = new javax.swing.JFileChooser(); testDataType = new javax.swing.JComboBox<>(); jLabel5 = new javax.swing.JLabel(); + jPanel3 = new javax.swing.JPanel(); + jPanel1 = new javax.swing.JPanel(); + error = new javax.swing.JLabel(); + jPanel5 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); - jLabel4 = new javax.swing.JLabel(); + jPanel6 = new javax.swing.JPanel(); projName = new javax.swing.JTextField(); + jPanel4 = new javax.swing.JPanel(); + jPanel7 = new javax.swing.JPanel(); + jLabel4 = new javax.swing.JLabel(); + jPanel8 = new javax.swing.JPanel(); projLocation = new javax.swing.JTextField(); + jPanel2 = new javax.swing.JPanel(); createProject = new javax.swing.JButton(); - error = new javax.swing.JLabel(); fileChooser.setDialogTitle("Select Project Location"); fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); @@ -68,12 +76,38 @@ private void initComponents() { jLabel5.setText("Testdata Type"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setTitle("Create new Project"); + setTitle("Create New Project"); + setMinimumSize(new java.awt.Dimension(120, 300)); setModal(true); + setPreferredSize(new java.awt.Dimension(602, 320)); + getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS)); + + jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(20, 20, 20, 20)); + jPanel3.setMinimumSize(new java.awt.Dimension(120, 100)); + jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.Y_AXIS)); + + jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 0, 5, 0)); + jPanel1.setLayout(new java.awt.GridLayout(1, 1)); + + error.setForeground(java.awt.Color.red); + error.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); + error.setText(" "); + jPanel1.add(error); + + jPanel3.add(jPanel1); + + jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 0, 5, 0)); + jPanel5.setLayout(new java.awt.GridLayout()); + jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jLabel3.setText("Project Name"); + jLabel3.setAlignmentX(-0.05F); + jPanel5.add(jLabel3); - jLabel4.setText("Project Location"); + jPanel3.add(jPanel5); + + jPanel6.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 0, 5, 0)); + jPanel6.setLayout(new java.awt.GridLayout()); projName.setText("NewProject"); projName.addActionListener(new java.awt.event.ActionListener() { @@ -81,6 +115,25 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { projNameActionPerformed(evt); } }); + jPanel6.add(projName); + + jPanel3.add(jPanel6); + + getContentPane().add(jPanel3); + + jPanel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(20, 20, 20, 20)); + jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.Y_AXIS)); + + jPanel7.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 0, 5, 0)); + jPanel7.setLayout(new java.awt.GridLayout()); + + jLabel4.setText("Project Location"); + jPanel7.add(jLabel4); + + jPanel4.add(jPanel7); + + jPanel8.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 0, 5, 0)); + jPanel8.setLayout(new java.awt.GridLayout()); projLocation.setEditable(false); projLocation.addActionListener(new java.awt.event.ActionListener() { @@ -88,6 +141,14 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { projLocationActionPerformed(evt); } }); + jPanel8.add(projLocation); + + jPanel4.add(jPanel8); + + getContentPane().add(jPanel4); + + jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(20, 0, 20, 0)); + jPanel2.setLayout(new java.awt.GridBagLayout()); createProject.setText("Create Project"); createProject.addActionListener(new java.awt.event.ActionListener() { @@ -95,48 +156,9 @@ public void actionPerformed(java.awt.event.ActionEvent evt) { createProjectActionPerformed(evt); } }); + jPanel2.add(createProject, new java.awt.GridBagConstraints()); - error.setForeground(java.awt.Color.red); - error.setText(" "); - - javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); - getContentPane().setLayout(layout); - layout.setHorizontalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() - .addGap(16, 16, 16) - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) - .addComponent(projName) - .addComponent(projLocation)) - .addGap(59, 59, 59)) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() - .addGap(217, 217, 217) - .addComponent(createProject) - .addGap(180, 180, 180)) - .addGroup(layout.createSequentialGroup() - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(error) - .addComponent(jLabel4) - .addComponent(jLabel3)) - .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - ); - layout.setVerticalGroup( - layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() - .addGap(12, 12, 12) - .addComponent(error) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(jLabel3) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) - .addComponent(projName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addGap(18, 18, 18) - .addComponent(jLabel4) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(projLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addGap(36, 36, 36) - .addComponent(createProject) - .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) - ); + getContentPane().add(jPanel2); pack(); }// //GEN-END:initComponents @@ -193,6 +215,14 @@ private void createProject(String location) { private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JPanel jPanel3; + private javax.swing.JPanel jPanel4; + private javax.swing.JPanel jPanel5; + private javax.swing.JPanel jPanel6; + private javax.swing.JPanel jPanel7; + private javax.swing.JPanel jPanel8; private javax.swing.JTextField projLocation; private javax.swing.JTextField projName; private javax.swing.JComboBox testDataType; diff --git a/README.md b/README.md index 6f78432a..4fc24f2e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # INGenious Playwright Studio - Test Automation for Everyone [![Build INGenious Source Code](https://github.com/ing-bank/INGenious/actions/workflows/maven.yml/badge.svg)](https://github.com/ing-bank/INGenious/actions/workflows/maven.yml) -![Static Badge](https://img.shields.io/badge/Version-2.3.1-%23FF6200) +![Static Badge](https://img.shields.io/badge/Version-2.4-%23FF6200) -------------------------------------------------------------------- diff --git a/Resources/Configuration/PageDump/DumpResources/js/jquery-3.4.1.min.js b/Resources/Configuration/PageDump/DumpResources/js/jquery-3.4.1.min.js deleted file mode 100644 index 07c00cd2..00000000 --- a/Resources/Configuration/PageDump/DumpResources/js/jquery-3.4.1.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
    ",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="
    ",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="
    a",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="
    t
    ",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="
    ",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t -}({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/\s*$/g,At={option:[1,""],legend:[1,"
    ","
    "],area:[1,"",""],param:[1,"",""],thead:[1,"","
    "],tr:[2,"","
    "],col:[2,"","
    "],td:[3,"","
    "],_default:x.support.htmlSerialize?[0,"",""]:[1,"X
    ","
    "]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?""!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); -u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("