what is accessTokenValue, tokenSecretValue in linkedin-j? - java

I try to connect with linkedin using linkedin-j api.
we get consumerKeyValue, consumerSecretValue when we register in for application in linked in how to get ccessTokenValue, tokenSecretValue.
following are two lines where we user ccessTokenValue, tokenSecretValue.
final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(consumerKeyValue, consumerSecretValue);
final LinkedInApiClient client = factory.createLinkedInApiClient(accessTokenValue, tokenSecretValue);

Related

How do you create ProjectApiRoot as Customer in Commercetools

I can create a ProjectApiRoot using the Java SDK and perform requests with that using the following code:
private static ProjectApiRoot createProjectClient() {
ProjectApiRoot apiRoot = ApiRootBuilder.of()
.defaultClient(ClientCredentials.of()
.withClientId(System.getenv("CTP_CLIENT_ID"))
.withClientSecret(System.getenv("CTP_CLIENT_SECRET"))
.build(),
ServiceRegion.GCP_EUROPE_WEST1)
.build(System.getenv("CTP_PROJECT_KEY"))
return apiRoot
}
However, I would like to authorize as a specific customer (email and password) and interact with the Commercetools API using the customer. The following code throws an error:
private static ProjectApiRoot createCustomerClient() {
def tokenUri = "https://auth.europe-west1.gcp.commercetools.com/oauth/*CTP_PROJECT_KEY*/customers/token"
def projectKey = System.getenv("CTP_PROJECT_KEY")
def scopes = System.getenv("CTP_SCOPES")
def credentials = ClientCredentials.of()
.withClientId("*email*")
.withClientSecret("*password*")
.withScopes(scopes)
.build()
def apiRootBuilder = ApiRootBuilder.of()
.withApiBaseUrl("https://api.europe-west1.gcp.commercetools.com")
.withClientCredentialsFlow(credentials, tokenUri)
return apiRootBuilder.build(projectKey)
}
Error:
io.vrap.rmf.base.client.oauth2.AuthException: detailMessage: Unauthorized
"message" : "Please provide valid client credentials using HTTP Basic Authentication.",
By using the withGlobalCustomerPasswordFlow instead of the withClientCredentialsFlow which authenticates the customer prior to doing the request.
But I would advise to do this only in a context where the customer is logging in everytime. Using it in any other context e.g. remembered log in of needs a more sophisticated approach as you need to store the bearer token and refresh token and can't easily use the middleware approach for authenticating the customer but instead do it not as part of an auth flow middleware.
Please see also https://github.com/commercetools/commercetools-sdk-java-v2/tree/main/commercetools/commercetools-sdk-java-api/src/integrationTest/java/commercetools/me

AWS elasticsearch access Request signing using Java

I want to connect to elastic search from Java. Elastic search domain is configured in AWS. I am using Jest library for this. Currently i have added my system ip in the elastic search configure access section. So i can access ES endpoint. But this is not the right way of doing it. What are the approches to it ? i know about signing the request but could not find any good reference of how to do it in java. Can anyone give some thoughts ?
This is how my code looks like
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig.Builder(elasticSearchserverUrl).connTimeout(10000).readTimeout(10000)
.multiThreaded(true).build());
JestClient client = factory.getObject();
Search.Builder searchBuilder = new Search.Builder(query).addIndices(indices).addType(type);
try {
SearchResult result = client.execute(searchBuilder.build());
List<Hit<String, Void>> hits = result.getHits(String.class);
for (Hit<String, Void> hit : hits) {
String log = hit.source;
System.out.println(log);
}
} catch (IOException e) {
}

azure java sdk authentication

