getLastLocation using Reflection with GoogleApiClient and LocationServices - java

I'm working on an Android Library and I need to remove the play services dependencies to be added by the developer who used my library. I need user location last location so I need to use reflection because the location library will not be included directly in my library.
But how to create the googleApiClient from the builder via reflection ?

Digging into reflection and Play Services produce the following script. It contain the code for getting AdvertisingId and the location.
Gist also available.
private void getLocation(Context context) {
Log.d(LOG_TAG, "getLocation");
if (context.getPackageManager().checkPermission(
Manifest.permission.ACCESS_FINE_LOCATION, context.getPackageName()) == PackageManager.PERMISSION_GRANTED ||
context.getPackageManager().checkPermission(
Manifest.permission.ACCESS_COARSE_LOCATION, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
try {
Class<?> apiClientBuilderClass = Class.forName("com.google.android.gms.common.api.GoogleApiClient$Builder");
Class<?> connectionCallbackClass = Class.forName("com.google.android.gms.common.api.GoogleApiClient$ConnectionCallbacks");
Class<?> connectionFailedCallbackClass = Class.forName("com.google.android.gms.common.api.GoogleApiClient$OnConnectionFailedListener");
Class<?> locationServicesClass = Class.forName("com.google.android.gms.location.LocationServices");
Constructor<?> constructorApiBuilder = apiClientBuilderClass.getConstructor(Context.class);
Object objectApiBuilder = constructorApiBuilder.newInstance(mContext);
// Create intance of listener ConnectionCallbacks
Class<?>[] connectionClassArray = new Class<?>[1];
connectionClassArray[0] = connectionCallbackClass;
sGoogleApiClientListener = Proxy.newProxyInstance(
connectionCallbackClass.getClassLoader(), connectionClassArray, new GoogleApiClientListener());
Method connectionMethodObject = apiClientBuilderClass.getMethod("addConnectionCallbacks", connectionCallbackClass);
connectionMethodObject.invoke(objectApiBuilder, sGoogleApiClientListener);
// Create instance of OnConnectionFailedListener listener
Class<?>[] connectionFailedClassArray = new Class<?>[1];
connectionFailedClassArray[0] = connectionFailedCallbackClass;
sGoogleApiClientFailedListener = Proxy.newProxyInstance(
connectionFailedCallbackClass.getClassLoader(), connectionFailedClassArray, new GoogleApiClientFailedListener());
Method connectionFailedMethodObject = apiClientBuilderClass.getMethod("addOnConnectionFailedListener", connectionFailedCallbackClass);
connectionFailedMethodObject.invoke(objectApiBuilder, sGoogleApiClientFailedListener);
// Add Api
Method addApiMethod = apiClientBuilderClass.getMethod("addApi", Class.forName("com.google.android.gms.common.api.Api"));
addApiMethod.invoke(objectApiBuilder, locationServicesClass.getField("API").get(null));
// Build
Method buildMethod = apiClientBuilderClass.getMethod("build");
sGoogleApiClient = buildMethod.invoke(objectApiBuilder);
// Connect
for (Method method : sGoogleApiClient.getClass().getMethods()) {
if (!"connect".equals(method.getName())) {
continue;
}
method.invoke(sGoogleApiClient);
break;
}
} catch (Exception e) {
// Location is not essential, so it's not an error
Log.v(LOG_TAG, "Exception on getLocation " + Log.getStackTraceString(e));
}
} else {
sLocation = "";
}
}
// GoogleApiClient for Locationsucceded
public void onConnected() {
Location lastLocation = null;
try {
// FusedLocationApi is a field of LocationServices, getting it.
Class<?> locationServicesClass = Class.forName("com.google.android.gms.location.LocationServices");
Class<?> locationProviderClass = Class.forName("com.google.android.gms.location.FusedLocationProviderApi");
for (Method method : locationProviderClass.getMethods()) {
if (!"getLastLocation".equals(method.getName())) {
continue;
}
Object object = locationServicesClass.getField("FusedLocationApi").get(null);
lastLocation = (Location) method.invoke(object, sGoogleApiClient);
break;
}
} catch (Exception e) {
// Location is not essential, so it's not an error
Log.v(LOG_TAG, "Exception on invoke onConnected for getLastLocation" + Log.getStackTraceString(e));
}
// Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(sGoogleApiClient);
if (lastLocation != null) {
sLocation = lastLocation.getLatitude() + "," + lastLocation.getLongitude();
Log.d(LOG_TAG, "Location received : " + sLocation);
} else {
sLocation = "";
}
newResourcesAvailable();
unregisterConnectionCallbacks();
}
// GoogleApiClient for Location failed somewhere
public void onConnectionSuspended() {
sLocation = "";
newResourcesAvailable();
unregisterConnectionCallbacks();
}
// GoogleApiClient for Location failed somewhere
public void onConnectionFailed() {
sLocation = "";
newResourcesAvailable();
unregisterConnectionCallbacks();
}
private void unregisterConnectionCallbacks(){
for (Method method : sGoogleApiClient.getClass().getMethods()) {
if (!"unregisterConnectionCallbacks".equals(method.getName())) {
continue;
}
try {
method.invoke(sGoogleApiClient, sGoogleApiClientListener);
} catch (Exception ignored) {
// Exception always occur here but cannot make it work
}
break;
}
for (Method method : sGoogleApiClient.getClass().getMethods()) {
if (!"unregisterConnectionFailedListener".equals(method.getName())) {
continue;
}
try {
method.invoke(sGoogleApiClient, sGoogleApiClientFailedListener);
} catch (Exception ignored) {
// Exception always occur here but cannot make it work
}
break;
}
}
protected class RetrieveAdvertisingId extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String id = "";
try {
Object AdvertisingInfoObject = getAdvertisingInfoObject(mContext);
id = (String) invokeInstanceMethod(AdvertisingInfoObject, "getId", null);
} catch (Exception e) {
// Catch reflection exception and GooglePlayServicesNotAvailableException |
// GooglePlayServicesRepairableException
Log.e(LOG_TAG, "Exception while getting AdvertisingId", e);
}
return id;
}
#Override
protected void onPostExecute(String advertisingId) {
super.onPostExecute(advertisingId);
if (advertisingId != null && !advertisingId.isEmpty()) {
Log.i(LOG_TAG, "Advertising ID retrieved: " + advertisingId);
sAdvertisingId = advertisingId;
} else {
Log.e(LOG_TAG, "AdversitingId is not available");
sAdvertisingId = "";
}
AsynchronousParameterManager.this.newResourcesAvailable();
}
}
/**
* Returns the AdvertisingIdInfo object
*
* #param context the android context
* #return the advertising id information object
* #throws Exception
*/
private Object getAdvertisingInfoObject(Context context) throws Exception {
return invokeStaticMethod(
"com.google.android.gms.ads.identifier.AdvertisingIdClient",
"getAdvertisingIdInfo",
new Class[]{Context.class},
context
);
}
/**
* Invokes a static method within a class
* if it can be found on the classpath.
*
* #param className The full defined classname
* #param methodName The name of the method to invoke
* #param cArgs The args that the method can take
* #param args The args to pass to the method on invocation
* #return the result of the method invoke
* #throws Exception
*/
private Object invokeStaticMethod(String className, String methodName,
Class[] cArgs, Object... args) throws Exception {
Class classObject = Class.forName(className);
return invokeMethod(classObject, methodName, null, cArgs, args);
}
/**
* Invokes a method on a static instance
* within a class by reflection.
*
* #param instance The instance to invoke a method on
* #param methodName The name of the method to invoke
* #param cArgs The args that the method can take
* #param args The args to pass to the method on invocation
* #return the result of the method invoke
* #throws Exception
*/
private Object invokeInstanceMethod(Object instance, String methodName,
Class[] cArgs, Object... args) throws Exception {
Class classObject = instance.getClass();
return invokeMethod(classObject, methodName, instance, cArgs, args);
}
/**
* Invokes methods of a class via reflection
*
* #param classObject The class to attempt invocation on
* #param methodName The name of the method to invoke
* #param instance The object instance to invoke on
* #param cArgs The args that the method can take
* #param args The args to pass to the method on invocation
* #return the result of the method invoke
* #throws Exception
*/
private Object invokeMethod(Class classObject, String methodName, Object instance,
Class[] cArgs, Object... args) throws Exception {
Method methodObject = classObject.getMethod(methodName, cArgs);
return methodObject.invoke(instance, args);
}
private class GoogleApiClientListener implements InvocationHandler {
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (args != null) {
if (method.getName().equals("onConnected")) {
AsynchronousParameterManager.this.onConnected();
} else if (method.getName().equals("onConnectionSuspended") ) {
AsynchronousParameterManager.this.onConnectionSuspended();
}
} else {
return 0;
}
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return null;
}
}
private class GoogleApiClientFailedListener implements InvocationHandler {
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
if (method.getName().equals("onConnectionFailed")) {
AsynchronousParameterManager.this.onConnectionFailed();
}
return 0;
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
}
}

