How to call ResolveCustomer and GetEntitlements from aws-marketplace? - aws-java-sdk

I find java sdk
but I can't find example of usage.
I need to call ResolveCustomer (produces a token for the product and user) and GetEntitlements (gives a list of rights for the product and the user).
Has anyone used this service?

Here is full example to get information about client from aws marketplace.
You should to use this librarys:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-marketplacemeteringservice</artifactId>
<version>1.11.192</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-marketplaceentitlement</artifactId>
<version>1.11.194</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
Java code:
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.marketplaceentitlement.AWSMarketplaceEntitlementClient;
import com.amazonaws.services.marketplaceentitlement.AWSMarketplaceEntitlementClientBuilder;
import com.amazonaws.services.marketplaceentitlement.model.GetEntitlementsRequest;
import com.amazonaws.services.marketplaceentitlement.model.GetEntitlementsResult;
import com.amazonaws.services.marketplacemetering.*;
import com.amazonaws.services.marketplacemetering.model.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class R
{
#Test
public void test() throws Exception
{
AWSCredentialsProvider provider = new AWSCredentialsProvider()
{
public AWSCredentials getCredentials()
{
return new AWSCredentials()
{
public String getAWSAccessKeyId()
{
return "<YOUR ACCESS KEY>";
}
public String getAWSSecretKey()
{
return "YOUR SECRET KEY";
}
};
}
public void refresh()
{
}
};
AWSMarketplaceMeteringClientBuilder b = AWSMarketplaceMeteringClient.builder();
b.setRegion("us-east-1"); // YOUR AWS REGION
b.setCredentials(provider);
AWSMarketplaceMetering c = b.build();
ResolveCustomerRequest r = new ResolveCustomerRequest();
r.setRegistrationToken(<YOUR "x-amzn-marketplace-token">); // it comes to your application in the url parameter when the user clicks the buy button in the aws market
final ResolveCustomerResult response = c.resolveCustomer(r);
AWSMarketplaceEntitlementClientBuilder entitlementClientBuilder = AWSMarketplaceEntitlementClient.builder();
entitlementClientBuilder.setRegion("us-east-1");
entitlementClientBuilder.setCredentials(provider);
GetEntitlementsRequest getEntitlementsRequest = new GetEntitlementsRequest();
getEntitlementsRequest.setProductCode(response.getProductCode());
getEntitlementsRequest.setFilter(new HashMap<String, List<String>>()
{{
put("CUSTOMER_IDENTIFIER", new ArrayList<String>()
{{
add(response.getCustomerIdentifier());
}});
}});
GetEntitlementsResult entitlementsResult = entitlementClientBuilder.build().getEntitlements(getEntitlementsRequest);
entitlementsResult = null;
}
}
Also your should add policy in your aws account:

Related

How can I implement the Android Car API for Andorid Studio to read out my EVs percentage?

I'm currently trying to display the percentage of my Ev Via Android Auto. I can't manage to get CarInfo carInfo = getCarContext().getCarService(CarHardwareManager.class).getCarInfo(); to run. I used this in my automotive build.gradle useLibrary 'android.car' and tried importing many things but that didn't help obviously.
This is my first file:
package com.example.aatest4;
import android.car.Car;
import android.car.CarInfoManager;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.car.app.CarAppMetadataHolderService;
import androidx.car.app.CarAppService;
import androidx.car.app.CarContext;
import androidx.car.app.Screen;
import androidx.car.app.Session;
import androidx.car.app.hardware.CarHardwareManager;
import androidx.car.app.hardware.info.CarInfo;
import androidx.car.app.validation.HostValidator;
//import android.content.ServiceConnection;
public class HelloWorldService extends CarAppService {
#NonNull
#Override
public HostValidator createHostValidator() {
return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR;
}
public Session onCreateSession() {
return new Session() {
#NonNull
#Override
public Screen onCreateScreen(#NonNull Intent intent) {
CarInfo carInfo = getCarContext().getCarService(CarHardwareManager.class).getCarInfo();
return new HelloWorldScreen(getCarContext());
}
};
}
}
and this my second:
package com.example.aatest4;
//import android.car.Car;
//import android.car.CarInfoManager;
import androidx.annotation.NonNull;
import androidx.car.app.CarContext;
import androidx.car.app.Screen;
import androidx.car.app.model.Pane;
import androidx.car.app.model.PaneTemplate;
import androidx.car.app.model.Row;
import androidx.car.app.model.Template;
public class HelloWorldScreen extends Screen {
//public HelloWorldScreen() {
public HelloWorldScreen(CarContext carContext) {
super(carContext);
}
#NonNull
#Override
public Template onGetTemplate() {
String akku = String.valueOf(50);
Row row = new Row.Builder().setTitle(akku + "% ").addText(akku + "%").build();
return new PaneTemplate.Builder(new Pane.Builder().addRow(row).build()) .setTitle("Akkuanzeige").build();
//Todo: Center?
}
}

