How to print outside of Main Argument? (It can be done) - printing

This is how you print outside of main.
public class PrintOutsideMain {
static {System.out.println ("You can go with this");}
public static void main(String[] args) {
System.out.println("Or This is where its at");
}
}
It works
run:
You can go with this
Or This is where its at
BUILD SUCCESSFUL (total time: 0 seconds)
Something I was looking for a while ago but I played around and found I could do this. I could not find an answer for this question so I chose to post it. I also did not find any information as to why it is not a good practice to do. I was never taught it was a bad practice to do.

Related

Is there a way to execute a multiple test methods in order on parameterized data

I am using JUnit5 and and wanted to construct my test class with ordered methods over a set of data.
So far I've looked into nested tests but I cannot seem to get the desired output
Is there anyway to do this? Can someone maybe just point me in the right direction because I've been tackling this for hours.
#ParameterizedTest
#MethodSource("getTestData")
#Order(1)
void shouldGetTestCaseNumber(Map<Object, Object> excelData) {
System.out.println(excelData.get("Test Case "));
}
#ParameterizedTest
#MethodSource("getTestData")
#Order(2)
void shouldGetEntitlement(Map<Object, Object> excelData) {
System.out.println(excelData.get("Entitlement"));
}
Collection<Arguments> getTestData() throws IOException {
TestDataService testDataService = new TestDataService();
List<Arguments> data = new ArrayList<>();
for(Object[] d: testDataService.getData()){
data.add(Arguments.of(d));
}
return data;
}
Right now the output would have all test cases for shouldGetTestCaseNumber() followed by shouldGetEntitlement() but I would like a single test case as
Test Case 1
shouldGetTestCaseNumber()
shouldGetEntitlement()
Test Case 2
shouldGetTestCaseNumber()
shouldGetEntitlement()
Like I said, I would just life if someone could point me in the right direction and I could go from there
No, it's not possible with the current feature set.
There's an open issue for this at https://github.com/junit-team/junit5/issues/871 ... and lot of related ones.
You may resort to dynamic tests and roll your own lightweight tests structure. But you'll loose all features that parameterized tests provide.
https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests

Amazon SWF queries

