Netbeans 8.1 how to expose a ejb in restful service - service

I work with Netbeans 8.1. I want to convert a EJB in restful service.
My EJB is
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package paqueteservicio;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
/**
*
* #author Carlota
*/
#Stateless
#Path("/collatz")
public class CollatzResource {
#GET
public String collatz(#QueryParam("base")long base){
int num = (int)base;
String secuencia = "Inicio"+num+"\n";
while (num != 1){
if (num %2 == 0){
num = num / 2;
}
else {
num = num * 3 + 1;
}
secuencia += num + "\n";
}
return secuencia;
}
}
How can I convert this EJB in Restful Service?. Is there any option?

The only thing you have to do is enable rest in your application:
#ApplicationPath("/rest")
public class JaxRsActivator extends Application {
/* class body intentionally left blank */
}

Related

EventHandler not capturing resourceChangedAttributes and resourceAddedAttributes filtered events in AEM 6.4

We have implemented an Event Handler registered as below:
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.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a node observer class which would observe the path /content/we-retail
* for any addition or updation of nodes (type = cq:PageContent).
* #author
*/
#Component(label = "Test Event Listener", immediate = true, metatype =
false, enabled = true)
#Properties({
/* #Property(name = EventConstants.EVENT_TOPIC, value = ReplicationAction.EVENT_TOPIC)
})*/
#Property(name = EventConstants.EVENT_TOPIC, value =
{"org/apache/sling/api/resource/Resource/ADDED",
"org/apache/sling/api/resource/Resource/CHANGED"}),
#Property(name = EventConstants.EVENT_FILTER, value = "(&" +
"(path=/content/we-retail/us/en/*/jcr:content) (|(" + SlingConstants
.PROPERTY_CHANGED_ATTRIBUTES + "=*jcr:title) "
+ "(" + ResourceChangeListener.CHANGES + "=*jcr:title)))")
})
#Service(EventHandler.class)
public class TestEventHandler implements EventHandler {
private static final Logger LOG = LoggerFactory.getLogger(TestEventHandler.class);
/*
* Reference of ResourceResolverFactory object.
*/
#Reference
private ResourceResolverFactory resourceResolverFactory;
/*
* (non-Javadoc)
* #see org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event)
*/
#Override
public void handleEvent(Event event) {
LOG.info("Hi event is called ......");
}
}
Issue is: Our handleEvent doesn't get trapped when change the property value for jcr:title on any page under the path: /content/we-retail/us/en
AEM version is: 6.4
sling version used is : org.apache.sling.api
Since 2.0.6 (Sling API Bundle 2.0.6) it is deprecated.
You should implement org.apache.sling.api.resource.observation.ResourceChangeListener
please see the sample: ResourceChangeListener sample

how to pass data to onTestSuccess method in Listener class of TESTNG for each iteration from #Test method used dataprovider