I would like to list available IP VM's in the new Azure portal using Java SDK.
Couple of years back in the good old classic portal, I had followed the usual management certificate procedure to access vm's,create vm's and work with Azure Endpoints.
Fast fwd now I see that they have used a new portal and new mechanisms to interact with Java SDK. I read somewhere in the above link that with the old way with certificates, I can manage only the class portal resources.
I'm trying to code a simple program which authenticates and lists the vm's of the new portal as a start. Seems like they have complicated it a lot.
I followed the below link to "Create service principal with password"
https://azure.microsoft.com/en-us/documentation/articles/resource-group-authenticate-service-principal/
Then I went to this link
https://azure.microsoft.com/en-us/documentation/samples/resources-java-manage-resource-group/
which asked me go the "See how to create an Auth file" link in above page
(mine is not a webapp and when I try to create the AD as a native client application, it is not allowing me to save keys in configure tab, so I had to create a web app)
After doing all this, I got stuck with this below error
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
'authority' Uri should have at least one segment in the path (i.e.https://<host>/<path>/...)
java.lang.IllegalArgumentException: 'authority' Uri should have at least one segment in the path (i.e. https://<host>/<path>/...)
at com.microsoft.aad.adal4j.AuthenticationAuthority.detectAuthorityType(AuthenticationAuthority.java:190)
at com.microsoft.aad.adal4j.AuthenticationAuthority.<init>(AuthenticationAuthority.java:73)
When I checked it says that the error is because I don't have a valid client application id in your Azure Active Directory.
Is there any simple way to authenticate and start using the API's?
#Vikram, I suggest that you can try to refer to the article to create an application on AAD.
Then you can follow the code below to get the access token for authentication.
// The parameters include clientId, clientSecret, tenantId, subscriptionId and resourceGroupName.
private static final String clientId = "<client-id>";
private static final String clientSecret = "<key>";
private static final String tenantId = "<tenant-id>";
private static final String subscriptionId = "<subscription-id>";
// The function for getting the access token via Class AuthenticationResult
private static AuthenticationResult getAccessTokenFromServicePrincipalCredentials()
throws ServiceUnavailableException, MalformedURLException, ExecutionException, InterruptedException {
AuthenticationContext context;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
// TODO: add your tenant id
context = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId, false, service);
// TODO: add your client id and client secret
ClientCredential cred = new ClientCredential(clientId, clientSecret);
Future<AuthenticationResult> future = context.acquireToken("https://management.azure.com/", cred, null);
result = future.get();
} finally {
service.shutdown();
}
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
}
return result;
}
String accessToken = getAccessTokenFromServicePrincipalCredentials().getAccessToken();
If you want to list the VMs on new portal, you can try to use the REST API List the resources in a subscription to get all resources and filter the VMs via the resource type Microsoft.Compute/virtualMachines.
Hope it helps.

Connect JIRA and retrieve Information

I have a Task that is to retrieve some Information from a JIRA account through Java. I downloaded the Jira API which is working with Java, but I have no idea how to make it work. I have to pass somewhere my username and password for log in and after that to retrieve what Information I want from what project I want.
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_URL);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser("admin");
// Here I am getting the error!!
User user = promise.claim();
///////////////////////////////////////
// Print the result
System.out.println(String.format("Your admin user's email address is: %s\r\n", user.getEmailAddress()));
// Done
System.out.println("Example complete. Now exiting.");
System.exit(0);
That above code is not working, because either if I pass a wrong password and a wrong username is showing me the same result. I have to know how to connect properly to JIRA and retrive some Information in JSON from there! Thank you for your time!
Here is the error
Caused by: com.atlassian.jira.rest.client.api.RestClientException: org.codehaus.jettison.json.JSONException: A JSONObject text must begin with '{' at character 9 of
I think you don't have the necessary permission to acces Jira , you have to connect with jira with an account that have the correct permissions!
The only thing I can think of is that you are sending incorrect creds. Try using the email address instead of just "admin".
Here is some code that might help: https://github.com/somaiah/jrjc
I check for an issue, but getting user info would be similar.
You can use the below code the get the results.Remember I am using this in my gradle project where I am downloading all the dependencies of JRCJ
import com.atlassian.jira.rest.client.api.JiraRestClientFactory
import com.atlassian.jira.rest.client.api.domain.User
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
/**
* TODO: Class description
*
* on 20 Jul 2017
*/
class Jira {
private static final String JIRA_URL = "https://JIRA.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDE"
private static final String JIRA_ADMIN_PASSWORD = "******"
static void main(String[] args) throws Exception
{
// Construct the JRJC client
System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD))
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
URI uri = new URI(JIRA_URL)
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD)
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser(JIRA_ADMIN_USERNAME)
User user = promise.claim()
// Print the result
System.out.println(String.format("Your user's email address is: %s\r\n", user.getEmailAddress()))
// Done
//System.out.println("Example complete. Now exiting.")
//System.exit(0)
}
}

