Does Splunk SDK service require Disconnect or Close - java

I am trying to do a Splunk Seach from Splunk java SDK. Here is the working code. My question is do I need to close service after each search. If yes, how to close it? Else is there a maximum number of jobs that I can create in each service?
ServiceArgs serviceArgs = new ServiceArgs();
serviceArgs.setUsername(splunkUserName);
serviceArgs.setHost(splunkHostname);
serviceArgs.setPort(Integer.parseInt(splunkPort));
serviceArgs.setPassword(splunkPassword));
HttpService.setSslSecurityProtocol(SSLSecurityProtocol.TLSv1_2);
Service service = Service.connect(serviceArgs);
JobArgs jobArgs = new JobArgs();
jobArgs.setExecutionMode(JobArgs.ExecutionMode.NORMAL);
jobArgs.setEarliestTime(startDate);
jobArgs.setLatestTime(endData);
jobArgs.setMaximumCount(maxResultCount);
Job job = service.getJobs().create(query,jobArgs);

My question is do I need to close service after each search
I would say it depends on your needs, I don't know well enough your application.
If yes, how to close it?
Anyway, you can : the com.splunk.Service have a logout method for this :
/**
* Forgets the current session token.
*
* #return The current {#code Service} instance.
*/
public Service logout() {
this.token = null;
this.removeAllCookies();
return this;
}
Else is there a maximum number of jobs that I can create in each service?
I would say yes, it should be the same limitation that the user have by making search through th UI.

Related

How to get the automatically defined port for a Spark Java Application?

In the API documentation for Java Spark (not Apache spark), you can specify a port of 0 to have it automatically select a port. Great!
However, I cannot figure out how to get that port after the server is started. I can see it in the logs:
15:41:12.459 [Thread-2] INFO spark.webserver.JettySparkServer - >> Listening on 0.0.0.0:63134
But I need to be able to get to it programmatically, so that my integration tests are able to run reliably every time.
So how do I get that port?
I could find no way to get this information in the API, and so I filed an issue on their github.
I was able to get at it via an ugly pile of reflection:
/**
* Meant to be called from a different thread, once the spark app is running
* This is probably only going to be used during the integration testing process, not ever in prod!
*
* #return the port it's running on
*/
public static int awaitRunningPort() throws Exception {
awaitInitialization();
//I have to get the port via reflection, which is fugly, but the API doesn't exist :(
//Since we'll only use this in testing, it's not going to kill us
Object instance = getInstance();
Class theClass = instance.getClass();
Field serverField = theClass.getDeclaredField("server");
serverField.setAccessible(true);
Object oneLevelDeepServer = serverField.get(instance);
Class jettyServerClass = oneLevelDeepServer.getClass();
Field jettyServerField = jettyServerClass.getDeclaredField("server");
jettyServerField.setAccessible(true);
//Have to pull in the jetty server stuff to do this mess
Server jettyServer = (Server)jettyServerField.get(oneLevelDeepServer);
int acquiredPort = ((ServerConnector)jettyServer.getConnectors()[0]).getLocalPort();
log.debug("Acquired port: {}", acquiredPort);
return acquiredPort;
}
This works well for me in our integration tests, but I'm not using https, and it does reach about two levels deep into the API via reflection grabbing protected fields. I could not find any other way to do it. Would be quite happy to be proven wrong.
This will work on Spark 2.6.0:
public static int start (String keystoreFile, String keystorePw)
{
secure(keystoreFile, keystorePw, null, null);
port(0);
staticFiles.location("/public");
get(Path.CLOCK, ClockController.time);
get(Path.CALENDAR, CalendarController.date);
// This is the important line. It must be *after* creating the routes and *before* the call to port()
awaitInitialization();
return port();
}
Without the call to awaitInitialization() port() would return 0.

Spring : Send automated email to member and admin after timer expires

