get ltpatoken2 expiry time - java

I am currently testing a web application deployed on IBM Websphere Application Server. I understand that I can set the LTPAToken timeout via the console configuration. However, is there any way I can retrieve the timeout duration or a listener in JAVA to indicate that the ltpatoken has expired?

You can get the token expiration time in your Java code like this (this will give you credential expiration time)
Subject callerSubject = WSSubject.getCallerSubject();
Set<WSCredential> credentials = callerSubject.getPublicCredentials(WSCredential.class);
// should contain only one credential
int credSize = credentials.size();
if( credSize != 1)
throw new RuntimeException("Invalid credential number: "+credSize);
WSCredential cred = credentials.iterator().next();
System.out.println("getExpiration: " + cred.getExpiration()+" date: " + new Date(cred.getExpiration()) + "<BR>");
if you are interested in particular in ltpatoken, you need to extend it a bit (but probably credential will be enough for you):
Set tokens = callerSubject.getPrivateCredentials();
for (Object o : tokens) {
if(o instanceof SingleSignonToken) {
SingleSignonToken ssoToken = (SingleSignonToken)o;
System.out.println("getName: " + ssoToken.getName()+"<BR>");
if("LtpaToken".equals(ssoToken.getName())){
System.out.println("getExpiration: " + ssoToken.getExpiration()+"<BR>");
}
}
}

The SingleSignonToken's getExpiration() method returns the expiration time in milliseconds. You can do something like this,
ssoToken.getExpiration() - System.currentTimeMillis();
to find out how much time this token has left. Or, you can call the isValid() method that will do that for you.

Related

VMWare java SDK: When doesn't an available PerfMetricID report Data?

I'm trying to use vmware sdk for java to collect the perfomance data of each entity (cluster/datastore/Host/VM) in the vmware environment.
The idea is to get the available PerfMetricIds for the target entity with queryAvailablePerfMetric, query those and report the details of the counter, the timestamp and the value.
However when I get the PerfMetricIds for an entity, not every detected (returned) PerfMetricId is reporting data. For example for each Datastore I get at least 4 ids which do not return data when queried, these IDs represent the counters associated with the average number of read and write operations, and for a cluster I'm missing the cpu usage, and so on ...
so I was wondering when does this happen? Shouldn't every metric returned by queryAvailablePerfMetric report data? what am I missing here?
Minimal code snippet:
// VMWare credentials
String vmwareUrl = args[0];
String vmwareUsername = args[1];
String vmwarePassword = args[2];
// connect to vCenter
ServiceInstance si = new ServiceInstance(new URL(vmwareUrl), vmwareUsername, vmwarePassword, true);
// get performance manager
PerformanceManager perfMgr = si.getPerformanceManager();
// define the time window (the last one hour)
Calendar calTo = Calendar.getInstance();
Calendar calFrom = Calendar.getInstance();
calFrom.setTime(calTo.getTime());
calFrom.add(Calendar.HOUR, -1);
// get any datastore for testing purposes
Folder rootFolder = si.getRootFolder();
ManagedEntity[] datastores = new InventoryNavigator(rootFolder).searchManagedEntities("Datastore");
ManagedEntity me = datastores[1];
// query all available metrics for the entity
PerfMetricId[] availablePmis = perfMgr.queryAvailablePerfMetric(me, calFrom, calTo, perfMgr.getHistoricalInterval()[0].getSamplingPeriod());
// create PerfQuerySpec
PerfQuerySpec qSpec = new PerfQuerySpec();
qSpec.setEntity(me.getMOR());
qSpec.setMetricId(availablePmis);
qSpec.setFormat("csv");
qSpec.setStartTime(calFrom);
qSpec.setEndTime(calTo);
// query perf
PerfEntityMetricBase[] perfValues = perfMgr.queryPerf(new PerfQuerySpec[]{qSpec});
// Printing
System.out.println("Found pmis (CounterIDs only): ");
for (PerfMetricId pmi : availablePmis){
System.out.print(pmi.getCounterId() + ", ");
}
System.out.print("\nPmis with values:");
int pmisCount=0;
for (PerfEntityMetricBase value : perfValues) {
PerfMetricSeriesCSV[] csvValues = ((PerfEntityMetricCSV) value).getValue();
pmisCount += csvValues.length;;
for (PerfMetricSeriesCSV csv : csvValues) {
System.out.println("Counter ID: " + csv.getId().getCounterId() + " ---- Metric instance: " + csv.getId().getInstance());
System.out.println("\tInfo: " + ((PerfEntityMetricCSV) value).getSampleInfoCSV());
System.out.println("\tValues: " + csv.getValue());
}
}
System.out.println("---------------");
System.out.println("Detected PMIs: " + availablePmis.length);
System.out.println("PMIs with values: " + pmisCount);
Any help (or discussions) would be appreciated