Over the last couple of years, I have done a fair amount of work on Amazon SWF, but the following points are still unclear to me and I am not able to find any straight forward answers on any forums yet.
These are pretty basic requirements I suppose, sure others might have come across too. Would be great if someone can clarify these.
Is there a simple way to return a workflow execution result (maybe just something as simple as boolean) back to workflow starter?
Is there a way to catch Activity timeout exception, so that we can do run customised actions in such scenarios?
Why doesn't WorkflowExecutionHistory contains Activities, why just Events?
Why there is no simple way of restarting a workflow from the point it failed?
I am considering to use SWF for more business processes at my workplace, but these limitations/doubts are holding me back!
FINAL WORKING SOLUTION
public class ReturnResultActivityImpl implements ReturnResultActivity {
SettableFuture future;
public ReturnResultActivityImpl() {
}
public ReturnResultActivityImpl(SettableFuture future) {
this.future = future;
}
public void returnResult(WorkflowResult workflowResult) {
System.out.print("Marking future as Completed");
future.set(workflowResult);
}
}
public class WorkflowResult {
public WorkflowResult(boolean s, String n) {
this.success = s;
this.note = n;
}
private boolean success;
private String note;
}
public class WorkflowStarter {
#Autowired
ReturnResultActivityClient returnResultActivityClient;
#Autowired
DummyWorkflowClientExternalFactory dummyWorkflowClientExternalFactory;
#Autowired
AmazonSimpleWorkflowClient swfClient;
String domain = "test-domain;
boolean isRegister = true;
int days = 7;
int terminationTimeoutSeconds = 5000;
int threadPollCount = 2;
int taskExecutorThreadCount = 4;
public String testWorkflow() throws Exception {
SettableFuture<WorkflowResult> workflowResultFuture = SettableFuture.create();
String taskListName = "testTaskList-" + RandomStringUtils.randomAlphabetic(8);
ReturnResultActivity activity = new ReturnResultActivityImpl(workflowResultFuture);
SpringActivityWorker activityWorker = buildReturnResultActivityWorker(taskListName, Arrays.asList(activity));
DummyWorkflowClientExternalFactory factory = new DummyWorkflowClientExternalFactoryImpl(swfClient, domain);
factory.getClient().doSomething(taskListName)
WorkflowResult result = workflowResultSettableFuture.get(20, TimeUnit.SECONDS);
return "Call result note - " + result.getNote();
}
public SpringActivityWorker buildReturnResultActivityWorker(String taskListName, List activityImplementations)
throws Exception {
return setupActivityWorker(swfClient, domain, taskListName, isRegister, days, activityImplementations,
terminationTimeoutSeconds, threadPollCount, taskExecutorThreadCount);
}
}
public class Workflow {
#Autowired
private DummyActivityClient dummyActivityClient;
#Autowired
private ReturnResultActivityClient returnResultActivityClient;
#Override
public void doSomething(final String resultActivityTaskListName) {
Promise<Void> activityPromise = dummyActivityClient.dummyActivity();
returnResult(resultActivityTaskListName, activityPromise);
}
#Asynchronous
private void returnResult(final String taskListname, Promise waitFor) {
ActivitySchedulingOptions schedulingOptions = new ActivitySchedulingOptions();
schedulingOptions.setTaskList(taskListname);
WorkflowResult result = new WorkflowResult(true,"All successful");
returnResultActivityClient.returnResult(result, schedulingOptions);
}
}
The standard pattern is to host a special activity in the workflow starter process that is used to deliver the result. Use a process specific task list to make sure that it is routed to a correct instance of the starter. Here are the steps to implement it:
Define an activity to receive the result. For example "returnResultActivity". Make this activity implementation to complete the Future passed to its constructor upon execution.
When the workflow is started it receives "resultActivityTaskList" as an input argument. At the end the workflow calls this activity with a workflow result. The activity is scheduled on the passed task list.
The workflow starter creates an ActivityWorker and an instance of a Future. Then it creates an instance of "returnResultActivity" with that future as a constructor parameter.
Then it registers the activity instance with the activity worker and configures it to poll on a randomly generated task list name. Then it calls "start workflow execution" passing the generated task list name as an input argument.
Then it wait on the Future to complete. The future.get() is going to return the workflow result.
Yes, if you are using the AWS Flow Framework a timeout exception is thrown when activity is timed out. If you are not using the Flow framework than you are making your life 100 times harder. BTW the workflow timeout is thrown into a parent workflow as a timeout exception as well. It is not possible to catch a workflow timeout exception from within the timing out instance itself. In this case it is recommended to not rely on workflow timeout, but just create a timer that would fire and notify workflow logic that some business event has timed out.
Because a single activity execution has multiple events associated to it. It should be pretty easy to write code that converts history to whatever representation of activities you like. Such code would just match the events that relate to each activities. Each event always has a reference to the related events, so it is easy to roll them up into higher level representation.
Unfortunately there is no easy answer to this one. Ideally SWF would support restarting workflow by copying its history up to the failure point. But it is not supported. I personally believe that workflow should be written in a way that it never fails but always deals with failures without failing. Obviously it doesn't work in case of failures due to unexpected conditions. In this case writing workflow in a way that it can be restarted from the beginning is the simplest approach.

Is it possible to see what's registered with OWIN's IAppBuilder?

I have a solution which makes use of many class libraries (optional plugins). It is actually very similar in design to nopCommerce. Anyway, I have the following interface:
public interface IOwinStartupConfiguration
{
void Configuration(IAppBuilder app);
}
Obviously what happens is that in my Startup class in the web project, I get a list of all registered IOwinStartupConfiguration instances in all plugins and then proceed to iterate over each one.
So far I only have one plugin using this, but that may change later. The thing I'm worried about is the possibility of more than 1 plugin calling something like:
app.MapSignalR();
Acccording to this page:
http://www.asp.net/signalr/overview/testing-and-debugging/troubleshooting
doing so would cause an error like
"A route named 'signalr.hubs' is already in the route collection"
Is it possible to see what's in the OWIN pipeline?
Ideally I would like to do something like this:
if (!app.IsSignalRMapped)
{
app.MapSignalR();
}
or
if (!app.HasMappedService("SignalR"))
{
app.MapSignalR();
}
Obviously I cannot find any such thing on the IAppBuilder interface. So what can I do in this situation?
I just stumbled upon MapWhen(), but it seemed a bit pointless. I was going to try something like this:
app.MapWhen(x => !existingConfigurations.Contains("SignalR"), x => app.MapSignalR());
where existingConfigurations is a new ICollection<string> passed in the modified method:
void Configuration(IAppBuilder app, ICollection<string> existingConfigurations)
However, I found it made more sense to simply do this:
if (!existingConfigurations.Contains("SignalR"))
{
app.MapSignalR();
existingConfigurations.Add("SignalR");
}
It's not a perfect solution, since someone could misspell "SignalR", for example. But since there's no IsSignalRMapped() method, it will have to suffice.
I haven't tried this but this might work:
var hub = GlobalHost.ConnectionManager.GetHubContext<MySignalRHub>();
if (hub == null)
{
app.MapSignalR();
}