I am working on a Spring-MVC application in which there is Service desk functionality I am working on. So, as a part of Service desk, users can create issues and assign a support-team member. In that, they can also assign in how much time issue needs to be resolved. I am setting the time in java.sql.TimeStamp.
Now, when the time expires, I would like to send an email to the support-team admin, the person who created the issue and the support-team member responsible for resolving the issue.
If it was a normal scheduled or cron job, I can just write a #Scheduled method and get it over with, but here, I would like to check for example after 6 hours if the issue was resolved or not. How do I accomplish that? I have no idea to be honest.
Here is service layer part the SupportRequest :
#Service
#Transactional
public class SupportRequestServiceImpl implements SupportRequestService{
private final SupportRequestDAO supportRequestDAO;
#Autowired
public SupportRequestServiceImpl(SupportRequestDAO supportRequestDAO){
this.supportRequestDAO = supportRequestDAO;
}
#Autowired
private SupportTeamService supportTeamService;
#Override
public int addSupportRequest(SupportRequest supportRequest, int assignedTeamId, Long groupId) {
SupportTeam supportTeam = this.supportTeamService.getSupportTeamMemberById(assignedTeamId);
if(!(supportTeam == null)){
supportRequest.setCreationTime(new Timestamp(System.currentTimeMillis()));
supportRequest.setAssignedTeamMemberId(supportTeam.getTeamId());
return this.supportRequestDAO.addSupportRequest(supportRequest,groupId);
}
return 0;
}
}
I don't know what else to show. Thanks a lot.
Update
Will something like this work?
long delay = 1000*60*60*12; // after 12 hrs
Timer timer = new Timer();
Calendar cal = Calendar.getInstance();
timer.schedule(new TimerTask() {
public void run() {
// Task here ...
System.out.println("inside the main");
Integer id = new Integer(10);
Assert.assertNotNull(id);
}
}, delay);
For these kind of scenario, there should be background process running. That process will check for issues that has not been fixed in given time. Then this process will send a message to whoever you want and then continue running in background.
There are different ways of doing this.
1. Batch Process
You can make batch process. Batch process will be running on your server, it will check for expired issues and then send mail to the support-team admin.
2. Techniques for Real-time Updates
You can also you real time update techniques in spring. Using this technique you will fire request after every given period that will check for expire issues. If any issue found that has not been fixed you can send mail. Please read the related document here : Spring MVC 3.2 Preview: Techniques for Real-time Updates
3. Web Socket
Web socked can also be useful for these kind of task. Find the good source here :
SPRING FRAMEWORK 4.0 M2: WEBSOCKET MESSAGING ARCHITECTURES

Disabling App Nap in Java

Our Java application makes background file transfer to a server. When the user wish to add a bunch of documents to the server and do something else with other applications, App Nap becomes active and slow down the window with the progress bar and the network transfert speed.
One solution is too opt out the entire application from App Nap, but it would be great if we could exclude some Java threads from being slowed down.
I am not sure how we could integrate the functionality of NSProcessInfo into Java...
Anybody have tried to do such thing from Java? Any ideas?
Thanks!
The following class From here uses the Java-Objective-C Bridge to integrate NSProcessInfo functionality from Java.
import ca.weblite.objc.Client;
import ca.weblite.objc.Proxy;
/**
* From https://github.com/shannah/Java-Objective-C-Bridge/blob/master/java/test/ca/weblite/objc/NSProcessInfoUtils.java
*/
public class NSProcessInfoUtils {
private final static long NSActivityUserInitiated = (0x00FFFFFFL | (1L << 20));
/**
* To ensure Mac OS X doesn't slow down your app because of App Nap, call this method
* #param reason the reason for allowing the app to work at full speed
* #return the activity id as a Proxy object
*/
public static Proxy beginActivityWithOptions(String reason) {
Client c = Client.getInstance();
Proxy processInfo = c.sendProxy("NSProcessInfo", "processInfo");
return processInfo.sendProxy("beginActivityWithOptions:reason:", NSActivityUserInitiated, reason);
}
/**
* When the activity is finished, to re-enable app napping call this method
* #param activity previously returned by beginActivityWithOptions()
*/
public static void endActivity(Proxy activity) {
if (activity != null) {
Client c = Client.getInstance();
Proxy processInfo = c.sendProxy("NSProcessInfo", "processInfo");
processInfo.send("endActivity:", activity);
}
}
}
Disclaimer: I'm the author of the Java-objective-c bridge
I am the author of the referenced app nap post, found this via track back analytics. I am not familiar with Java development, however the link below may provide a method to access NSProcessInfo in the recommended manner. Interested to see what you find.
https://code.google.com/p/rococoa/

