public class A
{
[...]
private int methoda(int i)
{
...
methodb();
....
}
private void methodb()
{...}
[...]
}
test:
#Test
#PrepareForTest({...})
public void testMethoda() throws Exception
{
//mytest
A a = PowerMockito.spy(new A());
Method privateMethod = a.getClass().getDeclaredMethod("methoda", int.class);
privateMethod.setAccessible(true);
PowerMockito.doNothing.when(a, "methodb");
..
}
with exception:
java.lang.NoSuchMethodException
who can tell me how to deal with this situation?
Related
I am trying to deserialize a simple xml with pojo but getting error as below:
Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of classname (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('checka')
at [Source: (com.ctc.wstx.sr.ValidatingStreamReader); line: 3, column: 15] (through reference chain: classname["testData"]->java.util.ArrayList[0])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
<tc>
<testData>
<post>checka</post>
<xtenantid>netwebshopa</xtenantid>
<jsonbody>Testa</jsonbody>
</testData>
<testData>
<post>check</post>
<xtenantid>netwebshop</xtenantid>
<jsonbody>Test</jsonbody>
</testData>
#JacksonXmlRootElement(localName = "tc")
public class TC {
private List<TestData> testData;
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
public class TestData {
private String post;
private String xtenantid;
private String jsonbody;
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public String getXtenantid() {
return xtenantid;
}
public void setXtenantid(String xtenantid) {
this.xtenantid = xtenantid;
}
public String getJsonbody() {
return jsonbody;
}
public void setJsonbody(String jsonbody) {
this.jsonbody = jsonbody;
}
}
You need a constructor with all parameters:
public class TestData(String post, String xtenantid, String jsonbody) {
this.post= post;
this.xtenantid= xtenantid;
this.jsonbody= jsonbody;
If you try to deserialize the class. You get something like this.
<tc>
<testData>
<testData>
<post>checka2</post>
<xtenantid>netwebshopa2</xtenantid>
<jsonbody>Testa2</jsonbody>
</testData>
<testData>
<post>checka1</post>
<xtenantid>netwebshopa1</xtenantid>
<jsonbody>Testa1</jsonbody>
</testData>
</testData>
The TestData class is duplicated because jackson uses elementWrapper by default.
To remove it, you must use #JacksonXmlElementWrapper(useWrapping = false).
The result should look like this.
public class ParrentXml {
#JacksonXmlElementWrapper(useWrapping = false)
List<ChildXml> childxmls = new ArrayList<>();
public List<ChildXml> getChildxmls() {
return childxmls;
}
public void setChildxmls(List<ChildXml> childxmls) {
this.childxmls = childxmls;
}
}
I am using Dagger - 2.6 and i have the following classes.
public class Trigger {
public static JSONObject triggerLambda(JSONObject jsonObject) {
DataTransformerComponent daggerDataTransformerComponent = DaggerDataTransformerComponent.create();
return daggerDataTransformerComponent.getHandler().handle(jsonObject);
}
}
Data Handler class:
public class DataHandler {
private static final Logger LOGGER = Logger.getLogger(DataHandler.class.getName());
private A a;
#Inject
public DataHandler(A a) {
this.a = a;
}
public JSONObject handle(JSONObject input) {
LOGGER.info("Json input received - " + input.toString());
return a.executeTransformation(input);
}
}
And a dependency:
public class A {
#Inject
public A() {
}
public JSONObject executeTransformation(JSONObject jsonObject) {
System.out.println("a");
return null;
}
}
My component class looks like:
#Component
public interface DataTransformerComponent {
DataHandler getHandler();
}
When i compile the above code it runs absolutely fine.
Now i want to make my A dependency #Singleton.
So i change my dependency class and component class as follows:
#Singleton
#Component
public interface DataTransformerComponent {
DataHandler getHandler();
}
Dependency class:
#Singleton
public class A {
#Inject
public A() {
}
public JSONObject executeTransformation(JSONObject jsonObject) {
System.out.println("a");
return null;
}
}
But now the generated component shows compilation errors saying:
A_Factory not found and it fails in the initialize() method.
DaggerDataTransformerComponent :
#Generated(
value = "dagger.internal.codegen.ComponentProcessor",
comments = "https://google.github.io/dagger"
)
public final class DaggerDataTransformerComponent implements DataTransformerComponent {
private Provider<A> aProvider;
private Provider<DataHandler> dataHandlerProvider;
private DaggerDataTransformerComponent(Builder builder) {
assert builder != null;
initialize(builder);
}
public static Builder builder() {
return new Builder();
}
public static DataTransformerComponent create() {
return builder().build();
}
#SuppressWarnings("unchecked")
private void initialize(final Builder builder) {
this.aProvider = DoubleCheck.provider(A_Factory.create());
this.dataHandlerProvider = DataHandler_Factory.create(aProvider);
}
#Override
public DataHandler getHandler() {
return dataHandlerProvider.get();
}
public static final class Builder {
private Builder() {}
public DataTransformerComponent build() {
return new DaggerDataTransformerComponent(this);
}
}
}
I am unable to figure out why it does not create _factory class when i use #Singleton annotation.?.
Just use regular JavaScript + node.js, its a lot simpler
I have referred multiple threads for solution but those did not help :( Any help to provide solution in terms of code on below problem is appreciated
class Program
{
static void Main(string[] args)
{
//StructureMapConfiguration();
var registry = new Registry();
registry.IncludeRegistry<DependencyRegistry>();
var container = new Container(registry);
var depend = container.GetInstance<ITest>();
var controller1 = new Controller1(depend);
controller1.M1();
var controller2 = new Controller2(depend);
controller1.M1();
Console.Read();
}
}
public interface ITest
{
void Method();
}
public class A : ITest
{
public void Method()
{
Console.WriteLine("A");
}
}
public class B : ITest
{
public void Method()
{
Console.WriteLine("B");
}
}
public class C : ITest
{
public void Method()
{
Console.WriteLine("C");
}
}
public interface IController
{
void M1();
}
public class Controller1 : IController
{
private ITest _test;
public Controller1()
{
}
public Controller1(ITest test)
{
_test = test;
}
public void M1()
{
_test.Method();
}
}
public class Controller2 : IController
{
private ITest _test;
public Controller2(ITest test)
{
_test = test;
}
public void M1()
{
_test.Method();
}
}
public class DependencyRegistry : Registry
{
public DependencyRegistry()
{
For<ITest>().Use<A>().Named("A");
For<ITest>().Use<B>().Named("B");
For<ITest>().Use<C>().Named("C");
For<IController>().Add<Controller1>().Ctor<ITest>().Is(i => i.GetInstance<ITest>("A"));
For<IController>().Add<Controller2>().Ctor<ITest>().Is(i => i.GetInstance<ITest>("B"));
Scan(x =>
{
x.AssembliesFromApplicationBaseDirectory();
x.AddAllTypesOf<ITest>().NameBy(type => type.Name);
x.WithDefaultConventions();
});
}
}
}
Actual Result:
Everytime I am getting instance of class C for Controller1 and Controller2
Expected Result:
For Controller1, I need instance of class A and for Controller2, I need instance of class B
Thanks in advance
In my windows service application I need to resolve components using configuration when service is starting. I use Castle Windsor as my IoC container.
Application looks like:
public class RootComponent : IRootComponent {
public RootComponent (IDataProvider1 provider1, IDataProvider2 provider2)
{
this.provider1 = provider1;
this.provider2 = provider2;
}
...
}
public class DataProvider1 : IDataProvider1
{
...
public DataProvider1 (IDbHelper dbHelper)
{
this.dbHelper = dbHelper;
}
...
}
public class DataProvider2 : IDataProvider2
{
...
public DataProvider1 (IDbHelper dbHelper)
{
this.dbHelper = dbHelper;
}
...
}
public interface IDbHelper
{
IDbConnection GetNewConnection();
DbParameter CreateDbParameter(string paramName, object paramValue);
string GetCommandString(string commandName);
}
public class MsSqlDbHelper : IDbHelper
{
...
public MsSqlDbHelper(string connectionString)
{
this.connectionString = connectionString;
}
...
}
public class PostgreDbHelper : IDbHelper
{
...
public PostgreDbHelper(string connectionString)
{
this.connectionString = connectionString;
}
...
}
I would like to register dependencies in service constructor and in OnStart method read the configuration and resolve correct IDbHelper based on it:
public partial class MyWindowsService : ServiceBase
{
public MyWindowsService()
{
InitializeComponent();
this.container = new WindsorContainer();
RegisterDependencies();
}
private void RegisterDependencies()
{
container.Register(
Classes.FromAssemblyInThisApplication().BasedOn<IRootComponent>().WithServiceFromInterface(),
Classes.FromAssemblyInThisApplication().BasedOn<IDataProvider1>().WithServiceFromInterface(),
Classes.FromAssemblyInThisApplication().BasedOn<IDataProvider2>().WithServiceFromInterface(),
Classes.FromAssemblyInThisApplication().BasedOn<IDbHelper>().WithServiceFromInterface()
.ConfigureFor<MsSqlDbHelper>(
registration => {
registration.DependsOn(Dependency.OnValue<string>(ConnectStringProvider.GetConnectionString("connectString1")));
registration.Named("msSql");
})
.ConfigureFor<PostgreDbHelper>(
registration => {
registration.DependsOn(Dependency.OnValue<string>(ConnectStringProvider.GetConnectionString("connectString2")));
registration.Named("postgreSql");
}));
}
protected override void OnStart(string[] args)
{
ResolveDependencies();
}
private void ResolveDependencies()
{
// Helper properties contain "msSql" or "postgreSql" value
root = container.Resolve<IRootComponent>(Config.Provider1Helper, Config.Provider2Helper);
}
...
}
I see three options how to resolve configured IDbHepler:
Typed factory facility
Child containers
Implement IHandlerSelector
What is the best way and why?
Solution is simpler than I expected. DynamicParameters is what I neeed:
private void RegisterDependencies()
{
container.Register(
Classes.FromAssemblyInThisApplication().BasedOn<IRootComponent>().WithServiceFromInterface(),
Classes.FromAssemblyInThisApplication().BasedOn<IDataProvider1>().WithServiceFromInterface()
.Configure(registration => registration.DynamicParameters((kernel, parameters) =>
{
IDbHelper dbHelper = kernel.Resolve<IDbHelper>(Config.Provider1Helper);
parameters.Add("dbHelper", dbHelper);
return k => k.ReleaseComponent(dbHelper);
})),
Classes.FromAssemblyInThisApplication().BasedOn<IDataProvider2>().WithServiceFromInterface(),
.Configure(registration => registration.DynamicParameters((kernel, parameters) =>
{
IDbHelper dbHelper = kernel.Resolve<IDbHelper>(Config.Provider2Helper);
parameters.Add("dbHelper", dbHelper);
return k => k.ReleaseComponent(dbHelper);
})),
Classes.FromAssemblyInThisApplication().BasedOn<IDbHelper>().WithServiceFromInterface()
.ConfigureFor<MsSqlDbHelper>(
registration => {
registration.DependsOn(Dependency.OnValue<string>(ConnectStringProvider.GetConnectionString("connectString1")));
registration.Named("msSql");
})
.ConfigureFor<PostgreDbHelper>(
registration => {
registration.DependsOn(Dependency.OnValue<string>(ConnectStringProvider.GetConnectionString("connectString2")));
registration.Named("postgreSql");
}));
}
protected override void OnStart(string[] args)
{
// Helper properties should contain "msSql" or "postgreSql" value
// take configuration from arguments
Config.Provider1Helper = UseMsSql(args, 0) ? "msSql" : "postgreSql";
Config.Provider2Helper = UseMsSql(args, 1) ? "msSql" : "postgreSql";
ResolveDependencies();
}
private void ResolveDependencies()
{
root = container.Resolve<IRootComponent>();
}
private bool UseMsSql(string[] args, int argNumber)
{
...
}
I am trying to write a simple multicore PureMVC helloword. I am getting Error: multitonKey for this Notifier not yet initialized!
at org.puremvc.as3.multicore.patterns.observer::Notifier/get facade()[C:\Documents and Settings\Owner.CapricornOne\My Documents\My Workspaces\PureMVC\PureMVC_AS3_MultiCore\src\org\puremvc\as3\multicore\patterns\observer\Notifier.as:89]
at com.jacksutest.view::ApplicationMediator()[C:\myworkspace\MyPureMVC\src\com\jacksutest\view\ApplicationMediator.as:15]
Here is the main mxml:
public static const APP_NAME : String = "MyPureMVC";
private var facade : ApplicationFacade = ApplicationFacade.getInstance(APP_NAME);
public function init() : void
{
facade.startup(this);
}
...
<components:WordForm id="theWordForm"/>
This is the ApplicationFacade.
public class ApplicationFacade extends Facade implements IFacade
{
public static const STARTUP : String = "Startup";
public static const VERIFY_WORD : String = "VerifyWord";
public function ApplicationFacade(key:String)
{
super(key);
}
public static function removeInstance(key:String):void
{
if( null != instanceMap )
{
if( null != instanceMap[key] )
{
delete instanceMap[key];
}
}
}
/**
* Singleton ApplicationFacade Factory Method
*/
public static function getInstance(key:String):ApplicationFacade
{
if ( null == instanceMap[key] )
{
instanceMap[key] = new ApplicationFacade(key);
}
return instanceMap[key] as ApplicationFacade;
}
/**
* Register Commands with the Controller
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(STARTUP, StartupCommand);
registerCommand(VERIFY_WORD, VerifyWordCommand);
}
public function startup(app : MyPureMVC):void
{
trace("In facade startup");
sendNotification(STARTUP, app);
}
public function verifyWord(wordDTO : WordDTO) : void
{
sendNotification(VERIFY_WORD, wordDTO);
}
}
}
This is startup command
public class StartupCommand extends MacroCommand
{
public function StartupCommand()
{
trace("Startup command created");
addSubCommand(ModelPrepCommand);
addSubCommand(ViewPrepCommand);
}
}
This is ViewPrepCommand
public class ViewPrepCommand extends SimpleCommand
{
override public function execute( note : INotification ) : void
{
var app : MyPureMVC = note.getBody() as MyPureMVC;
facade.registerMediator(new ApplicationMediator(app));
}
}
And this is ApplicationMediator:
public class ApplicationMediator extends Mediator implements IMediator
{
public static const NAME : String = "MyPureMVCApplicationMediator";
public function ApplicationMediator(mainApp : MyPureMVC)
{
facade.registerMediator(new WordFormMediator(mainApp.theWordForm));
}
Error happens when facade.registerMediator.
Find the problem. I should not reference facade in the constructor of ApplicationMediator.
Instead, I should call the facade.registerMediator in onRegister method.
public static const NAME : String = "MyPureMVCApplicationMediator";
public function ApplicationMediator(viewComponent : MyPureMVC)
{
super( NAME, viewComponent );
}
override public function onRegister():void
{
// Retrieve reference to frequently consulted Proxies
facade.registerMediator(new WordFormMediator(mainApp.theWordForm));
}
public function get mainApp() : MyPureMVC
{
return viewComponent as MyPureMVC;
}