Unreal Engine 4 Blank Module - c++

I'm trying to get into unreal engine 4 module development, starting out with blank module for starters, but hitting a block at the start.
Tutorial that I went through for a non-game module: https://wiki.unrealengine.com/An_Int...to_UE4_Plugins. I tried going exactly by the source and later modifying everything to TestPlugin (since I couldn't get it to work by the tutorial either).
For some reason, whenever I try to activate the module within the editor, I get the "can't find the "Module" module". I am trying to figure out if I missed something, here is the code that I have so far:
../Engine/Plugins/TestPlugin/TestPlugin.uplugin
{
"FileVersion" : 3,
"FriendlyName" : "Test Plugin",
"Version" : 1,
"VersionName": "1.0",
"EngineVersion" : 1579795,
"Description" : "Description goes here",
"Category" : "Test.Module",
"CreatedBy" : "arhon",
"CreatedByURL" : "http://stackoverflowcom",
"CanContainContent" : "true",
"Modules" :
[
{
"Name" : "Module",
"Type" : "Developer",
"LoadingPhase" : "PreDefault"
}
]
}
../Engine/Plugins/TestPlugin/Source/TestPlugin/TestPlugin.cpp
void FTestPlugin::StartupTestPlugin()
{
if (ITestPlugin::IsAvailable())
{
UE_LOG(TestPlugin, Log, TEXT("%s"), ITestPlugin::Get().IsThisNumber42(42) ? TEXT("True") : TEXT("False"));
UE_LOG(TestPlugin, Log, TEXT("%s"), ITestPlugin::Get().IsThisNumber42(12) ? TEXT("True") : TEXT("False"));
}
}
../Engine/Plugins/TestPlugin/Source/TestPlugin/TestPlugin.Build.cs
using UnrealBuildTool;
public class TestPlugin : ModuleRules
{
public TestPlugin(TargetInfo Target)
{
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
PrivateDependencyModuleNames.AddRange(new string[] { "TestPlugin" });
DynamicallyLoadedModuleNames.AddRange(new string[] { "StandAlone" });
}
}
../Engine/Plugins/TestPlugin/Source/TestPlugin/Public/ITestPlugin.h
#pragma once
#include "ModuleManager.h"
/**
* The public interface to this module. In most cases, this interface is only public to sibling modules
* within this plugin.
*/
class ITestPlugin : public ITestPluginInterface
{
public:
/**
* Singleton-like access to this module's interface. This is just for convenience!
* Beware of calling this during the shutdown phase, though. Your module might have been unloaded already.
*
* #return Returns singleton instance, loading the module on demand if needed
*/
static inline ITestPlugin& Get()
{
return FModuleManager::LoadModuleChecked< ITestPlugin >("TestPlugin");
}
/**
* Checks to see if this module is loaded and ready. It is only valid to call Get() if IsAvailable() returns true.
*
* #return True if the module is loaded and ready to use
*/
static inline bool IsAvailable()
{
return FModuleManager::Get().IsModuleLoaded("TestPlugin");
}
virtual bool IsThisNumber42(int32 num) = 0;
};
../Engine/Plugins/TestPlugin/Source/TestPlugin/Private/TestPluginPrivatePCH.h
#include "ITestPlugin.h"
// You should place include statements to your module's private header files here. You only need to
// add includes for headers that are used in most of your module's source files though.
../Engine/Plugins/TestPlugin/Source/TestPlugin/Private/TestPlugin.h
#pragma once
class TestPluginImpl : public ITestPlugin
{
public:
/** IModuleInterface implementation */
void StartupTestPlugin();
void ShutdownTestPlugin();
bool IsThisNumber42(int32 num);
};
../Engine/Plugins/TestPlugin/Source/TestPlugin/Private/TestPlugin.cpp
#include "TestPluginPrivatePCH.h"
#include "TestPlugin.h"
void TestPluginImpl::StartupTestPlugin()
{
}
void TestPluginImpl::ShutdownTestPlugin()
{
}
bool TestPluginImpl::IsThisNumber42(int32 num)
{
return num == 42;
}
IMPLEMENT_MODULE(TestPluginImpl, TestPlugin)

