Ok I read all the other links, and i tried variants of the different solutions mentioned, however none of them work for me.
My Issue, I have the following Code:
package com.autotest.test.css;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import com.google.common.base.Predicate;
import java.util.concurrent.TimeUnit;
import cucumber.annotation.*;
import cucumber.annotation.en.*;
import static org.junit.Assert.assertEquals;
public class SaleStepsPre {
private WebDriver driver;
private String baseUrl;
#Before
public void setUp() {
System.setProperty("webdriver.chrome.driver", "/Users/AppData/Local/Google/Chrome/Application/chromedriver.exe");
driver = new ChromeDriver();
baseUrl = "http://xxxxx";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Given("^I navigate to the css application$")
public void I_navigate_to_the_css_application() {
driver.get(baseUrl + "/care/a#brochureware-home");
}
#When("^I select the prepaid catalog$")
public void I_select_the_prepaid_catalog() {
driver.findElement(By.xpath("//div[#id='brochureware-home']/div/div/div/div[2]/div[2]/div/div")).click();
}
#When("^I select the add to basket for product$")
public void I_select_the_add_to_basket_for_product() {
driver.findElement(By.xpath("//*[#id='salesItem']/div[1]/div[1]/div/div[5]/div[1]/button")).click();
}
#When("^then I Click on the basket icon to go to basket$")
public void then_I_Click_on_the_basket_icon_to_go_to_basket() {
// times out after 5 seconds
// while the following loop runs, the DOM changes -
// page is refreshed, or element is removed and re-added
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//WebElement searchBox;
//searchBox = driver.findElement(By.xpath("//input[#type='text']"));
//driver.findElement(By.xpath("html/body/div[2]/div[1]/nav/div[1]/div[3]/div[2]/div/ul[1]/li[5]/a/img")).click();
driver.findElement(By.cssSelector("c-menuimage")).click();
}
//#When("^then I click on the checkout button$")
//public void then_I_click_on_the_checkout_button() {
//driver.findElement(By.xpath("(//button[#type='button'])[9]")).click();
//}
#Then("^show product y$")
public void show_product_y() {
}
}
However I get following error:
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
B
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
This is the css path of basket icon, which is on a menu.
body > div:nth-child(3) > div:nth-child(1) > nav > div.container-fluid.c-wide > div.c-kill > div.collapse.navbar-collapse.c-2ndmenu > div > ul.nav.navbar-nav.navbar-left > li:nth-child(5) > a > img
The website is GWT, and the steps are:
1. Click on item add to basket
2. Adds to basket
3. Click on basket to go to basket.
However I cant seem to get this right.
I had problems, that the implicit wait only works for real page reloads, when the page is dynamicaly reloaded (like ajax) , then this will fail.
You can try expected conditions to wait for for items, they are nice and easy to use and robust. You can configure them to ignore certain exceptions,
so you can try to locate an element for a given time and then fail. This works even with ajax
In my case i have a small method like (it ignored the NoSuchElement exception):
protected <T> T waitForPageToLoad(ExpectedCondition<T> condition, String errorMessage) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(MAX_WAITING_TIME, SECONDS).ignoring(StaleElementReferenceException.class).ignoring(NoSuchElementException.class).pollingEvery(100, MILLISECONDS).withMessage(errorMessage);
T result = wait.until(condition);
return result;
}
MAX_WAITING_TIME is the time until this method throws an exception
Then you can use this with an expected condition like this:
public static final ExpectedCondition<Boolean> WAIT_FOR_BASKET = ExpectedConditions.visibilityOfElementLocated(By.cssSelector("c-menuimage"));
I have plenty of them in a utility class so they are static. you can do it like you want.
The full usage looks like:
WebElement elem = waitForPageToLoad(waitForPageToLoad);
elem.click();
This solution is originated here at stack overflow but i cant find the original question/answer, so kudos to the real guy who posted this
Related
Good Morning
I'm currently doing a plugIn for ImageJ in JAVA that needs to call the function "Maximum Intensity Z-projection", which I know that is already in ImageJ if you go for "Image/Stacks/Z Project...". Documentation here: http://imagej.net/Z-functions#Maximum_Intensity_Z-projection
I know how to call plugins from another plugins, but doing the same thing in this case I get all the time my "Error" message.
public class Maximum_Intensity implements PlugIn{
ImagePlus img = WindowManager.getCurrentImage();
#Override
public void run(String arg0) {
// TODO Auto-generated method stub
Object ZProjector = null;
ZProjector = IJ.runPlugIn(img, "ZProjector", arg0);
if(ZProjector==null){
String arg = "Error";
IJ.showMessage(arg);
}
}
}
How can I do it? Thank you so much.
You can easily use the macro recorder for help to record all commands in ImageJ, see:
https://imagej.nih.gov/ij/docs/guide/146-31.html#sub:Record...
Enable Java for the recorder and then use the "Create" action to create an ImageJ plugin from the recorded interface actions.
In the following example (created with the Recorder) I applied the Max. Intensity function on a stack.
import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.*;
public class My_Plugin implements PlugIn {
public void run(String arg) {
ImagePlus imp = IJ.openImage("http://imagej.nih.gov/ij/images/mri-stack.zip");
IJ.run(imp, "Z Project...", "projection=[Max Intensity]");
imp.show();
}
}
The ZProjector class description can be found here (for instantiation):
https://imagej.nih.gov/ij/developer/api/ij/plugin/ZProjector.html
How to replace sling:resourceType value in bulk using Query and Scipt.
For example I want to change sling:resourceType value
from app/component/linkButton to app/component/content/linkbutton1.
The component is being used on 20 pages, and I want change it using query rather than manually on each page.
the best choice for the purpose is groovy console .
Bellow script which do the job:
import javax.jcr.Node
getNode('/content/').recurse { resourceNode ->
if (resourceNode.hasProperty('sling:resourceType')) {
final def resourceType = resourceNode.getProperty('sling:resourceType').string
if (resourceType.equals('OLD_RESOURCE_TYPE')) {
println "changing " + resourceNode.path
resourceNode.setProperty('sling:resourceType', 'NEW_RESOURCE_TYPE')
resourceNode.save();
}
}
}
You can use the ACS AEM Tools open source project which includes AEM Fiddle. AEM Fiddle allows you to run scripts directly on the AEM instance without have to build.
If you use AEM Fiddle, navigate to http://localhost:4502/miscadmin#/etc/acs-tools/aem-fiddle, click the plus sign in the top right and select .java. Insert this code and run. Make sure you update the query's path.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.jcr.query.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
public class fiddle extends SlingAllMethodsServlet {
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
ResourceResolver resolver = null;
out.println("starting...");
try {
resolver = request.getResourceResolver();
if (resolver != null) {
Iterator<Resource> resources = resolver.findResources("/jcr:root/content/mysite//*[#sling:resourceType='app/component/linkButton']", Query.XPATH);
while (resources.hasNext()) {
Resource resource = resources.next();
ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
properties.put("sling:resourceType", "app/component/linkButton1");
resolver.commit();
out.println(resource.getPath());
}
}
} catch(Exception e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace(out);
} finally {
if (resolver != null && resolver.isLive()) {
resolver.close();
resolver = null;
}
}
out.println("...finished");
}
}
If you'd rather use JSP as you've stated, the code is the same:
<%#include file="/libs/foundation/global.jsp"%><%
%><%#page session="false" contentType="text/html; charset=utf-8"
pageEncoding="UTF-8"
import="org.apache.sling.api.resource.*,
java.util.*,
javax.jcr.*,
com.day.cq.search.*,
com.day.cq.wcm.api.*,
com.day.cq.dam.api.*,
javax.jcr.query.Query,
org.apache.sling.api.resource.ModifiableValueMap"%><%
Iterator<Resource> resources = resourceResolver.findResources("/jcr:root/content/mysite//*[#sling:resourceType='app/component/linkButton']", Query.XPATH);
while (resources.hasNext()) {
Resource current = resources.next();
ModifiableValueMap props = current.adaptTo(ModifiableValueMap.class);
props.put("sling:resourceType", "app/component/linkButton1");
resourceResolver.commit();
%>
<%=current.getPath()%>
<%
}
%>
Another dirty method, but worked for me. :)
Package the path and download the zip file.
Extract to a folder.
Based on your operating system,
If using Windows, use Notepad++ to find an replace in all files under directory with your search pattern.
If linux, use find or sed commands to replace all occurrences inside a director
How about AEM ACS TOOLS?
It is bulk updating tool for sling:resourceType or cq:Template.
Click here for the article on Getting Started
Click here for the Github Repo
Good Luck...
You can also have a look at sling pipes.
https://sling.apache.org/documentation/bundles/sling-pipes.html
this is the perfect solution for your problem
I implemented workflows, but it would be nice to know if there are hooks provided by the client library which allow to hook in. When a workflow was triggered and finished, a CQ.Notification should be displayed. Or do i need to implement a polling library by myself?
As far as I know, there is no built-in CQ area to see when something is done, aside from looking here:
http://yoursite.com:port/libs/cq/workflow/content/console.html
Once there, you can go to the 'Instances' tab and see what's happening.
In one application that I worked on, we ended up writing our own method that sends notifications to us based on one of our workflows (our workflow ties into it - from the workflow models area, you can set your process to be a servlet that you've put into CQ). Here is the main piece of code from our servlet that catches the process being active, and then calls our methods to email us based on what it finds:
import com.day.cq.workflow.WorkflowException;
import com.day.cq.workflow.WorkflowSession;
import com.day.cq.workflow.exec.WorkItem;
import com.day.cq.workflow.exec.WorkflowData;
import com.day.cq.workflow.exec.WorkflowProcess;
import com.day.cq.workflow.metadata.MetaDataMap;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import java.util.Arrays;
public class YourServletName implements WorkflowProcess {
#Override
public void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap args) throws WorkflowException {
session = workflowSession.getSession();
final WorkflowData data = workItem.getWorkflowData();
String type = data.getPayloadType();
String[] argStrings = args.get("PROCESS_ARGS", ARG_UPDATED).split(",");
String reason = argStrings[0];
String baseUrl = argStrings[1];
try {
if (type.equals(TYPE_JCR_PATH) && data.getPayload() != null) {
String resourcePath = data.getPayload().toString();
logger.info("Send Notification that {} has been {}.", resourcePath, reason.toLowerCase());
if (resourcePath != null && !resourcePath.isEmpty()) {
ResourceInfo resourceInfo = new ResourceInfo(resourcePath, baseUrl);
sendEmail(resourceInfo, reason);
}
}
} catch (EmailException ex) {
logger.warn("Failed to send Email");
throw new WorkflowException(ex);
} catch (MailingException ex) {
logger.warn("Failed to send Email");
throw new WorkflowException(ex);
}
}
}
You can find more info in the documentation for Extending Workflow Functionality.
Look at the first code block on that page, and that will give you the best idea of how you can implement a custom workflow handler.
EDIT
If you want to see it on the front-end, you could do an AJAX call to get the JSON list of currently running workflows - you can hit this url:
http://localhost:4502/etc/workflow/instances.RUNNING.json
Then you could loop through them and see if yours is in there. This isn't very nice though, since they are all just listed by IDs. I would instead suggest using the querybuilder, or again, just doing an AJAX GET. This is one example:
1_group.0_path=/etc/workflow/instances
2_group.0_type=cq:Workflow
0_group.property.2_value=COMPLETED
0_group.property=status
0_group.property.and=true
3_group.property=modelId
3_group.property.2_value=/etc/workflow/models/your-model-name/jcr:content/model
3_group.property.and=true
Then the URL would look something like this:
http://yoursiteurl:port/libs/cq/search/content/querydebug.html?_charset_=UTF-8&query=http%3A%2F%2Fyoursiteurl%3Aport%3F%0D%0A1_group.0_path%3D%2Fetc%2Fworkflow%2Finstances%0D%0A2_group.0_type%3Dcq%3AWorkflow%0D%0A0_group.property.2_value%3DRUNNING%0D%0A0_group.property%3Dstatus%0D%0A0_group.property.and%3Dtrue%0D%0A3_group.property%3DmodelId%0D%0A3_group.property.2_value%3D%2Fetc%2Fworkflow%2Fmodels%2Fyour-model-name%2Fjcr%3Acontent%2Fmodel%0D%0A3_group.property.and%3Dtrue
It's ugly, but it gets you the results you need, and then you can parse them to get further information you need.
My aim is to extend the eclipse QuickFix component and automate the process of solving syntax errors. Basically, the QuickFix component provides a list of solutions and my task is to select the best possible fix and apply it to the buggy code. But, for now I've been requested to print the resolutions for a marker in the console. I've tried to work out a tutorial and I'm kind of stuck right now. The tutorial I've tried to workout is: http://www.informit.com/articles/article.aspx?p=370625&seqNum=21
I've first added the extension in my plugin.xml file
<extension point="org.eclipse.ui.ide.markerResolution">
<markerResolutionGenerator
markerType="org.eclipse.core.resources.problemmarker"
class="org.eclipse.escript.quickfix.QuickFixer"/>
</extension>
Then i have created the two classes QuickFixer and QuickFix.
package quickfixer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.IMarkerResolutionGenerator;
class QuickFixer implements IMarkerResolutionGenerator {
public IMarkerResolution[] getResolutions(IMarker arg0) {
try {
Object problem = arg0.getAttribute("Whatsup");
return new IMarkerResolution[] {
new QuickFix("Fix #1 for "+problem),
new QuickFix("Fix #2 for "+problem),
};
} catch(CoreException e) {
return new IMarkerResolution[0];
}
}
}
then the class QuickFix:
package quickfixer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IMarkerResolution;
public class QuickFix implements IMarkerResolution {
String label;
QuickFix(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void run(IMarker arg0) {
MessageDialog.openInformation(null, "QuickFix Demo",
"This quick-fix is not yet implemented");
System.out.println("Label: " + label);
}
}
I've managed to correct all the errors i encountered and then i have run the plugin.
I have not been able to get the label printed out in the console.Any suggestions???...
Using System.out is not a good idea. Check the relevant FAQ on why
you should avoid using standard output or standard error in your
plug-in
and use proper logging (or the debugger).
I have an Output tab created and I would like to listen for user's input (to do a chat like component). Of course you can't predict when the user is going to type.
I found the org.jivesoftware.smack.util package and the related ObservableReader and ReaderListener that should do the trick, but I'm missing something and can't figure it out... yet.
Here's the code I have:
/*
* Enable/create the tabs we need for the component
*/
package sample.component;
import com.dreamer.outputhandler.OutputHandler;
import org.jivesoftware.smack.util.ObservableReader;
import org.jivesoftware.smack.util.ReaderListener;
import org.openide.modules.ModuleInstall;
/**
* Manages a module's lifecycle. Remember that an installer is optional and
* often not needed at all.
*/
public class Installer extends ModuleInstall implements ReaderListener {
private final String normal = "Output";
#Override
public void restored() {
OutputHandler.output(normal, "Welcome! Type something below.");
OutputHandler.setInputEnabled(normal, true);
ObservableReader reader = new ObservableReader(OutputHandler.getReader(normal));
reader.addReaderListener(this);
}
#Override
public void read(String read) {
System.out.println("Read: " + read);
OutputHandler.output(normal, "You typed: " + read);
}
}
OutPutHandler is a helper class I created to handle the output tabs. You can see its source here
Any idea?
Finally got it! It was a mix of the above code with this forum post and this classes: org.jivesoftware.smack.util.ObservableReader and org.jivesoftware.smack.util.ReaderListener. See the FAQ here