Temporal: How to create a namespace progmatically? - temporal

It is possible to create a namespace via the CLI, but how to do it using Java SDK?

Programmatically it is done through gRPC API exposed by the service.
In Java the generated gRPC client is accessible through WorkflowServiceStubs:
WorkflowServiceStubs service =
WorkflowServiceStubs.newInstance(
WorkflowServiceStubsOptions.newBuilder().setTarget(serviceAddress).build());
RegisterNamespaceRequest request =
RegisterNamespaceRequest.newBuilder()
.setNamespace(NAMESPACE)
.setWorkflowExecutionRetentionPeriod(Durations.fromDays(7))
.build();
service.blockingStub().registerNamespace(request);
In Go SDK you can use higher-level NamespaceClient:
client, err := client.NewNamespaceClient(client.Options{HostPort: ts.config.ServiceAddr})
...
err = client.Register(ctx, &workflowservice.RegisterNamespaceRequest{
Name: name,
WorkflowExecutionRetentionPeriod: &retention,
})
OP and additional discussion here.

Related

Where to find Open API (Swagger) specification for the Confluence Server REST API?

For the Atlassian Confluence Cloud REST API there is an Open API (formerly Swagger) specification available here: https://developer.atlassian.com/cloud/confluence/swagger.v3.json
I was not able to find such an Open API specification for the Confluence Server REST API. Any hints as to where to find it are appreciated.
Here is what I found :)
I share my doc with you :
API Jira Cloud platform
https://developer.atlassian.com/cloud/jira/platform/rest/v3/intro/
https://developer.atlassian.com/cloud/jira/platform/swagger.json
https://developer.atlassian.com/cloud/jira/platform/swagger.v3.json
https://developer.atlassian.com/cloud/jira/platform/swagger-v3.v3.json
API Jira Software Cloud
https://developer.atlassian.com/cloud/jira/software/rest/intro/
https://developer.atlassian.com/cloud/jira/software/swagger.json
https://developer.atlassian.com/cloud/jira/software/swagger.v3.json
API Confluence Cloud
https://developer.atlassian.com/cloud/confluence/rest/v1/intro/
https://developer.atlassian.com/cloud/confluence/swagger.json
https://developer.atlassian.com/cloud/confluence/swagger.v3.json
Jira Service Management Cloud
https://developer.atlassian.com/cloud/jira/service-desk/rest/intro/
https://developer.atlassian.com/cloud/jira/service-desk/swagger.json
https://developer.atlassian.com/cloud/jira/service-desk/swagger.v3.json
Here is my script: in the “Postman environment” variables or in the “collection variables”, add:
baseUrl = https://XXX.atlassian.net
username = XXX#XXX.com
token = <token> https://id.atlassian.com/manage-profile/security/api-tokens
In the “Pre-request Script” of the collection, add:
postman.setEnvironmentVariable(
"base64",
btoa(postman.getEnvironmentVariable("username") + ":" + postman.getEnvironmentVariable("token"))
);
pm.request.headers.add({
key: "Authorization",
value: "Basic " + postman.getEnvironmentVariable("base64")
});
After adding this configuration: you must disable the “Authorization” configurations of each endpoint (because they are configured for the old Basic mode in login/password which no longer works deprecated)

Failing to create services on Google Cloud Run with API using Java SDK

