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"
Related
I would like to get cpu usage to update my database using java continuously.
At the first loop, this code is readable the correct cpu usage.
After then, it returns wrong values less than 0.
So, I stucked.
I used jdk 1.8.124.
plz, let me know how to get cpu usage continuously.
lib
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.HardwareAbstractionLayer;
src
public static void main(String[] args) {
OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
while (true) {
System.out.println(bean.getProcessCpuLoad());
System.out.println(bean.getSystemCpuLoad());
try {
Thread.sleep(3000);
}
catch (Exception e){
System.out.println(e.toString());
break;
}
}
}
It's done by using Oshi lib.
I can get cpu usage every 20 seconds
lib
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.HardwareAbstractionLayer;
src
private SystemInfo si = new SystemInfo();
private HardwareAbstractionLayer hal = si.getHardware();
private CentralProcessor cpu = hal.getProcessor();
long[] prevTicks = new long[TickType.values().length];
public static double getCPU()
{
double cpuLoad = cpu.getSystemCpuLoadBetweenTicks( prevTicks ) * 100;
prevTicks = cpu.getSystemCpuLoadTicks();
System.out.println("cpuLoad : " + cpuLoad);
return cpuLoad;
}
public static void main(String[] args) throws Exception{
while(true) {
// Sleep 20 seconds
tCPU = (int)getCPU();
}
}
I use the following code to get the CPU load, which works without invoking hidden methods in com.sun.* classes:
public static Double getProcessCpuLoad() {
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
AttributeList list = mbs.getAttributes(name, new String[]{"ProcessCpuLoad"});
return Optional.ofNullable(list)
.map(l -> l.isEmpty() ? null : l)
.map(List::iterator)
.map(Iterator::next)
.map(Attribute.class::cast)
.map(Attribute::getValue)
.map(Double.class::cast)
.orElse(null);
} catch (Exception ex) {
return null;
}
}
Works fine, tested with JRE 8/11/13.
Problem:
Receiving a stream of command line warnings as video plays - deprecated pixel format used, make sure you did set range correctly
Question:
How can I stop the warnings from happening or being displayed?
Update - Fixed:
The solution was too override the logging callback and don't do anything in the logging call method. FFmpeg logging is then disabled.
The reason for the message from FFmpeg is because it is grabbing frames from an old video format so is unavoidable if playing older videos.
NOTE:
This solution completely disables all output from FFmpeg. Even FFmpeg errors are muted.
Code below (just frame grabbing, not timed playback).
package test.javacv;
import java.io.File;
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.CustomLogCallback;
public class TestPlay implements Runnable {
private static String video_loc = null;
private static CanvasFrame canvas = new CanvasFrame("Test JavaCV player");
public static void main(String[] args) { new Thread(new TestPlay(args[0])).start(); }
static {
CustomLogCallback.set();
}
public void run() { play_video(video_loc); }
public TestPlay(String loc) {
video_loc = loc;
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
public static final void play_video(String vid_loc) {
try {
File file = new File(vid_loc);
FFmpegFrameGrabber ffmpeg_fg = new FFmpegFrameGrabber(file.getAbsolutePath());
Frame frm;
ffmpeg_fg.setAudioChannels(0);
ffmpeg_fg.start();
for(;;)
if((frm = ffmpeg_fg.grab()) != null) canvas.showImage(frm);
else {
ffmpeg_fg.setTimestamp(0);
break;
}
ffmpeg_fg.stop();
} catch(Exception ex) { ex("play_video vid_loc:" + vid_loc, ex); }
}
public static final void ex(String txt, Exception ex) {
System.out.println("EXCEPTION: " + txt + " stack..."); ex.printStackTrace(System.out); }
}
Logging class
// custom logger to override all logging output
package org.bytedeco.javacv;
import org.bytedeco.javacpp.BytePointer;
import static org.bytedeco.javacpp.avutil.LogCallback;
import static org.bytedeco.javacpp.avutil.setLogCallback;
public class CustomLogCallback extends LogCallback {
static final CustomLogCallback instance = new CustomLogCallback();
public static CustomLogCallback getInstance() { return instance; }
public static void set() { setLogCallback(getInstance()); }
#Override
public void call(int level, BytePointer msg) {}
}
You can adjust the logging level in JavaCV using org.bytedeco.javacpp.avutil.av_log_set_level().
calling avutil.av_log_set_level(avutil.AV_LOG_QUIET); will probably get you what you want.
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
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.
I am writing an IntelliJ IDEA plugin for saving sessions of open tabs called Tab Session. This question is a follow-up of IntelliJ IDEA Plugin Development: Save groups of tabs, save them persistently and reload a set of tabs if requested by the user.
Currently, splitted windows are not supported. Therefore i want to do two things:
Retrieve information about all splitted or unsplitted windows that are containers for editor tabs. I need their position and split direction (horizontal or vertical).
When this information is saved and a tab session needs to be loaded, i need to reconstruct the splitted panes and their tabs exactly as they were before.
Due to the lack of documentation i am currently browsing through the source code and found this promising piece of code:
private EditorsSplitters getSplittersFromFocus() {
return FileEditorManagerEx.getInstanceEx(myProject).getSplitters();
}
It allows me to iterate through the set of splitted windows by using EditorWindow[] windows = getSplittersFromFocus.getOrderedWindows(). They contain the editor tabs and information about their width and height. But i did not find any information about the split direction and how to reconstruct the splitted windows as they were before.
Can anyone help?
This is untested code, but as it closely resmbles the procedures inside EditorsSplitters writeExternal and writePanel functions I am positive this will work.
Presented are two methods:
access output of writeExternal -> should be the more stable API and offers easier access to file information
access components of splitter -> this way writeExternal creates it's information; sadly there is at least one protected field without getter involved (window.myPanel inside findWindowWith)
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.impl.EditorsSplitters;
import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import org.jdom.Element;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class SplitterAction extends AnAction {
public SplitterAction() {
super("Splitter _Action");
}
private static class Info {
}
private static class SplitInfo extends Info {
public Info first;
public Info second;
public boolean vertical;
public float proportions;
}
private static class FileInfo extends Info {
public String[] fileNames;
}
#Override
public void actionPerformed(AnActionEvent anActionEvent) {
final Project project = anActionEvent.getProject();
final FileEditorManagerImpl fileEditorManager = (FileEditorManagerImpl) FileEditorManager.getInstance(project);
EditorsSplitters splitters = fileEditorManager.getSplitters();
// com.intellij.openapi.fileEditor.impl.EditorsSplitters.writeExternal() and
// com.intellij.openapi.fileEditor.impl.EditorsSplitters#writePanel inspired this
final Component component = splitters.getComponent(0);
final SplitInfo infos = splitterVisitor(component);
// or you could use this
Element root = new Element("root");
splitters.writeExternal(root);
elementVisitor(root);
// to restore from writeExternal the following should suffice
splitters.readExternal(root);
splitters.openFiles();
}
/**
* Reads writeExternal output
*/
private Info elementVisitor(Element root) {
final Element splitter = root.getChild("splitter");
if (splitter != null) {
// see com.intellij.openapi.fileEditor.impl.EditorsSplitters#writePanel
final SplitInfo splitInfo = new SplitInfo();
// "vertical" or "horizontal"
splitInfo.vertical = "vertical".equals(splitter.getAttributeValue("split-orientation"));
splitInfo.proportions = Float.parseFloat(splitter.getAttributeValue("split-proportion"));
Element first = splitter.getChild("split-first");
if (first != null) {
splitInfo.first = elementVisitor(first);
}
Element second = splitter.getChild("split-second");
if (second != null) {
splitInfo.second = elementVisitor(second);
}
return splitInfo;
}
final Element leaf = root.getChild("leaf");
if (leaf != null) {
final ArrayList<String> fileNames = new ArrayList<String>();
for (Element file : leaf.getChildren("file")) {
final String fileName = file.getAttributeValue("leaf-file-name");
fileNames.add(fileName);
// further attributes see com.intellij.openapi.fileEditor.impl.EditorsSplitters#writeComposite
}
final FileInfo fileInfo = new FileInfo();
fileInfo.fileNames = fileNames.toArray(new String[fileNames.size()]);
return fileInfo;
}
return null;
}
/**
* Acts directly upon Component
*/
private SplitInfo splitterVisitor(Component component) {
if (component instanceof JPanel && ((JPanel) component).getComponentCount() > 0) {
final Component child = ((JPanel) component).getComponent(0);
if (child instanceof Splitter) {
final Splitter splitter = (Splitter) child;
final SplitInfo splitInfos = new SplitInfo();
splitInfos.vertical = splitter.isVertical();
splitInfos.proportions = splitter.getProportion();
splitInfos.first = splitterVisitor(splitter.getFirstComponent());
splitInfos.second = splitterVisitor(splitter.getSecondComponent());
return splitInfos;
}
// TODO: retrieve file information
}
return null;
}
}