Simple URI and local path use in MediaPlayer-javaFX - java

I have the following code to display the spectrum of audio.But it uses URI.But how to use simple paths like C:/abc/asas.wav ...or something?Any idea?
It gives me Exception when i use local paths:
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
Code:
package chartaudiobar;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.media.AudioSpectrumListener;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class ChartAudioBar extends Application {
private XYChart.Data<String, Number>[] series1Data;
private AudioSpectrumListener audioSpectrumListener;
private static final String AUDIO_URI = System.getProperty("demo.audio.url","http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv");
private static MediaPlayer audioMediaPlayer;
private static final boolean PLAY_AUDIO = Boolean.parseBoolean(System.getProperty("demo.play.audio","true"));
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
root.getChildren().add(createChart());
audioSpectrumListener = new AudioSpectrumListener() {
#Override public void spectrumDataUpdate(double timestamp, double duration,
float[] magnitudes, float[] phases) {
for (int i = 0; i < series1Data.length; i++) {
series1Data[i].setYValue(magnitudes[i] + 60);
}
}
};
}
public void play() {
this.startAudio();
}
#Override public void stop() {
this.stopAudio();
}
protected BarChart<String, Number> createChart() {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis(0,50,10);
final BarChart<String,Number> bc = new BarChart<String,Number>(xAxis,yAxis);
bc.setId("barAudioDemo");
bc.setLegendVisible(false);
bc.setAnimated(false);
bc.setBarGap(0);
bc.setCategoryGap(1);
bc.setVerticalGridLinesVisible(false);
// setup chart
bc.setTitle("Live Audio Spectrum Data");
xAxis.setLabel("Frequency Bands");
yAxis.setLabel("Magnitudes");
yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis,null,"dB"));
// add starting data
XYChart.Series<String,Number> series1 = new XYChart.Series<String,Number>();
series1.setName("Data Series 1");
//noinspection unchecked
series1Data = new XYChart.Data[128];
String[] categories = new String[128];
for (int i=0; i<series1Data.length; i++) {
categories[i] = Integer.toString(i+1);
series1Data[i] = new XYChart.Data<String,Number>(categories[i],50);
series1.getData().add(series1Data[i]);
}
bc.getData().add(series1);
return bc;
}
private void startAudio() {
if (PLAY_AUDIO) {
getAudioMediaPlayer().setAudioSpectrumListener(audioSpectrumListener);
getAudioMediaPlayer().play();
}
}
private void stopAudio() {
if (getAudioMediaPlayer().getAudioSpectrumListener() == audioSpectrumListener) {
getAudioMediaPlayer().pause();
}
}
private static MediaPlayer getAudioMediaPlayer() {
if (audioMediaPlayer == null) {
Media audioMedia = new Media(AUDIO_URI);
audioMediaPlayer = new MediaPlayer(audioMedia);
}
return audioMediaPlayer;
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
play();
}
public static void main(String[] args) { launch(args); }
}
So how to use local paths here?

I had the same problem, i used this:
File file = new File("C:\\abc\\asas.wav");
audio = new Media(file.toURI().toURL().toString());
audioMediaPlayer = new MediaPlayer(audio);

You can convert path to URI by adding protocol
C:/abc/asas.wav will be file:/C:/abc/asas.wav in Your example