In the .uplugin file, look at your module name, then in testplugin.cpp, look at this line:
IMPLEMENT_MODULE(TestPluginImpl, TestPlugin)
I'm sure they need to match.
e.g.:
"Modules" :
[
{
"Name" : "NebulaAudioAnalysisPlugin",
"Type" : "Runtime"
}
]
and my implementation looks like:
IMPLEMENT_MODULE(FNebulaAudioAnalysisPlugin, NebulaAudioAnalysisPlugin)
I found this all out the hard way...

Related

Halt the workflow and return the response to Controller

Create Order triggers the Rest End point and starts the workflow (Its a TASK ). CreateOrderController
Problem is CreateOrderController is always returning Success.I want to return ResponseEntity.ok("Not Success "); as shown in 2nd image and stop the call of Save Order Database
How to achieve it?
> #RestController
> public class CreateOrderController {
>
> #Autowired
> private RuntimeService runtimeService;
>
>
>
> #PostMapping("/rest/create/order")
> public ResponseEntity<?> createOrder(#RequestBody OrderInfo orderInfo) {
> Map<String, Object> inputData = new HashMap<String, Object>();
> inputData.put("orderInfo", orderInfo);
> ProcessInstance p = runtimeService.startProcessInstanceByKey("hello-world-process",inputData);
>
>
>
> return ResponseEntity.ok("Success");
>
> }
If you are executing the complete process in one transaction, then an exception along the way will create a rollback. However, you usually have a transaction boundary somewhere. You can query the status of the process instance after it has been started via the history endpoint.
The execute method returns void. Let the delegate write process data instead of returning a value. You can find a setVariable method on the delegateExecution you are getting in as a parameter.
You can get the data values in the REST response as shown in this example: https://docs.camunda.org/manual/7.18/reference/rest/process-definition/post-start-process-instance/#starting-a-process-instance-with-variables-in-return
Request:
{
"variables":{
"aVariable" : {
"value" : "aStringValue",
"type": "String"},
"anotherVariable" : {
"value" : true,
"type": "Boolean",
"valueInfo" : {
"transient" : true
}
}
},
"businessKey" : "myBusinessKey",
"withVariablesInReturn": true
}
Response
{
"links": [
{
"method": "GET",
"href": "http://localhost:8080/rest-test/process-instance/aProcInstId",
"rel": "self"
}
],
"id": "aProcInstId",
"definitionId": "aProcessDefinitionId",
"businessKey": "myBusinessKey",
"ended": false,
"suspended": false,
"tenantId": null,
"variables": {
"anotherVariable": {
"type": "Boolean",
"value": true,
"valueInfo": {
"transient" : true
}
},
"aVariable": {
"type": "String",
"value": "aStringValue",
"valueInfo": { }
}
}
}
Alternatively, error handling options in the delegate code / process include:
a) Simply throw an exception in your execute() method, for instance a new RuntimeException() and observe in Cockpit how Camunda creates a technical incident for the process (https://docs.camunda.org/manual/7.18/webapps/cockpit/bpmn/failed-jobs/).
b) You can also use custom exceptions and error codes, e.g. as shown here:
// Defining a custom exception.
public class MyException extends ProcessEngineException {
public MyException(String message, int code) {
super(message, code);
}
}
// Delegation code that throws MyException with a custom error code.
public class MyJavaDelegate implements JavaDelegate {
#Override
public void execute(DelegateExecution execution) {
String myErrorMessage = "My error message.";
int myErrorCode = 22_222;
throw new MyException(myErrorMessage, myErrorCode);
}
}
Src: https://docs.camunda.org/manual/7.18/user-guide/process-engine/delegation-code/#exception-codes
c) If you don't want to create e technical incident but prefer to throw a 'business' error which you can catch in the process model, so the process can take a different (error) path:
public class BookOutGoodsDelegate implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
try {
...
} catch (NotOnStockException ex) {
throw new BpmnError("Business issue");
}
}
}
src: https://docs.camunda.org/manual/7.18/user-guide/process-engine/delegation-code/#throw-bpmn-errors-from-delegation-code