Related

Spring RestTemplate exchange throws UnhandledHttpStatusException

Overview:
I am going to use RestTemplate to invoke a get request from external REST webservice.
My code is as follows:
#Slf4j
#Component("AccMemberDetailsApiControllerImpl")
public class AccMemberDetailsApiControllerImpl implements MemberDetailsApiController {
private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type";
private static final String AUTHORIZATION_HEADER_NAME = "Authorization";
private static final String USERID_PARAMETER_NAME = "userId";
private static final String VEHICLEID_PARAMETER_NAME = "vehicleId";
private static final ObjectMapper mapper = new ObjectMapper();
/**
* This constant is used to check whether or not the response from ACC is an empty JSON string
*/
private static final String EMPTY_RESPONSE = "{}";
#Value("${com.blss.memberServices.provider.posServiceURL}")
private String accPosServiceURL;
#Autowired
private RestTemplate restTemplate;
#Autowired
private AccTokenUtility accTokenUtility;
#Autowired
private ResourceMessage resourceMessage;
void setAccTokenUtility(AccTokenUtility accTokenUtility) {
this.accTokenUtility = accTokenUtility;
}
void setResourceMessage(ResourceMessage resourceMessage) {
this.resourceMessage = resourceMessage;
}
/**
* #see MemberDetailsApiController#getMemberDetails(String, String)
*/
#Override
public MemberDetailsModel getMemberDetails(String storeId, String membershipIdentifier) {
/**
* Getting CAD token
*/
String token = accTokenUtility.getCadToken();
/**
* Preparing the request
*/
HttpHeaders headers = new HttpHeaders();
// headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set(CONTENT_TYPE_HEADER_NAME, MediaType.APPLICATION_JSON_VALUE);
headers.set(AUTHORIZATION_HEADER_NAME, token);
HttpEntity<String> entity = new HttpEntity<>(headers);
/**
* Creating the dispatch URL by means of userId and vehicleId
*/
String dispatchURL = accPosServiceURL + "DispatchedEvent/{userId}/{vehicleId}";
/**
* Creating the URL variables and being valued by corresponding method parameters
*/
Map<String, String> parameters = new HashMap<>();
// parameters.put(USERID_PARAMETER_NAME, storeId);
parameters.put(USERID_PARAMETER_NAME, "mr2");
// parameters.put(VEHICLEID_PARAMETER_NAME, membershipIdentifier);
parameters.put(VEHICLEID_PARAMETER_NAME, "VEH1");
/**
* Calling the rest webservice and returning response with body of type {#link AccMemberDetails}
*/
ResponseEntity<String> response;
MemberDetailsModel memberDetailsModel = null;
AccMemberDetails accMemberDetails;
try {
response = restTemplate.exchange(dispatchURL, HttpMethod.GET, entity, String.class, parameters);
if (response == null || StringUtils.isBlank(response.getBody()) || EMPTY_RESPONSE.equals(response.getBody())) {
throw new ResourceNotFoundException(resourceMessage.getMessage(MEMBER_ERROR_NOT_FOUND, storeId, membershipIdentifier));
} else {
accMemberDetails = deserialize(response.getBody(), AccMemberDetails.class);
String accErrorMessage = accMemberDetails.getUserMessage();
if (!StringUtils.isBlank(accErrorMessage)) {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_ERROR_MESSAGE_FROM_API, "ACC", accErrorMessage));
}
memberDetailsModel = convert(accMemberDetails);
}
} catch (RestClientException e) {
handleExceptions(e, storeId, membershipIdentifier);
}
return memberDetailsModel;
}
/**
* This method is responsible for deserializing string REST response into an object of type {#link AccMemberDetails}
*/
<T> T deserialize(final String response, final Class<T> responseClass) {
try {
return mapper.readValue(response, responseClass);
} catch (IOException e) {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_ERROR_MAP_RESPONSE_OBJECT), e);
}
}
/**
* This method is responsible for converting an instance of type {#link AccMemberDetails} to an instance of type
* {#link MemberDetailsModel}
*
* #param accMemberDetails an instance of type {#link AccMemberDetails}
* #return an instance of type {#link MemberDetailsModel}
*/
MemberDetailsModel convert(AccMemberDetails accMemberDetails) {
MemberDetailsModel memberDetailsModel = new MemberDetailsModel();
memberDetailsModel.setEventId(accMemberDetails.getEventId());
memberDetailsModel.setMemberName(accMemberDetails.getMemberName());
memberDetailsModel.setMembershipNumber(accMemberDetails.getMembershipNumber());
memberDetailsModel.setMembershipLevel(accMemberDetails.getPricingLevel());
return memberDetailsModel;
}
/**
* This method is responsible for handling Exceptions may be thrown by ACC REST webservice
*
* #param e an instance of type {#link RestClientException}
* #param storeId an instance of type {#link String} and used in building exception messages
* #param membershipIdentifier an instance of type {#link String} and used in building exception messages
*/
private void handleExceptions(RestClientException e, String storeId, String membershipIdentifier) {
if (e instanceof HttpStatusCodeException) {
HttpStatusCodeException httpStatusCodeException = (HttpStatusCodeException) e;
HttpStatus httpStatusCode = httpStatusCodeException.getStatusCode();
if (404 == httpStatusCode.value()) {
throw new ResourceNotFoundException(resourceMessage.getMessage(MEMBER_ERROR_NOT_FOUND, storeId, membershipIdentifier), e);
} else if (500 == httpStatusCode.value()) {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_SERVER_ERROR, "ACC"), e);
} else {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_HTTP_STATUS_CODE_ERROR, "HttpStatusCodeException", "ACC"), e);
}
} else {
throw new InternalServerException(resourceMessage.getMessage(MEMBER_REST_CLIENT_ERROR, "RestClientException", "ACC"), e);
}
}
Problem
However I got UnhandledHttpStatusException after calling "restTemplate.exchange(dispatchURL, HttpMethod.GET, entity, String.class, parameters);" in the code snippet. the exception stack trace is as follows:
Caused by: org.springframework.web.client.UnknownHttpStatusCodeException: Unknown status code [443] null
at org.springframework.web.client.DefaultResponseErrorHandler.getHttpStatusCode(DefaultResponseErrorHandler.java:60)
at org.springframework.web.client.DefaultResponseErrorHandler.hasError(DefaultResponseErrorHandler.java:50)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:629)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:565)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:484)
at com.blss.retailServices.memberServices.controllers.impl.acc.AccMemberDetailsApiControllerImpl.getMemberDetails(AccMemberDetailsApiControllerImpl.java:110)
Now I would be grateful if anyone could suggest me a solution.
I called this webservice with curl by using "-v" in order to get more info in response. As a result, I got the same exception (443) from their side. So, It sounds like they should have a better exception handler to return meaningful exception messages.