The way to run method each X minutes

It seems like I just need to implement kind of a listener, if there is no something similar already.
Let's say I have a method which is executed each time build finishes (RunListener event); but that's not enough and I want to run the method each X minutes. I'm stuck!
So, I wonder if there is a way to do it (kind of a listener, event trigger, whatever).
Any info, thoughts are welcomed!
If you want to execute a task regularly in a Jenkins plugin, you can implement the PeriodicWork extension point.
A minimal example that would automatically register with Jenkins, and be executed every three minutes:
#Extension
public class MyPeriodicTask extends PeriodicWork {
#Override
public long getRecurrencePeriod() {
return TimeUnit.MINUTES.toMillis(3);
}
#Override
protected void doRun() throws Exception {
// Do something here, quickly.
// If it will take longer, use AsyncPeriodWork instead
}
}

May a scenario not have a When in BDD?

I'm currently learning/testing BDD using SpecFlow, and it works great!
Before I choose to ask my question, I have read this one, and I felt like I had to ask my question despite the fact that the same problem is addressed, because of the Exception scenario which is not mentioned.
I'm actually testing this scenario:
Scenario: I should get an error whenever I try to remove an item from an empty stack
Given I have an empty stack
When I pop from it
Then I should get an error
public class StackBehaviour {
public void GivenIHaveAnEmptyStack() { stack = new CustomStack<string>(); }
// This will throw whenever called!
// So the Then method will never be run!
// I feel like I should just put a comment which says why it's empty,
// allowing a fellow programmer to understand the exact intention.
public void WhenIPopFromIt() { stack.Pop(); }
// It is here that it verifies whether the CustomStack meets the expected behaviour.
public void ThenIShouldGetAnError() {
Assert.Throws<IndexOutOfRangeException>(delegate {
stack.Pop();
});
}
private CustomStack<string> stack;
}
public class CustomStack<T> {
public T Pop() {
if (stack.Count == 0)
throw new IndexOutOfRangeException("Cannot pop from an empty stack!");
T item = stack[stack.Count-1];
stack.RemoveAt(stack.Count-1);
return item;
}
private ArrayList stack = new ArrayList();
}
I think that leaving a comment in the When method is correct, so that the business requirement doesn't lack any information, and on the code behind, I put it clear what my intention is exactly by commenting.
What do you think? Any other ideas why I shouldn't make it?
There is another trick that you can use where the bindings help make the feature's meaning a little clearer. In this case, let's start at the end.
Then I should get an error
Your problem is a basically here, you know want an error, but you don't know how to get it. In fact you've already missed it, the error has already occurred in the When step, and in your code example, you moved the action into the then step just so you could get the error.
But what if keep the when performing the action amd re-express our then to reflect what really happens
Then I should have had an error
Seems a trivial change but now our feature reflects that the error should have been associated with the When step and we are simply evaluating it later, and that is something we can code. We just need something to remember the error in the when and deliver it to the then.
private Exception errorFromWhen = null;
public void WhenIPopFromIt()
{
try
{
stack.Pop();
}
catch(Exception ex)
{
errorFromWhen = ex;
}
}
public void ThenIShouldGetAnError()
{
errorFromWhen.ShouldNotBeNull();
errorFromWhen.ShouldBe<IndexOutOfRangeException>();
}
SpecFlow has absolutely no problems with this, in fact due to its mini Dependency injection system, you can even pass this state between binding classes if necessary.
May a scenario not have a When in BDD?
In Specflow, neither given, when or then are mandatory.
However in your example, I don't believe this is a good use of Specflow and BDD. In this answer here Marcus states:
"BDD is about ensuring that we're building the right thing, TDD is about ensuring that we're building it right."
In your example the scope of what is being tested i.e. the CustomStack, should be tested via TDD. It is the end solution that makes use of the CustomStack should be tested via BDD (and hence SpecFlow) e.g. if this CustomStack was being exercised via a certain action on a website.
This answer is also pertinent to your question.

Resources