AWS API Gateway - Integration Response body mapping

In AWS API Gateway Integration Response body mapping I have following code:
#set($inputRoot = $input.path('$.Item'))
[
#foreach($elem in $inputRoot.Events)
{
"id": $elem.id,
"from" : $elem.from,
"to" : $elem.to,
"spent" : $elem.spent,
#if("$!elem.comment" != "")
"comment": $elem.comment,
#end
"project" : {
"id" : $elem.project.id,
"number" : $elem.project.number,
"name" : $elem.project.name
}
}
#if($foreach.hasNext),#end
#end
]
The data comes from a lambda functions which queries a DynamoDB Table
API gateway returns the data like this:
[
{
"id": 123443214,
"from" : 19:34,
"to" : 22:30,
"spent" : 02:56,
"project" : {
"id" : 4321,
"number" : CIB,
"name" : Backend
}
}
, {
"id": 12341234,
"from" : 19:34,
"to" : 22:30,
"spent" : 02:56,
"project" : {
"id" : 12341234,
"number" : CIB,
"name" : Backend
}
}
]
So it it's already formatted. How do I get APi Gateway to return the response unformatted? So that it's just pure json, without break lines, indentations etc.?
Thanks in advance!
(Small preliminary remark: you are missing some quotes around JSON string values).
It's possible to remove line breaks using ## and indentation using #**#, as follow, but the template will look a bit ugly:
#set($inputRoot = $input.path('$.Item'))##
[##
#foreach($elem in $inputRoot.Events)##
{##
#**#"id":$elem.id,##
#**#"from": $elem.from,##
#**#"to":$elem.to,##
#**#"spent":$elem.spent,##
#if("$!elem.comment" != "")##
#* *#"comment":$elem.comment,##
#end##
#**#"project":{##
#**#"id":$elem.project.id,##
#**#"number":"$elem.project.number",##
#**#"name":"$elem.project.name"##
}##
}##
#if($foreach.hasNext),#end##
#end##
]##
Since the only reason the indentation is in here at first is readability of the template, I would go another direction.
For instance, you can add a post-processing tidy formatter in your View servlet) using org.json:
import org.json.JSONObject;
....
Writer writer = new StringWriter();
getVelocityView().merge(template, context, writer);
String compactJSON = new JSONObject(writer.toString()).toString();
response.getWriter().write(compactJSON);
But this will only work for small JSON files since the response is buffered into memory, so let's keep on searching for a more elegant solution.
The way to go is to pre-process your template, using a custom ResouceLoader.
CompactJSONResourceLoader.java
package my.custom.loader;
import java.io.InputStream;
import java.io.IOException;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.runtime.resource.loader.ResourceLoaderFactory;
public class CompactJSONResourceLoader extends ResourceLoader
{
protected ResourceLoader innerLoader = null;
#Override
public void init(ExtendedProperties configuration)
{
try
{
String innerLoaderID = configuration.getString("innerLoader") + ".resource.loader";
String innerLoaderClass = rsvc.getConfiguration().getString(innerLoaderID + ".class");
innerLoader = ResourceLoaderFactory.getLoader(rsvc, innerLoaderClass);
ExtendedProperties innerConfiguration = rsvc.getConfiguration().subset(innerLoaderID);
innerLoader.commonInit(rsvc, innerConfiguration);
innerLoader.init(innerConfiguration);
}
catch (Exception e)
{
log.error("could not initialize CompactJSONResourceLoader inner loader", e);
}
}
protected class CompactJSONInputStream extends InputStream
{
InputStream innerStream = null;
boolean insideQuotes = false;
public CompactJSONInputStream(InputStream innerStream)
{
this.innerStream = innerStream;
}
#Override
public int read() throws IOException
{
int ch;
do
{
ch = innerStream.read();
if (insideQuotes)
{
if (ch == '"') insideQuotes = false;
break;
}
else if (!Character.isWhitespace(ch))
{
if (ch == '"') insideQuotes = true;
break;
}
}
while (ch != -1);
return ch;
}
}
#Override
public InputStream getResourceStream(String source) throws ResourceNotFoundException
{
return new CompactJSONInputStream(innerLoader.getResourceStream(source));
}
#Override
public boolean isSourceModified(Resource resource)
{
return innerLoader.isSourceModified(resource);
}
#Override
public long getLastModified(Resource resource)
{
return innerLoader.getLastModified(resource);
}
}
And you would then need to configure Velocity with the following properties:
resource.loader = compact
compact.resource.loader.class = my.custom.loader.CompactJSONResourceLoader
compact.resource.loader.innerLoader = file
(you would replace file with the resource loader you are currently using, of course).