It’s 4 years after Jyoti Shaw posted this question, how to use a local music file in class ChartAudioBar. Wafu has the answer on his webpage https://osu.ppy.sh/forum/p/4629060 Look about halfway down on the page, under his heading “Frequency spectrum” and click on “Code” to see the source code.
Wafu’s solution is similar to that of Sam de Meyer in his answer above.
//We don't need this line, because we need to use a local music file.
//private static final String AUDIO_URI = System.getProperty("demo.audio.url","http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv");
private static MediaPlayer audioMediaPlayer;
//We don't need this as well as it's equally useless as previous thing.
//private static final boolean PLAY_AUDIO = Boolean.parseBoolean(System.getProperty("demo.play.audio","true"));
//We anyway need output of the default chart, so let's say we'll put it to file data.txt, hence the 'import java.io.File' needs to be added to imports.
private static File filedata = new File("data.txt");
// *****************************************************************************
private static MediaPlayer getAudioMediaPlayer() {
if (audioMediaPlayer == null) {
//We need code below, but I commented it anyway to show the difference, we need a local file, so this won't work.
//Media audioMedia = new Media(AUDIO_URI);
//So we create a local file, for example mp3.mp3 in current folder, it can be anything you want.
//File audiofile = new File("mp3.mp3");
File audiofile = new File("C:/music/SummerMix.mp3");
//Now we need to make audioMedia as it was previously - So it needs to be URI, which .toURI() ensures easily, but as well as that, it needs a string URI, so .toString() will ensure this.
Media audioMedia = new Media(audiofile.toURI().toString());
audioMediaPlayer = new MediaPlayer(audioMedia);
}
return audioMediaPlayer;
}

Related

JavaFX error "Application launch must not be called more than once" while running 2 Test cases

I am using JavaFX to write a sample video player. But the tests fails when run together, ( Note: individually test passes).
Error: Unexpected exception thrown: java.lang.IllegalStateException: Application launch must not be called more than once
I understand that calling launch() twice on same Application Instance is causing this issue as per this . But I am not able to understand, that after one test completes, why the app is still running ? Why new instance is not getting created for 2nd test. testUnsupportedVideoFileThrowsError() succeeds but testSupportedVideoFilePlaysSuccessfully() fails.
package media;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import java.io.File;
public class PlayVideoSnippet extends Application {
private static String source;
private Media media = null;
private MediaPlayer mediaPlayer = null;
private MediaView mediaView = null;
private Scene scene = null;
public static void playVideo(String source) {
PlayVideoSnippet.source = source;
PlayVideoSnippet.launch();
}
#Override
public void start(Stage stage) throws InterruptedException {
try {
media = new Media(new File(source).toURI().toString());
//onError close the app
media.setOnError(() -> {
Platform.exit();
});
//Create MediaPlayer, with media
mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
//onEnd of media, close the app
mediaPlayer.setOnEndOfMedia(() -> {
Platform.exit();
});
//Create media viewer
mediaView = new MediaView(mediaPlayer);
//create scene
scene = new Scene(new Group(), media.getWidth(), media.getHeight());
stage.setScene(scene);
stage.setTitle("Video Player");
//attach the mediaView to the scene root
((Group) scene.getRoot()).getChildren().add(mediaView);
stage.show();
} finally {
System.out.println("Inside finally");
stage.close();
}
}
}
package media;
import javafx.scene.media.MediaException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PlayVideoSnippetTest {
/**
* Tests for {#link PlayVideoSnippet#playVideo(String)}.
*/
final String PATH_OF_SUPPORTED_VIDEO_FILE = "src/test/resources/file_example_MP4_480_1_5MG.mp4";
final String PATH_OF_UNSUPPORTED_VIDEO_FILE = "src/test/resources/file_example_WMV_480_1_2MB.wmv";
#Test
void testSupportedVideoFilePlaysSuccessfully() {
assertDoesNotThrow(() -> PlayVideoSnippet.playVideo(PATH_OF_SUPPORTED_VIDEO_FILE));
}
#Test
void testUnsupportedVideoFileThrowsError() {
RuntimeException exception = assertThrows(RuntimeException.class, () -> PlayVideoSnippet.playVideo(PATH_OF_UNSUPPORTED_VIDEO_FILE));
assertTrue(exception.getCause().getClass().equals(MediaException.class));
}
}
I was able to fix the issue with help of below inputs:
Using TestFX for testing purpose as suggested by #jewelsea.
Inputs from #James_D
StackOver flow issue
ApplicationTest.launch() method internally takes care of setting up primary stage and cleaning before each test.
Solution:
import org.junit.jupiter.api.Test;
import org.testfx.framework.junit5.ApplicationTest;
class VideoTest extends ApplicationTest {
final String pathOfSupportedFile = "video.mp4";
final String pathOfUnsupportedFile = "video.wmv";
#Test
void testSupportedVideoFilePlaysSuccessfully() throws Exception {
assertDoesNotThrow(() -> PlayVideoSnippetTest.launch(PlayVideoSnippet.class,
new String[]{pathOfSupportedFile}));
}
#Test
void testUnsupportedVideoFileThrowsError() throws Exception {
RuntimeException exception = assertThrows(RuntimeException.class,
() -> PlayVideoSnippetTest.launch(PlayVideoSnippet.class,
new String[]{pathOfUnsupportedFile}));
assertTrue(exception.getCause().getCause().getClass().equals(MediaException.class));
}
}

