Running the SimulationStarter class in the AlgoTrader - java

I am trying to run the SimulationStarted class with the moving average strategy in the open source edition of AlgoTrader.
When I start the SimulationStarter I get ArrayIndexOutOfBoundsException.
I am trying to run it through eclipse. From AlgoTrader they run it with the following command
java.exe -cp target/classes;../../AlgoTrader/code/target/classes;../../AlgoTrader/code/lib/*;target/* -Dsimulation=true -DdataSource.dataSet=1year com.algoTrader.starter.SimulationStarter simulateWithCurrentParams
So is it even possible to run it through eclipse or this is the only way?
If anyone has any ideas or suggestions it will be much appreciated.
Here is the code for the SimulationStarter and ServiceLocator classes.
package com.algoTrader.starter;
import org.apache.commons.math.*;
import org.apache.log4j.Logger;
import com.algoTrader.ServiceLocator;
import com.algoTrader.service.SimulationServiceImpl;
import com.algoTrader.util.MyLogger;
public class SimulationStarter {
private static Logger logger = MyLogger.getLogger(SimulationServiceImpl.class.getName());
public static void main(String[] args) throws ConvergenceException, FunctionEvaluationException {
ServiceLocator.serverInstance().init("beanRefFactorySimulation.xml");
if ("simulateWithCurrentParams".equals(args[0])) {
ServiceLocator.serverInstance().getSimulationService().simulateWithCurrentParams();
} else if ("optimizeSingleParamLinear".equals(args[0])) {
String strategyName = args[1];
for (int i = 2; i < args.length; i++) {
String[] params = args[i].split(":");
String parameter = params[0];
double min = Double.parseDouble(params[1]);
double max = Double.parseDouble(params[2]);
double increment = Double.parseDouble(params[3]);
ServiceLocator.serverInstance().getSimulationService().optimizeSingleParamLinear(strategyName, parameter, min, max, increment);
}
}
ServiceLocator.serverInstance().shutdown();
}
}
And the service locator class
package com.algoTrader;
import com.algoTrader.entity.StrategyImpl;
import com.algoTrader.util.ConfigurationUtil;
public class ServiceLocator {
private static boolean simulation = ConfigurationUtil.getBaseConfig().getBoolean("simulation");
private static String strategyName = ConfigurationUtil.getBaseConfig().getString("strategyName");
public static CommonServiceLocator commonInstance() {
if (!simulation && !StrategyImpl.BASE.equals(strategyName)) {
return RemoteServiceLocator.instance();
} else {
return ServerServiceLocator.instance();
}
}
public static ServerServiceLocator serverInstance() {
if (!simulation && !StrategyImpl.BASE.equals(strategyName)) {
throw new IllegalArgumentException("serverInstance cannot be called from the client");
} else {
return ServerServiceLocator.instance();
}
}
}

To Fix this error you will need to open the Run Configuraitons in Eclipse and Add the program Arguments and the VM Arguments and the ArrayIndexOutOfBoundsException will be gone.
The bad news are that there is another error: 2014-01-22 11:15:35,771 ERROR JDBCExceptionReporter Access denied for user 'algouser'#'localhost' (using password: YES)
Which I will be investigating now

In order to run AlgoTrader you need to have a database (MySQL) and configure DB in the source code of AlgoTrader. Without DB AlgoTrader does not work.

Related

How to run a gradle task from a java code?

I need to run the gradle eclipse task to an external gradle project from a java method, is it possible to do it using the Gradle Tooling API ?
The Gradle forum gives a nice example for doing this programmatically but since it disregards the projects individual gradle wrapper, it can't guarantee the smooth execution of your build and even break your application. For more information why you always should rely on the gradle wrapper read here and here.
Using the Gradle wrapper
The recommended approach is to run exec and call the projects wrapper while passing the task as a parameter. This example calls the current projects wrapper and passes jar as a parameter:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Main
{
private static String PATH_TO_GRADLE_PROJECT = "./";
private static String GRADLEW_EXECUTABLE = "gradlew.bat";
private static String BLANK = " ";
private static String GRADLE_TASK = "jar";
public static void main(String[] args)
{
String command = PATH_TO_GRADLE_PROJECT + GRADLEW_EXECUTABLE + BLANK + GRADLE_TASK;
try
{
Runtime.getRuntime().exec(command);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Using the Gradle Tooling API
To use the Gradle tooling api on a external project, you simply have to define the property forProjectDirectory of your GradleConnectorobject. To run a task call run() on the BuildLauncher object. The example below demostrates the basic principle:
import org.gradle.tooling.BuildLauncher;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import java.io.File;
public class ToolingAPI
{
private static final String GRADLE_INSTALLATION = "C:\\Program Files\\Gradle";
private static final String GRADLE_PROJECT_DIRECTORY = "path_to_root_of_a_gradle_project";
private static final String GRADLE_TASK = "help";
private GradleConnector connector;
public ToolingAPI(String gradleInstallationDir, String projectDir)
{
connector = GradleConnector.newConnector();
connector.useInstallation(new File(gradleInstallationDir));
connector.forProjectDirectory(new File(projectDir));
}
public void executeTask(String... tasks)
{
ProjectConnection connection = connector.connect();
BuildLauncher build = connection.newBuild();
build.forTasks(tasks);
build.run();
connection.close();
}
public static void main(String[] args)
{
ToolingAPI toolingAPI = new ToolingAPI(GRADLE_INSTALLATION, GRADLE_PROJECT_DIRECTORY);
toolingAPI.executeTask(GRADLE_TASK);
}
}
The downside of this approach is the location unawareness of gradle when executing a task. In case you call any file creation or modification method in a custom task like new File("somefile") a exception will be raised.

"Attributes and objects cannot be resolved" - error

The following code is for reading or writing files with java, but:
Eclipse prints these errors:
buffer_1 cannot be resolved to a variable
file_reader cannot be resolved
also other attributes...
what is wrong in this code here:
//Class File_RW
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}
//main method # class Start:
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}
I can't find any mistake. I have also tried to include a try catch statement into the constructor of the class "File_RW", but the error messages were the same.
Yes, there are errors in your code - which are of really basic nature: you are declaring variables instead of fields.
Meaning: you have them in the constructor, but they need to go one layer up! When you declare an entity within a constructor or method, then it is a variable that only exists within that constructor/method.
If you want that multiple methods can make use of that entity, it needs to be a field, declared in the scope of the enclosing class, like:
class FileRW {
private File fileToRead = new File...
...
and then you can use your fields within all your methods! Please note: you can do the actual setup within your constructor:
class FileRW {
private File fileToRead;
public FileRW() {
fileToRead = ..
but you don't have to.
Finally: please read about java language conventions. You avoid using "_" within names (just for SOME_CONSTANT)!
javacode already running...thx
same program edited with c++ in visual Studio express...
visit the stackoverflow entry link:
c++ file read write-error: Microsoft Visual C++ Runtime libr..debug Assertion failed, expr. stream.valid()

Why is this not creating a properties file?

I am trying to make a properties file in Java. Sadly, when I startup Minecraft (As this is a mod in Forge) the file is not created. I will be so thankful to anyone who helps me. Here is the code:
package mymod.properties;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class WriteToProperties {
public static void main(String[] args) {
Properties prop = new Properties();
try {
prop.setProperty("Test", "Yay");
prop.store(new FileOutputStream("Test.properties"), null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Basically what you want is initialize(event.getSuggestedConfigurationFile());
Forge basically wishes to hand you the default settings to you. I also suggest you structure things logically, so it's nice, clean and accessible later on, and easier to manage.
I use this as a config loader
package tschallacka.magiccookies.init;
import java.io.File;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import tschallacka.magiccookies.MagicCookies;
import tschallacka.magiccookies.api.ModHooks;
import tschallacka.magiccookies.api.Preferences;
public class ConfigLoader {
public static Configuration config;
public static final String CATEGORY_GENERAL = "GeneralSettings";
public static final String CATEGORY_SERVER = "ServerPerformance";
public static void init(FMLPreInitializationEvent event) {
ModHooks.MODID = MagicCookies.MODID;
ModHooks.MODNAME = MagicCookies.MODNAME;
ModHooks.VERSION = MagicCookies.VERSION;
try {
initialize(event.getSuggestedConfigurationFile());
}
catch (Exception e) {
MagicCookies.log.error("MagicCookie failed to load preferences. Reverting to default");
}
finally {
if (config != null) {
save();
}
}
}
private static void initialize(final File file) {
config = new Configuration(file);
config.addCustomCategoryComment(CATEGORY_GENERAL, "General Settings");
config.addCustomCategoryComment(CATEGORY_SERVER, "Server performance settings");
Preferences.magicCookieIsLoaded = true;
config.load();
syncConfigurable();
}
private static void save() {
config.save();
}
private static void syncConfigurable() {
final Property awesomeMod = config.get(Configuration.CATEGORY_GENERAL, "awesome_mod", Preferences.awesomeMod);
awesomeMod.comment = "Set this to yes if you think this mod is awesome, maybe it will at some time unlock a special thing.... or not... but that's only for people who think this is an wesome Mod ;-)";
Preferences.awesomeMod = awesomeMod.getString();
final Property numberOfBlocksPlacingPerTickByStripper = config.get(CATEGORY_SERVER,"number_of_blocks_placing_per_tick_by_stripper",Preferences.numberOfBlocksPlacingPerTickByStripper);
numberOfBlocksPlacingPerTickByStripper.comment = "This affects how many blocks will be placed per tick by the creative stripper tool per tick. The stripper tool will only place blocks if ticks are take less than 50ms. If you experience lag lower this number, if you don't experience lag and want faster copy pasting, make this number higher. For an awesome slowmo build of your caste set this to 1 ;-). Set to 0 to render everything in one go per chunk";
Preferences.numberOfBlocksPlacingPerTickByStripper = numberOfBlocksPlacingPerTickByStripper.getInt();
final Property averageTickTimeCalculationSpan = config.get(CATEGORY_SERVER,"number_of_ticks_used_for_average_time_per_tick_calculation",Preferences.averageTickTimeCalculationSpan);
averageTickTimeCalculationSpan.comment = "This number is the number of tick execution times are added together to calculation an average. The higher number means less lag by some things like the strippers, but can also lead to longer execution times for the strippers. Basically if your server is always running behind on server ticks set this value to 1, to at least get some work done when your server is running under 50ms tickspeed";
Preferences.averageTickTimeCalculationSpan = averageTickTimeCalculationSpan.getInt();
final Property acceptableTickduration = config.get(CATEGORY_SERVER,"acceptable_tick_duration",Preferences.acceptableTickduration);
acceptableTickduration.comment = "Define here what you see as acceptable tick speed where MagicCookies can do some of its magic. If average tick speed or current tick speed is higher than this value it won't perform some tasks to help manage server load.";
Preferences.acceptableTickduration = (long)acceptableTickduration.getDouble();
}
}
The value holder Preferences class.
This is purely so I can do Preferences.valuename everywhere.
package tschallacka.magiccookies.api;
/**
* Here the preferences of MagicCookies will be stored
* and kept after the config's are loaded.
* #author Tschallacka
*
*/
public class Preferences {
public static boolean magicCookieIsLoaded = false;
public static String awesomeMod = "Well?";
public static boolean isLoadedThaumcraft = false;
public static int numberOfBlocksPlacingPerTickByStripper = 0;
public static int averageTickTimeCalculationSpan = 60;
public static long acceptableTickduration = 50l;
public static int darkShrineFrequency = 0;
public static boolean darkShrineSpawnLogging = true;
public static boolean entropyTempleSpawnLogging = true;
public static int entropySize = 30;
}
In your main mod file:
#EventHandler
public void preInit(FMLPreInitializationEvent e) {
MagicCookies.log.warn("Preinit starting");
MinecraftForge.EVENT_BUS.register((Object)MagicCookies.instance);
ConfigLoader.init(e);
}
And after that you can just fetch all your preferences from the Preferences class
This file was created in root of your project. If you want some specific path to save, create folder in root of your project like props and change path in FileOutputStream constructor to "props\\Test.properties"