readable substitution of IEnumerable of Interfaces

I have the following interfaces
public interface IRibbonCommandsProvider
{
IEnumerable<IRibbonCommand> GetRibbonCommands();
}
public interface IRibbonCommand
{
string Group { get; }
string Tab { get; }
string Name { get; }
string Image { get; }
void Execute();
}
And the follwing substitution code:
public class TabsViewModelTests
{
[Fact]
public void Initialize_BuildsCorrectRibbonTree()
{
var commands = Substitute.For<IRibbonCommandsProvider>();
commands.GetRibbonCommands().Returns(
new[]
{
new RibbonCommand { Tab = "Tab1", Group = "Group1", Name = "Name1" },
new RibbonCommand { Tab = "Tab1", Group = "Group1", Name = "Name2" },
new RibbonCommand { Tab = "Tab2", Group = "Group1", Name = "Name3" },
new RibbonCommand { Tab = "Tab2", Group = "Group2", Name = "Name3" }
});
...
}
private class RibbonCommand : IRibbonCommand
{
public string Group { get; set; }
public string Tab { get; set; }
public string Name { get; set; }
public string Image { get; set; }
public void Execute() {}
}
}
Using NSubstitute, is there a clever way to get rid of the stub RibbonCommand class (that is nothing but a fake IRibbonCommand implementation - and that's NSubstitute's job) and still have list of fake ribbon commands that is as easily readable as the above?.
I can't come up with a readable way using NSubsitute's .Returns() fluent method without ending with a lot more (and unreadable) code.
Update:
A cool NSubstitute extension method could look like this. I just don't know if and how this can be built:
public static ConfiguredCall ReturnsMany<T>(
this IEnumerable<T> value,
Action<T> configureThis,
params Action<T>[] configureThese)
{
...
}
It would be used like this:
commands.GetRibbonCommands().ReturnsMany(
subst =>
{
subst.Tab.Returns("Tab1");
subst.Group.Returns("Group1");
subst.Name.Returns("Name1");
},
subst =>
{
subst.Tab.Returns("Tab1");
subst.Group.Returns("Group1");
subst.Name.Returns("Name2");
},
subst =>
{
subst.Tab.Returns("Tab2");
subst.Group.Returns("Group1");
subst.Name.Returns("Name3");
},
subst =>
{
subst.Tab.Returns("Tab2");
subst.Group.Returns("Group1");
subst.Name.Returns("Name3");
});
I think what you've got is very good — quite succinct and clear.
If you really want to get rid of the class you can use a substitute creation method for IRibbonCommand:
private IRibbonCommand Create(string tab, string group, string name)
{
var cmd = Substitute.For<IRibbonCommand>();
cmd.Tab.Returns(tab);
cmd.Group.Returns(group);
cmd.Name.Returns(name);
return cmd;
}
[Fact]
public void Initialize_BuildsCorrectRibbonTree()
{
var ribbonCommands = new[] {
Create("tab1", "group1", "name1"),
Create("tab1", "group1", "name2"),
Create("tab2", "group1", "name3"),
Create("tab2", "group1", "name4")
};
var commands = Substitute.For<IRibbonCommandsProvider>();
commands.GetRibbonCommands().Returns(ribbonCommands);
// ...
}
This doesn't buy you much, although it does mean your test code will be more protected from changes to the IRibbonCommand interface (e.g. an additional property will not require changing your test code), and means you can check received calls and stub other calls on individual items.
Aside: Can use argument names if you want to more closely match the original code:
Create(tab: "tab1", group: "group1", name: "name1"),
As alternative you may setup Command inside test. Then move config func out of the test and optionally generalize for other types as you go. Yagni it.
UPDATED to working test
[Test]
public void Test()
{
Func<Action<IRibbonCommand>, IRibbonCommand> cmd = config =>
{
var c = Substitute.For<IRibbonCommand>();
config(c);
return c;
};
var ribbonCommands = new[]
{
cmd(c => { c.Tab.Returns("Tab1"); c.Group.Returns("Group1"); c.Name.Returns("Name1"); }),
cmd(c => { c.Tab.Returns("Tab1"); c.Group.Returns("Group1"); c.Name.Returns("Name2"); }),
cmd(c => { c.Tab.Returns("Tab2"); c.Group.Returns("Group1"); c.Name.Returns("Name3"); }),
cmd(c => { c.Tab.Returns("Tab2"); c.Group.Returns("Group1"); c.Name.Returns("Name4"); })
};
var commandsProvider = Substitute.For<IRibbonCommandsProvider>();
commandsProvider.GetRibbonCommands().Returns(ribbonCommands);
}
I don't see anything out of the box that's going to do what you're after. One option might be for you to write your own extension method to make the construction easier. So, something like this:
public static class ReadOnlySubstitute {
static public T For<T>(object source) where T : class {
var sub = Substitute.For<T>();
foreach (var prop in source.GetType().GetProperties()) {
sub.GetType().GetProperty(prop.Name).GetValue(sub).Returns(prop.GetValue(source));
}
return sub;
}
}
The above code essentially creates a substitute for the given interface and then sets up a return on each of properties specified in the supplied object.
This could then be used in your test like this to supply anonymous objects with the parameters:
[Test]
public void Initialize_BuildsCorrectRibbonTree() {
var ribbonCommands = new[]
{
ReadOnlySubstitute.For<IRibbonCommand>(new {Tab="Tab1", Group="Grp1", Name="Nam1"}),
ReadOnlySubstitute.For<IRibbonCommand>(new {Tab="Tab1", Group="Grp1", Name="Nam2"}),
ReadOnlySubstitute.For<IRibbonCommand>(new {Tab="Tab2", Group="Grp1", Name="Nam3"}),
ReadOnlySubstitute.For<IRibbonCommand>(new {Tab="Tab2", Group="Grp2", Name="Nam3"})
};
var commands = Substitute.For<IRibbonCommandsProvider>();
commands.GetRibbonCommands().Returns(ribbonCommands);
....
}
It's not quite as concise as using the RibbonCommand class, since you have to construct the array before passing it into the Returns method because NSubstitute gets confused if you try to setup the Returns on the elements at the same time as on the GetRibbonCommands, but I think it's fairly close.
This is really an enhancement (subjective) of #dadhi's answer, combined with an answer from #David Tchepak to a different question.
So, rather than having to create a new Func for each interface your want to use, as described by #dadhi, you can instead create a generic method that takes an Action. You could be this in a shared class, something like this:
static class ConfiguredSub {
public static T For<T>(Action<T> config) where T : class {
var c = Substitute.For<T>();
config(c);
return c;
}
}
The problem that I encountered with my other answer was that if you have nested Returns, NSubstitute gets confused and starts throwing exceptions. It turns out that as described by #David here, you can pass a Func to defer the execution and get round this issue. If you combine these two things, then you get something pretty close to what you're after.
[Test]
public void Initialize_BuildsCorrectRibbonTree() {
var commands = Substitute.For<IRibbonCommandsProvider>();
commands.GetRibbonCommands().Returns(x => new[] {
ConfiguredSub.For<IRibbonCommand>(subst =>
{
subst.Tab.Returns("Tab1");
subst.Group.Returns("Group1");
subst.Name.Returns("Name1");
}),
ConfiguredSub.For<IRibbonCommand>(subst =>
{
subst.Tab.Returns("Tab1");
subst.Group.Returns("Group1");
subst.Name.Returns("Name2");
}),
ConfiguredSub.For<IRibbonCommand>(subst =>
{
subst.Tab.Returns("Tab2");
subst.Group.Returns("Group1");
subst.Name.Returns("Name3");
}),
ConfiguredSub.For<IRibbonCommand>(subst =>
{
subst.Tab.Returns("Tab2");
subst.Group.Returns("Group1");
subst.Name.Returns("Name4");
})
});
// ...
}