Syntax error on token "start" , identifier expected after this token [duplicate]

This question already has answers here:
Method calls inside a Java class return an "identifier expected after this token" error
(8 answers)
Closed 1 year ago.
I've been trying to create an agent thanks to Jade on Java with this code:
import jade.core.ProfileImpl;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
public class Agents {
jade.core.Runtime rt= jade.core.Runtime.instance();
ProfileImpl pMain= new ProfileImpl();
AgentContainer mc = rt.createMainContainer(pMain);
AgentController rma= mc.createNewAgent("rma", "jade.tools.rma.rma", null);
rma.start();
}
I keep getting the error "Syntax error on token "start" , identifier expected after this token" and I cannot understand why.
By not going into finding problems with your code, I suggest to use the code below to solve your error.
Initialization code for agent and adding to the container
package package.se.samplejade;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;
public class LaunchAgents {
private static final String AGENT_CLASS_STRING ="package.se.samplejade.SampleAgent";
private static final String AGENTNAME_STRING = "sampleAgent";
public static void main(String[] args) {
LaunchAgents LaunchAgents = new LaunchAgents();
LaunchAgents.initilizeAgent();
}
/**
* Creates a new agent and adds it to the container
*
* #param
* #return true or false
*/
public boolean initilizeAgent() {
AgentController agentcontroller = null;
Object[] initObjects = new Object[2];
initObjects[0] = new Object(); // add any object needed to initialize the agent
initObjects[1] = new Object();
try {
agentcontroller = Container.getController().createNewAgent(AGENTNAME_STRING, AGENT_CLASS_STRING,
initObjects);
agentcontroller.start();
return true;
} catch (StaleProxyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
The JADE container initialization
package.se.samplejade ;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.ContainerController;
public final class Container {
// get a JADE runtime
private static jade.core.Runtime runtime = jade.core.Runtime.instance();
// Create a profile, where the launch arguments are stored
private static Profile profile2 = new ProfileImpl();
private static Profile profile = new ProfileImpl();
// create the Main-container
private static ContainerController mainContainer = null;
private static ContainerController containerController = null;
/**
* Returns the path of the container to the JADE agents
*/
public synchronized static ContainerController getController() {
// create the Main-container
if (mainContainer == null) {
profile.setParameter(Profile.CONTAINER_NAME, "Container");
profile.setParameter(Profile.GUI, "true");
mainContainer = runtime.createMainContainer(profile2);
containerController = runtime.createAgentContainer(profile);
}
return containerController;
}
}
The agents code
package.se.samplejade;
import jade.core.Agent;
public class SampleAgent extends Agent {
#Override
protected void setup() {
//Put your agent initialization code with the objects passed in the initialization
}
}

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

Exception: java.lang.NoClassDefFoundError: org.ehcache.CacheMangerBuilder

I'll preface this by saying "I have no idea what I'm doing" with java, let alone ehcache, but I'm trying to learn.
That said, I have this code I've written that ran fine until I added the ehcache stuff. I had been simply writing to and reading from files, which worked fine but slow, so I'm trying to speed things up by using cache instead.
When I run my program, I get the following error, and I don't understand what it's telling me is wrong:
Exception in thread "Connect thread - [6, 5]."
java.lang.NoClassDefFoundError: org.ehcache.CacheManagerBuilder
at com.ibm.tpf.internal.ZSTATEngine.doFilter(ZSTATEngine.java:24)
at com.ibm.tpf.etos.filter.FilterFramework.filterMessage(FilterFramework.java:229)
at com.ibm.tpf.etos.api.APIFramework.addMessage(APIFramework.java:304)
at com.ibm.tpf.etos.comm.ETOSConnection.addMessage(ETOSConnection.java:765)
at com.ibm.tpf.etos.comm.ETOSModel._connect(ETOSModel.java:528)
at com.ibm.tpf.etos.comm.ETOSModel$ConnectThread.run(ETOSModel.java:706)
Caused by: java.lang.NoClassDefFoundError:
org.ehcache.CacheMangerBuilder
at java.net.URLClassLoader.findClass(URLClassLoader.java:496)
at java.lang.ClassLoader.loadClass(ClassLoader.java:631)
at java.lang.ClassLoader.loadClass(ClassLoader.java:597)
... 6 more
I tried to mimic the cache code found on the ehcache 3.0 documentation page... but I must've done something horribly wrong. Anyone mind taking a look?
package com.ibm.tpf.internal;
import java.awt.Color;
import java.io.File;
import org.ehcache.*;
import org.ehcache.config.CacheConfigurationBuilder;
import com.ibm.tpf.etos.TPFFilter.*;
import com.ibm.tpf.etos.api.*;
import com.ibm.tpf.etos.filter.*;
public class ZSTATEngine implements ETOSFilterEngine {
FilterFramework fw = null;
String[] names = null;
public ZSTATEngine(FilterFramework filFW, String[] parms) {
super();
this.fw = filFW;
}
public MessageBlock doFilter(MessageBlock msgBlock) throws FilterRuntimeException {
File file = new File("{path omitted}\\FILTER.DAT");
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("csmpCache",CacheConfigurationBuilder.newCacheConfigurationBuilder().buildConfig(Long.class, String.class)).build(false);
cacheManager.init();
Cache<Long, String> csmpCache = cacheManager.getCache("csmpCache", Long.class, String.class);
if(msgBlock.getMsgID().equals("CSMP0097I")) {
csmpCache.put(1L, msgBlock.getMsg()); /* 1L is a key */
msgBlock.setSuppressed(TernarySwitch.ON);
}
else {
if(msgBlock.getFlag() == Constants.ETOS_ONE_MSG || msgBlock.getFlag() == Constants.ETOS_START_MSG) {
if(file.exists() && file.isFile()) {
String csmpValue = csmpCache.get(1L);
MessageBlock mbCSMP = new MessageBlock(csmpValue, Constants.ETOS_ONE_MSG);
mbCSMP.setForeground(Color.BLUE);
msgBlock.setForeground(Color.BLUE);
fw.addFilteredMessage(mbCSMP);
}
}
}
cacheManager.close();
return msgBlock; /* whatever gets returned is what the system prints */
}
private Color ColorStringInterpreter(String colorMsg) throws FilterRuntimeException {
if (colorMsg.toUpperCase().startsWith("TOS")) { /* if it starts with TOS, then we're using color names */
String[] colorParts = colorMsg.split("_",2);
String colorTxt = colorParts[1].toString().trim();
if (colorTxt.toUpperCase() != "NONE") {
Color finalColor = Colors.fromString(colorTxt);
return finalColor;
}
}
else {
String[] colorParts = colorMsg.split("_",3); /* otherwise we're using RGB values */
String sRed = colorParts[0].toString().trim();
String sGreen = colorParts[1].toString().trim();
String sBlue = colorParts[2].toString().trim();
int iRed = Integer.parseInt(sRed);
int iGreen = Integer.parseInt(sGreen);
int iBlue = Integer.parseInt(sBlue);
Color finalColor = new Color (iRed, iGreen, iBlue);
return finalColor;
}
return null;
}
public String getName() {
return null;
}
public void modifyState(Object[] newParams) throws FilterConfigurationException, FilterRuntimeException {
}
public boolean isActive() {
return false;
}
public void shutdown() {
}
}
Thank you for your time

Categories

Resources