Discrete event simulation (java)

I have two classes, Neuron and Synapse( synapse has sub classes primary, secondary). When a Neuron's voltage exceeds its threshold it fires but also sends an impulse to all Synapses. I created a method which creates an event when voltage > threshold. My Question is: how to I create an event to trigger an event of an object from another class? ( the code I have gives an error: not an enclosing class ) If needed I can post my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.regex.Pattern;
import java.util.Scanner;
// Simulation classes
class Simulator {
/**
* Framework for discrete event simulation.
*/
public interface Action {
// actions contain the specific code of each event
void trigger(float time);
}
private static class Event {
public float time; // the time of this event
public Action act; // what to do at that time
}
private static PriorityQueue<Event> eventSet
= new PriorityQueue<Event>(
(Event e1, Event e2) -> Float.compare(e1.time, e2.time)
);
static void schedule(float time, Action act) {
/**
* Call schedule to make act happen at time. Users typically pass the
* action as a lambda expression:
* <PRE>
* Simulator.schedule(t,(float time)->method(params,time))
* </PRE>
*/
Event e = new Event();
e.time = time;
e.act = act;
eventSet.add(e);
}
static void run() {
/**
* Call run after scheduling some initial events to run the simulation.
*/
while (!eventSet.isEmpty()) {
Event e = eventSet.remove();
e.act.trigger(e.time);
}
}
}
// Utility classes
/**
* Error reporting methods
*/
class Errors {
static void fatal(String message) {
System.err.println("Fatal error: " + message);
System.exit(1);
}
static void warning(String message) {
System.err.println("Error: " + message);
}
}
/**
* Input scanning support methods
*/
class ScanSupport {
/**
* Interface allowing error messages passed as lambda expressions
*/
public interface ErrorMessage {
abstract String myString();
}
/**
* Force there to be a line end here, complain if not
*/
static void lineEnd(Scanner sc, ErrorMessage message) {
String skip = sc.nextLine();
if (!"".equals(skip)) {
// Bug: do we want to allow comments here
Errors.warning(
message.myString()
+ " -- expected a newline"
);
}
// Bug: should we allow comments here?
// Bug: what if sc.nextLine() was illegal (illegal state)
}
/* really private to nextName */
private static final Pattern name = Pattern.compile("[A-Za-z]\\w*");
/**
* Get the next float, or complain if there isn't one
*/
static String nextName(Scanner sc, ErrorMessage message) {
if (sc.hasNext(name)) {
return sc.next(name);
} else {
Errors.warning(
message.myString()
+ " -- expected a name"
);
return null;
}
}
/**
* Get the next float, or complain if there isn't one
*/
static float nextFloat(Scanner sc, ErrorMessage message) {
if (sc.hasNextFloat()) {
return sc.nextFloat();
} else {
Errors.warning(
message.myString()
+ " -- expected a number"
);
return 99.99f;
}
}
}
// Simulation classes
/**
* Neurons are joined by synapses
*
* #see Synapse
*/
class Neuron {
String name; // name of this neuron
public static class IllegalNameEx extends Exception {
}
// default values below for errors with incompletely defined neurons
private float threshold = 99.99f;// voltage at which the neuron fires
public float voltage = 99.99f; // voltage at the given time
private float time = 0.0f; // (see above)
private LinkedList<Synapse> synapses; // the outputs of this neuron
// initializer
public Neuron(Scanner sc) throws IllegalNameEx {
// scan and process one neuron
String name = ScanSupport.nextName(
sc,
() -> "Neuron ???"
);
if (name == null) { // nextName() already reported syntax error
sc.nextLine();
throw new IllegalNameEx();
}
this.name = name;
if ((NeuronNetwork.findNeuron(name) != null)
|| (NeuronNetwork.findSynapse(name) != null)) {
Errors.warning(
"Neuron " + name
+ " -- duplicate declaration"
);
sc.nextLine();
throw new IllegalNameEx();
}
threshold = ScanSupport.nextFloat(
sc,
() -> Neuron.this.toString()
);
voltage = ScanSupport.nextFloat(
sc,
() -> Neuron.this.toString()
);
ScanSupport.lineEnd(
sc,
() -> Neuron.this.toString()
);
}
// other methods
public String toString() {
return (time + " "
+ "Neuron "
+ name);
}
// simulation methods
public void fireNeuron(float t) {
if (this.voltage > this.threshold) {
Simulator.schedule(
t,
(float time) -> this.voltageZero(time)
);
Simulator.schedule(
t,
(float time) -> Synapse.this.impulse(time)
);
}
}
public void voltageZero(float t) {
voltage = 0.0f;
System.out.println(this.toString());
}
}
/**
* Synapses come in several flavors
*
* #see Neuron
* #see PrimarySynapse
* #see SecondarySynapse
*/
abstract class Synapse {
// default values below for errors with incompletely defined synapses
Neuron source; // source for this synapse
Float delay = 99.99f;
Float strength = 99.99f;
String name = null; // name of this synapse, if it has one
public static class IllegalNameEx extends Exception {
}
// really private to Synapse initializer
private static final Pattern noName = Pattern.compile("-");
// generic initializer
static Synapse newSynapse(Scanner sc) throws IllegalNameEx {
// proxies for fields until we know the type of this synapse
String myName = null;
Neuron mySource = null;
// only one of the following proxies will be non-null
Neuron myPrimaryDest = null;
Synapse mySecondaryDest = null;
// the Synapse we're allocating
Synapse mySynapse = null;
// scan and process one synapse
if (sc.hasNext(noName)) { // unnamed synapse
sc.next(noName);
} else { // named synapse, process the name
myName = ScanSupport.nextName(
sc,
() -> "Synapse ???"
);
if (myName == null) {
// nextName() already reported syntax error
sc.nextLine();
throw new IllegalNameEx();
}
if ((NeuronNetwork.findNeuron(myName) != null)
|| (NeuronNetwork.findSynapse(myName) != null)) {
Errors.warning(
"Synapse " + myName
+ " -- duplicate declaration"
);
sc.nextLine();
throw new IllegalNameEx();
}
}
// the following is needed because of limits of java lambda
final String finalName = myName;
String sourceName = ScanSupport.nextName(
sc,
() -> ("Synapse "
+ (finalName != null ? finalName : "-")
+ " ???")
);
String dstName = ScanSupport.nextName(
sc,
() -> ("Synapse "
+ (finalName != null ? finalName : "-")
+ " "
+ (sourceName != null ? sourceName : "---")
+ " ???")
);
mySource = NeuronNetwork.findNeuron(sourceName);
myPrimaryDest = NeuronNetwork.findNeuron(dstName);
if (myPrimaryDest == null) {
mySecondaryDest = NeuronNetwork.findSynapse(dstName);
mySynapse = new SecondarySynapse(mySecondaryDest);
} else {
mySynapse = new PrimarySynapse(myPrimaryDest);
}
// the following is needed because of limits of java lambda
final Synapse finalSynapse = mySynapse;
finalSynapse.name = finalName;
finalSynapse.source = mySource;
finalSynapse.delay = ScanSupport.nextFloat(
sc,
() -> finalSynapse.toString()
);
finalSynapse.strength = ScanSupport.nextFloat(
sc,
() -> finalSynapse.toString()
);
ScanSupport.lineEnd(
sc,
() -> finalSynapse.toString()
);
// check correctness of fields
if ((sourceName != null) && (mySource == null)) {
Errors.warning(
finalSynapse.toString()
+ " -- no such source"
);
}
if ((dstName != null)
&& (myPrimaryDest == null)
&& (mySecondaryDest == null)) {
Errors.warning(
finalSynapse.toString()
+ " -- no such destination"
);
}
if (finalSynapse.delay < 0.0f) {
Errors.warning(
finalSynapse.toString()
+ " -- illegal negative delay"
);
finalSynapse.delay = 99.99f;
}
return finalSynapse;
}
// other methods
public abstract String toString();
// simulation
public void impulse(float t) {
Simulator.schedule(
t + delay,
(float time) -> this.synapseFire(time)
);
}
public abstract void synapseFire(float t);
}
/**
* Primary Synapses join neurons to neurons
*
* #see Neuron
* #see Synapse
*/
class PrimarySynapse extends Synapse {
Neuron destination;
public PrimarySynapse(Neuron dst) {
// Called from Synapse.newSynapse() and nowhere else
// All the field initialization and checking is done there,
// except the following:
destination = dst;
}
// other methods
public String toString() {
return ("Synapse "
+ (name != null ? name : "-")
+ " "
+ (source != null ? source.name : "---")
+ " "
+ (destination != null ? destination.name : "---")
+ " " + delay + " " + strength);
}
//simulation methods
public void synapseFire(float t) {
// when a primary synapse is fired, destination neuron voltage is incremented by strength
float oldVoltage = destination.voltage; // used to print old voltage vs new
destination.voltage = destination.voltage + strength;
}
}
/**
* Secondary synapses join neurons to primary synapses
*
* #see Neuron
* #see Synapse
* #see PrimarySynapse
*/
class SecondarySynapse extends Synapse {
PrimarySynapse destination;
public SecondarySynapse(Synapse dst) {
// Called from Synapse.newSynapse() and nowhere else
// All the field initialization and checking is done there,
// except the following:
if ((dst != null)
&& (dst instanceof SecondarySynapse)) {
Errors.warning(
this.toString()
+ " -- destination is a secondary synapse"
);
destination = null;
} else {
destination = (PrimarySynapse) dst;
}
}
// other methods
public String toString() {
return ("Synapse "
+ (name != null ? name : "-")
+ " "
+ (source != null ? source.name : "---")
+ " "
+ (destination != null ? destination.name : "---")
+ " " + delay + " " + strength);
}
//simulation methods
public void synapseFire(float t) {
// when a secondary fires, the destination synapses strength is incremented by strength
float oldStrength = destination.strength; // used to print old strength vs new
destination.strength = destination.strength + strength;
}
}
/**
* NeuronNetwork is the main class that builds the whole model
*
* #see Neuron
* #see Synapse
*/
public class NeuronNetwork {
// the sets of all neurons and synapses
static LinkedList<Neuron> neurons
= new LinkedList<Neuron>();
static LinkedList<Synapse> synapses
= new LinkedList<Synapse>();
/**
* Look up s in neurons, find that Neuron if it exists return null if not.
*/
public static Neuron findNeuron(String s) {
/* special case added because scan-support can return null */
if (s == null) {
return null;
}
/* search the neuron list */
for (Neuron n : neurons) {
if (n.name.equals(s)) {
return n;
}
}
return null;
}
/**
* Look up s in synapses, find that Synapse if it exists return null if not.
*/
public static Synapse findSynapse(String s) {
/* special case added because scan-support can return null */
if (s == null) {
return null;
}
/* search the synapse list */
for (Synapse sy : synapses) {
if ((sy.name != null) && (sy.name.equals(s))) {
return sy;
}
}
return null;
}
/**
* Initialize the neuron network by scanning its description
*/
static void initializeNetwork(Scanner sc) {
while (sc.hasNext()) {
String command = sc.next();
if ("neuron".equals(command)) {
try {
neurons.add(new Neuron(sc));
} catch (Neuron.IllegalNameEx e) {
}
} else if ("synapse".equals(command)) {
try {
synapses.add(Synapse.newSynapse(sc));
} catch (Synapse.IllegalNameEx e) {
}
} else {
Errors.warning(command + " -- what is that");
sc.nextLine();
}
}
}
/**
* Print out the neuron network from the data structure
*/
static void printNetwork() {
for (Neuron n : neurons) {
System.out.println(n.toString());
}
for (Synapse s : synapses) {
System.out.println(s.toString());
}
}
/**
* Main program
*
* #see initializeNetwork
* #see printNetwork
*/
public static void main(String[] args) {
if (args.length < 1) {
Errors.fatal("missing file name");
}
if (args.length > 1) {
Errors.fatal("too many arguments");
}
try {
initializeNetwork(new Scanner(new File(args[0])));
} catch (FileNotFoundException e) {
Errors.fatal("file not found: " + args[0]);
}
printNetwork();
}
}

