Custom Exception class Jenkins Groovy - jenkins

I created a custom exception class and put it inside src/org/team/pipeline/TestResultFailed.groovy:
package org.team.pipeline
public class TestResultFailed extends Exception {
// Parameterless Constructor
public TestResultFailed() {}
// Constructor that accepts a message
public TestResultFailed(String message) {
super(message);
}
}
The only issue is the class (and thus even exception) cannot be easily imported from shared library to Jenkins pipeline. Therefore, it's not possible to directly throw exception from Jenkins pipeline.
To bypass that, I tried to "wrap" my new exception into shared library function in vars/teamUtils.groovy:
import org.team.pipeline.*
def getTestResultFailedClass() {
return TestResultFailed
}
And then I import and use it in Jenkinsfile as follows:
TestResultFailed = teamUtils.getTestResultFailedClass()
try {
throw new TestResultFailed.TestResultFailed("error")
} catch (TestResultFailed err) {
log.info("Exception caught: ${err}")
}
However, I get this error:
unable to resolve class TestResultFailed.TestResultFailed
and no matter what I tried I'm still getting this error. Any help is very appreciated.

Related

Can't inject the guice dependency in the jersey filter

In the process of setup a bridge between guice and jersey, I ran into one problem.
When trying to create a jersey filter, I was unable to inject guice dependencies into it.
I found a duplicate, however there is no solution to the problem there.
Everything is exactly the same.
The only difference is that I don't get a startup error. The filter works, but my dependencies are null.
Interestingly, Filter and HttpFilter work fine. But it doesn't really work for me.
There's another thing that's interesting. In the resource, which I understand is an HK2 dependency, I can inject guice bean.
#ApplicationPath("/test")
private static class TestApplicationConfig extends ResourceConfig
{
public TestApplicationConfig()
{
register(JacksonFeature.class);
register(AuthFilter.class);
register(new ContainerLifecycleListener()
{
public void onStartup(Container container)
{
ServletContainer servletContainer = (ServletContainer) container;
ServiceLocator serviceLocator = container.getApplicationHandler().getServiceLocator();
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
Injector injector = (Injector) servletContainer
.getServletContext()
.getAttribute(Injector.class.getName());
guiceBridge.bridgeGuiceInjector(injector);
}
public void onReload(Container container)
{
}
public void onShutdown(Container container)
{
}
});
}
}
In ServletModule child.
serve(path).with(ServletContainer.class, ImmutableMap.of(
"javax.ws.rs.Application", TestApplicationConfig.class.getName(),
"jersey.config.server.provider.packages", sb.toString()));
I trying with register(AuthFilter.class) and #Provider
#Singleton
#Provider
public class AuthFilter implements ContainerRequestFilter
{
#Inject
private SomeInjectedService someInjectedService; **// null here**
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
// some code
}
}
SomeInjectedService I register by guice
bind(SomeInjectedService.class).asEagerSingleton();
Where can I start diagnosing and what can I do?
UPD:
I noticed different behavior when using different annotations.
If I use javax.inject.Inject, I get the following error message.
org.glassfish.hk2.api.MultiException: A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=SomeInjectedService,parent=AuthFilter,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1496814489)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of some.package.AuthFilter errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on some.package.AuthFilter
If com.google.inject.Inject, just null. As I understand this method is not correct.
Considering that javax Inject is trying to inject the service but can't find it. Can we conclude that the bridge is not working correctly? But if it's not working correctly, why can I inject this service into my resource?
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class SomeResource
{
private final SomeInjectedService someInjectedResource;
#Inject // here I use javax annotation and this code working correctry
public SomeResource(SomeInjectedService someInjectedResource)
{
this.someInjectedResource = someInjectedResource;
}
#GET
#Path("/{user}")
public Response returnSomeResponse(#PathParam("user") String user) throws Exception
{
// some code
}
}

Grails 4 service not being injected inside Grails Data Service

This is about a Grails service injected into a Data Service. The problem is that the injected service is null at runtime. Here is an example.
class MessagingService {
def sendEmail(String message) {
...
}
}
interface IFlowService {
...
}
#Service(Flow)
abstract class FlowService implements IFlowService {
MessagingService messagingService
void sendFoo() {
messagingService.sendEmail(message)
}
}
FlowService and MessagingService both reside under grails-app/services.
When FlowService calls sendEmail there is an NPE because messagingService is null.
MessagingService is hand-written and is not associated with a domain.
This project uses Grails 4.0.10 and the issue occurred several times. When the usual Gails magic (i.e. injection) didn't work I solved the first one or two issues with kludges, you know, just to avoid getting stuck.
Now it seems to me the issue is quite predictable, it happens every time I write a service not associated with a domain. Did I miss something in the documentation? What is the appropriate way to handle this?
Kludge: To get around the issue I include a method sayHi in the problematic service. It just logs a debug message. I invoke sayHi from BootStrap to check that it works. It does, surprisingly. Then I add code in BootStrap to assign the service to the supposedly injected property in the service. [Shudder]
I tried to reproduce the same-
interface IFlowService {
}
#Service(Flow)
abstract class FlowService implements IFlowService {
MessagingService messagingService
void hello() {
println "hello"
messagingService.hi() // <- NPE
}
}
class MessagingService {
void hi() {
println "hi"
}
}
This seems to be a bug to be in Grails. But you can easily solve this (probably as a workaround) by just adding #Autowired in the service-
import org.springframework.beans.factory.annotation.Autowired
#Service(Flow)
abstract class FlowService implements IFlowService {
#Autowired
MessagingService messagingService
void hello() {
println "hello"
messagingService.hi() // <- No NPE
}
}
It prints-

Getting closed before endTest call in Selenium using Extent Reports

BaseTest.java:
private static ReportService reportService; // Calling report service interface
#BeforeSuite:
reportService = new ExtentReportService(getConfig()); // New instance of ExtentReportService.
#BeforeMethod:
reportService.startTest(testname); // Starting the test and passing the name and description of the test.
#AfterMethod:
reportService.endTest(); // Ending the test
#AfterSuite:
reportService.close(); // Closing the test
**ExtentReportService.java:** // Contains different extent API methods. (These are designed to be generic.)
protected static ExtentReports extent; // static instance of ExtentReports
protected static ExtentTest test; //static instance of ExtentTTest
#Override // StartTest method
startTest(Method method) {
testMetaData = getTestMetaData(method);
test=extent.startTest(testMetaData.getId(),testMetaData.getSummary());
}
#Override //End test method
endTest() {
extent.endTest(test);
extent.flush();
}
The above is my selenium code.
When I am executing my suite file with parallel="methods" and thread count="3", I am getting the following error: "com.relevantcodes.extentreports.ExtentTestInterruptedException: Close was called before test could end safely using EndTest.".
While debugging, I found that even before all endTest() in AfterMehtod were executed, AfterSuite was being called.
I tried different variations such that the code works, such as, removing static, calling endTest() in the test itself rather than after method, removing close() call from AfterSuite and many other variations. But still getting the same error.
I tried all the possible solutions given on the internet, but to no use.
Attaching a hierarchy file for the ExtentReport used in my project
I also the following solution given in StackOverflow:
Extent report :com.relevantcodes.extentreports.ExtentTestInterruptedException: Close was called before test could end safely using EndTest
Unsynchronized output
XMF file for parallel test.
ExtentReports Intialized in ExtentManager class using Singleton().
public class ExtentManager {
private static ExtentReports extent;
public static ExtentReports getInstance() {
if(extent == null) {
extent = new ExtentReports(System.getProperty("user.dir")+"\target\surefire-reports\html\extent.html", true, DisplayOrder.OLDEST_FIRST);
extent.loadConfig(new File(System.getProperty("user.dir")+"src\test\resources\extentconfig\ReportsConfig.xml"));
}
return extent;
}
}
Declared in TestBase class as global.
public ExtentReports repo= ExtentManager.getInstance();
public static ExtentTest test
Call startTest in public void onTestStart(ITestResult result)
test = repo.startTest(result.getName().toUpperCase());
Call endTest in CustomListener Class both in a)public void onTestFailure(ITestResult result); b)public void onTestSuccess(ITestResult result).
repo.endTest(test)
Call close() OR flush() in #AfterSuite in TestBase class but NOT both!
//repo.close();
repo.flush();
Note: I have ExtentReports ver-2.41.2, and TestNg ver-7.1.0.
After the above steps, error 'Getting closed before endTest call in Selenium using Extent Reports' got resolved.
Extent report generates each test successfully in the report.
Try it out!