Liferay 7.2 api json url 404

I have:
Eclispse
Version: 2019-06 (4.12.0)
Build id: 20190614-1200
Liferay 7.2.0 CE GA1.
I use Gradle.
I followed this tutorial:
https://www.liferaystack.com/2017/11/rest-extender-and-jax-rs-restful-web-service-in-liferay-7-dxp.html
I created a rest module.
I created two file of configuration inside the folder "src/main/resources/configuration":
com.liferay.portal.remote.cxf.common.configuration.CXFEndpointPublisherConfiguration-cxf.properties
Code:
contextPath=/my-rest-service
authVerifierProperties=auth.verifier.BasicAuthHeaderAuthVerifier.urls.includes=*
com.liferay.portal.remote.rest.extender.configuration.RestExtenderConfiguration-rest.properties
Code:
contextPaths=/my-rest-service
jaxRsServiceFilterStrings=(component.name=com.liferaystack.application.MyRestServiceApplication)
This is the MyRestWebserviceApplication.java:
package com.liferaystack.application;
import java.util.Collections;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Application;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;
/**
* #author pinoteam
*/
#ApplicationPath("/my-rest-service")
#Component(immediate = true, service = Application.class)
public class MyRestWebserviceApplication extends Application {
public Set<Object> getSingletons() {
return Collections.<Object>singleton(this);
}
#GET
#Produces("text/plain")
public String working() {
return "It works!";
}
#GET
#Path("/morning")
#Produces("text/plain")
public String hello() {
return "Good morning!";
}
#GET
#Path("/mattina")
#Produces("text/plain")
public String helloGa() {
return "Good morning!";
}
#GET
#Path("/morning/{name}")
#Produces("text/plain")
public String morning(
#PathParam("name") String name,
#QueryParam("drink") String drink) {
String greeting = "Good Morning " + name;
if (drink != null) {
greeting += ". Would you like some " + drink + "?";
}
return greeting;
}
}
I run build and deploy.
The app is active, but nothing work.
In control panel i have not any Rest Extender Configuration and i have not api at any url.
what am i missing? any idea?
The tutorial you link is for Liferay 7.0 - the package/path names of the configuration files might have changed, and I've seen a context path being declared in bnd.bnd, rather than those property files - things might have changed since then.
An alternative starting point might be the blade sample, which is written for 7.2, and provides a Whiteboard-properties in the Java class:
#Component(
property = {
JaxrsWhiteboardConstants.JAX_RS_APPLICATION_BASE + "=/users",
JaxrsWhiteboardConstants.JAX_RS_NAME + "=Users"
},
service = Application.class
)
public class UsersRestService extends Application {
#GET
#Path("/list")
#Produces("text/plain")
public String getUsers() {
...
}
...
That plugin's configuration file is rather trivial (looks optional on first glance, but don't take my word for it)

It´s possible to do Database driven tests using data tables using Karate? [duplicate]