In GoogleCloudMessaging API, how to handle the renewal or expiration of registration ID?

As the question says that How to find out when does the registration ID has become invalid in GoogleCloudMessaging API?
I already read the answers on few questions on similar topic: Do GCM registration id's expire? and Google Coud Mesaging (GCM) and registration_id expiry, how will I know? . The issue with those question is that the answers there are for C2DMor old GCM API which used GCMRegistrar instead of GoogleCloudMessaging API. The previous two methods have been depreciated.
I'll try to break my confusion/question stepwise:
1) Under the heading Enable GCM, in the second point it says:
Google may periodically refresh the registration ID, so you should design your Android application with the understanding that the com.google.android.c2dm.intent.REGISTRATION intent may be called multiple times. Your Android application needs to be able to respond accordingly.
The registration ID lasts until the Android application explicitly unregisters itself, or until Google refreshes the registration ID for your Android application. Whenever the application receives a com.google.android.c2dm.intent.REGISTRATION intent with a registration_id extra, it should save the ID for future use, pass it to the 3rd-party server to complete the registration, and keep track of whether the server completed the registration. If the server fails to complete the registration, it should try again or unregister from GCM.
2) Now, if that's the case then I should handle the intent in a BroadcastReceiver and send the register() request again to get a new registration ID. But the issue is that on the same page under heading ERROR_MAIN_THREAD, it says that:
GCM methods are blocking. You should not run them in the main thread or in broadcast receivers.
3) I also understand that there are other two scenarios when the registration ID changes( as mentioned under Advanced Topics under heading Keeping the Registration State in Sync):
Application update and Backup&restore. I am already handling them on opening of the app.
4) In GCMRegistrar API, inside GCMBaseIntentService, there used to be a callback onRegistered() method, which got called when the device got registered. Here I used to persist the registration ID and send to 3rd party servers.
But, now How should I handle the updation or renewal of the registration ID, persist it and send it to 3rd party server?
It might be that either I am getting confused by reading all of it or I am missing something. I would be really thankful for your help.
Update
Even on Handling registration ID changes in Google Cloud Messaging on Android thread, there is no mentioning of how to handle the periodic refreshing of ID by Google?
I am giving a way as What I implemented in my application
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
//displayMessage(context, getString(R.string.gcm_registered));
//ServerUtilities.register(context, registrationId);
//1. Store this id to application Prefs on each request of device registration
//2. Clear this id from app prefs on each request of device un-registration
//3. Now add an if check for new registartion id to server, you can write a method on server side to check if this reg-id matching for this device or not (and you need an unique identification of device to be stored on server)
//4. That method will clear that if id is matching it meanse this is existing reg-id, and if not matching this is updated reg-id.
//5. If this is updated reg-id, update on server and update into application prefs.
}
You can do like this also
if reg_id exists_into prefrences then
if stored_id equals_to new_reg_id then
do nothing
else
say server to reg_id updated
update prefrences with new id
end if
else
update this id to application prefs
say server that your device is registered
end if
But problem arises when, user clears the application data and you will loose the current reg-id.
Update for new API example Credits goes to Eran and His Answer Handling registration ID changes in Google Cloud Messaging on Android
Google changed their Demo App to use the new interface. They refresh the registration ID by setting an expiration date on the value persisted locally by the app. When the app starts, they load their locally stored registration id. If it is "expired" (which in the demo means it was received from GCM over 7 days ago), they call gcm.register(senderID) again.
This doesn't handle the hypothetical scenario in which a registration ID is refreshed by Google for an app that hasn't been launched for a long time. In that case, the app won't be aware of the change, and neither will the 3rd party server.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
context = getApplicationContext();
regid = getRegistrationId(context);
if (regid.length() == 0) {
registerBackground();
}
gcm = GoogleCloudMessaging.getInstance(this);
}
/**
* Gets the current registration id for application on GCM service.
* <p>
* If result is empty, the registration has failed.
*
* #return registration id, or empty string if the registration is not
* complete.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.length() == 0) {
Log.v(TAG, "Registration not found.");
return "";
}
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion || isRegistrationExpired()) {
Log.v(TAG, "App version changed or registration expired.");
return "";
}
return registrationId;
}
/**
* Checks if the registration has expired.
*
* <p>To avoid the scenario where the device sends the registration to the
* server but the server loses it, the app developer may choose to re-register
* after REGISTRATION_EXPIRY_TIME_MS.
*
* #return true if the registration has expired.
*/
private boolean isRegistrationExpired() {
final SharedPreferences prefs = getGCMPreferences(context);
// checks if the information is not stale
long expirationTime =
prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
return System.currentTimeMillis() > expirationTime;
}
Just to add to Pankaj's answer:
This(the example on getting started documents by Google) doesn't handle the hypothetical scenario in which a registration ID is
refreshed by Google for an app that hasn't been launched for a long
time. In that case, the app won't be aware of the change, and neither
will the 3rd party server.
Its true that the example on Getting
started documentation does not handle that case. So the developer
need to handle himself.
Also the answer says that They refresh the registration ID by setting an expiration date on the value persisted locally by the app. When the app starts, they load their locally stored registration id. If it is "expired" they call gcm.register(senderID) again.
The issue is that the seven days local expiry of the registration ID in the sample is to avoid the scenario where the device sends the
registration to the 3rd party server but the server loses it. It does
not handle the refreshing of the ID from Google servers.
The second point under the heading Enable GCM on Architectural
Overview page, it says:
Note that Google may periodically refresh the registration ID, so
you should design your Android application with the understanding
that the com.google.android.c2dm.intent.REGISTRATION intent may be
called multiple times. Your Android application needs to be able to
respond accordingly.
So, for handling that you should have a Broadcast Listener which
could handle com.google.android.c2dm.intent.REGISTRATION intent,
which Google send to the app when it has to refresh the registration
ID.
There is another part of the question which states about the problem is that inside the Broadcast Listener I cannot call register the for Push ID again. This is because the
documentation says:
GCM methods are blocking. You should not run them in the main thread or in broadcast receiver.
I think that issue is completely different from the statement. When you register a broadcast receiver, it will have an Intent which will contain the new registration ID from Google. I DON'T need to call gcm.register() method again in the Broadcast listener.
Hope this helps someone understand how to handle the renewal of registration ID.