Unexpected results moving files between folders

I am trying to add a very simple feature to a Java program. The feature I want to add simply moves all the files from two folders to a third "archive" folder. The code is simple and I understand it 100% the problem is only one of the folder's contents is being moved. I have went over the code with a fine-tooth comb and tried repasting the directory several times, nothing seems to work. If anyone could help me figure out why my 2nd folder's contents aren't being moved I would REALLY appreciate it.
FYI in order to test this code you need to add a couple folders to "My Documents".
"Pain008Files", "Camt54 Files" and "archive". Also you just need to add some type of text file to the Pain008 and Camt5 folder, it can only have a random letter just something that can be moved.
At runtime the Pain008Files folder correctly has all it's files moved to the archive folder. The Camt54 Files does not. The only problem I can think of is that perhaps the space in the Camt54 Files name is causing a problem but that doesn't make sense so I thought I would hold off on changing it till I get some help. Thanks in advance!
Main Class
package fileHandling;
public class moveTestMain
{
public static void main(String args[]){
GetUser gUser = new GetUser();
gUser.getUser();
MoveFiles mFiles = new MoveFiles();
mFiles.moveCamtFiles();
mFiles.movePainFiles();
}
}
Gets the user-name class
package fileHandling;
public class GetUser
{
public static String currentUser = null;
public void getUser(){
currentUser = System.getProperty("user.name");
}
}
Move the files class
package fileHandling;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
public class MoveFiles
{
public static ArrayList<File> pain008Files;
public static ArrayList<File> camt54Files;;
public void movePainFiles(){
File pain008File = new File("C:\\Users\\"+GetUser.currentUser+"\\Documents\\Pain008Files");
pain008Files = new ArrayList<File>(Arrays.asList(pain008File.listFiles()));
System.out.println(pain008Files);
for(int i = 0; i < pain008Files.size(); i++){
System.out.println("Test");
int cutAmount = GetUser.currentUser.length();
String fileName = pain008Files.get(i).toString().substring(33+cutAmount,pain008Files.get(i).toString().length());
System.out.println(fileName);
System.out.println(pain008Files.get(i).toString());
pain008Files.get(i).renameTo(new File("C:\\Users\\"+GetUser.currentUser+"\\Documents\\archive\\"+
"archivedPain_"+fileName));
}
}
public void moveCamtFiles(){
File camt54File = new File("C:\\Users\\"+GetUser.currentUser+"\\Documents\\Camt54 Files");
camt54Files = new ArrayList<File>(Arrays.asList(camt54File.listFiles()));
for(int i = 0; i < camt54Files.size(); i++){
int cutAmount = GetUser.currentUser.length();
String fileName = camt54Files.get(i).toString().substring(32+cutAmount,camt54Files.get(i).toString().length());
camt54Files.get(i).renameTo(new File("C:\\Users\\"+GetUser.currentUser+"\\Documents\\archive\\"+
"archivedCamt_"+fileName));
}
}
SHORT ANSWER:
Your code has some typo errors in routes or somewhere...
LONG ANSWER:
I adapted it to local testing in my computer and works fine.
public void movePainFiles() {
File pain008File = new File("C:\\tmp\\pain");
pain008Files = new ArrayList<File>(Arrays.asList(pain008File.listFiles()));
System.out.println(pain008Files);
for (int i = 0; i < pain008Files.size(); i++) {
System.out.println(pain008Files.get(i).toString());
pain008Files.get(i).renameTo(new File("C:\\tmp\\archive\\" + "archivedPain_" + pain008Files.get(i).getName()));
}
}
public void moveCamtFiles() {
File camt54File = new File("C:\\tmp\\camt");
camt54Files = new ArrayList<File>(Arrays.asList(camt54File.listFiles()));
for (int i = 0; i < camt54Files.size(); i++) {
System.out.println(camt54Files.get(i).toString());
camt54Files.get(i).renameTo(new File("C:\\tmp\\archive\\" + "archivedCamt_" + camt54Files.get(i).getName()));
}
}
OUTPUT:
C:\tmp\camt\xxx.pdf
C:\tmp\camt\yyy.pdf
C:\tmp\camt\zzz.pdf
[C:\tmp\pain\Q37024973.txt, C:\tmp\pain\Q37545784.txt]
C:\tmp\pain\Q37024973.txt
C:\tmp\pain\Q37545784.txt

phonegap android plugin using a native library

I'm trying to create a phonegap plugin for an android device, sadly my Java is terrible.
I have a simple helloworld project i'm working in to try and get this going.
I've created a plugin which loads fine and works ( just a simple return string example )
From this i then have tried to add my native library code.
public class Medida extends CordovaPlugin
{
static {
System.loadLibrary("finger");
}
public native static int SFM_Init(byte[] dev);
The error message i keep encountering is:
10-28 15:23:03.207: W/dalvikvm(11618): No implementation found for native Lorg/apache/cordova/plugin/Medida;.SFM_Init ([B)I
Now - I'm taking the libfinger.so file from a full JAVA android project and trying to wrap it into a phonegap plugin (why? Because i can code phonegap, but no java).
The files are all been placed in the correct locations
the libfinger.so file is in the libs/ folder
So my question is - what else do i need to add-in or do to get the JAVA plugin to work with the libfinger.so - so i can call all the clases etc..
Thanks for looking - spents days trying to find out, but there is not much info on calling loadlibrary for plugins which i understand.
John
Main java class
package org.apache.cordova.plugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class Medida extends CordovaPlugin{
static {
System.loadLibrary("finger");
}
public native static int SFM_Init(byte[] dev);
static final String LOG_TAG = "Medida.Java: ";
int fd = 0;
String retval = null;
int[] nQuality = {0};
int[] nBufferSize = {0};
private final String retSuccess = "OK";
public static final int REFRESH = 1;
public static final int ERROR = 0;
private Thread thread = null;
private int peripheral_fd = 1;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("dave")) {
String message = args.getString(0);
this.dave("Medida CALLING DAVE " + message, callbackContext);
return true;
}
else if (action.equals("scanfinger_getID")){
this.scanfinger_getID( args, callbackContext);
return true;
}
return false;
}
private void dave(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(" --- Medida FROM DAVE: " + message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
private void scanfinger_getID(JSONArray args, CallbackContext callbackContext) throws JSONException {
String message = args.getString(0);
JSONObject object = new JSONObject(message);
String id = object.getString("id");
String dev = "/dev/ttySAC3";
byte[] devName = dev.getBytes();
fd = SFM_Init(devName);
callbackContext.success("Got to scanfinger_getID: " + id);
}
}
Try to define the method as a class method (taken from here):
public class Medida extends CordovaPlugin {
static {
System.loadLibrary("finger");
}
public native int SFM_Init(byte[] dev);
}
EDIT
From the error it seems that there is no method called SFM_Init in the native library, try to list the exported methods and see the exact definition: How do I list the symbols in a .so file

Categories

Resources