java.lang.IllegalArgumentException when reading from string - java

In my project I want to read from string my package name but I got following error.
before I change may code it was like that:
static {
sURLMatcher.addURI("com.nooshindroid.yastashir2.model", "alarm", ALARMS);
sURLMatcher.addURI("com.nooshindroid.yastashir2.model", "alarm/#", ALARMS_ID);
}
In my application class I get the like this:
public static String context;
#Override
public void onCreate() {
context = getApplicationContext().getResources().getString(R.string.package_app);
}
and when I change it like this :
static {
sURLMatcher.addURI(AlarmApplication.context+".model", "alarm", ALARMS);
sURLMatcher.addURI(AlarmApplication.context+".model", "alarm/#", ALARMS_ID);
}
and here is my error:
Unable to create application com.nooshindroid.yastashir2.AlarmApplication: java.lang.IllegalArgumentException: Unknown URL content://com.nooshindroid.yastashir2.model/alarm
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4809)
at android.app.ActivityThread.access$1600(ActivityThread.java:154)

Code in the static initialisation block runs before your Application's onCreate. So your context field is still null when you add URIs to the matcher.
Can you maybe instead use BuildConfig.APPLICATION_ID + ".model" in your static initialisation? BuildConfig fields are written at build time, so will be available in the static initialisation block. If APPLICATION_ID doesn't suit your needs, you can always add a custom build config field in your build.gradle file.

Related

I am unable to transfer values between samplers using JavaSamplerContext.getJMeterVariables() in jmeter java