FCM : setting the TTL ("time_to_live" or lifespan) attribute with a Java Server (Google documentation is wrong/unclear)

I've searched for hours and can't find an answer (lots of unanswered questions on SO, among other things).
My current code
/**
* Use when the server has determined how many Alerts are situated inside
* a single Monitored Zone of a user.
*
* Documentation:
* https://firebase.google.com/docs/cloud-messaging/admin/send-messages
*
* #param registrationToken tokens of the devices the notif is sent to
* #param mzName name of the Monitored Zone (can be its ID)
* #param nbrAlertes number of alerts detected inside the MZ
*/
public static void sendMzLiveAlertNotif(ArrayList<String> registrationToken,
String mzName, int nbrAlertes) {
if(registrationToken.size() == 0 || nbrAlertes == 0 || mzName.isEmpty())
return;
registrationToken.forEach(token -> {
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("title", NotifType.NEW_LIVE_ALERT.getTitle())
.putData("body", "\"" + mzName + "\" contient " + nbrAlertes + " alertes.")
.putData("tag", mzName)
.putData("nbrAlerts", nbrAlertes+"")
.setToken(token)
.build();
try {
// Send a message to the device.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
} catch (Exception e) {
e.printStackTrace();
}
});
}
This worked perfectly, until I wanted to add a lifespan to my notifications. I am still trying to figure out what is the proper way to do so with Java.
My question
I'm wondering how I am supposed to impose a 30 hours lifespan to my message (and also why it works without me using the setAndroidConfig method that Google seems to use).
My server is coded in Java, and the notifications are pushed to an Android application.
My initial thought was to go for:
Message message = Message.builder()
.putData("title", NotifType.NEW_LIVE_ALERT.getTitle())
.putData("body", "\"" + mzName + "\" contient " + nbrAlertes + " alertes.")
.putData("tag", mzName)
.putData("nbrAlerts", nbrAlertes+"")
.setToken(token)
.setAndroidConfig(AndroidConfig.builder()
.setTtl(3600 * 30) // 30 hours ?
.build())
.build();
... but after seeing how Google uses the AndroidConfig for the whole thing, I'm wondering if I should too.
Google Documentation
The only examples I can find are from Google themselves. Here is an example:
#Test
public void testAndroidMessageWithoutNotification() throws IOException {
Message message = Message.builder()
.setAndroidConfig(AndroidConfig.builder()
.setCollapseKey("test-key")
.setPriority(Priority.HIGH)
.setTtl(10)
.setRestrictedPackageName("test-pkg-name")
.putData("k1", "v1")
.putAllData(ImmutableMap.of("k2", "v2", "k3", "v3"))
.build())
.setTopic("test-topic")
.build();
Map<String, Object> data = ImmutableMap.<String, Object>of(
"collapse_key", "test-key",
"priority", "high",
"ttl", "0.010000000s", // 10 ms = 10,000,000 ns
"restricted_package_name", "test-pkg-name",
"data", ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3")
);
assertJsonEquals(ImmutableMap.of("topic", "test-topic", "android", data), message);
}
Do you see the .setTtl(10)and the "ttl", "0.010000000s", // 10 ms = 10,000,000 ns parts? It confuses me. Their documentation says (emphasis is mine):
time_to_live : Optional, number : This parameter specifies how long (in seconds) the message should be kept in FCM storage if the
device is offline. The maximum time to live supported is 4 weeks, and
the default value is 4 weeks. For more information, see Setting the
lifespan of a
message.
The link they tell us to read says:
On Android and Web/JavaScript, you can specify the maximum lifespan of
a message. The value must be a duration from 0 to 2,419,200 seconds
(28 days), and it corresponds to the maximum period of time for which
FCM stores and attempts to deliver the message. Requests that don't
contain this field default to the maximum period of four weeks.
They clearly want the thing to be in seconds. Yet their tests show usage of milliseconds ?! It is frustrating to find so many examples in JavaScript, and almost nothing in Java within their documentation!
In itself, one can also find this contradictory documentation:
public AndroidConfig.Builder setTtl (long ttl)
Sets the time-to-live duration of the message in milliseconds.
A good case of confusing documentation.
You should go with ms, so for 30 hours you would get something like this:
Message message = Message.builder()
.putData("title", NotifType.NEW_USER_ALERT.getTitle())
.putData("body", "\"" + mzName + "\" contient " + nbrAlertes + " alertes.")
.putData("tag", mzName)
.putData("nbrAlerts", nbrAlertes+"")
.setToken(token)
.setAndroidConfig(AndroidConfig.builder()
.setTtl(30*3600*1000) // 30 hours
.build())
.build();