, i have a #Test method with dataprovider , i have a Listener.class , my target is that when my #Test method is success, the status of case in testrail is setted as "Passed" automatically in onTestSuccess Method of Listener class , this process is ok, but when i use dataprovider for #Test Method, this causes the problem
i want that same method must be worked (let say) three times because of dataprovider and different case id data must be sent to onTestSuccess method for each iteration from #Test method
My Listener.class
package com.myproject.test.listeners;
import java.lang.reflect.Method;
import org.testng.IClass;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class Listener implements ITestListener, ISuiteListener, IInvokedMethodListener {
...
public void onTestStart(ITestResult result) {
}
public void onTestSuccess(ITestResult result) {
try {
Program pr = new Program();
System.out.println("onTestSuccess Method for :" + result.getName());
String TestID = null;
String TestRunID = null;
for (Method testMethod : result.getTestClass().getRealClass().getMethods()) {
if (testMethod.getName().equals(result.getName()) && testMethod.isAnnotationPresent(UseAsTestRailId.class)) {
UseAsTestRailId useAsTestName = testMethod.getAnnotation(UseAsTestRailId.class);
TestID = Integer.toString(useAsTestName.testRailCaseId());
TestRunID = Integer.toString(useAsTestName.testRailRunId());
System.out.println("Case ID---> " + TestID + " Run ID--> " + TestRunID);
// 1 = Passed
pr.enterTestResult(TestRunID, TestID, 1);
}
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
...
}
My test class (SettingsTests.java) including my #Test method (checkCurrentPasswordFormatIsValidatedTest)
#Listeners(com.test.listeners.Listener.class)
//listener annotation row is written in BaseTest class
public class SettingsTests extends BaseTest {
...
/**
* Test Case - C5001275 - Check that "Please enter at least 8 characters."
* message is displayed when entered value into "Current Password" field in
* wrong format This case will run two times!
*
* #param currentPasswordValue
*/
#Test(dataProvider = "currentPasswordTestWithWrongValue")
#UseAsTestRailId(testRailCaseId = 5001275,testRailRunId = 56662)
// aim is that to send different case id for each iteration,now even if method works twice , only one testRailCaseId is sent
public void checkCurrentPasswordFormatIsValidatedTest(String currentPasswordValue) {
logger.trace("STARTING TEST: checkCurrentPasswordFormatisValidatedTest");
logger.trace("Test Step : Enter current password in wrong format");
settingsPageObject.enterCurrentPassword(currentPasswordValue);
logger.trace("Test Step : Click on the button 'UPDATE' ");
settingsPageObject.clickOnUpdateButton();
logger.trace("Expected Result: The message 'Please enter at least 8 characters.' is displayed on screen.");
Assert.assertEquals(settingsPageObject.getCurrentPasswordWrongText(), "Please enter at least 8 characters.");
}
#DataProvider(name = "currentPasswordTestWithWrongValue")
public static Object[][] validateTestWithCurrentPasswordInWrongFormat() {
return new Object[][] { { RandomStringUtils.randomAlphabetic(7) }, { RandomStringUtils.randomAlphabetic(1) } };
}
...
}
My annotation class (UseAsTestRailId.java)
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface UseAsTestRailId
{
int testRailCaseId() default 0;
int testRailRunId() default 0;
String[] tags() default "";
}
Some #Test methods to set two case status, some #Test methods to set three case status in testRail,so the more dataprovider data set needed the more case id needed , it must be dynamical
You can use the setattribute value in the testresult object to set custom value. Get the currentresult from Reporter : Reporter.getCurrentTestresult and then setAttribute ("TC_id",sasdf) and use that in your ontestsuccess using the getAttribute ("TC_id") on result object.

How do I specify a Pointcut which includes all public methods in a package hierarchy but excludes some specfic methods?

I have the following simple Aspect.
package com.example.foo.aspects;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
#Aspect
public class TimingProfiler
{
private static final Log logger = LogFactory.getLog(TimingProfiler.class);
#Pointcut("execution(String *.toString())"
+ " || execution(int *.hashCode())"
+ " || execution(boolean *.equals(Object))"
+ " || execution(int *.getId())"
+ " || execution(String *.getName())")
public void whatIDontWantToMatch(){}
#Pointcut("execution(public * com.example.foo..*(..))")
public void whatIWantToMatch(){}
#Pointcut("whatIWantToMatch() && ! whatIDontWantToMatch()")
public void allIWantToMatch(){}
#Around("allIWantToMatch()")
public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable
{
Signature signature = joinPoint.getStaticPart().getSignature();
logger.info("Entering method " + signature);
Object returnValue = joinPoint.proceed();
logger.info("Leaving method " + signature);
return returnValue;
}
}
I get the following message during compilation, however.
[INFO] Join point 'method-execution(com.example.foo.bar.baz.snack.SnackIdentifier com.example.foo.bar.baz.snack.Snack.getId())' in Type 'com.example.foo.bar.baz.snack.Snack' (Snack.java:78) advised by around advice from 'com.example.foo.aspects.TimingProfiler' (foo-profiler-lib.jar!TimingProfiler.class(from TimingProfiler.java))
And when I run the code I get log messages from the methods I am trying to exclude.
How do I correctly include all of the public methods found in the com.example.foo package while excluding some specific ones?
I was overlooking the fact that my PointCut was excluding int getId() and the methods I was seeing show up in the output were SnackIdentifier getId(). The correct answer to this question is to pay attention.

how to draw directed edges with "IGraphContentProvider"?

I am using ZEST and RCP to build a graph visalization tool. I used IGraphContentProvider and the LabelProvider for drawing the graph.
How can I draw a directed edge between two nodes using IGraphContentProvider?
Late answer, but I've just something similar:
You may do this, by providing a IEntityConnectionStyleProvider. It has a method called getConnectionStyle(src, dest). You can return the costant ZestStyles.CONNECTIONS_DIRECTED there, if all the connections are directed. Otherwise, you have to decide based on the source and destination, wether to draw a directed edge.
You may also want to look at IGraphEntityRelationshipContentProvider. With that content provider you can just add objects to the graph and later on decide which are connected.
Not a Zest expert, but a IGraphContentProvider seems limited to access the underlying obejct of a given relationship.
The getSource() and getDestination() methods will help a viewer like a Graphviewer, from AbstractStructuredGraphViewer view the edge defined by those "source-Destination" couples.
See this example for instance.
/*******************************************************************************
* Copyright 2005-2007, CHISEL Group, University of Victoria, Victoria, BC,
* Canada. All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: The Chisel Group, University of Victoria
******************************************************************************/
package org.eclipse.zest.core.examples.jface;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.zest.core.viewers.GraphViewer;
import org.eclipse.zest.core.viewers.IGraphContentProvider;
import org.eclipse.zest.layouts.LayoutStyles;
import org.eclipse.zest.layouts.algorithms.SpringLayoutAlgorithm;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* This snippet shows how to use the IGraphContentProvider to create a graph with Zest.
* In this example, getElements returns 3 edges:
* * Rock2Paper
* * Paper2Scissors
* * Scissors2Rock
*
* And for each of these, the source and destination are returned in getSource and getDestination.
*
* A label provider is also used to create the text and icons for the graph.
*
* #author Ian Bull
*
*/
public class GraphJFaceSnippet2 {
static class MyContentProvider implements IGraphContentProvider {
public Object getSource(Object rel) {
if ("Rock2Paper".equals(rel)) {
return "Rock";
} else if ("Paper2Scissors".equals(rel)) {
return "Paper";
} else if ("Scissors2Rock".equals(rel)) {
return "Scissors";
}
return null;
}
public Object[] getElements(Object input) {
return new Object[] { "Rock2Paper", "Paper2Scissors", "Scissors2Rock" };
}
public Object getDestination(Object rel) {
if ("Rock2Paper".equals(rel)) {
return "Paper";
} else if ("Paper2Scissors".equals(rel)) {
return "Scissors";
} else if ("Scissors2Rock".equals(rel)) {
return "Rock";
}
return null;
}
public double getWeight(Object connection) {
return 0;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
static class MyLabelProvider extends LabelProvider {
final Image image = Display.getDefault().getSystemImage(SWT.ICON_WARNING);
public Image getImage(Object element) {
if (element.equals("Rock") || element.equals("Paper") || element.equals("Scissors")) {
return image;
}
return null;
}
public String getText(Object element) {
return element.toString();
}
}
static GraphViewer viewer = null;
/**
* #param args
*/
public static void main(String[] args) {
Display d = new Display();
Shell shell = new Shell(d);
shell.setText("GraphJFaceSnippet2");
shell.setLayout(new FillLayout(SWT.VERTICAL));
shell.setSize(400, 400);
viewer = new GraphViewer(shell, SWT.NONE);
viewer.setContentProvider(new MyContentProvider());
viewer.setLabelProvider(new MyLabelProvider());
viewer.setLayoutAlgorithm(new SpringLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING));
viewer.setInput(new Object());
shell.open();
while (!shell.isDisposed()) {
while (!d.readAndDispatch()) {
d.sleep();
}
}
}
}

Eclipse 3.3 Europa JDT TextHover

I want to show my own text hover in eclipse for some specific words? Please provide me some examples
You can start by looking at Koder examples.
E.g. this CEditorTextHoverDispatcher or this UCTextHover
package com.ut2003.uceditor;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.swt.graphics.Point;
public class UCTextHover implements ITextHover
{
/* (non-Javadoc)
* Method declared on ITextHover
*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion)
{
if (hoverRegion != null)
{
try
{
if (hoverRegion.getLength() > -1)
return textViewer.getDocument().get(hoverRegion.getOffset(), hoverRegion.getLength());
}
catch (BadLocationException x)
{
}
}
return "Empty Selection";
}
/* (non-Javadoc)
* Method declared on ITextHover
*/
public IRegion getHoverRegion(ITextViewer textViewer, int offset)
{
Point selection = textViewer.getSelectedRange();
if (selection.x <= offset && offset < selection.x + selection.y)
return new Region(selection.x, selection.y);
return new Region(offset, 0);
}
}
You would set a TextHover in a SourceViewerConfiguration like this GasSourceViewerConfiguration or this CalcSourceViewerConfiguration
package com.example.calc.ui.editors;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.reconciler.MonoReconciler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
/**
* #author cdaly
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class CalcSourceViewerConfiguration extends SourceViewerConfiguration {
private CalcEditor _editor;
public CalcSourceViewerConfiguration(CalcEditor editor){
_editor = editor;
}
/* (non-Javadoc)
* #see org.eclipse.jface.text.source.SourceViewerConfiguration#getReconciler(org.eclipse.jface.text.source.ISourceViewer)
*/
public IReconciler getReconciler(ISourceViewer sourceViewer) {
return new MonoReconciler(_editor.getReconcilingStrategy(), false);
}
/* (non-Javadoc)
* #see org.eclipse.jface.text.source.SourceViewerConfiguration#getTextHover(org.eclipse.jface.text.source.ISourceViewer, java.lang.String)
*/
public ITextHover getTextHover(
ISourceViewer sourceViewer,
String contentType) {
ITextHover hover;
if (_editor != null && _editor instanceof CalcEditor) {
hover = new CalcTextHover((CalcEditor)_editor);
} else {
hover = null;
}
return hover;
}
}
Beyond that, I have not much more information: the examples I have found are more programmatic than declarative (i.e. "plugin.xml"), so you may want to explore some more code.
Another good example: Eclipse: Rich Hovers Redux (it is for eclipse3.4 though, but the full example can give you another hint at how a custom ITextHover is added to the current editor)
The best thing is to use the java editor plugin along with eclipse first. Take eclipse help ->welcome->Samples->Java Editor plugin