I am relatively new to Jmeter so please bearvwith me :) According to the documentation, getJMeterVariables returns the jmeter variables for the current thread which I believed was instantiated when I created the JavaSamplerContext. However, it seems like its not the case as JavaSamplerContext.getJMeterVariables is null and when I try to add values to it:
JavaSamplerContext.getJMeterVariables().put("something","something");
I get null pointer exception. My goal is to debug how values pass between samplers and my scenario is something like the following - a main class that calls the different samplers and looks like:
public static void main(String[] args) {
Sampler1 sampler1 = new Sampler1();
Sampler2 sampler2 = new Sampler2();
JavaSamplerContext context = new JavaSamplerContext(getArguments());
Sampler1.runTest(context);
Sampler2.runTest(context);
}
I would like to use JavaSamplerContext.getJMeterVariables().put("something","something") to transfer values between sampler1 and sampler2 and hence Sampler1 for example looks like:
public class Sampler1 extends AbstractJavaSamplerClient {
#Override
public SampleResult runTest(JavaSamplerContext context) {
SampleResult result = new SampleResult();
result.sampleStart();
Something1 something1 = doSomething();
String something2 = doSomething2()
result.sampleEnd();
context.getJMeterVariables().putObject("something1Key",Something1);
context.getJMeterVariables().put("something2Key",something2);
return result;
}
While sampler2 will have: (Note that I am trying to transfer both String and an Object)
public class Sampler2 extends AbstractJavaSamplerClient {
#Override
public SampleResult runTest(JavaSamplerContext context) {
String something2 = context.getJMeterVariables().get("something2Key");
Something1 something1 = (Something1) context.getJMeterVariables().getObject("something1Key");
...
}
What am I missing?
I don't think you can run the code like you do, if you look at getJMeterVariables() function source code you will see that it calls JMeterContext class which is null because I fail to see where you start JMeter in your code.
You may want to take a look at SleepTest or JavaTest example implementations which are being used in Java Request Sampler to get the overall idea of using AbstractJavaSamplerClient, but again if you try to run them directly - you get an error because JMeter Context will not be initialized.
So compile your classes into .jar file, drop it under JMeter Classpath and run JMeter - the variables should be set/transferred across samplers.
If you want to run JMeter from Java code - take a look at Five Ways To Launch a JMeter Test without Using the JMeter GUI article

Spring Boot - Could not find a suitable constructor error

Hi I am trying to read a file as an argument from the main class and accessing the argument in another class in Spring boot.
The main class looks like this
public class DemorestApplication extends SpringBootServletInitializer {
public static void main(String[] args) throws IOException {
new DemorestApplication().configure(new SpringApplicationBuilder(DemorestApplication.class)).run(args);
new UsersResources(args[0]);
}
}
And I am passing an argument to another class named UsersResources constructor
#Path("/sample")
public class UsersResources {
private String value;
UsersResources(String value){
this.value=value;
}
//new code
#GET
#Path("Data/file/{path}")
#Produces("application/json")
public Map<String, Map<String, List<Map<String, Map<String, String>>>>> getApplicationName1(#PathParam("path") String path) throws IOException {
ReadExceldy prop = new ReadExceldy();
FileInputStream Fs = new FileInputStream(System.getProperty("user.dir")+"\\"+value);
Properties properties = new Properties();
properties.load(Fs);
String Loc=properties.getProperty("filepath");
String Na=path;
String filename=Loc+Na;
return prop.fileToJson(filename);
}
}
I'm trying to run this code but it's throwing an error saying
java.lang.NoSuchMethodException: Could not find a suitable constructor in com.springsampleapplication.UsersResources class
at org.glassfish.jersey.internal.inject.JerseyClassAnalyzer.getConstructor(JerseyClassAnalyzer.java:192) ~[jersey-common-2.25.1.jar:na]
The issue might be with Spring trying to initialize UsersResources class and expecting a constructor with no arguments, when you have it only with a String parameter. Try adding such constructor: public UsersResources() {}
Other thought that came into mind is that this could be because of UsersResources constructor not having a visibility modifier (it means it is package protected), you could try adding public visibility modifier to it (though Spring should be able to initialize even private constructors). Are the DemorestApplication and UsersResources classes in the same package though? As otherwise the code should not compile, since UsersResources(String value) is not visible outside of the package it is in. But the error is a bit different in such case: The constructor xxx is undefined, so probably this is not the case.
Since it seems you are using Jersey you need to have a public constructor:
Root resource classes are instantiated by the JAX-RS runtime and MUST have a public constructor for which the JAX-RS runtime can provide all parameter values. Note that a zero argument constructor is permissible under this rule.
See How to register a static class in Jersey?
Since you have defined a constructor in your class, no default constructor is generated. A work around is to make this class a Spring component with #Component et al.

Android Studio Apply Changes non-static method cannot be referenced, but method is static

I have a problem compiling my android app in Android Studio. I get an error like this:
Error:(51, 48) error: non-static method buildUsernameUrlString(String)
cannot be referenced from a static context
Also this one:
Error:(63, 38) error: OAUTH_URL has private access in TwitchApi
I'm aware of the concept of static methods etc. which is why I my TwitchApi class looks like this:
public class TwitchApi {
// more stuff here
public static String OAUTH_URL = Uri.parse("https://api.twitch.tv/kraken/oauth2/authorize")
.buildUpon()
.appendQueryParameter("response_type", "token")
.appendQueryParameter("client_id", CLIENT_ID)
.appendQueryParameter("redirect_uri", REDIRECT_URL)
.appendQueryParameter("scope", "user_read chat_login").build().toString();
public static String buildUsernameUrlString(String accessToken)
{
return BASE_URI
.buildUpon()
.appendQueryParameter("client_id", CLIENT_ID)
.appendQueryParameter("oauth_token", accessToken)
.build()
.toString();
}
}
So my method is clearly static, also public, and the property OAUTH_URL is public and static aswell.
I call the method like this:
String usernameUrlString = TwitchApi.buildUsernameUrlString(matcher.group(1));
What's weird is that I only get this error when doing "Applying Changes" which seems to be like a hot-swap for changes to not compile the entire application again.
A full compilation has no error.
Has anyone any idea how to get around this error? I really like the Apply Changes feature it speeds up development by a lot.
Try to delete .build folder and rebuild the project. It will solve your problem.

Powermock - mocking static class members

I'm trying to mock the following class which contains some static members
public class ClientFact {
private static final String BASE_URL = Config.getProperty("prop1");
private static final String USERID = Config.getProperty("prop2");
......................
public static Client createClient() throws AppException {
}
}
but i'm running into issues with the static member variables which are populated by Config.getProperty. This class does a read on a properties file like so
public class Config {
...............
public static String getProperty(Param param) {
String value = null;
if (param != null) {
value = properties.getProperty(param.toString());
}
return value;
}
}
I'm trying to mock this call since i dont care about the loaded properties in my test. This is what ive tried
#RunWith(PowerMockRunner.class)
#PrepareForTest({ClientFact.class})
public class MyTests {
#Test
public void test() {
PowerMock.mockStaticPartial(Config.class, "getProperty");
EasyMock.expect(Config.getProperty(EasyMock.anyObject())).andReturn(EasyMock.anyString()).anyTimes();
PowerMock.mockStatic(ClientFact.class);
}
}
but its giving the following error...
java.lang.NoSuchMethodError: org/easymock/internal/MocksControl.createMock(Ljava/lang/Class;[Ljava/lang/reflect/Method;)Ljava/lang/Object;
at org.powermock.api.easymock.PowerMock.doCreateMock(PowerMock.java:2214)
at org.powermock.api.easymock.PowerMock.doMock(PowerMock.java:2163)
any ideas what im doign wrong here?
A non-answer: consider not making static calls there.
You see, that directly couples that one class to the implementation of that static method in some other class; for no real reason. (and for the record: it seems strange that a USER_ID String is a static field in your ClientFact class. Do you really intend that all ClientFacts are using the same USER_ID?!)
You could replace that static call with a non-static version (for example by introducing an interface); and then you can use dependency injection to make an instance of that interface available to your class under test. And then all your testing works without the need to Powermock.
Long story short: very often (but not always!) the need to turn to Powermock originates in production code which wasn't written to be testable (like in your case). Thus instead of using the big bad Powermock hammer to "fix" your testing problem, you should consider improving your production code.
You might want to listen to those videos to get a better understanding what I am talking about.

java.util.ServiceLoader not loading my provider class

I am trying to put together a basic SPI-based registry of Handlers, which I lookup from a HandlerRegistry. When I use the ServiceLoader.load(Handler.class) to initialize the providers, and then iterate the list to lazily load them, I am not seeing any instances of the class. Keeping this as simple as possible, my HandlerRegistry class is:
public class HandlerRegistry
{
private static HandlerRegistry registry;
private ServiceLoader<Handler> handlerLoader;
private HandlerRegistry()
{
handlerLoader = ServiceLoader.load(Handler.class);
}
public static synchronized HandlerRegistry getRegistry()
{
if (registry == null) {
registry = new HandlerRegistry();
registry.init();
}
return registry;
}
private void init()
{
System.out.println("HandlerRegistry.init()");
}
public Handler lookup(String item)
{
System.out.println("lookup("+item+")");
try {
Iterator<Handler> it = handlerLoader.iterator();
while (it.hasNext()) {
Handler handler = it.next();
System.out.println("found handler "+handler);
}
}
catch (ServiceConfigurationError err) {
err.printStackTrace();
}
return null;
}
}
I have a com.example.handler.Handler interface (empty for now for simplicity), and a com.example.handler.handlers.DummyHandler class which implements that interface. I have created a file in my jar called META-INF/services/com.example.handler.Handler, which contains the single line
com.example.handler.handlers.DummyHandler
according to the javadoc. My unit test simply calls the lookup() method to verify looking up the handler for an item. Of course there will eventulaly need to be a check of some kind to see if this is the right handler for this item, but at this point I am not even seeing my DummyHandler class get loaded by the registry. Am I doing something wrong here?
Thanks!
The answer appears to be in the sensitivity to exactly how this is configured. I had been placing my provider name resource file (the one named com.example.handler.Handler) directly in the top level project directory, i.e., /resources/META-INF/services/com.example.handler.Handler. I had configured my build.gradle to pull the file out and put it into the jar:
jar { from('resources') { include 'META-INF/services/*.*' } }
When I inspected the jar file, the file was there, right where I expected it to be, so I thought all was well. On a kick, I happened to move the resources folder from down under src/main, and presto! it works. I inspected the jar file and it appears identical to one built the previous way, but for some reason this one works. I will update further if I can determine a difference, but at least my test case works now.

Categories

Resources