Error trying to call Java method from Rascal

I am trying to call a Java method from Rascal, but I'm getting this error:
Cannot link method com.mypackage.Teste because: class not found
Rascal code:
#javaClass{com.mypackage.Teste}
java void testeJava();
Java code:
package com.mypackage;
public class Teste {
public void testeJava() {
System.out.println("it worked");
}
}
The com.mypackage package is inside my src folder, along with all of the Rascal code. I've also tried to use src.com.mypackage.Teste as well, but had the same result.
What am I doing wrong?
The class needs one constructor that has one argument of the IValueFactory type. You will often store this in a field, as it is the way to respond to the function call. (Build IValues with this factory)
package com.mypackage;
import io.usethesource.vallang.IValueFactory;
public class Teste {
private final IValueFactory vf;
public Tests(IValueFactor vf) {
this.vf = vf;
}
public void testeJava() {
System.out.println("it worked");
}
}

Register HoverProvider with Xtend

I try to implement a custom HoverProvider according to this tutorial: enter link description here
However, I'm stuck translating to Java code of MyDSLUiModuleto Xtend.
The register-method should read like this:
def Class<? extends IEObjectDocumentationProvider> bindIEObjectDocumentationProviderr() {
return MyDSLHoverProvider.class
}
However, this doesn't compile since MyDSLHoverProvider only implements the IEObjectDocumentationProvider but not extend this class (MyDSLHoverProvider is the same as in the tutorial).
Therefore this error is thrown:
Type mismatch: cannot convert from Class<? extends Class> to Class<? extends IEObjectDocumentationProvider>
How can I get around this error?
Btw: If I test my DSL in an Eclipse instance, I get a wierd NPE:
!ENTRY org.eclipse.oomph.setup.ui 2 0 2016-09-16 16:42:34.203
!MESSAGE java.lang.NullPointerException
!STACK 0
java.lang.NullPointerException
at org.eclipse.oomph.setup.ui.SetupUIPlugin.performStartup(SetupUIPlugin.java:373)
at org.eclipse.oomph.setup.ui.SetupUIPlugin.access$4(SetupUIPlugin.java:344)
at org.eclipse.oomph.setup.ui.SetupUIPlugin$1$1.run(SetupUIPlugin.java:241)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
I have no clue where this exception comes from.
The class MyDSLHoverProvider looks like this:
import org.eclipse.emf.ecore.EObject
import org.eclipse.xtext.documentation.IEObjectDocumentationProvider
class MyDSLHoverProvider implements IEObjectDocumentationProvider {
override getDocumentation(EObject o) {
println("Hover: " + o)
if (o instanceof MyFieldElements) {
return "This is a nice Greeting with nice <b>markup</b> in the <i>documentation</i>";
}
}
}
Edit:
I found a way to display the tooltips, but it seems strange.
A tooltip is shown for this rule:
name = ID
but if I rename it to
myField = ID
the tooltip is not triggered.
Is this the expected behaviour?
the correct Xtend syntax is
def Class<? extends IEObjectDocumentationProvider> bindIEObjectDocumentationProviderr() {
return MyDSLHoverProvider
}
or
def Class<? extends IEObjectDocumentationProvider> bindIEObjectDocumentationProviderr() {
MyDSLHoverProvider
}
MyDSLHoverProvider.classis the same as MyDslHoverProvider.class.getClass() in Java

Resources