This question already has an answer here:
How to pull data from a DB to compare with rest api response from karate
(1 answer)
Closed 1 year ago.
When writing my API tests with Cucumber I have implemented some step definitions that allow specifying the data that needs to exist in the database for each scenario.
Something like this:
Given I have database table "users" with data:
| id | name |
| 1 | User 1 |
This will do an insert in the specified table.
Is it possible to do something like this with Karate?
Thank you.
Yes it is, you will need a insertRows method in your DBUTIL file which i borrowed from #peter
you can then call the methods and pass the variable from the table
Background:
* def config = {username: 'XXXX', password: 'XXXXX', url: 'jdbc:oracle:thin:#XXXXX.net:6236/XXXX_XXXXX', driverClassName: 'oracle.jdbc.driver.OracleDriver'}
* def DbUtil = Java.type('util.DbUtils')
* def db = new DbUtil(config)
def Value = db.insertrows(INSERT INTO sales.promotions (promotion_name,discount, start_date,expired_date)VALUES(<name>);)*
below is the example of DB file, you will need to add dependencies with maven or gradle
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc6_g</artifactId>
<version>12.1.0.2</version>
</dependency>
package util;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class DbUtils {
private static final Logger logger = LoggerFactory.getLogger(DbUtils.class);
private final JdbcTemplate jdbc;
public DbUtils(Map<String, Object> config) {
String url = (String) config.get("url");
String username = (String) config.get("username");
String password = (String) config.get("password");
String driver = (String) config.get("driverClassName");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
jdbc = new JdbcTemplate(dataSource);
logger.info("init jdbc template: {}", url);
}
public Object readValue(String query) {
return jdbc.queryForObject(query, Object.class);
}
public Map<String, Object> readRow(String query) {
return jdbc.queryForMap(query);
}
public List<Map<String, Object>> readRows(String query) {
return jdbc.queryForList(query);
}
public void insertRows(final String sql){
jdbc.batchUpdate(new String[]{sql});
}
}

How to read xml file key value using netflix archaius API?

I am new in Netflix Archaius. Can anyone please provide sample code to read key value from xml file ?
Also would like to see values are update automatically when I changed any key in XML file ...
Regards,
Ashish
Sample JUnit on how to use xml for key/value pairs and using Archaius to automatically load the changes :
Important note on the sample code : The program exits after the first callback. If you want to test more callbacks, increase the counter at class variable 'latch'
package com.test.config;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.configuration.XMLPropertiesConfiguration;
import org.junit.Test;
import com.netflix.config.AbstractPollingScheduler;
import com.netflix.config.ConcurrentMapConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicConfiguration;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import com.netflix.config.FixedDelayPollingScheduler;
import com.netflix.config.PollResult;
import com.netflix.config.PolledConfigurationSource;
public class TestArchaius {
CountDownLatch latch = new CountDownLatch(1);
#Test
public void tes() throws Exception {
AbstractPollingScheduler scheduler = new FixedDelayPollingScheduler(0, 1000, false);
DynamicConfiguration dynamicConfiguration = new DynamicConfiguration(new MyPolledConfigurationSource(), scheduler);
ConfigurationManager.install(dynamicConfiguration);
DynamicStringProperty fieldsProperty = DynamicPropertyFactory.getInstance().getStringProperty("key1", "");
fieldsProperty.addCallback(() -> {
System.out.println(fieldsProperty.get());
latch.countDown();
});
latch.await();
}
class MyPolledConfigurationSource implements PolledConfigurationSource {
#Override
public PollResult poll(boolean initial, Object checkPoint) throws Exception {
ConcurrentMapConfiguration configFromPropertiesFile = new ConcurrentMapConfiguration(
new XMLPropertiesConfiguration("test.xml"));
Map<String, Object> fullProperties = new HashMap<String, Object>();
configFromPropertiesFile.getProperties().forEach((k, v) -> fullProperties.put((String) k, v));
return PollResult.createFull(fullProperties);
}
}
}
test.xml :
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Description of the property list</comment>
<entry key="key1">value1</entry>
<entry key="key2">value2</entry>
<entry key="key3">value3</entry>
</properties>

