Pending steps with jbehave - selenium

I am getting pending steps for jbehave stories and please find the configuration details below: All the story steps are correct to my knowledge.I am not getting where i am going wrong in configuration. Could you please help me.
build.gradle:
def buildNumber = System.getProperty('buildNumber') ?: '0'
def buildVersion = '1.0.0-' + buildNumber
version = buildVersion
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'maven'
repositories {
maven { url 'http://repo1.maven.org/maven2/' }
maven { url 'https://mvnrepository.com/' }
maven {url 'https://mvnrepository.com/artifact/org.jbehave'}
mavenCentral()
}
dependencies {
compile 'com.google.guava:guava:18.0'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.8.1'
compile group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.1.0'
testCompile group: 'junit', name: 'junit', version: '4.11'
compile 'org.codehaus.groovy:groovy-all:2.3.11'
compile('org.springframework:spring-core:4.0.5.RELEASE') {
exclude(module: 'commons-logging')
}
compile(group: 'org.jbehave.web', name: 'jbehave-web-selenium', version: '4.0-beta-1') {
exclude(module: 'selenium-remote-control')
exclude(module: 'selenium-java')
exclude(module: 'jbehave-core')
}
compile 'javax.servlet:javax.servlet-api:3.0.1'
compile 'org.springframework:spring-webmvc:4.0.5.RELEASE'
compile 'org.springframework:spring-jdbc:4.0.5.RELEASE'
compile 'org.springframework:spring-test:4.0.5.RELEASE'
compile 'io.springfox:springfox-spring-web:2.2.2'
compile 'io.springfox:springfox-swagger-ui:2.2.2'
compile 'io.springfox:springfox-swagger2:2.2.2'
compile 'com.googlecode.json-simple:json-simple:1.1.1'
compile 'org.jbehave.site:jbehave-site-resources:3.1.1'
compile 'org.jbehave:jbehave-spring:3.9.3'
compile 'org.jbehave:jbehave-core:4.1.3'
compile 'commons-dbcp:commons-dbcp:1.2.2'
compile 'org.slf4j:slf4j-api:1.7.6'
compile 'com.jcraft:jsch:0.1.53'
compile 'org.json:json:20140107'
compile 'log4j:log4j:1.2.11'
compile 'org.assertj:assertj-core:2.3.0'
compile group: 'commons-io', name: 'commons-io', version: '2.5'
// https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-chrome-driver
compile group: 'org.seleniumhq.selenium', name: 'selenium-chrome-driver', version: '2.33.0'
compile group: 'org.seleniumhq.selenium', name: 'selenium-server', version: '3.7.1'
// https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.7.1'
compile group: 'org.picocontainer', name: 'picocontainer', version: '2.15'
compile group: 'joda-time', name: 'joda-time', version: '2.8.1'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
compile group: 'org.apache.httpcomponents', name: 'httpclient', version:'4.3.1'
compile group: 'org.codehaus.plexus', name: 'plexus-utils', version:'3.0.22'
compile group: 'commons-lang', name: 'commons-lang', version: '2.3'
// testCompile 'org.jbehave:jbehave-core:3.9.3'
compile 'org.jbehave.site:jbehave-site-resources:3.1.1:#zip'
}
sourceSets.test.resources.srcDir 'src/test/java'
/** userDefined task to copy the srories from /src/main/stories into build/classes/test/stories*/
task copyStories(type: Copy) {
from 'src/main/resources' into "${buildDir}/classes/test"
from 'src/main/stories' into "${buildDir}/classes/test/stories"
}
sourceSets {
test {
java {
srcDir "src/main/java"
}
resources {
srcDir "src/main/resources"
}
}
}
/* This is to copy the system properties from gradle available to Junit test classes*/
test {
systemProperty "metaFilters", System.getProperty("metaFilters", "")
doFirst {
copy {
from(zipTree(jarPath("jbehave-core"))) {
include "style/*"
}
into("build/reports/jbehave/view")
}
copy {
from(zipTree(jarPath("jbehave-site-resources"))) {
include "js/**/*"
include "style/**/*"
include "images/*"
}
into("build/reports/jbehave/view")
}
}
systemProperties System.getProperties()
dependsOn([clean,copyStories])
}
def jarPath(String jarName) {
configurations.testCompile.find({ it.name.startsWith(jarName) }).absolutePath
}
Jbheave extending junitstories class as
public class JbehaveStories extends JUnitStories{
private static final String _STORIES_SEPARATOR = ",";
public static HtmlOutput qmoHtmlOutput;
public static StoryData storyData;
public static List<String> storyToExecute = null;
static CrossReference crossReference = new CrossReference().withJsonOnly().withOutputAfterEachStory(true);
Logger logger = Logger.getLogger(JbehaveStories.class);
Logger log = Logger.getLogger(JbehaveStories.class);
ContextView contextView = new LocalFrameContextView().sized(640, 120);
SeleniumContext seleniumContext = new SeleniumContext();
private org.jbehave.web.selenium.WebDriverProvider driverProvider = new org.jbehave.web.selenium.PropertyWebDriverProvider();
private WebDriverSteps lifecycleSteps = new PerStoriesWebDriverSteps(driverProvider);
// SeleniumStepMonitor stepMonitor = new SeleniumStepMonitor(contextView, seleniumContext,crossReference.getStepMonitor());
Format[] formats = new Format[]{new SeleniumContextOutput(seleniumContext), CONSOLE, XML, HTML};
StoryReporterBuilder reporterBuilder = new StoryReporterBuilder(storyData)
.withCodeLocation(codeLocationFromClass(WebJbehaveStories.class)).withFailureTrace(true)
.withFailureTraceCompression(true).withDefaultFormats().withFormats(formats)
.withCrossReference(crossReference);
private ApplicationContext applicationContext;
public WebJbehaveStories() {
super();
try {
System.setProperty("webdriver.chrome.driver", "src/main/resources/drivers/chromedriver.exe");
storyData = new StoryData();
// String path = BNSFWebJbehaveStories.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "stories/log4j.properties";
// PropertyConfigurator.configure(path);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Configuration configuration() {
new WebDriverScreenshotOnFailure(driverProvider, new StoryReporterBuilder());
Class<? extends Embeddable> embeddableClass = this.getClass();
ParameterConverters parameterConverters = new ParameterConverters();
LoadFromClasspath resourceLoader = new LoadFromClasspath(embeddableClass);
TableTransformers tableTranformers = new TableTransformers();
ExamplesTableFactory examplesTableFactory = new ExamplesTableFactory(new LocalizedKeywords(), resourceLoader,
parameterConverters, tableTranformers);
parameterConverters.addConverters(new ParameterConverters.DateConverter(new SimpleDateFormat("yyyy-MM-dd")),
new ParameterConverters.ExamplesTableConverter(examplesTableFactory));
return new SeleniumConfiguration().useSeleniumContext(seleniumContext)
.usePendingStepStrategy(new FailingUponPendingStep())
.useStoryControls(new StoryControls().doResetStateBeforeScenario(true))
.useStoryLoader(new LoadFromClasspath(WebJbehaveStories.class))
.useStoryReporterBuilder(new StoryReporterBuilder())
.useStoryParser(new RegexStoryParser(examplesTableFactory))
.useStoryReporterBuilder(new StoryReporterBuilder(storyData)
.withCodeLocation(CodeLocations.codeLocationFromPath(getClassPath()))
.withCrossReference(crossReference)
.withFormats(Format.CONSOLE, Format.HTML, XML))
.useParameterControls(new ParameterControls()
.useDelimiterNamedParameters(true))
.useParameterConverters(parameterConverters)
.useStepPatternParser(new RegexPrefixCapturingPatternParser()).doDryRun(true);
}
private List<String> getMetaFilters() {
String metaFilterStr = System.getProperty("meta.filter");
metaFilterStr = metaFilterStr == null ? "" : metaFilterStr;
List<String> metaFilters = Arrays.asList(metaFilterStr.split(","));
log.info("**** MetaFilters = " + metaFilters);
return metaFilters;
}
private String getClassPath() {
URL fileUrl = codeLocationFromClass(this.getClass());
String classpath = getPathFromURL(fileUrl);
System.out.println("getClassPath classpath = " + classpath);
// class may come from a jar file
if (classpath.endsWith(".jar!")) {
int idx = classpath.lastIndexOf('.');
classpath = classpath.substring(0, idx);
}
return classpath;
}
#Override
public InjectableStepsFactory stepsFactory() {
if (this.applicationContext == null) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(WebJbehaveStories.class);
this.applicationContext = applicationContext;
}
return new SpringStepsFactory(configuration(), this.applicationContext);
}
#Override
public void run() throws Throwable {
Embedder embedder = configuredEmbedder();
embedder.embedderControls().useStoryTimeoutInSecs(450000);
embedder.useMetaFilters(getMetaFilters());
// These should be enabled so that even though the stories fail it wont go to catch method. Its useful when running multiple scenarios
embedder.embedderControls().doIgnoreFailureInStories(true);
embedder.embedderControls().doIgnoreFailureInView(false);
embedder.embedderControls().doGenerateViewAfterStories(true);
embedder.configuration().storyControls().doIgnoreMetaFiltersIfGivenStory(true);
List<String> storyPaths = storyPaths();
try {
embedder.runStoriesAsPaths(storyPaths);
} catch (Exception e) {
e.printStackTrace();
Loggers.CONSOLE_LOGGER.error("STORY FAILED DUE TO:");
e.printStackTrace(System.err);
Loggers.FILE_LOGGER.error("STORY FAILED DUE TO:");
e.printStackTrace(System.err);
Loggers.CONSOLE_LOGGER.info("Driver instance is closing");
Loggers.FILE_LOGGER.info("Driver instance is closing");
embedder.generateCrossReference();
throw new Throwable(e.fillInStackTrace());
} finally {
try {
Loggers.CONSOLE_LOGGER.info("Driver instance is closing");
driver.quit();
Loggers.FILE_LOGGER.info("Driver instance is closing");
} catch (Exception e) {
System.out.println("Issue in closing driver instance in run method: " + e.getMessage());// Wantedly not caught the exception
}
embedder.generateCrossReference();
}
}
public String getStoryFromStoryPaths(String storyName, List<String> storyPaths) {
for (String story : storyPaths) {
System.out.println("story = " + story);
int stroryLength = story.split("/").length;
if (story.split("/")[stroryLength - 1].equalsIgnoreCase(storyName)) return story;
}
return "";
}
#Override
protected List<String> storyPaths() {
final List<String> globList = new ArrayList<String>();
final String[] globs = storyFilter().split(_STORIES_SEPARATOR);
for (final String story : globs) {
globList.add("**/*" + story + (story.endsWith(".story") ? "" : ".story"));
}
log.info("******************************************************************************");
log.info("**** globList = " + globList);
log.info("******************************************************************************");
String classpath = getClassPath();
log.info("classpath=" + classpath);
List<String> paths = new StoryFinder().findPaths(classpath, globList, null);
log.info("**** story paths = " + paths.toString());
return paths;
}
private String storyFilter() {
String storyFilter = System.getProperty("story.filter");
if (storyFilter == null) {
storyFilter = "";
}
return storyFilter;
}
public String captureReportName() {
String storyName = null;
String fileNames[] = reporterBuilder.outputDirectory().list();
for (int i = 0; i < fileNames.length; i++) {
if (fileNames[i].contains("html") & !fileNames[i].contains("BeforeStories")) {
String name[] = fileNames[i].split(".html");
storyName = name[0];
}
}
return storyName;
}
}
The error i am getting is as follows:
(stories/HomePage.story)
Narrative:
As a user
I want to perform an action
So that I can achieve a business goal
Scenario: scenario description
Given I enter login details (PENDING)
#Given("I enter login details")
#Pending
public void givenIEnterLoginDetails() {
// PENDING
}
Failed to run story stories/HomePage.story
org.jbehave.core.failures.PendingStepsFound: [Given I enter login details]
HomePage.story
Meta:
Narrative:
As a user
I want to perform an action
So that I can achieve a business goal
Scenario: scenario description
Given I enter login details
public class HomePageSteps {
#Autowired HomePage homePage;
#When("I enter login details")
public void enter() {
try {
homePage.enterLoginDetails();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
#Given("I enter login details")
public void enterx() {
try {
homePage.enterLoginDetails();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}

Related

How to write Unit Test for Hybris DAO Implementation

I am new with unit test and I am trying to test this method, but it did not manage to capture the query of the method, I only managed to get it to enter an exception but not to take the query and return it.
Is there a way to return "result.getResult().get(0)" in the unit test?
Thanks
#Override
public HouseModel findByCode(String code) {
var sQuery = "SELECT {h:pk} FROM {House as h} WHERE {h:id} = ?id ";
var query = new FlexibleSearchQuery(sQuery);
query.addQueryParameter("id", Objects.requireNonNullElse(code, ""));
SearchResult<HouseModel> result = flexibleSearchService.search(query);
return result.getResult().get(0);
}
Code Test:
#Test
public void testFindByCode() {
when(flexibleSearchService.search((FlexibleSearchQuery) any())).thenThrow(new RuntimeException("test"));
RuntimeException exception = new RuntimeException();
try {
var result2 = houseDAOImpl.findByCode("testcode");
} catch (RuntimeException e) {
e.printStackTrace();
exception = e;
}
boolean shouldtrue = exception.getMessage().equalsIgnoreCase("test");
System.out.println(exception.getMessage());
System.out.println(shouldtrue);
assertTrue(shouldtrue);
}
Hybris supports TransactionTest incase of interaction with db.
public class HouseDAOImpTest extends HybrisJUnit4TransactionalTest
{
private TypeService typeService;
private ModelService modelService;
private DeeplinkUrlDao dao;
private List<HouseModel> createdRules;
/**
* #throws java.lang.Exception
*/
#Before
public void setUp() throws Exception
{
createdRules = createHouses();
houseDAOImpl = (HouseFinderDao) Registry.getApplicationContext().getBean("houseFinderDao");
}
#Test
public void testFindByCode()
{
final HouseModel hm = houseDAOImpl.findByCode("testcode");
assertThat(hm.getCode(), is(equalTo(""testcode""));
}
private ModelService getModelService()
{
if (modelService == null)
{
modelService = (ModelService) Registry.getApplicationContext().getBean("modelService");
}
return modelService;
}
private TypeService getTypeService()
{
if (typeService == null)
{
typeService = (TypeService) Registry.getApplicationContext().getBean("typeService");
}
return typeService;
}
/**
* Creates the Houses.
*/
private List<HouseModel> createHouses()
{
final List<HouseModel> result = new ArrayList<HouseModel>();
final HouseModel houseModel1 = getModelService().create(HouseModel.class);
houseModel.setCode("testcode");
modelService.save(houseModel1);
// create other houses model and follow previous steps
result.add(houseModel1);
result.add(houseModel2);
result.add(houseModel3);
return result;
}
}

org.apache.fop.fo.flow.ExternalGraphic catches and logs ImageException I want to handle myself

I am transforming an Image into pdf for test purposes.
To ensure that the Image is compatible with the printing process later on, I'm running a quick test print during the upload.
I'm creating a simple Test-PDF with a transformer. When I try to print an image with an incompatible format, the ImageManager of the transformer throws an ImageException, starting in the preloadImage() function:
public ImageInfo preloadImage(String uri, Source src)
throws ImageException, IOException {
Iterator iter = registry.getPreloaderIterator();
while (iter.hasNext()) {
ImagePreloader preloader = (ImagePreloader)iter.next();
ImageInfo info = preloader.preloadImage(uri, src, imageContext);
if (info != null) {
return info;
}
}
throw new ImageException("The file format is not supported. No ImagePreloader found for "
+ uri);
}
throwing it to:
public ImageInfo needImageInfo(String uri, ImageSessionContext session, ImageManager manager)
throws ImageException, IOException {
//Fetch unique version of the URI and use it for synchronization so we have some sort of
//"row-level" locking instead of "table-level" locking (to use a database analogy).
//The fine locking strategy is necessary since preloading an image is a potentially long
//operation.
if (isInvalidURI(uri)) {
throw new FileNotFoundException("Image not found: " + uri);
}
String lockURI = uri.intern();
synchronized (lockURI) {
ImageInfo info = getImageInfo(uri);
if (info == null) {
try {
Source src = session.needSource(uri);
if (src == null) {
registerInvalidURI(uri);
throw new FileNotFoundException("Image not found: " + uri);
}
info = manager.preloadImage(uri, src);
session.returnSource(uri, src);
} catch (IOException ioe) {
registerInvalidURI(uri);
throw ioe;
} catch (ImageException e) {
registerInvalidURI(uri);
throw e;
}
putImageInfo(info);
}
return info;
}
}
throwing it to :
public ImageInfo getImageInfo(String uri, ImageSessionContext session)
throws ImageException, IOException {
if (getCache() != null) {
return getCache().needImageInfo(uri, session, this);
} else {
return preloadImage(uri, session);
}
}
Finally it gets caught and logged in the ExternalGraphic.class:
/** {#inheritDoc} */
public void bind(PropertyList pList) throws FOPException {
super.bind(pList);
src = pList.get(PR_SRC).getString();
//Additional processing: obtain the image's intrinsic size and baseline information
url = URISpecification.getURL(src);
FOUserAgent userAgent = getUserAgent();
ImageManager manager = userAgent.getFactory().getImageManager();
ImageInfo info = null;
try {
info = manager.getImageInfo(url, userAgent.getImageSessionContext());
} catch (ImageException e) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageError(this, url, e, getLocator());
} catch (FileNotFoundException fnfe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageNotFound(this, url, fnfe, getLocator());
} catch (IOException ioe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageIOError(this, url, ioe, getLocator());
}
if (info != null) {
this.intrinsicWidth = info.getSize().getWidthMpt();
this.intrinsicHeight = info.getSize().getHeightMpt();
int baseline = info.getSize().getBaselinePositionFromBottom();
if (baseline != 0) {
this.intrinsicAlignmentAdjust
= FixedLength.getInstance(-baseline);
}
}
}
That way it isn't accessible for me in my code that uses the transformer.
I tried to use a custom ErrorListener, but the transformer only registers fatalErrors to the ErrorListener.
Is there any way to access the Exception and handle it myself without changing the code of the library?
It was easier than I thought. Before I call the transformation I register a costum EventListener to the User Agent of the Fop I'm using. This Listener just stores the Information what kind of Event was triggered, so I can throw an Exception if it's an ImageError.
My Listener:
import org.apache.fop.events.Event;
import org.apache.fop.events.EventListener;
public class ImageErrorListener implements EventListener
{
private String eventKey = "";
private boolean imageError = false;
#Override
public void processEvent(Event event)
{
eventKey = event.getEventKey();
if(eventKey.equals("imageError")) {
imageError = true;
}
}
public String getEventKey()
{
return eventKey;
}
public void setEventKey(String eventKey)
{
this.eventKey = eventKey;
}
public boolean isImageError()
{
return imageError;
}
public void setImageError(boolean imageError)
{
this.imageError = imageError;
}
}
Use of the Listener:
// Start XSLT transformation and FOP processing
ImageErrorListener imageListener = new ImageErrorListener();
fop.getUserAgent().getEventBroadcaster().addEventListener(imageListener);
if (res != null)
{
transformer.transform(xmlDomStreamSource, res);
}
if(imageListener.isImageError()) {
throw new ImageException("");
}
fop is of the type Fop ,xmlDomStreamSource ist the xml-Source I want to transform and res is my SAXResult.

NoInitialContextException in CXF Local Transport for testing the JAX-RS

I am following this tutorial: https://cwiki.apache.org/confluence/display/CXF20DOC/JAXRS+Testing
But I get this error:
javax.naming.NoInitialContextException:Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
This is my local server class:
public class CXFLocalTransportTestSuite {
public static final Logger LOGGER = LogManager.getLogger();
public static final String ENDPOINT_ADDRESS = "local://service0";
private static Server server;
#BeforeClass
public static void initialize() throws Exception {
startServer();
}
private static void startServer() throws Exception {
JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
factory.setAddress(ENDPOINT_ADDRESS);
List<Class<?>> resourceClasses = new ArrayList<Class<?>>();
resourceClasses.add(CommunicationWSRESTImpl.class);
factory.setResourceClasses(resourceClasses);
List<ResourceProvider> resourceProviders = new ArrayList<>();
resourceProviders.add(new SingletonResourceProvider(new CommunicationWSRESTImpl()));
factory.setResourceProviders(resourceProviders);
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJaxbJsonProvider());
providers.add(new ApiOriginFilter());
providers.add(new AuthenticationFilter());
providers.add(new AuthorizationFilter());
factory.setProviders(providers);
server = factory.create();
server.start();
LOGGER.info("LOCAL TRANSPORT STARTED");
}
#AfterClass
public static void destroy() throws Exception {
server.stop();
server.destroy();
LOGGER.info("LOCAL TRANSPORT STOPPED");
}
}
And a client example:
public class CommunicationApiTest {
// [PUBLIC PROFILE]
// --------------------------------------------------------------------------------------------------------
#Test
public void getLinkedComponentsTest() {
// PATH. PARAM.
// ********************************************************************************************************
String userId = "1";
String componentInstance = "a3449197-cc72-49eb-bc14-5d43a80dfa80";
String portId = "00";
// ********************************************************************************************************
WebClient client = WebClient.create(CXFLocalTransportTestSuite.ENDPOINT_ADDRESS);
client.path("/communication/getLinkedComponents/{userId}-{componentInstance}-{portId}", userId, componentInstance, portId);
client.header("Authorization", "Bearer " + CXFLocalTransportTestSuite.authenticationTokenPublicProfile);
Response res = client.get();
if (null != res) {
assertEquals(StatusCode.SUCCESSFUL_OPERATION.getStatusCode(), res.getStatus());
assertNotNull(res.getEntity());
// VALID RESPONSE
// ********************************************************************************************************
assertEquals("> Modules has not been initialized for userID = 1", res.readEntity(GetLinksResult.class).getMessage());
// ********************************************************************************************************
}
}
}
Finally, this is the jax-rs implementation on the server side:
#Path("/communication")
public class CommunicationWSRESTImpl implements CommunicationWS {
#Path("/getLinkedComponents/{userId}-{componentInstance}-{portId}")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getLinkedComponents(
#HeaderParam("Authorization") String accessToken,
#PathParam("userId") String userId,
#PathParam("componentInstance") String componentInstance,
#PathParam("portId") String portId) {
LOGGER.info("[CommunicationWSREST - getLinksComponents] userId: " + userId + " -- componentInstace: "
+ componentInstance + " -- portId: " + portId);
GetLinksResult result = new GetLinksResult();
result.setGotten(false);
result.setPortList(null);
if (userId != null && userId.compareTo("") != 0) {
if (componentInstance != null && componentInstance.compareTo("") != 0) {
if (portId != null && portId.compareTo("") != 0) {
TMM tmm = null;
javax.naming.Context initialContext;
try {
initialContext = new InitialContext();
tmm = (TMM) initialContext.lookup("java:app/cos/TMM");
result = tmm.calculateConnectedPorts(userId, componentInstance, portId);
} catch (Exception e) {
LOGGER.error(e);
result.setMessage("> Internal Server Error");
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build();
}
} else {
LOGGER.error("Not found or Empty Port Error");
result.setMessage("> Not found or Empty Port Error");
return Response.status(Status.NOT_FOUND).entity(result).build();
}
} else {
LOGGER.error("Not found or Empty Component Instance Error");
result.setMessage("> Not found or Empty Component Instance Error");
return Response.status(Status.NOT_FOUND).entity(result).build();
}
} else {
LOGGER.error("Not found or Empty userid Error");
result.setMessage("> Not found or Empty username Error");
return Response.status(Status.NOT_FOUND).entity(result).build();
}
return Response.ok(result).build();
}
}
Maybe the problem is the local transport is not correctly configured what launches the exception because of the lookup (see: server side):
TMM tmm = null;
javax.naming.Context initialContext;
try {
initialContext = new InitialContext();
tmm = (TMM) initialContext.lookup("java:app/cos/TMM");
result = tmm.calculateConnectedPorts(userId, componentInstance, portId);
} catch (Exception e) {
..
The problem is most likely because you are running your test in a Java SE environment that is not configured with a JNDI server. If you run your test as part of a WAR inside a Java EE app server, this would probably work just fine.
So you might need to either run your unit test inside an app server or you could try mocking a JNDI server like what is described here: http://en.newinstance.it/2009/03/27/mocking-jndi/#
Hope this helps,
Andy

How to add windows credentials to an apache camel route?

I need to authenticate myself when I want to access a REST api.
I have created a simple example with apache's WinHttpClients which works and also accepts a self signed crt which is used by that site.
These are my dependencies
dependencies {
compile 'org.apache.httpcomponents:httpclient:4.5.+'
compile 'org.apache.httpcomponents:httpclient-win:4.5.+'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
And this is the working code (authorization works, acceptance of crt works)
public class Application {
public static void main(String[] args) throws IOException {
if (WinHttpClients.isWinAuthAvailable()) {
PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
buildSSLSocketFactory());
HttpClientBuilder clientBuilder = WinHttpClients.custom().useSystemProperties();
clientBuilder.setConnectionManager(httpClientConnectionManager);
CloseableHttpClient httpClient = clientBuilder.build();
HttpHost httpHost = new HttpHost("server.evilcorp.com", 443, "https");
HttpGet httpGet = new HttpGet(
"/evilwebapi/streams/endpointalpha/data");
httpGet.setHeader("accept", "application/json");
CloseableHttpResponse httpResponse = httpClient.execute(httpHost, httpGet);
String content = EntityUtils.toString(httpResponse.getEntity());
System.out.println(content); // returns expected json result
}
}
private static Registry<ConnectionSocketFactory> buildSSLSocketFactory() {
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(buildSSLContext(), NoopHostnameVerifier.INSTANCE);
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
}
private static SSLContext buildSSLContext() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
System.out.println("Failed to initialize SSL handling.\n" + e);
}
return sslContext;
}
}
When I try to access the same site through apache camel I get a 401 status.
I tried to configure camel's httpComponent in various ways but so far I can't make authentication work. This is the current camel setup.
These are my dependencies:
dependencies {
compile 'org.apache.camel:camel-core:2.18.+'
compile 'org.apache.camel:camel-sql:2.18.+'
compile 'org.apache.camel:camel-http4:2.18.+'
compile 'org.apache.camel:camel-jetty:2.18.+'
compile 'org.apache.camel:camel-jackson:2.18.+'
compile 'org.apache.camel:camel-guava-eventbus:2.18.+'
compile 'org.apache.camel:camel-quartz2:2.18.+'
compile 'com.fasterxml.jackson.core:jackson-core:2.7.+'
compile 'org.apache.httpcomponents:httpclient:4.5.+'
compile 'org.apache.httpcomponents:httpclient-win:4.5.+'
testRuntime files('src/test/resources')
runtime files('src/main/resources')
}
And this is the RouteBuilder which does not work (authorization doesm't works, statusCode: 401)
context = new DefaultCamelContext(registry);
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:model.properties");
context.addComponent("properties", pc);
try {
context.addRoutes(new RouteBuilder() {
public void configure() {
HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
httpComponent.setHttpClientConfigurer(new WinHttpClientConfigurer());
httpComponent.setClientConnectionManager(new PoolingHttpClientConnectionManager(WinHttpClientConfigurer.buildSSLSocketFactory()));
httpComponent.setHttpConfiguration(buildHttpConfiguration());
getContext().getProperties().put("CamelJacksonEnableTypeConverter", "true");
getContext().getProperties().put("CamelJacksonTypeConverterToPojo", "true");
from("quartz2://pipull?cron=0+0/1+*+1/1+*+?+*")
.setHeader(Exchange.HTTP_QUERY,
simple("start='${header.start}'&end='${header.end}'"))
.multicast().parallelProcessing()
.to("direct:model");
from("direct:model")
.setHeader("contractRef", simple("${properties:model.name}"))
.to("https4://server.evilcorp.com/evilwebapi/streams/endpointalpha/data")
.to("direct:transform");
from("direct:transform").unmarshal()
.json(JsonLibrary.Jackson, Model.class)
.bean(ProcessorImpl.class)
.to("guava-eventbus:botBus");
}
private HttpConfiguration buildHttpConfiguration() {
WindowsCredentialsProvider credentialsProvider = new WindowsCredentialsProvider(
new SystemDefaultCredentialsProvider());
Credentials credentials = credentialsProvider.getCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM));
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setAuthMethod(AuthSchemes.NTLM);
httpConfiguration.setAuthUsername(credentials.getUserPrincipal().getName());
return httpConfiguration;
}
});
context.start();
} catch (Exception e) {
isRunning.set(false);
throw new RuntimeException(e);
}
I have resolved the problem through subtyping HttpComponent and adding that to the camel context.
public class WinHttpComponent extends HttpComponent {
private static final Logger LOG = LoggerFactory.getLogger(WinHttpComponent.class);
public WinHttpComponent() {
this(HttpEndpoint.class);
}
public WinHttpComponent(Class<? extends HttpEndpoint> endpointClass) {
super(endpointClass);
}
#Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
// copy-paste everything from super method
// replace this
// HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// with this
HttpClientBuilder clientBuilder = WinHttpClients.custom().useSystemProperties();
// copy-paste everything from super method
}
}
context = new DefaultCamelContext(registry);
context.addComponent("https4", new WinHttpComponent());
try {
context.addRoutes(new RouteBuilder() {
public void configure() {
HttpComponent httpComponent = getContext().getComponent("https4", HttpComponent.class);
// connection manager which accepts self-signed cert
httpComponent.setClientConnectionManager(new PoolingHttpClientConnectionManager(
NoopSslVerifierHttpClientConfigurer.buildSSLSocketFactory()));
...
...
...
}
}

How to add and configure asmack in android

Please can you help with a break down of how you got asmack working in your android. I cant get it to work for my application. I keep geting java.lang.verifyError.
Be sure to include latest version i.e. asmack-android-17-0.8.3 of asmack library in libs folder.
Adding this might remove java.lang.VerifyError.
I do it the following way, it works perfectly.
public void login(View view)
{
new Connection().execute("username", "password");
}
private class Connection extends AsyncTask<String, Void, Integer>
{
private static final int CONNECTION_FAILURE = 0;
private static final int LOGIN_FAILURE = 1;
private static final int SUCCESS = 2;
#Override
protected Integer doInBackground(String... strings)
{
ConnectionConfiguration conConfig = new ConnectionConfiguration("192.168.1.100", 5222, "domain");
connection = new XMPPConnection(conConfig);
try
{
connection.connect();
Log.i("AppName", "CONNECTED TO " + connection.getHost());
}
catch(Exception e)
{
Log.e("AppName", e.getMessage());
return CONNECTION_FAILURE;
}
try
{
connection.login(strings[0], strings[1]);
Log.i("AppName", "LOGGED IN AS " + connection.getUser());
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
}
catch(Exception e)
{
Log.e("AppName", e.getMessage());
return LOGIN_FAILURE;
}
return SUCCESS;
}
}