I don't know how to acquire token without username and password using the adal4j library. I have this code:
public class GetToken implements AuthenticationCallback {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "resource";
String redirectUrl = "redirecturl";
String authority = "https://login.microsoftonline.com/common/";
ExecutorService executor = null;
ClientAssertion clientId = new ClientAssertion("my-client-id");
AuthenticationCallback callback;
// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext;
try {
authContext = new AuthenticationContext(authority, false,executor);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Future <AuthenticationResult> result = authContext.acquireToken(resource, clientId, callback);
}
#Override
public void onSuccess(AuthenticationResult result) {
// TODO Auto-generated method stub
}
#Override
public void onFailure(Throwable exc) {
// TODO Auto-generated method stub
}
}
And I don't know how to acquire token ....
Check this link: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-webapp-java#step-8-create-the-basicfilter-file-for-basicfilter-mvc
Look into the getAccessToke() method.This is what you're looking for:
ExecutorService executor = Executors.newFixedThreadPool(1);
Hope this helps!
You will get an IllegalArgumentException as the Executor service passed to AuthenticationContext is null.
Related
I have a Topology which contains a KafkaSpout and 2 bolts.
BoltParseJsonInput and its execute method:
public void execute(Tuple input) {
// TODO Auto-generated method stub
String data = input.getString(4);
js = new JSONObject(data);
String userId = js.getString("userId");
String timestamp = js.getString("timestamp");
counter++;
System.out.println(counter);
collector.emit(input, new Values(userId, timestamp));
collector.ack(input);
}
BoltInsertRedis and its execute method
public void execute(Tuple input) {
// TODO Auto-generated method stub
String userId = input.getStringByField("userId");
int timestamp = 0;
try {
timestamp = convertTimestampToEpoch(input.getStringByField("timestamp"));
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String timestep = this.prefix + timestamp/10;
String curTimestamp = jedis.hget(timestep, userId);
if(curTimestamp == null || Integer.parseInt(curTimestamp) < timestamp) {
jedis.hset(timestep, userId, Integer.toString(timestamp));
}
collector.ack(input);
}
BoltInsertRedis get the input from BoltParseJsonInput
builder.setBolt("ParseJsonInput-Bolt", new BoltParseJsonInput()).shuffleGrouping("Kafka-Spout");
builder.setBolt("BoltRedisUserLastActive-Bolt", new BoltRedisUserLastActive()).shuffleGrouping("ParseJsonInput-Bolt");
But when I submit this topology into Storm, BoltInsertRedis execute more than BoltParseJsonInput
Can you explain to me what is the problem here?
I found that my ParseJsonBolt had made an exception at message 25700 and it keeps replaying execution at that point. When I made a try catch, it works well
Below is code for which i'm trying to write text case and added what i did but getting null pointer exp
public boolean doVersionLimitCheck(Long mneId) throws DMMException {
CALogUtil.getInstance().logMethodEntry("doVersionLimitCheck",
ConfigArchiveManagerImpl.class.getName());
boolean status = false;
status = validateArchivedVersions(mneId);
CALogUtil.getInstance().logDebug("Version Roll over status::" + status);
CALogUtil.getInstance().logMethodExit("doVersionLimitCheck",
ConfigArchiveManagerImpl.class.getName());
return status;
}
for this i did like below.
#Test
public void testDoVersionLimitCheck() {
Long mneId=Long.valueOf("123");
ConfigArchiveManagerImpl impl = new ConfigArchiveManagerImpl();
try {
Mockito.doReturn(true).when(Mockito.mock(ConfigArchiveManagerImpl.class)).validateArchivedVersions(Mockito.anyLong());
} catch (DMMException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
impl.doVersionLimitCheck(mneId);
} catch (DMMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to spy on the SUT in order to test one method and mock the other:
#Test
public void testDoVersionLimitCheck() {
Long mneId=Long.valueOf("123");
ConfigArchiveManagerImpl impl = Mockito.spy(new ConfigArchiveManagerImpl());
try {
Mockito.doReturn(true).when(impl ).validateArchivedVersions(Mockito.anyLong());
} catch (DMMException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I'm running AzureClient java sdk. I create keyvault client like this:
ApplicationTokenCredentials applicationTokenCredentials=new
ApplicationTokenCredentials(APPLICATION_ID, "DOMAIN", CLIENT_SECRET,
AzureEnvironment.AZURE);
vc = new KeyVaultClient(applicationTokenCredentials);
And the i write this code to get key from azure directory:
Future<KeyBundle> keyBundleFuture = vc.getKeyAsync(testKeyIdentifier, new ServiceCallback<KeyBundle>() {
public void failure(Throwable throwable) {
}
public void success(KeyBundle keyBundle) {
System.out.print(keyBundle.toString());
}
});
KeyBundle keyBundle = keyBundleFuture.get();
But i'm getting this error
Exception in thread "main" java.util.concurrent.ExecutionException: com.microsoft.azure.keyvault.models.KeyVaultErrorException: Status code 401.
Also to note that I have given permissions to my applocation from azure portal to access keyvault
According to the status code 401 of your error and the REST API reference Authentication, requests, and responses of Key Vault, it was caused by using incorrect credentials with Azure Java SDK. To access Key Vault using Azure SDK must be authenticated with KeyVaultCredentials which need to be implemented the method doAuthenticate.
As reference, here is my sample code below.
ServiceClientCredentials credentials = new KeyVaultCredentials() {
#Override
public String doAuthenticate(String authorization, String resource, String scope) {
AuthenticationResult res = null;
try {
res = GetAccessToken(authorization, resource, clientId, secret);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res.getAccessToken();
}
private AuthenticationResult GetAccessToken(String authorization, String resource, String clientID, String clientKey)
throws InterruptedException, ExecutionException {
AuthenticationContext ctx = null;
ExecutorService service = Executors.newFixedThreadPool(1);
try {
ctx = new AuthenticationContext(authorization, false, service);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Future<AuthenticationResult> resp = ctx.acquireToken(resource, new ClientCredential(
clientID, clientKey), null);
AuthenticationResult res = resp.get();
return res;
}
};
KeyVaultClient client = new KeyVaultClient(credentials);
String keyIdentifier = "https://<your-keyvault>.vault.azure.net/keys/<your-key>/xxxxxxxxxxxxxxxxxxxxxx";
KeyBundle keyBundle = client.getKey(keyIdentifier);
Then, it works.
it is throw NullPointerException when i use RPCServiceClient and asynchronous call.But it is normal using RPCServiceClient.invokeBlocking.
my axis2 version is 1.6.4.
this is my code:
public void sendMsg(String xmldata, AxisCallback callback) throws AxisFault {
String webServiceURL = "http://171.8.212.68:8191/axis2/services/UserService";
String sendflag = "true";
if ("true".equals(sendflag)) {
RPCServiceClient serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
EndpointReference targetEPR = new EndpointReference(webServiceURL);
options.setTo(targetEPR);
Object[] opAddEntryArgs = new Object[]{xmldata};
QName opAddEntry = new QName("http://downstream.sysinterface.topsms.topnet.com", "sendMsg");
if (callback == null) {
callback = new AxisCallback() {
public void onComplete() {
// TODO Auto-generated method stub
System.out.println("***********onComplete");
}
public void onError(Exception exception) {
// TODO Auto-generated method stub
exception.printStackTrace();
System.out.println("***********onError:"+exception.getMessage()+":"+ Arrays.toString(exception.getStackTrace()));
System.out.println(getStackTrace(exception));
}
public void onFault(MessageContext context) {
// TODO Auto-generated method stub
System.out.println("***********onFault");
}
public void onMessage(MessageContext context) {
// TODO Auto-generated method stub
System.out.println("***********onMessage");
}
};
}
serviceClient.invokeNonBlocking(opAddEntry, opAddEntryArgs, callback);
serviceClient.cleanupTransport();
serviceClient.cleanup();
}
}
Exception is below:
java.lang.NullPointerException
at org.apache.axis2.context.AbstractContext.needPropertyDifferences(AbstractContext.java:239)
at org.apache.axis2.context.AbstractContext.setProperty(AbstractContext.java:202)
at org.apache.axis2.transport.http.AbstractHTTPSender.getHttpClient(AbstractHTTPSender.java:568)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:157)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:396)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:223)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient$NonBlockingInvocationWorker.run(OutInAxisOperation.java:446)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:767)
My post request code as follows
When post request to the server it reach twice in to the server
and i am sure call httpRequest once.When i call once the request reach server twice or thrise;
private void invokePostOrderRestService(
final RestPostDataCallback<Order> callback,
final RequestOrder requestOrder) {
String URL = BASE_URL + "postOrder";
Log.e("post ordercccccc", "orderPosted");
JSONObject jsonObject = convertOrderRequestToJson(requestOrder);
if (jsonObject != null) {
OrderProApplication
.getContext()
.getRestClient()
.postJsonObject(URL, jsonObject,
new ResponseListener<JSONObject>() {
#Override
public void onSuccess(JSONObject response) {
// TODO Auto-generated method stub
Log.e("Order Post Success","Post Order Successssssssssssssssss");
String status = "";
try {
status = response.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (status.equals("OK")) {
callback.onRestPostDataCompleted(
ResultCode.RESULT_OK, null);
} else {
callback.onRestPostDataCompleted(
ResultCode.RESULT_FAIL, null);
}
}
#Override
public void onRestError(RestError error) {
// TODO Auto-generated method stub
Log.e("Order Post Failed","Post Order failedddddddddddddddddddd");
i = i + 1;
callback.onRestPostDataCompleted(
ResultCode.RESULT_FAIL, null);
}
});
} else {
callback.onRestPostDataCompleted(ResultCode.RESULT_FAIL, null);
}
}
And am pretty sure my url is correct.
Thanks:).
Most likely your method is being called twice. Check where you are calling out the method - this might be occurred thanks to misunderstanding of Activity/Fragment lifecycle.
Put a print in the beginning of your invoke method and check, if it prints out twice.