Disabling App Nap in Java - 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/

Related

Call to Reader.Capture() in DigitalPersona U.are.U SDK does not return

I am developing an application for a DigitalPersona U.are.U 4500 fingerprint reader and using the U.are.U 2.2.3 SDK Java API.
The sample Java application that ships with the SDK works flawlessly.
However, when I try to do the same thing in my own sample application, the call to the Reader.Capture() method never returns, even though I can see the reader flashing when recording my fingerprint.
Below is a variation on the sample code I have tried with.
Other things I have tried:
Running the capture code in an instance of the class (i.e. not in a static context)
Running the capture operation in its own thread as well, but the results are the same.
Using the CaptureThread class from the demo application
The only difference I can see between my sample and the SDK sample app is that the latter is a graphical application. But why would that make a difference?
Unplugging the device causes the call to fail with an exception. That is about the only way I can get it to return.
import com.digitalpersona.uareu.*;
public class Main{
static Reader r;
public static void main(String[] args) {
try {
// Pick first available reader
ReaderCollection rc = UareUGlobal.GetReaderCollection();
rc.GetReaders();
r = rc.get(0);
if (r==null)
return;
// Open Reader
r.Open(Reader.Priority.COOPERATIVE);
System.out.println(r.GetStatus().status); // Outputs READY
// The following call just hangs and never returns...
Reader.CaptureResult
cr = r.Capture(Fid.Format.ISO_19794_4_2005, Reader.ImageProcessing.IMG_PROC_DEFAULT, 500, -1);
System.out.println(cr.quality.name()); // Just to test
} catch (UareUException e) {
e.printStackTrace();
}
}
}
The last two parameters, the two ints, passed to the Capture method are the resolution and the timeout respectively; passing -1 for the timeout blocks indefinitely. This is taken from the sample application as well.
I finally managed to get an example working.
Strange as it may seem, it only works in the context of a Java GUI application.
So, simply extending a JFrame and starting the reader capture on a separate thread seems to be sufficient.
This requirement is not specified anywhere in the SDK documentation that I can see.
UPDATE
It seems the problem is worse than I initially thought. Not only must the API be called in the context of a Java GUI application, but the GUI must also be in focus, otherwise the capture call simply does not return.
I have verified this with the example SDK applications. The Capture() method does not return if the apps are not in focus. This also applies to the C# examples, where the windows must be in focus, which suggests that this is built into the DLLs that ship with the solution.
This is terrible for our scenario, where we want to develop a local service that a browser can communicate with because, while the browser is in focus, obviously the Java application is not.
I faced the similar issue and it can be fixed by opening a reader in exclusive mode as below,
m_reader.Open(Reader.Priority.EXCLUSIVE);
Refer to below lines from documents,
public static final Reader.Priority COOPERATIVE
Client uses this priority to open reader in cooperative mode. Multiple clients with this priority are allowed. Client receives captured images if it has window with focus.
public static final Reader.Priority EXCLUSIVE
Client uses this priority to open reader exclusively. Only one client with this priority is allowed.

Uniquely identifying the user in the Android application via the Play store?

I have an android application that does not have login / register structure but users can start subscription with in-app purchase.
I want to be able to recognize the user on different devices where the user logs in with the same play store account. So I want to be able to uniquely identify a user through the play store account.
Since my application is in the child and family category, I cannot access AccountManager-style sensitive data.
How can I do that. Does anyone have great ideas?
There is a great library which I hope will help you solve your problem as I'm already using it in some products.
You can try This library
This library perfectly handles Subscriptions as well as Purchases with and without payload. you just have to place implementation 'com.anjlab.android.iab.v3:library:1.0.44' in your build.gradle and you are good to go.
When your build.gradle is ready, implement BillingProcessor.IBillingHandler with your activity.
Then intialize your billing processor by placing this code in onCreate.
bp = new BillingProcessor(this, "YOUR LICENSE KEY FROM GOOGLE PLAY CONSOLE HERE", this);
bp.initialize();
You will get the following override methods,
#Override
public void onBillingInitialized() {
/*
* Called when BillingProcessor was initialized and it's ready to purchase
*/
}
#Override
public void onProductPurchased(String productId, TransactionDetails details) {
/*
* Called when requested PRODUCT ID was successfully purchased
*/
}
#Override
public void onBillingError(int errorCode, Throwable error) {
/*
* Called when some error occurred. See Constants class for more details
*
* Note - this includes handling the case where the user canceled the buy dialog:
* errorCode = Constants.BILLING_RESPONSE_RESULT_USER_CANCELED
*/
}
#Override
public void onPurchaseHistoryRestored() {
/*
* Called when purchase history was restored and the list of all owned PRODUCT ID's
* was loaded from Google Play
*/
}
Here is the trick, onPurchaseHistoryRestored is the actual method you are looking for. This method will get called whenever there is a subscription or purchase already available against a specific email. This library will automatically handle it for you. Let me know if it help you.
Don't forget to add this <uses-permission android:name="com.android.vending.BILLING" /> permission in your Manifest.
If you want to query the subscription status of users who log in to the same account on different devices, you can use the BillingClient.queryPurchases() interface to query the subscription status. If the interface returns a subscription, it is within the subscription validity period, and you need to continue providing services.

Does Splunk SDK service require Disconnect or Close

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.

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.

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