Android error the method getOrCreateThreadId is undefined for the type Telephony.Threads

I am building an Android app in Eclipse.
In one class method, there is this code:
threadId = Threads.getOrCreateThreadId(mContext, recipients);
mContext is a context, and recipients is Set <string>
Eclipse shows an error in that line saying:
The method getOrCreateThreadId(Context, Set<String>) is undefined for type Telephony.Threads
In file Telephony.java, there is the Threads class defining this method:
/**
* Helper functions for the "threads" table used by MMS and SMS.
*/
public static final class Threads implements ThreadsColumns {
private static final String[] ID_PROJECTION = { BaseColumns._ID };
private static final String STANDARD_ENCODING = "UTF-8";
private static final Uri THREAD_ID_CONTENT_URI = Uri.parse(
"content://mms-sms/threadID");
public static final Uri CONTENT_URI = Uri.withAppendedPath(
MmsSms.CONTENT_URI, "conversations");
public static final Uri OBSOLETE_THREADS_URI = Uri.withAppendedPath(
CONTENT_URI, "obsolete");
public static final int COMMON_THREAD = 0;
public static final int BROADCAST_THREAD = 1;
// No one should construct an instance of this class.
private Threads() {
}
/**
* This is a single-recipient version of
* getOrCreateThreadId. It's convenient for use with SMS
* messages.
*/
public static long getOrCreateThreadId(Context context, String recipient) {
Set<String> recipients = new HashSet<String>();
recipients.add(recipient);
return getOrCreateThreadId(context, recipients);
}
/**
* Given the recipients list and subject of an unsaved message,
* return its thread ID. If the message starts a new thread,
* allocate a new thread ID. Otherwise, use the appropriate
* existing thread ID.
*
* Find the thread ID of the same set of recipients (in
* any order, without any additions). If one
* is found, return it. Otherwise, return a unique thread ID.
*/
public static long getOrCreateThreadId(
Context context, Set<String> recipients) {
Uri.Builder uriBuilder = THREAD_ID_CONTENT_URI.buildUpon();
for (String recipient : recipients) {
if (Mms.isEmailAddress(recipient)) {
recipient = Mms.extractAddrSpec(recipient);
}
uriBuilder.appendQueryParameter("recipient", recipient);
}
Uri uri = uriBuilder.build();
Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(),
uri, ID_PROJECTION, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
return cursor.getLong(0);
}
} finally {
cursor.close();
}
}
throw new IllegalArgumentException("Unable to find or allocate a thread ID.");
}
}
Why isn't it finding the method and telling me it is undefined?
Thanks!
You have to use reflection java, so you need to search for this method and invoke it like that:
public long getOrCreateThreadId(Context context,
ArrayList<String> recipientsAddress) {
Set<String> recipients = new HashSet<String>(recipientsAddress);
Class[] paramTypes = new Class[2];
paramTypes[0] = Context.class;
paramTypes[1] = Set.class;
Method getOrCreateThreadId=null;
Class classToInvestigate=null;
Object cC=null;
try {
String className = "android.provider.Telephony";
classToInvestigate = Class.forName(className);
//cC = classToInvestigate.newInstance();
Class[] classes = classToInvestigate.getClasses();
Toast.makeText(context, "*****Classes: "+classes.length, Toast.LENGTH_LONG).show();
Class threadsClass = null;
for(Class c:classes){
if(c.equals((Class)Telephony.Threads.class))
threadsClass = c;
}
getOrCreateThreadId = threadsClass.getMethod("getOrCreateThreadId", paramTypes);
getOrCreateThreadId.setAccessible(true);
Log.e("Methode", "" + getOrCreateThreadId.toString());
//Toast.makeText(getApplicationContext(), getOrCreateThreadId.toString(), Toast.LENGTH_LONG).show();
Object arglist[] = new Object[2];
arglist[0] = context;
arglist[1] = recipients; // Not a real phone number
Long threadId=(Long)getOrCreateThreadId.invoke(null,arglist);
Toast.makeText(context, "*****ThreadId"+threadId.longValue(), Toast.LENGTH_LONG).show();
return threadId;
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
Toast.makeText(context, "NoSuchMethodException "+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
Toast.makeText(context, "ClassNotFoundException "+e1.getMessage(), Toast.LENGTH_LONG).show();
e1.printStackTrace();
}catch (IllegalAccessException e3) {
// TODO Auto-generated catch block
Toast.makeText(context, "IllegalAccessException "+e3.getMessage(), Toast.LENGTH_LONG).show();
e3.printStackTrace();
} catch (InvocationTargetException e4) {
Toast.makeText(context, "InvocationTargetException "+e4.getMessage(), Toast.LENGTH_LONG).show();
e4.printStackTrace();
}
return -1;
}
That's work for me
Here's a simpler version of the above reflection code:
private static long getOrCreateThreadId(Context context, Set<String> recipientsAddress) {
try {
Class<?> clazz = Class.forName("android.provider.Telephony$Threads");
Method method = clazz.getMethod("getOrCreateThreadId", Context.class, Set.class);
method.setAccessible(true);
return (Long) method.invoke(null, context, recipientsAddress);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to find or allocate a thread ID.", e);
}
}

Error with Java WebStart Signed Jars on 1.7.0_40

We are aware of the issue with jar softlinker
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6967414
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6805618
and have used following class (found on web and modified to take care of JAVA 7 as well.)
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A utility class for working around the java webstart jar signing/security bug
* <p/>
* see http://bugs.sun.com/view_bug.do?bug_id=6967414 and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6805618
*
* #author Scott Chan
*/
public class JarSignersHardLinker {
private static final String JRE_1_DOT = "1.";
private static final String DOT_ZERO_UNDERSCORE = ".0_";
/**
* the 1.6.0 update where this problem first occurred
*/
private static final int PROBLEM_JRE_UPDATE = 19;
private static final int PROBLEM_JRE_MAJOR_VERSION = 6;
public static final List sm_hardRefs = new ArrayList();
protected static void makeHardSignersRef(JarFile jar) throws java.io.IOException {
if (jar != null && jar.getClass().getName().equals("com.sun.deploy.cache.CachedJarFile")) {
Logger.info("Making hard refs for: " + jar.getName());
//lets attempt to get at the each of the soft links.
//first need to call the relevant no-arg method to ensure that the soft ref is populated
//then we access the private member, resolve the softlink and throw it in a static list.
callNoArgMethod("getSigners", jar);
makeHardLink("signersRef", jar);
callNoArgMethod("getSignerMap", jar);
makeHardLink("signerMapRef", jar);
// callNoArgMethod("getCodeSources", jar);
// makeHardLink("codeSourcesRef", jar);
callNoArgMethod("getCodeSourceCache", jar);
makeHardLink("codeSourceCacheRef", jar);
}
}
/**
* if the specified field for the given instance is a Softreference
* That soft reference is resolved and the returned ref is stored in a static list,
* making it a hard link that should never be garbage collected
*
* #param fieldName
* #param instance
*/
private static void makeHardLink(String fieldName, Object instance) {
//System.out.println("attempting hard ref to " + instance.getClass().getName() + "." + fieldName);
try {
Field signersRef = instance.getClass().getDeclaredField(fieldName);
signersRef.setAccessible(true);
Object o = signersRef.get(instance);
if (o instanceof SoftReference) {
SoftReference r = (SoftReference) o;
Object o2 = r.get();
sm_hardRefs.add(o2);
} else {
Logger.warn(fieldName + ": is not an instance of soft reference");
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* Call the given no-arg method on the given instance
*
* #param methodName
* #param instance
*/
private static void callNoArgMethod(String methodName, Object instance) {
// System.out.println("calling noarg method hard ref to " + instance.getClass().getName() + "." + methodName + "()");
try {
Method m = instance.getClass().getDeclaredMethod(methodName);
m.setAccessible(true);
m.invoke(instance);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* is the preloader enabled. ie: will the preloader run in the current environment
*
* #return
*/
public static boolean isHardLinkerEnabled() {
boolean isHardLinkerDisabled = false; //change this to use whatever mechanism you use to enable or disable the preloader
return !isHardLinkerDisabled && isRunningOnJre1_6_0_19OrHigher() && isRunningOnWebstart();
}
/**
* is the application currently running on webstart
* <p/>
* detect the presence of a JNLPclassloader
*
* #return
*/
public static boolean isRunningOnWebstart() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
while (cl != null) {
if (cl.getClass().getName().equals("com.sun.jnlp.JNLPClassLoader")) {
return true;
}
cl = cl.getParent();
}
return false;
}
/**
* Is the JRE 1.6.0_19 or higher?
* TBFI-5349: Java has a bug, sometimes Jars get garbage collected. To resolve this we are making
* hard references to the Jars.
*
* This method checks for java version. The bug is in 1.6.0_19 and above release hence checking for version 19
* #return
*/
public static boolean isRunningOnJre1_6_0_19OrHigher() {
String javaVersion = System.getProperty("java.version");
String updateStr = null;
String javaMajorVersionStr = null;
boolean isHardReferenceRequired = false;
// Problem persist in JAVA 7 and probable in JAVA 8 as well. So changing the patter.
Pattern pattern = Pattern.compile(JRE_1_DOT + "([6-9]+)" + DOT_ZERO_UNDERSCORE + "([0-9]+)(.*)");
Matcher matcher = pattern.matcher(javaVersion);
while (matcher.find()) {
javaMajorVersionStr = matcher.group(1);
updateStr = matcher.group(2);
break;
}
Logger.info("Java version: " + javaMajorVersionStr + " update string: " + updateStr);
try {
if (javaMajorVersionStr != null) {
int java_version = Integer.parseInt(javaMajorVersionStr);
if (java_version > PROBLEM_JRE_MAJOR_VERSION) {
isHardReferenceRequired = true;
} else if (java_version == PROBLEM_JRE_MAJOR_VERSION && Integer.parseInt(updateStr) >= PROBLEM_JRE_UPDATE) {
isHardReferenceRequired = true;
}
}
return isHardReferenceRequired;
} catch (NumberFormatException e) {
//then unable to determine java Major version or update level
e.printStackTrace();
return isHardReferenceRequired;
}
}
/**
* get all the JarFile objects for all of the jars in the classpath
*
* #return
*/
public static Set<JarFile> getAllJarsFilesInClassPath() {
Set<JarFile> jars = new LinkedHashSet<JarFile>();
for (URL url : getAllJarUrls()) {
try {
jars.add(getJarFile(url));
} catch (IOException e) {
Logger.error("unable to retrieve jar at URL: " + url);
}
}
return jars;
}
/**
* Returns set of URLS for the jars in the classpath.
* URLS will have the protocol of jar eg: jar:http://HOST/PATH/JARNAME.jar!/META-INF/MANIFEST.MF
*/
static Set<URL> getAllJarUrls() {
try {
Set<URL> urls = new LinkedHashSet<URL>();
Enumeration<URL> mfUrls = Thread.currentThread().getContextClassLoader().getResources("META-INF/MANIFEST.MF");
while (mfUrls.hasMoreElements()) {
URL jarUrl = mfUrls.nextElement();
// System.out.println(jarUrl);
if (!jarUrl.getProtocol().equals("jar")) {
continue;
}
urls.add(jarUrl);
}
return urls;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* get the jarFile object for the given url
*
* #param jarUrl
* #return
* #throws IOException
*/
public static JarFile getJarFile(URL jarUrl) throws IOException {
URLConnection urlConnnection = jarUrl.openConnection();
if (urlConnnection instanceof JarURLConnection) {
// Using a JarURLConnection will load the JAR from the cache when using Webstart 1.6
// In Webstart 1.5, the URL will point to the cached JAR on the local filesystem
JarURLConnection jcon = (JarURLConnection) urlConnnection;
return jcon.getJarFile();
} else {
throw new AssertionError("Expected JarURLConnection");
}
}
/**
* Spawn a new thread to run through each jar in the classpath and create a hardlink
* to the jars softly referenced signers infomation.
*/
public static void go() {
if (!isHardLinkerEnabled()) {
return;
}
Logger.info("Starting Resource Preloader Hardlinker");
Thread t = new Thread(new Runnable() {
public void run() {
try {
Set<JarFile> jars = getAllJarsFilesInClassPath();
for (JarFile jar : jars) {
makeHardSignersRef(jar);
}
} catch (Exception e) {
Logger.warn("Problem preloading resources", e);
} catch (Error e) {
Logger.error("Error preloading resources", e);
}
}
});
t.start();
}
}
When we launch the application with JRE6 it works fine. But the problem is with JRE7. When the application is launched with JRE7 we get below exception in the log. From the exception we know that the jars are not hard referenced and that the user can have problems if the jars get garbage collected. We have a release next week and need to find a work around for this issue.
java.lang.NoSuchMethodException: com.sun.deploy.cache.CachedJarFile.getSigners()
at java.lang.Class.getDeclaredMethod(Unknown Source)
at com.XXXXXX.ui.main.JarSignersHardLinker.callNoArgMethod(JarSignersHardLinker.java:96)
at com.XXXXXX.ui.main.JarSignersHardLinker.makeHardSignersRef(JarSignersHardLinker.java:45)
at com.XXXXXX.ui.main.JarSignersHardLinker$1.run(JarSignersHardLinker.java:262)
at java.lang.Thread.run(Unknown Source)
java.lang.NoSuchFieldException: signersRef
at java.lang.Class.getDeclaredField(Unknown Source)
at com.XXXXXX.ui.main.JarSignersHardLinker.makeHardLink(JarSignersHardLinker.java:69)
at com.XXXXXX.ui.main.JarSignersHardLinker.makeHardSignersRef(JarSignersHardLinker.java:46)
at com.XXXXXX.ui.main.JarSignersHardLinker$1.run(JarSignersHardLinker.java:262)
at java.lang.Thread.run(Unknown Source)
This exception is repeated 52 times (for all the JAR's).
We have made sure that all the 52 jars/files (except the JNLP itself) are signed properly and that the java cache is cleard before the application is launched.
JAVA version used is JDK 7u40 on windows machine.
Options tried are:
Removing the jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
from java.securites file.
Checking the jar signer certificate. Signer certificate uses SHA1withRSA as signing algorithm.
Note:
THE SOURCE CODE IS COMPILED IN JAVA 5u11 AND RUN IN JAVA 7u40
We have observed one more difference. With JRE6, when we run the same
piece of code, it first loades JAVAWS.jar, Deploy.jar and plugin .jar from java/jre6/lib path but with JRE7 these jars are not loaded.
This has been tried in both 64 and 32 bits java version with no luck.
Any help here is really appreciated.
#jorge_B: We sign the jars using ant task. But due to a problem in JAVA 6u19 (where the softreferenced jars are sometimes garbage collected) we have decided to hardlink the jars as soon as we hit a java version 6u19 or above. This issue is not with jar signing. The issue is when we try to hard reference the jars. our jars are not getting hard referenced, insted we are getting nosuchmethod and nosuchfield exception in the log.
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A utility class for working around the java webstart jar signing/security bug
* <p/>
* see http://bugs.sun.com/view_bug.do?bug_id=6967414 and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6805618
*
* #author Scott Chan
*/
public class JarSignersHardLinker {
private static final String JRE_VERSION_START = "1.";
private static final int PROBLEM_JRE_VERSION = 6;
private static final String DOT_ZERO = ".0_";
/**
* the 1.6.0 update where this problem first occurred
*/
private static final int PROBLEM_JRE_UPDATE = 19;
private static String majorVersionStr = null;
public static final List sm_hardRefs = new ArrayList();
protected static void makeHardSignersRef(JarFile jar) throws java.io.IOException {
Logger.info("Making hard refs for: " + (jar != null ? jar.getName() : null) + " with Java Version: "+majorVersionStr);
if (jar != null && jar.getClass().getName().equals("com.sun.deploy.cache.CachedJarFile")) {
//lets attempt to get at the each of the soft links.
//first neet to call the relevant no-arg method to ensure that the soft ref is populated
//then we access the private member, resolve the softlink and throw it in a static list.
if (majorVersionStr != null && Integer.parseInt(majorVersionStr) > PROBLEM_JRE_VERSION) {
callNoArgMethod("getSigningData", jar);
makeHardLink("signingDataRef", jar);
} else {
callNoArgMethod("getSigners", jar);
makeHardLink("signersRef", jar);
callNoArgMethod("getSignerMap", jar);
makeHardLink("signerMapRef", jar);
// callNoArgMethod("getCodeSources", jar);
// makeHardLink("codeSourcesRef", jar);
callNoArgMethod("getCodeSourceCache", jar);
makeHardLink("codeSourceCacheRef", jar);
}
}
}
/**
* if the specified field for the given instance is a Softreference
* That soft reference is resolved and the returned ref is stored in a static list,
* making it a hard link that should never be garbage collected
*
* #param fieldName
* #param instance
*/
private static void makeHardLink(String fieldName, Object instance) {
Logger.info("attempting hard ref to " + instance.getClass().getName() + "." + fieldName);
try {
Field signersRef = instance.getClass().getDeclaredField(fieldName);
signersRef.setAccessible(true);
Object o = signersRef.get(instance);
if (o instanceof SoftReference) {
SoftReference r = (SoftReference) o;
Object o2 = r.get();
sm_hardRefs.add(o2);
} else {
Logger.warn(fieldName + ": is not an instance of soft reference");
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* Call the given no-arg method on the given instance
*
* #param methodName
* #param instance
*/
private static void callNoArgMethod(String methodName, Object instance) {
Logger.info("calling noarg method hard ref to " + instance.getClass().getName() + "." + methodName + "()");
try {
Method m = instance.getClass().getDeclaredMethod(methodName);
m.setAccessible(true);
m.invoke(instance);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* is the preloader enabled. ie: will the preloader run in the current environment
*
* #return
*/
public static boolean isHardLinkerEnabled() {
boolean isHardLinkerDisabled = false; //change this to use whatever mechanism you use to enable or disable the preloader
return !isHardLinkerDisabled && isRunningOnJre1_6_0_19OrHigher() && isRunningOnWebstart();
}
/**
* is the application currently running on webstart
* <p/>
* detect the presence of a JNLPclassloader
*
* #return
*/
public static boolean isRunningOnWebstart() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
while (cl != null) {
if (cl.getClass().getName().equals("com.sun.jnlp.JNLPClassLoader")) {
return true;
}
cl = cl.getParent();
}
return false;
}
/**
* Is the JRE 1.6.0_19 or higher?
*
* #return
*/
public static boolean isRunningOnJre1_6_0_19OrHigher() {
String javaVersion = System.getProperty("java.version");
// Sometimes java releases version 1.X.0_YY-rev for specific issue and specific user,
// to resolve this we use patter instead of string split.
//ERP-6460: Checking whether JRE is 6 update 19 or higher
String updateStr = null;
majorVersionStr = null;
boolean isHardReferenceRequired = false;
Pattern pattern = Pattern.compile(JRE_VERSION_START + "([6-9]+)" + DOT_ZERO + "([0-9]+)(.*)");
Matcher matcher = pattern.matcher(javaVersion);
while (matcher.find()) {
majorVersionStr = matcher.group(1);
updateStr = matcher.group(2);
break;
}
try {
if (majorVersionStr != null) {
int java_version = Integer.parseInt(majorVersionStr);
if (java_version > PROBLEM_JRE_VERSION) {
isHardReferenceRequired = true;
} else if (java_version == PROBLEM_JRE_VERSION && Integer.parseInt(updateStr) >= PROBLEM_JRE_UPDATE) {
isHardReferenceRequired = true;
}
}
return isHardReferenceRequired;
} catch (NumberFormatException e) {
e.printStackTrace();
return isHardReferenceRequired;
}
}
/**
* get all the JarFile objects for all of the jars in the classpath
*
* #return
*/
public static Set<JarFile> getAllJarsFilesInClassPath() {
Set<JarFile> jars = new LinkedHashSet<JarFile>();
for (URL url : getAllJarUrls()) {
try {
jars.add(getJarFile(url));
} catch (IOException e) {
Logger.error("unable to retrieve jar at URL: " + url);
}
}
return jars;
}
/**
* Returns set of URLS for the jars in the classpath.
* URLS will have the protocol of jar eg: jar:http://HOST/PATH/JARNAME.jar!/META-INF/MANIFEST.MF
*/
static Set<URL> getAllJarUrls() {
try {
Set<URL> urls = new LinkedHashSet<URL>();
Enumeration<URL> mfUrls = Thread.currentThread().getContextClassLoader().getResources("META-INF/MANIFEST.MF");
while (mfUrls.hasMoreElements()) {
URL jarUrl = mfUrls.nextElement();
// System.out.println(jarUrl);
if (!jarUrl.getProtocol().equals("jar")) {
continue;
}
urls.add(jarUrl);
}
return urls;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* get the jarFile object for the given url
*
* #param jarUrl
* #return
* #throws IOException
*/
public static JarFile getJarFile(URL jarUrl) throws IOException {
URLConnection urlConnnection = jarUrl.openConnection();
if (urlConnnection instanceof JarURLConnection) {
// Using a JarURLConnection will load the JAR from the cache when using Webstart 1.6
// In Webstart 1.5, the URL will point to the cached JAR on the local filesystem
JarURLConnection jcon = (JarURLConnection) urlConnnection;
return jcon.getJarFile();
} else {
throw new AssertionError("Expected JarURLConnection");
}
}
/**
* Spawn a new thread to run through each jar in the classpath and create a hardlink
* to the jars softly referenced signers infomation.
*/
public static void go() {
if (!isHardLinkerEnabled()) {
return;
}
Logger.info("Starting Resource Preloader Hardlinker");
Thread t = new Thread(new Runnable() {
public void run() {
try {
Set<JarFile> jars = getAllJarsFilesInClassPath();
for (JarFile jar : jars) {
makeHardSignersRef(jar);
}
} catch (Exception e) {
Logger.error("Problem preloading resources", e);
} catch (Error e) {
Logger.error("Error preloading resources", e);
}
}
});
t.start();
}
}

Cast a string to Class in java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am Passing a string to a setter method
PostPublication postPublication = new PostPublication();
/*
* Class MessageCont = Class.forName(messageContext
* .getProperty("MessageContent").toString());
*/
postPublication
.setMessageContent((MessageContent_type0) messageContext
.getProperty("MessageContent"));
The Setter method at PostPublication Class is
public void setMessageContent(
org.openoandm.www.xml.isbm.MessageContent_type0 param) {
this.localMessageContent = param;
}
Declaration of localMessageContent is
protected org.openoandm.www.xml.isbm.MessageContent_type0 localMessageContent;
MessageContent_type0 class code
/**
* MessageContent_type0.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST)
*/
package org.openoandm.www.xml.isbm;
/**
* MessageContent_type0 bean class
*/
#SuppressWarnings({"unchecked","unused"})
public class MessageContent_type0
implements org.apache.axis2.databinding.ADBBean{
/* This type was generated from the piece of schema that had
name = MessageContent_type0
Namespace URI = http://www.openoandm.org/xml/ISBM/
Namespace Prefix = ns1
*/
/**
* field for ExtraElement
*/
protected org.apache.axiom.om.OMElement localExtraElement ;
/**
* Auto generated getter method
* #return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getExtraElement(){
return localExtraElement;
}
/**
* Auto generated setter method
* #param param ExtraElement
*/
public void setExtraElement(org.apache.axiom.om.OMElement param){
this.localExtraElement=param;
}
/**
*
* #param parentQName
* #param factory
* #return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,parentQName);
return factory.createOMElement(dataSource,parentQName);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.openoandm.org/xml/ISBM/");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":MessageContent_type0",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"MessageContent_type0",
xmlWriter);
}
}
if (localExtraElement != null) {
localExtraElement.serialize(xmlWriter);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://www.openoandm.org/xml/ISBM/")){
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
if (localExtraElement != null){
elementList.add(org.apache.axis2.databinding.utils.Constants.OM_ELEMENT_KEY);
elementList.add(localExtraElement);
} else {
throw new org.apache.axis2.databinding.ADBException("extraElement cannot be null!!");
}
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static MessageContent_type0 parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
MessageContent_type0 object =
new MessageContent_type0();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"MessageContent_type0".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (MessageContent_type0)org.openoandm.www.xml.isbm.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement()){
//use the QName from the parser as the name for the builder
javax.xml.namespace.QName startQname1 = reader.getName();
// We need to wrap the reader so that it produces a fake START_DOCUMENT event
// this is needed by the builder classes
org.apache.axis2.databinding.utils.NamedStaxOMBuilder builder1 =
new org.apache.axis2.databinding.utils.NamedStaxOMBuilder(
new org.apache.axis2.util.StreamWrapper(reader),startQname1);
object.setExtraElement(builder1.getOMElement());
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
When i am passing data to set the setter method it throws exception as
java.lang.String cannot be cast to org.openoandm.www.xml.isbm.MessageContent_type0
How can i set the setter method by passing string in it?Thanks in advance
You need to turn your String into a MessageContent_type0, a simple cast won't do.
No idea what this class is, but maybe there is something like
new MessageContent_type0(myString);
it is not allowed in java. you can either upcast or downcast any object in a inheritance-hierarchy. But can not cast to anything out of the inheritance-hierarchy.
in your case, in type of localMessageContent there must be some constructor with string param or method like setMessage(string)

Categories

Resources