passing parameters to native reduce script of ElasticSearch facet script

I'm trying to use elasticsearch facet script, but when I get to the reduce phase's NativeScriptFactory the passed map parameter is empty.
Here's my query:
"facets": {
"myFacet": {
"script": {
"lang": "native",
"map_script": "MyMap",
"reduce_script": "MyReduce",
"params" : {
"facet" : {}
}
}
}
}
When I use the default reducer, I get this response:
"facets": {
"myFacet": {
"_type": "script",
"facet": [
{
"222790": 7,
"762984": 7
}
]
}
}
My map script looks like this:
public class MyMapScript extends AbstractSearchScript {
private Map<String, Double> _myScores;
public MyMapScript(Map<String, Object> stringObjectMap) {
_myScores = (Map<String, Double>) stringObjectMap.get("facet");
}
#Override
public Object run() {
ScriptDocValues.NumericLong tags = (ScriptDocValues.NumericLong) doc().get("tags");
for (Long t : tags.getValues()){
Double score = 7.0;
_myScores.put(t.toString(), score);
}
return _myScores;
}
}
and the reduce script factory, which gets an empty map as a parameter:
public class MyReduceScriptFactory implements NativeScriptFactory {
#Override
public ExecutableScript newScript(#Nullable Map<String, Object> stringObjectMap) {
return new MyReduceScript(stringObjectMap);
}
}
What do I have to do to get the mapper's output to the reducer?
Apparently this was fixed at latest version, I was using an older one.