JUnit reporter does not show detailed report for each step in JBehave

I'm trying to set up JBehave for testing web services.
Template story is running well, but I can see in JUnit Panel only Acceptance suite class execution result. What I want is to see execution result for each story in suite and for each step in story like it is shown in simple JUnit tests or in Thucydides framework.
Here is my acceptance suite class: so maybe I Haven't configured something, or either I have to notate my step methods some other way, but I didn't find an answer yet.
package ***.qa_webservices_testing.jbehave;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.jbehave.core.Embeddable;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.parsers.RegexPrefixCapturingPatternParser;
import org.jbehave.core.reporters.CrossReference;
import org.jbehave.core.reporters.Format;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.jbehave.core.steps.ParameterConverters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ***.qa_webservices_testing.jbehave.steps.actions.TestAction;
/**
* suite class.
*/
public class AcceptanceTestSuite extends JUnitStories {
private static final String CTC_STORIES_PATTERN = "ctc.stories";
private static final String STORY_BASE = "src/test/resources";
private static final String DEFAULT_STORY_NAME = "stories/**/*.story";
private static final Logger LOGGER = LoggerFactory.getLogger(AcceptanceTestSuite.class);
private final CrossReference xref = new CrossReference();
public AcceptanceTestSuite() {
configuredEmbedder()
.embedderControls()
.doGenerateViewAfterStories(true)
.doIgnoreFailureInStories(false)
.doIgnoreFailureInView(true)
.doVerboseFailures(true)
.useThreads(2)
.useStoryTimeoutInSecs(60);
}
#Override
public Configuration configuration() {
Class<? extends Embeddable> embeddableClass = this.getClass();
Properties viewResources = new Properties();
viewResources.put("decorateNonHtml", "true");
viewResources.put("reports", "ftl/jbehave-reports-with-totals.ftl");
// Start from default ParameterConverters instance
ParameterConverters parameterConverters = new ParameterConverters();
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromClasspath(embeddableClass))
.useStoryReporterBuilder(new StoryReporterBuilder()
.withCodeLocation(CodeLocations.codeLocationFromClass(embeddableClass))
.withDefaultFormats()
.withViewResources(viewResources)
.withFormats(Format.CONSOLE, Format.TXT, Format.HTML_TEMPLATE, Format.XML_TEMPLATE)
.withFailureTrace(true)
.withFailureTraceCompression(false)
.withMultiThreading(false)
.withCrossReference(xref))
.useParameterConverters(parameterConverters)
// use '%' instead of '$' to identify parameters
.useStepPatternParser(new RegexPrefixCapturingPatternParser(
"%"))
.useStepMonitor(xref.getStepMonitor());
}
#Override
protected List<String> storyPaths() {
String storiesPattern = System.getProperty(CTC_STORIES_PATTERN);
if (storiesPattern == null) {
storiesPattern = DEFAULT_STORY_NAME;
} else {
storiesPattern = "**/" + storiesPattern;
}
LOGGER.info("will search stories by pattern {}", storiesPattern);
List<String> result = new StoryFinder().findPaths(STORY_BASE, Arrays.asList(storiesPattern), Arrays.asList(""));
for (String item : result) {
LOGGER.info("story to be used: {}", item);
}
return result;
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new TestAction());
}
}
my test methods look like:
Customer customer = new cutomer();
#Given ("I have Access to Server")
public void givenIHaveAccesToServer() {
customer.haveAccesToServer();
}
So they are notated only by JBehave notations.
The result returned in Junit panel is only like here (I yet have no rights to post images):
You should try this open source library:
https://github.com/codecentric/jbehave-junit-runner
It does exactly what you ask for :)
Yes, the codecentric runner works very nicely.
https://github.com/codecentric/jbehave-junit-runner