How to get client list using SOAP Web Services in Netsuite ERP?

I am really new to SOAP web services and to Netsuite ERP and I am trying to generate a report in my company where I need to obtain all the Clients and their Invoices using the data available in Netsuite ERP. I followed the Java and Axis tutorial they offer with their sample app for the ERP and I successfully created a Java project in Eclipse that consumes the WSDL for netsuite 2015-2 and compiles the needed classes to run the sample app. So, I followed an example found in their CRM exapmle app to obtain a Client's information but the only problem is that their example method needs you to introduce the Client's ID. Here is the sample code:
public int getCustomerList() throws RemoteException,
ExceededUsageLimitFault, UnexpectedErrorFault, InvalidSessionFault,
ExceededRecordCountFault, UnsupportedEncodingException {
// This operation requires a valid session
this.login(true);
// Prompt for list of internalIds and put in an array
_console
.write("\ninternalIds for records to retrieved (separated by commas): ");
String reqKeys = _console.readLn();
String[] internalIds = reqKeys.split(",");
return getCustomerList(internalIds, false);
}
private int getCustomerList(String[] internalIds, boolean isExternal)
throws RemoteException, ExceededUsageLimitFault,
UnexpectedErrorFault, InvalidSessionFault, ExceededRecordCountFault {
// Build an array of RecordRef objects and invoke the getList()
// operation to retrieve these records
RecordRef[] recordRefs = new RecordRef[internalIds.length];
for (int i = 0; i < internalIds.length; i++) {
RecordRef recordRef = new RecordRef();
recordRef.setInternalId(internalIds[i]);
recordRefs[i] = recordRef;
recordRefs[i].setType(RecordType.customer);
}
// Invoke getList() operation
ReadResponseList getResponseList = _port.getList(recordRefs);
// Process response from get() operation
if (!isExternal)
_console.info("\nRecords returned from getList() operation: \n");
int numRecords = 0;
ReadResponse[] getResponses = getResponseList.getReadResponse();
for (int i = 0; i < getResponses.length; i++) {
_console.info("\n Record[" + i + "]: ");
if (!getResponses[i].getStatus().isIsSuccess()) {
_console.errorForRecord(getStatusDetails(getResponses[i]
.getStatus()));
} else {
numRecords++;
Customer customer = (Customer) getResponses[i].getRecord();
_console.info(" internalId="
+ customer.getInternalId()
+ "\n entityId="
+ customer.getEntityId()
+ (customer.getCompanyName() == null ? ""
: ("\n companyName=" + customer
.getCompanyName()))
+ (customer.getEntityStatus() == null ? ""
: ("\n status=" + customer.getEntityStatus().getName()))
+ (customer.getEmail() == null ? ""
: ("\n email=" + customer.getEmail()))
+ (customer.getPhone() == null ? ""
: ("\n phone=" + customer.getPhone()))
+ "\n isInactive="
+ customer.getIsInactive()
+ (customer.getDateCreated() != null ? ""
: ("\n dateCreated=" + customer
.getDateCreated().toString())));
}
}
return numRecords;
}
So as you can see, this method needs the internal ID of each Customer which I find not useful as I have a many Customers and I don't want to pass each Customer's ID. I read their API docs (which I find hard to navigate and kind of useless) and I found a web service called getAll() that gives all the records given a getAllRecord object which requires a getAllRecordType object. However, the getAllRecordType object does not support Customer entities, so I can't obtain all the customers on the ERP this way.
Is there an easy way to obtain all the Customers in my Netsuite ERP (maybe using other thing rather than the SOAP Web Services they offer? I am desperate about this situation as understanding how Netsuite's Web Services API has been really troublesome.
Thanks!
You would normally use a search to select a list of customers. On a large account you would not normally get all customers on any regular basis. If you are trying to get the invoices you might just find it more practical to get those with a search.
You wrote "in your company". Are you trying to write an application of some sort? If this is an internal project (and even if it's not) you'll probably find using SuiteScripts much more efficient in terms of your time and frustration level.
I made it using the following code on my getCustomerList method:
CustomerSearch customerSrch = new CustomerSearch();
SearchResult searchResult = _port.search(customerSrch);
System.out.println(searchResult.getTotalRecords());
RecordList rl = searchResult.getRecordList();
for (int i = 0; i <searchResult.getTotalRecords()-1; i++) {
Record r = rl.getRecord(i);
System.out.println("Customer # " + i);
Customer testcust = (Customer)r;
System.out.println("First Name: " + testcust.getFirstName());
}

AmazonCloudWatchClient not sending HTTP requests

first time i'm using aws api in java to get the cloud watch statistics for my ec2-instance. i googled about this and i found some code snippet. here it is
AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(
new BasicAWSCredentials(AccessKey, SecretKey));
cloudWatch.setEndpoint("ec2-<my-static-ip>.compute-1.amazonaws.com");
long offsetInMilliseconds = 1000 * 60 * 60 * 24;
Dimension instanceDimension = new Dimension();
instanceDimension.setName("Instanceid");
instanceDimension.setValue(InstanceId);
GetMetricStatisticsRequest request = new GetMetricStatisticsRequest()
.withStartTime(
new Date(new Date().getTime()
- offsetInMilliseconds))
.withNamespace("AWS/EC2")
.withPeriod(60 * 60)
.withDimensions(
new Dimension().withName("InstanceId").withValue(
InstanceId))
.withMetricName("CPUUtilization")
.withStatistics("Average", "Maximum")
.withEndTime(new Date());
GetMetricStatisticsResult getMetricStatisticsResult = cloudWatch
.getMetricStatistics(request);
double avgCPUUtilization = 0;
List dataPoint = getMetricStatisticsResult.getDatapoints();
for (Object aDataPoint : dataPoint) {
Datapoint dp = (Datapoint) aDataPoint;
avgCPUUtilization = dp.getAverage();
System.out.println(InstanceId
+ " instance's average CPU utilization : "
+ dp.getAverage());
}
} catch (AmazonServiceException ase) {
System.out
.println("Caught an AmazonServiceException, which means the request was made "
+ "to Amazon EC2, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
}
so, using this code i tried to get statistics, but first time it throws error saying
com.amazonaws.AmazonClientException: Unable to execute HTTP request:Connection to https://ec2-<my-static-ip>.compute-1.amazonaws.com refused
then i thought it was sending https requests. so i enabled ssl on my instance and tried, then i'm getting below exception.
com.amazonaws.AmazonClientException: Unable to execute HTTP request: peer not authenticated
i was using OpenJDK in my instance, so i thought that may causing the problem. then i removed openjdk and installed Oracle JDK 1.7. but still same problem.
My questions are,
1) how can i send only HTTP (instead of HTTPS) requests to get statistics?
2)how to get rid of this problem, so that i can get my results?
But please don't ask me to read any docs, because i messed up by searching in net, blogs,forums, docs... etc. then i end up here. so, please just provide me solution or tell me where i'm going wrong.
Can anybody please help me out this issue.
thank you in Advance.
Got Solution.
1) removed setting end point for AmazonCloudWatchClient.
2) problem with the AWS credentials (Access key ID, Secret key).So, i created another set of credentials and gave CloudWatchFullAccess policy for the user.
Now it is working like Charm... :-)
Thanks.