How do I mock the autofac's autogenerated delegate factories?

I'm struggling to get a unit test working for one of my classes. I want to inject my factory instead of the autogenerated factory the autofac resolves to. How do I register my own function as the delegate to replace the autogenerated delegate factory?
My code looks something like this is outline form:
interface IEntryImporter { ... }
class EntryImporter : IEntryImporter {
public EntryImporter(ISeries series, IMatch match, Entry.Factory entryFactory) {
:
}
:
}
interface IEntry : { ... }
class Entry : IEntry {
public delegate IEntry Factory();
public Entry() { ... }
}
interface IMatch : { ... }
class Match : IMatch { ... }
interface ISeries : { ... }
class Series : ISeries { ... }
void IEntry MyEntryFactory() {
var entry = new Mock<IEntry>();
:
return entry.Object;
}
void TestMe() {
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Entry>().As<IEntry>();
builder.RegisterType<Match>().As<IMatch>();
builder.RegisterType<Series>().As<ISeries>();
builder.RegisterType<EntryImporter>.As<IEntryImporter>();
var series = new Mock<ISeries>(MockBehavior.Strict);
builder.RegisterInstance<ISeries>(series.Object);
var match = new Mock<IMatch>(MockBehavior.Strict);
builder.RegisterInstance<IMatch>(match.Object);
// How to register MyEntryFactory as Entry.Factory for autofac to resolve?
using(var container = builder.Build()) {
var importer = container.Resolve<IEntryImporter>();
:
}
}
You can register your own method for use as the mock entry factory as follows:
builder.Register<Entry.Factory>(c => MyEntryFactory).As<Entry.Factory>();
I have got your sample working as part of Autofac Answers on GitHub.