I had used S4SDK VDM on my Integration Testing to test my ODATA services. There were some issues during the implementation & Alexander bestowed me to get it working. (VDM for Integration Tests)
When I had executed the JUnit in eclipse it works well. However when the JUnit runs during the Maven Build/ in the pipeline, it fails with the below error
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] BusinessServiceIT.createBusinessService:132->createLandscapeObject:214 » ErpOData
[INFO]
[ERROR] Tests run: 21, Failures: 0, Errors: 1, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 09:34 min
[INFO] Finished at: 2019-06-13T16:00:26+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M3:test (default-test) on project x-srv-landscapeManagement-integration-tests: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\xxxxx\git\x-service-landscapeManagement\srv\integration-tests\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR] mvn <goals> -rf :x-srv-landscapeManagement-integration-tests
public static void beforeClass() {
mockUtil.mockDefaults();
mockUtil.mockAuditLog();
lsoCreateHelper.withCustomHttpHeader("Authorization", jwToken).onRequestAndImplicitRequests();
connectionHelper.withCustomHttpHeader("Authorization", jwToken).onRequestAndImplicitRequests();
}```
``` #Before
public void beforeEach() throws URISyntaxException, IOException, ODataException {
mockUtil.mockDestination("localhorst", new URI("http://localhost:" + randomServerPort));
erpConfCtx = new ErpConfigContext("localhorst");
final String publicKey = FileUtils.readFile("publicKey.txt");
final Map<String, String> verificationkey = ImmutableMap.of("verificationkey", publicKey);
final JsonObject xsuaaServiceCredentials = new Gson().toJsonTree(verificationkey).getAsJsonObject();
when(((ScpCfCloudPlatform) CloudPlatformAccessor.getCloudPlatform())
.getXsuaaServiceCredentials(org.mockito.ArgumentMatchers.any(DecodedJWT.class)))
.thenReturn(xsuaaServiceCredentials);
}```
private UUID createLandscapeObject(String lsoType, String name, String customerNumber, String source,
String usecase, String tenantId, String tenantType) throws ODataException {
Properties properties = new Properties();
List<Properties> propertySet = new ArrayList<>();
if (usecase != null) {
properties.setName("useCase");
properties.setValue(usecase);
properties.setSource(source);
propertySet.add(properties);
}
if (tenantId != null) {
propertySet = new ArrayList<>();
properties.setName("TenantId");
properties.setValue(tenantId);
properties.setSource(source);
propertySet.add(properties);
}
if (tenantType != null) {
propertySet = new ArrayList<>();
properties.setName("TenantType");
properties.setValue(tenantType);
properties.setSource(source);
propertySet.add(properties);
}
LandscapeObjects landscapeObjects = new LandscapeObjects(null, null, null, null, null, name, "benufromit_test",
lsoType, customerNumber, source, null, null, propertySet);
LOG.info("benu-business1");
final LandscapeObjectsCreateFluentHelper lsoCreateHelper = lmsService.createLandscapeObjects(landscapeObjects)
.withCustomHttpHeader("Authorization", jwToken).onRequestAndImplicitRequests();
landscapeObjects = lsoCreateHelper.execute(erpConfCtx);
return landscapeObjects.getId();
}```
[ERROR] Errors:
[ERROR] BusinessServiceIT.createBusinessService:132->createLandscapeObject:214 » ErpOData
target\surefire-reports
-------------------------------------------------------------------------------
Test set: com.sap.crun.landscape.BusinessServiceIT
-------------------------------------------------------------------------------
Tests run: 3, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 66.107 s <<< FAILURE! - in com.sap.crun.landscape.BusinessServiceIT
createBusinessService(com.sap.crun.landscape.BusinessServiceIT) Time elapsed: 2.463 s <<< ERROR!
com.sap.cloud.sdk.s4hana.datamodel.odata.helper.ODataVdmErrorResultHandler$ErpODataException:
The endpoint responded with HTTP error code 500.
. .
Full error message:
<?xml version='1.0' encoding='UTF-8'?><error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><code/><message xml:lang="en">Service not available: LandscapeService.</message></error>
at com.sap.crun.landscape.BusinessServiceIT.createLandscapeObject(BusinessServiceIT.java:214)
at com.sap.crun.landscape.BusinessServiceIT.createBusinessService(BusinessServiceIT.java:132)```
**TestApplication**
package com.sap.crun.landscape;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = {"com.sap.cloud.servicesdk.spring", "com.sap.crun.landscape"})
#ServletComponentScan( "com.sap.cloud.sdk" )
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
Related
I have a rest endpoint as below:
#PostMapping(value = "/customers/{customerId}")
public SomeResponse manageCustomers(#PathVariable String customerId){
...
}
This endpoint picks customer data from one system for the given customerId and saves it in another system. Thus, it doesn't require any request body.
I need to write an integration test for this. When I use testRestTemplate for this, I can't find a good enough method where I can pass requestEntity as null. Whenever I do that, I get an exception saying 'uriTemplate must not be null'.
I have tried to use 'postForObject', 'exchange' methods but doesn't work. Any ideas?
Below is my IT:
#SpringBootTest(webEnvironmentSpringBootTest.WebEnvironment.RANDOM_PORT)
#DirtiesContext
#ActiveProfiles("test")
class CustomerIT extends Specification{
#LocalServerPort
private int port;
#Autowired
private TestRestTemplate restTemplate
def "should get customer from first system and save in second system"() {
given:
def customerUrl = new URI("http://localhost:" + port + "/customers/1234")
def expected = new SomeObject(1)
when:
def someObject =
restTemplate.postForEntity(customerUrl, null, SomeObject.class)
then:
someObject != null
someObject == expected
}
}
Using postForEntity(url, null, ResponseType.class) works for me.
My postmapping is equal to your except for the responseType. I used Map just as an example
#PostMapping(value = "/customers/{customerId}")
public Map<String, String> manageCustomers(#PathVariable String customerId){
return new HashMap<String, String>(){{ put("customerId", customerId); }};
}
Test to verify that it works
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CustomerControllerTest {
#LocalServerPort
private int port;
private final TestRestTemplate testRestTemplate = new TestRestTemplate();
#Test
public void postEmptyBodyShouldReturn200OK() {
String customerId = "123";
ResponseEntity responseEntity = testRestTemplate
.postForEntity(format("http://localhost:%s/ping/customers/%s", port, customerId), null, Map.class);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_UTF8);
assertThat(responseEntity.getBody()).isNotNull();
assertThat(((LinkedHashMap) responseEntity.getBody()).size()).isEqualTo(1);
assertThat(((LinkedHashMap) responseEntity.getBody()).get("customerId")).isEqualTo(customerId);
}
}
Running this test in maven
$ mvn -Dtest=CustomerControllerTest test
(...removed unnecessary output...)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.137 s - in com.ins.example.demo.rest.CustomerControllerTest
10:04:54.683 [Thread-3] INFO o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.940 s
[INFO] Finished at: 2019-04-07T10:04:55+02:00
[INFO] ------------------------------------------------------------------------
I just added a custom predicate class to my project and the maven build just broke with this error. Do I need to add some more dependencies ?
[ERROR] Failed to execute goal org.apache.felix:maven-scr-plugin:1.21.0:scr (generate-scr-descriptor) on project data-providers: Execution generate-scr-descriptor of goal org.apache.felix:maven-scr-plugin:1.21.0:scr failed: An API incompatibility was encountered while executing org.apache.felix:maven-scr-plugin:1.21.0:scr: java.lang.VerifyError: Constructor must call super() or this() before return
[ERROR] Exception Details:
[ERROR] Location:
[ERROR] com/day/cq/search/eval/AbstractPredicateEvaluator.<init>()V #1: return
[ERROR] Reason:
[ERROR] Error exists in the bytecode
[ERROR] Bytecode:
[ERROR] 0x0000000: 2ab1
[ERROR]
[ERROR] -----------------------------------------------------
[ERROR] realm = plugin>org.apache.felix:maven-scr-plugin:1.21.0
[ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
[ERROR] urls[0] = file:/C:/Users/rmahna/.m2/repository/org/apache/felix/maven-scr-plugin/1.21.0/maven-scr-plugin-1.21.0.jar
[ERROR] urls[1] = file:/C:/Users/rmahna/.m2/repository/org/apache/maven/maven-archiver/2.2/maven-archiver-2.2.jar
[ERROR] urls[2] = file:/C:/Users/rmahna/.m2/repository/junit/junit/3.8.1/junit-3.8.1.jar
[ERROR] urls[3] = file:/C:/Users/rmahna/.m2/repository/org/codehaus/plexus/plexus-archiver/1.0-alpha-7/plexus-archiver-1.0-alpha-7.jar
[ERROR] urls[4] = file:/C:/Users/rmahna/.m2/repository/org/apache/felix/org.apache.felix.scr.generator/1.13.0/org.apache.felix.scr.generator-1.13.0.jar
[ERROR] urls[5] = file:/C:/Users/rmahna/.m2/repository/org/ow2/asm/asm-all/5.0.2/asm-all-5.0.2.jar
[ERROR] urls[6] = file:/C:/Users/rmahna/.m2/repository/org/osgi/org.osgi.core/4.2.0/org.osgi.core-4.2.0.jar
[ERROR] urls[7] = file:/C:/Users/rmahna/.m2/repository/org/osgi/org.osgi.compendium/4.2.0/org.osgi.compendium-4.2.0.jar
[ERROR] urls[8] = file:/C:/Users/rmahna/.m2/repository/org/sonatype/plexus/plexus-build-api/0.0.7/plexus-build-api-0.0.7.jar
[ERROR] urls[9] = file:/C:/Users/rmahna/.m2/repository/org/codehaus/plexus/plexus-utils/1.5.8/plexus-utils-1.5.8.jar
[ERROR] Number of foreign imports: 1
[ERROR] import: Entry[import from realm ClassRealm[project>com.kpmg.cmi.bundles:data-providers:2.0.4, parent: ClassRealm[maven.api, parent: null]]]
[ERROR]
[ERROR] -----------------------------------------------------
My sample Java class is below. I've removed the business logic but even this exact file causes the error.
package my.project.custom.predicates;
import java.util.Comparator;
import javax.jcr.query.Row;
import org.apache.felix.scr.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.search.Predicate;
import com.day.cq.search.eval.AbstractPredicateEvaluator;
import com.day.cq.search.eval.EvaluationContext;
#Component(metatype =false, factory="com.day.cq.search.eval.PredicateEvaluator/mypredicate_eval")
public class MyCustomPredicate extends AbstractPredicateEvaluator {
private static final Logger log = LoggerFactory.getLogger(MyCustomPredicate.class);
public static final String MY_PROPERTY = "my_property";
#Override
public boolean includes(Predicate predicate, Row row, EvaluationContext context) {
if(predicate.hasNonEmptyValue(MY_PROPERTY)){
return true;
}
return super.includes(predicate, row, context);
}
#Override
public String getXPathExpression(Predicate predicate, EvaluationContext context) {
if(!predicate.hasNonEmptyValue(MY_PROPERTY)){
return null;
}
/**
* Some generic string comparisons and processing
*/
return super.getXPathExpression(predicate, context);
}
#Override
public Comparator<Row> getOrderByComparator(final Predicate predicate, final EvaluationContext context) {
return new Comparator<Row>() {
public int compare(Row r1, Row r2) {
String[] property1;
String[] property2;
try {
log.info("inside try method");
//lots of string comparisons
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
}
return 1;
}
};
}
}
I see that you're using the maven-scr-plugin. This plugin has been entirely replaced by standard annotations for the last two releases of the OSGi specification and is now in maintenance mode. My recommendation would be to use the standard annotations instead. The standard annotations are very similar in their use, and will be processed by tools such as the bnd-maven-plugin or maven-bundle-plugin. You are almost certainly already using one of these plugins - the current version (at time of writing) for both plugins is 3.5.0. I would recommend using this version if you need to process Java 8 or Java 9 byte code.
The resulting file will look like this:
package my.project.custom.predicates;
import java.util.Comparator;
import javax.jcr.query.Row;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.search.Predicate;
import com.day.cq.search.eval.AbstractPredicateEvaluator;
import com.day.cq.search.eval.EvaluationContext;
#Component
public class MyCustomPredicate extends AbstractPredicateEvaluator {
// Your implementation in here
}
I am trying to write an OSGI class which should populate the configuration dialog in Felix console, my Service implementation as shown below. but when i try to run mvn clean install -PautoInstallPackage am getting the below error. any help is appreciated.
[ERROR] Failed to execute goal
org.apache.maven.plugins:maven-compiler-plugin:3.2:compile
(default-compile) on project osgiexample.core: Compilation failure
[ERROR]
/E://osgiexample/core/src/main/java/osgiexample/core/serviceimpl/TestServiceImpl.java:[40,10]
cannot find symbol
[ERROR] symbol: class Activate
[ERROR] location:
class osgiexample.core.serviceimpl.TestServiceImpl
#Component(immediate=true, label="TEST Service", description="Hello There - This is a Service component", metatype=true)
#Service(value=TestService.class)
public class TestServiceImpl implements TestService {
#Property(value="http://testservice/myservice?wsdl")
static final String SERVICE_ENDPOINT_URL = "service.endpoint.url";
private String serviceEndpointUrl;
#Override
public String getData() {
// TODO Auto-generated method stub
return null;
}
#Activate
public void activate(final Map<String, Object> props) {
System.out.println("Calling Activate Method");
this.serviceEndpointUrl = (String)props.get(SERVICE_ENDPOINT_URL);
System.out.println("ServiceEndpointUrl:" + this.serviceEndpointUrl);
}
}
Add below Activate annotation import statement should resolve your issue
import org.apache.felix.scr.annotations.Activate;
I'm creating a Mojo which doesn't need a project to run.
I would like to use something similar to org.apache.maven.model.FileSet (providing multiple directories with includes and excludes) as a #parameter but my problem is that I need to be able to set those values using command line.
Any idea how to achieve this?
See:
Guide to Developing Java Plugins, Parameter Types With Multiple Values
Using Plugin Tools Java5 Annotations
Maven Plugin Tool for Annotations, Supported Annotations
org.apache.maven.model.FileSet
POM
<groupId>so</groupId>
<artifactId>multiple-values-maven-plugin</artifactId>
<version>1.0</version>
<packaging>maven-plugin</packaging>
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.4</version>
<scope>provided</scope><!-- annotations are needed only to build the plugin -->
</dependency>
</dependencies>
<!-- This latest plugin has to be used if using Java 8 classes. -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.4</version>
</plugin>
</plugins>
</build>
Mojo
package so;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.maven.model.FileSet;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
#Mojo( name = "values", requiresProject = false )
public class MultipleValuesMojo extends AbstractMojo
{
#Parameter( property = "array", required = true )
private String[] array;
#Parameter( property = "list", required = true )
private List<String> list;
#Parameter( property = "set", required = true )
private String[] setElements;
private Set<String> set;
#Parameter( property = "map", required = true )
private String[] mapEntries;
private Map<String, String> map;
#Parameter( property = "includes", required = true )
private List<String> includes;
#Parameter( property = "excludes", required = true )
private List<String> excludes;
#Override
public void execute() throws MojoExecutionException
{
getLog().info( "Array: " + Arrays.toString( array ) );
getLog().info( " List: " + list.toString() );
set = Arrays.stream( setElements ).collect( Collectors.toSet() ); // with Java >=8
addSetElementsToSet(); // with Java <8
getLog().info( " Set: " + set.toString() );
map = Arrays.stream( mapEntries ).collect( Collectors.toMap( s -> s, s -> s ) ); // with Java >=8
putMapEntriesToMap(); // with Java <8
getLog().info( " Map: " + map.toString() );
getLog().info( "Includes: " + includes.toString() );
getLog().info( "Excludes: " + excludes.toString() );
FileSet fileSet = new FileSet();
fileSet.setIncludes( includes );
fileSet.setExcludes( excludes );
getLog().info( " FileSet: " + fileSet.toString() );
} // execute()
private void addSetElementsToSet()
{
set = new HashSet<String>( setElements.length );
for ( String entry : setElements )
{
set.add( entry );
}
} // addSetElementsToSet()
private void putMapEntriesToMap()
{
map = new HashMap<String, String>( mapEntries.length );
for ( String entry : mapEntries )
{
int equalsPosition = entry.indexOf( "=" );
map.put(
entry.substring( 0, equalsPosition ),
entry.substring( equalsPosition + 1 ) );
}
} // putMapEntriesToMap()
} // MultipleValuesMojo
Run
mvn so:multiple-value-maven-plugin:values
-Darray=VALUE_1,VALUE_2,VALUE_3
-Dlist=VALUE_1,VALUE_2,VALUE_3
-Dset=VALUE_1,VALUE_2,VALUE_3
-Dmap=KEY_1=VALUE_1,KEY_2=VALUE_2,KEY_3=VALUE_3
-Dincludes=/,/usr/*
-Dexcludes=/root,/tmp
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building multiple-values-maven-plugin 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- multiple-values-maven-plugin:1.0:values (default-cli) # multiple-values-maven-plugin ---
[INFO] Array: [VALUE_1, VALUE_2, VALUE_3]
[INFO] List: [VALUE_1, VALUE_2, VALUE_3]
[INFO] Set: [VALUE_3, VALUE_2, VALUE_1]
[INFO] Map: {KEY_1=VALUE_1, KEY_3=VALUE_3, KEY_2=VALUE_2}
[INFO] Includes: [/, /usr/*]
[INFO] Excludes: [/root, /tmp]
[INFO] FileSet: FileSet {directory: null, PatternSet [includes: {/, /usr/*}, excludes: {/root, /tmp}]}
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.671 s
[INFO] Finished at: 2015-07-25T21:44:09+02:00
[INFO] Final Memory: 11M/115M
[INFO] ------------------------------------------------------------------------
Anyone looking for the solution:
-D<some-property>.fileSet=['path-to-fileset']
did the trick for me. It might require slight modification, depending on a plugin you're configuring, but you get the idea.
Tested on Maven 3.5.0
I have simple presenter. Announce the call to the class of singleton
private RandomString randomString = RandomString.getInstance();
When assembling maven I have error
[INFO] [ERROR] Error injecting by.gwttest.client.client.application.packet.PacketPagePresenter$MyProxy: Unable to create or inherit binding: No #Inject or default constructor found for by.gwttest.client.client.application.packet.PacketPagePresenter$MyProxy
[INFO] Path to required node:
[INFO]
[INFO] by.gwttest.client.client.application.packet.PacketPagePresenter$MyProxy [com.gwtplatform.mvp.client.gin.AbstractPresenterModule.bindPresenter(AbstractPresenterModule.java:121)]
[INFO]
[INFO] [ERROR] Error injecting by.gwttest.client.client.application.packet.PacketPageView$Binder: Unable to create or inherit binding: No #Inject or default constructor found for by.gwttest.client.client.application.packet.PacketPageView$Binder
[INFO] Path to required node:
[INFO]
[INFO] by.gwttest.client.client.application.packet.PacketPageView [com.gwtplatform.mvp.client.gin.AbstractPresenterModule.bindPresenter(AbstractPresenterModule.java:120)]
[INFO] -> by.gwttest.client.client.application.packet.PacketPageView$Binder [#Inject constructor of by.gwttest.client.client.application.packet.PacketPageView]
[INFO]
[INFO] [ERROR] Errors in 'gen/com/gwtplatform/mvp/client/DesktopGinjectorProvider.java'
[INFO] [ERROR] Line 8: Failed to resolve 'com.gwtplatform.mvp.client.DesktopGinjector' via deferred binding
RandomString
...
private RandomString() {
}
private static class RandomStringHolder {
private final static RandomString instance = new RandomString();
}
public static RandomString getInstance() {
return RandomStringHolder.instance;
}
...
With what it can be connected? Without declaring RandomString project going
Your error is unrelated to the RandomString. The error says that you are missing a #Inject annotated constructor.
Make sure that your PacketPageView and PacketPagePresenter have an empty constructor that is annotated with #Inject.
#Inject
public PacketPagePresenter() {
}
Error was in this code
private String convertMStoTime(long millis) {
//return null;
return String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
}
TimeUnit dont'realese in GWT