JavaScript Cookie Creation Issue

I am currently trying to create a cookie in JavaScript. The idea is that when the user clicks the extension icon whilst watching a YouTube video it gets the tab name and saves it as a cookie. This is so that I can then access the cookie from my Java program.
I am using chrome and I can't see the cookie in the list when I have pressed it even though the alert successfully displays so I am wondering if anyone can see an issue with my code.
Also if anyone has a better idea of how to get the tab name to my Java program I would be happy to hear your ideas.
Thanks everyone, here's my code:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
createCookie(cookieName, cookieValue);
});
}
function createCookie(name, value)
{
var expires = new Date().getTime() + (1000 * 3600);
var domain = ";domain=.youtube.com";
document.cookie = name + "=" + value + ";expires=" + expires + domain + ";path=/";
alert(name + " = " + value + ". Date = " + expires);
}
EDIT: I have changed my code to use the chrome API's provided by Google, great success!
If anyone has the same problem I have used the Google API's for chrome concerning cookies.
My new code is the following:
chrome.browserAction.onClicked.addListener(run);
function run()
{
var cookieName, cookieValue, cookieURL;
cookieName = "Tab";
chrome.tabs.getSelected(null, function(tab)
{
cookieValue = tab.title;
cookieURL = tab.url;
createCookie(cookieName, cookieValue, cookieURL);
});
}
function createCookie(cookieName, cookieValue, cookieURL)
{
chrome.cookies.set({name: cookieName, value: cookieValue, domain: ".youtube.com", url: cookieURL});
}
Note: In the manifest file you will need permissions for tabs, cookies and the website domain. Furthermore I have not stated when the cookie expires thus it expires when the session is closed.

Categories