Java Service Bus Shared Access Token

Configuration config =
ServiceBusConfiguration.configureWithSASAuthentication(
URL,
"RootManageSharedAccessKey",
token,
".servicebus.windows.net"
);
This is the code for configuration for java service bus implementation. I am interested in passing a shared access signature not a shared access key. I am not sure if this implementation for the java azure sdk supports this. How exactly would I do this. I keep getting a 401-unauthorized error when I use the shared access signature token in the token variable. Any ideas?
According to the source code of Azure Service Bus SDK for Java, the four arguments for the function configureWithSASAuthentication should be the namespace, sasKeyName, sasKey & serviceBusRootUri(default pass ".servicebus.windows.net").
The namespace, sasKeyName & sasKey you can find them via click the CONNECTION INFORMATION button at the bottom of your service bus, please see the figures below.
Fig 1. The CONNECTION INFORMATION button at the bottom of the service bus page
Fig 2. Copy the CONNECTION STRING and extract the namespace, sasKeyName & sasKey
For example, the connection string is Endpoint=sb://abc-ns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=ABCdefg123!##=, then the namespace, sasKeyName, sasKey are separately abc-ns, RootManageSharedAccessKey, ABCdefg123!##=.
So the code should be as below.
Configuration config =
ServiceBusConfiguration.configureWithSASAuthentication(
"abc-ns",
"RootManageSharedAccessKey",
"ABCdefg123!##=",
".servicebus.windows.net"
);
And you can also find them at the CONFIGURE tab of your service bus page, please see the figure below.
Fig 3. The CONFIGURE tab
I can see that you created a Configuration object here. Normally we use it to creat a topic in Java, eg:
Configuration config =
ServiceBusConfiguration.configureWithSASAuthentication(
"namespace",
"sasKeyName",
"sasKey",
"serviceBusRootUri"
);
ServiceBusContract service = ServiceBusService.create(config);
TopicInfo topicInfo = new TopicInfo("TestTopic");
CreateTopicResult result = service.createTopic(topicInfo);
or to create a queue, eg:
Configuration config =
ServiceBusConfiguration.configureWithSASAuthentication(
"namespace",
"sasKeyName",
"sasKey",
"serviceBusRootUri"
);
ServiceBusContract service = ServiceBusService.create(config);
QueueInfo queueInfo = new QueueInfo("TestQueue");
CreateQueueResult result = service.createQueue(queueInfo);
and also we can create them by shared access signature:
create a topic(c#)
Uri uri = ServiceBusEnvironment.CreateServiceUri("sb", "namespace", string.Empty);
string name = "sasKeyName";
string key = "sasKey";
TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(name, key);
NamespaceManager namespaceManager = new NamespaceManager(uri, tokenProvider);
namespaceManager.CreateTopic("DataCollectionTopic");
create a queue(c#):
Uri uri = ServiceBusEnvironment.CreateServiceUri("sb",
"namespace", string.Empty);
string name = "sasKeyName";
string key = "sasKey";
TokenProvider tokenProvider =
TokenProvider.CreateSharedAccessSignatureTokenProvider(name, key);
NamespaceManager namespaceManager =
new NamespaceManager(uri, tokenProvider);
namespaceManager.CreateQueue("DataCollectionQueue");
The namespace, sasKeyName, sasKey are configured in portal just as what Perter showed.

Categories