how to set request time out of web service client(java)

I am working on a desktop based application that is like drop box, I have a function downloadFile(long fileId) that download file for me from web, desktop side of the application is in java where web service is written in .Net
I have generated WS client using netbeans
The issue is: Some times it happens that downloadFile(long fileId) function get stuck,
What ever the reason behind it, I want if web service function does not give any response till a given time I snatch the control back from that function and generate a new call after some time. Is it possible using java?
EDIT I think that it could be done if can set the request time out of the web service but i don't have idea how to set time out in the client generated by netbeans
In the class FileUpload that is root class of web service(Generated by netBeans) there were some constructors of the class and function of the super class, one of them i was using to create SOAP object. That was looking like
#WebEndpoint(name = "FileUploadSoap")
public FileUploadSoap getFileUploadSoap() {
return super.getPort(new QName("http://svc.qleapahead.com/",
"FileUploadSoap"), FileUploadSoap.class);
}
in this function i made some modifications in order to set time out parameter and this became like
#WebEndpoint(name = "FileUploadSoap")
public FileUploadSoap getFileUploadSoap() {
FileUploadSoap fileUploadSoap = super.getPort(new QName(
"http://svc.qleapahead.com/", "FileUploadSoap"),
FileUploadSoap.class);
((BindingProvider) fileUploadSoap).getRequestContext().put(
"com.sun.xml.internal.ws.request.timeout", 1000 * 2 * 60);
return fileUploadSoap;
}
and problem solved...
in short this statement helped me a lot
((BindingProvider) fileUploadSoap).getRequestContext().put(
"com.sun.xml.internal.ws.request.timeout", 1000 * 2 * 60);
Depending on the framework you use for calling the webservice, there will be some way of setting a readTimeout causing the call to fail with some kind of exception.
Cheers,

Categories

Resources