I create a Cloud Run client, however, couldn't find a way to list a service that is deployed with Cloud Run on GKE (for Anthos).
Create the client:
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
credential.createScoped("https://www.googleapis.com/auth/cloud-platform");
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
CloudRun.Builder builder = new CloudRun.Builder(httpTransport, jsonFactory, requestInitializer);
return builder.setApplicationName(applicationName)
.setRootUrl(cloudRunRootUrl)
.build();
} catch (IOException e) {
e.printStackTrace();
}
try to list services:
services = cloudRun.namespaces().services()
.list("namespaces/default")
.execute()
.getItems();
My "hello" service is deploy on a GKE cluster under the namespace default. The above code doesn't work because the client always see "default" as project_id and complains about permission stuff. If I put the project_id rather than "default", permission errors are gone, but no services will be found.
I tried another project that does have Google fully-managed cloud run services, the same code returns result (with .list("namespaces/")).
How to access the service on GKE?
And my next question would be, how to programmatically create Cloud Run services on GKE?
Edit - for creating a service
As I couldn't figure out how to interact with Cloud Run on GKE, I took a step back to try fully managed one. The following code to create a service fails, and the error message just doesn't provide much useful insight, how to make it work?
Service deployedService = null;
// Map<String,String> annotations = new HashMap<>();
// annotations.put("client.knative.dev/user-image","gcr.io/cloudrun/hello");
ServiceSpec spec = new ServiceSpec();
List<Container> containers = new ArrayList<>();
containers.add(new Container().setImage("gcr.io/cloudrun/hello"));
spec.setTemplate(new RevisionTemplate().setMetadata(new ObjectMeta().setName("hello-fully-managed-v0.1.0"))
.setSpec(new RevisionSpec().setContainerConcurrency(20)
.setContainers(containers)
.setTimeoutSeconds(100)
)
);
helloService.setApiVersion("serving.knative.dev/v1")
.setMetadata(new ObjectMeta().setName("hello-fully-managed")
.setNamespace("data-infrastructure-test-env")
// .setAnnotations(annotations)
)
.setSpec(spec)
.setKind("Service");
try {
deployedService = cloudRun.namespaces().services()
.create("namespaces/data-infrastructure-test-env",helloService)
.execute();
} catch (IOException e) {
e.printStackTrace();
response.add(e.toString());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
Error message I got:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "The request has errors",
"reason" : "badRequest"
} ],
"message" : "The request has errors",
"status" : "INVALID_ARGUMENT"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
And the base_url is: https://europe-west1-run.googleapis.com
Your question is quite detailed (and is about Java which I am no expert in) and there are actually too many questions in there (ideally, please ask only 1 question here). However, I'll try to answer a few things you asked:
First, Cloud Run (managed, and on GKE) both implement the Knative Serving API. I've explained this at https://ahmet.im/blog/cloud-run-is-a-knative/ In fact, Cloud Run on GKE is just the open source Knative components installed to your cluster.
And my next question would be, how to programmatically create Cloud Run services on GKE?
You will have a very hard time (if possible at all) using the Cloud Run API client libraries (e.g. new CloudRun above) because these are designed for *.googleapis.com endpoints.
The Knative API part of "Cloud Run on GKE" is actually just your Kubernetes (GKE) master API endpoint (which runs on an IP address, with a TLS certificate that isn't trusted by root CAs, but you can find the CA cert in GKE GetCluster API call to verify the cert.) The TLS is part is why it's so hard to use the API Client libraries.
Knative APIs are just Kubernetes objects. So your best bet is one of these:
See Kubernetes java client (https://github.com/kubernetes-client/java) actually allows dynamic objects. (Go implementation does) and try to use that to create Knative CRDs.
Use kubectl apply.
Ask Knative Serving open source repository for help (they should be providing client libraries, maybe they're already there I'm not sure)
To program Cloud Run (managed) with the API Client Libraries, you need to explicitly override the API endpoint to the region e.g. us-central1-run.googleapis.com. (This is documented on each API call's REST API reference documentation.)
I have written a blog post in detail (with sample code in Go) on how to create/update services on Cloud Run (managed) using the Knative Serving API here: https://ahmet.im/blog/gcloud-run-deploy/
If you want to see how gcloud run deploy works, and which APIs it calls, you can pass --log-http option to observe the request/response traffic.
As for the error you got, it seems like the error message isn't helpful, but it might be coming from anywhere (as you're trying to imitate Knative API in GCP client libraries). I recommend reading my blog posts and sample code in depth.
UPDATES: Our engineering team's looking at the issue, it appears that there's currently a bug not adding the "details" field to the error. That's being worked on.
In your case, we see the following errors from requests:
field: "spec.template.spec"
description: "Missing template spec."
Means you are not properly filling up the spec field as I shown in my blog post and sample code.
field: "metadata.name"
description: "The revision name must be prefixed by the name of the enclosing Service or Configuration with a trailing -"
Make sure the name you are specifying adheres the patterns specified in API docs. Try to create that name manually perhaps in the UI or gcloud CLI.
field: "api_version"
description: "Unsupported API version \'serving.knative.dev/v1\'. Expected \'serving.knative.dev/v1alpha1\'"
Do not use v1alpha1 API, use v1 directly.
We'll try to get the details to the error message, however it appears that you need to study the sample code I linked in my blog post more in detail:
https://github.com/GoogleCloudPlatform/cloud-run-button/blob/a52c7fbaae33a3e06c112206c7227a0ef9649647/cmd/cloudshell_open/deploy.go#L26-L112
The Java SDK is automatically generated from the fact that the Cloud Run (fully managed) API is public. It does not support Cloud Run for Anthos.
(gcloud.run.deploy) The revision name must be prefixed by the name of the enclosing Service or Configuration with a trailing -revision name
revision name name should be 65 character then problem will be resolved in Automation pipeline with GCP revision suffix should be less revision name is the combination of (service name +revision suffix) will automatically created by GCP.

How to use bluetooth devices and FIWARE IoT Agent

I would like to use my bluetooth device (for example I'm going to create an app to be installed in a tablet) to send data (set of attributes) in Orion Context Broker via IoT Agent.
I'm looking for the FIWARE IoT Agent and probably I've to use IoT Agent LWM2M. Is it correct?
Thanks in advance and regards.
Pasquale
Assuming you have freedom of choice, you probably don't need an IoT Agent for that, you just need a service acting as a bluetooth receiver which can receive your message and pass it on using a recognisable transport.
For example, you can receive data using the following Stack Overflow answer
You can then extract the necessary information to identify the device and the context to be updated.
You can programmatically send NGSI requests in any language capable of HTTP - just generate a library using the NGSI Swagger file - an example is shown in the tutorials
// Initialization - first require the NGSI v2 npm library and set
// the client instance
const NgsiV2 = require('ngsi_v2');
const defaultClient = NgsiV2.ApiClient.instance;
defaultClient.basePath = 'http://localhost:1026/v2';
// This is a promise to make an HTTP PATCH request to the /v2/entities/<entity-id>/attr end point
function updateExistingEntityAttributes(entityId, body, opts, headers = {}) {
return new Promise((resolve, reject) => {
defaultClient.defaultHeaders = headers;
const apiInstance = new NgsiV2.EntitiesApi();
apiInstance.updateExistingEntityAttributes(
entityId,
body,
opts,
(error, data, response) => {
return error ? reject(error) : resolve(data);
}
);
});
}
If you really want to do this with an IoT Agent, you can use the IoT Agent Node lib and and create your own IoT Agent

SEMP API equivalent for url "/SEMP/v2/config/msgVpns/default"

URL .../SEMP/v2/config/msgVpns/default returns data
{
"data":{
"authenticationBasicEnabled":true,
"authenticationBasicProfileName":"default",
"authenticationBasicRadiusDomain":"",
"authenticationBasicType":"radius",
"authenticationClientCertAllowApiProvidedUsernameEnabled":false,
....
What is the Java API to return this data? Apparently there is no getMsgVpnsDefault(...) method
Generally speaking what is the translation of URL's into API calls? This doesn't seem to be addressed in the documentation.
What is the Java API to return this data? Apparently there is no getMsgVpnsDefault(...) method
There's no API provided by Solace.
SEMP(v2 in your case) is a series of REST commands to be executed over the management port to manage the configuration of the Solace routers.
This is not to be mistaken for the Java API that's provided for messaging over the messaging port/interface.
Generally speaking what is the translation of URL's into API calls?
The complete list of URL's is documented here:
https://docs.solace.com/API-Developer-Online-Ref-Documentation/swagger-ui/index.html#/
In the Solace Samples repository on GitHub there's a gradle file which uses Swagger CodeGen to generate a POJO wrapper around SEMP v2.
This then gives you a Java API to interact with Solace routers.
WRT your original question about getMsgVpnsDefault(...) I believe you'd use
MsgVpn defaultVPN = sempApiInstance.getMsgVpn("default", null);
Or you could grab the list of all VPNs
MsgVpnsResponse resp = sempApiInstance.getMsgVpns(1000, null, null, null);
List<MsgVpn> allVpsn = resp.getData();
then iterate over the list checking until you find one whose name is "default"
https://github.com/SolaceSamples/solace-samples-semp/tree/master/java

Proxy for OAuthUtil.GetAccessToken

I've setup a perfectly functioning application (in VB) that allows user to access his Google Sheets.
The application follows Google's OAuth documentation for displaying a sign-in dialog in a web browser, obtains user's permission and access codes, uses access codes to obtain access token, and then uses the Google Sheet's Query service to get hold of Google Sheets. Very simple. Works fine.
Problem occurs on computers that have internet proxy defined on them. In the rest of my application and most of Google Sheets API, I can define a manual internet proxy. GData's RequestFactory allows manually configuring proxy server. The only line of code that doesn't support (to my current knowledge) is the OAuthUtil library used for obtaining access token. It doesn't allow defining internet proxy server, hence it is unable to resolve host on computers behind proxy environment. Following is my pseudo code:
Dim parameters As New OAuth2Parameters
parameters.ClientId = CLIENT_ID
parameters.ClientSecret = CLIENT_SECRET
parameters.RedirectUri = REDIRECT_URI
parameters.Scope = SCOPE
>>Show browser window and obtain access code
parameters.AccessCode = login.Token
OAuthUtil.GetAccessToken(parameters) '<< Point of failure
Dim requestFactory As GOAuth2RequestFactory = New GOAuth2RequestFactory(Nothing, My.Application.Info.ProductName, parameters)
requestFactory.Proxy = GetProxySettings() '<< my code for defining proxy
myService = New SpreadsheetsService("Application")
myService.RequestFactory = requestFactory
Another important aspect is that my application works on Mac OSX as well using Wine (for web browser I use GeckoFX). If internet proxy is globally defined on the environment then the OAuthUtil works fine, but this doesn't work for Wine. I have tried setting internet proxy in the command-line environment, or in the registry and refreshed system settings, still the applications running in Wine do not understand that proxy is defined. Hence proxy has to be manually defined.
I need help to figure out a solution by any of the following:
* A way to forcefully/manually define proxy for OAuthUtil for obtaining access token
* Any other way to obtain OAuth access token if proxy cannot be defined as above (maybe WebClient can be used?)
* Some way to define global internet proxy in Wine so applications like GData API read and understand the proxy setting. Though I'd rather prefer manually defined proxy at application level.
Any ideas folks?
Regards
F.A.
I've figured it out. Turns out that the 'OAuthUtil.GetAccessToken' only uses system-defined proxy. There is no way to manually define internet proxy, like RequestFactory supports. So there is a work-around using WebClient:
Try
'// Get access token from code
Using WC As New WebClient
' Define proxy
WC.Proxy = GetProxySettings()
' Set parameters
WC.Headers(HttpRequestHeader.ContentType) = "application/x-www-form-urlencoded"
' Get response
Dim postURL = "https://www.googleapis.com/oauth2/v4/token"
Dim postParams = "code=" & parameters.AccessCode &
"&client_id=" & Uri.EscapeDataString(CLIENT_ID) &
"&client_secret=" & Uri.EscapeDataString(CLIENT_SECRET) &
"&redirect_uri=" & Uri.EscapeDataString(REDIRECT_URI) &
"&grant_type=authorization_code"
Dim responsebody As String = WC.UploadString(postURL, postParams)
' Read response
Dim jObj As JObject = JsonConvert.DeserializeObject(responsebody)
' Store token
parameters.AccessToken = jObj("access_token").ToString
parameters.RefreshToken = jObj("refresh_token").ToString
parameters.TokenType = jObj("token_type").ToString
parameters.TokenExpiry = Now().AddSeconds(CDbl(jObj("expires_in").ToString))
End Using
Catch ex As Exception
MsgBox("Error obtaining access token: " & ex.Message, MsgBoxStyle.Critical)
Return Nothing
End Try

Resources