I'm working at the moment on a Mod for Minecraft with a dedicated Gui system written in C++ and Qt5. I let my GUI and Minecraft communicate through a named pipe, but I have there a small problem. I can read and write with a simple Java and C++(Qt) program into the pipe. But when I create a new instance of my Pipeendpoint class in post init of Minecraft Forge it can't read anything from the Pipe. In a standalone system, it can read stuff.
Not working Forge Implementation:
package de.CoderDE.CodersAnimationEditor;
import java.io.FileNotFoundException;
import de.CoderDE.CodersAnimationEditor.Pipe.PipeEndpoint;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
#SideOnly(Side.CLIENT)
public class ClientProxy extends CommonProxy {
static PipeEndpoint pendpoint;
#Override
public void preInit(FMLPreInitializationEvent e) {
super.preInit(e);
}
#Override
public void init(FMLInitializationEvent e) {
super.init(e);
}
#Override
public void postInit(FMLPostInitializationEvent e) {
super.postInit(e);
try {
pendpoint = new PipeEndpoint();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
Working standalone implementation:
import java.io.FileNotFoundException;
import de.CoderDE.CodersAnimationEditor.Pipe.PipeEndpoint;
public class Main {
static PipeEndpoint pipe;
public static void main(String[] args) {
try {
pipe = new PipeEndpoint();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And the important PipeEndpoint class:
package de.CoderDE.CodersAnimationEditor.Pipe;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class PipeEndpoint {
private Thread reciever;
private RandomAccessFile pipe;
public PipeEndpoint() throws FileNotFoundException {
pipe = new RandomAccessFile("\\\\.\\pipe\\CodersAnimationEditor", "rw");
reciever = new Thread(new PipeEndpointReciever());
reciever.start();
}
private class PipeEndpointReciever implements Runnable {
#Override
public void run() {
try {
while (true) {
System.out.print((char)pipe.read());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And with "can't read anything" I mean that it never returns from pipe.read().
Oh, and the Java application starts after the C++(Qt) LocalServer started listening and waits for a new connection.
Related
I'm trying to attach to a running JVM to debug it using the Virtual Machine class in java. I'm currently have java 8, with jdk1.8.0_11. I have tried to add a manifest to it, with but to no avail. I'm also importing the tools.jar file from my JDK\libs folder.
My code:
import java.io.IOException;
import java.util.List;
import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
public class loadVM {
public static void main(String[] args) {
String name = "replaceAfterNameFound";
List <VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor vmd: vms) {
System.out.println(vmd.displayName());
if (vmd.displayName().equals(name)) {
try {
VirtualMachine vm = VirtualMachine.attach(vmd.id());
String agent = "";
vm.loadAgent(agent);
} catch(AttachNotSupportedException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(AgentLoadException e) {
e.printStackTrace();
} catch(AgentInitializationException e) {
e.printStackTrace();
}
}
}
}
}
Here is a copy of the error I get when running it:
java.util.ServiceConfigurationError:com.sun.tools.attach.spi.AttachProvider:
Provider sun.tools.attach.WindowsAttachProvider could not be
instantiated
Thank you guys for all your help!
I wrote this audio class that is used by my soundplayer class it works correctly with no errors but causes my game to hiccup or jerk when the sound is used in quick succession (i.e. rapid jumping). I thought that by loading it in once and rewinding it each time(with the mark and reset methods) the sound would stay in RAM but it doesn't seem to be doing that.I am open to any changes or a total rewrite. i just need it to work I've been stuck on audio for months.
package com.bigdirty1985.squaresthatmove.sound;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class Sound {
#SuppressWarnings("restriction")
private AudioStream audioStream;
private File file;
#SuppressWarnings("restriction")
public Sound(File file) {
this.file = file;
try {
this.audioStream = new AudioStream(new FileInputStream(this.file));
this.audioStream.mark(100000000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings("restriction")
public void play() {
AudioPlayer.player.stop(this.audioStream);
AudioPlayer.player.start(this.audioStream);
try {
this.audioStream.reset();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings("restriction")
public void stop() {
AudioPlayer.player.stop(this.audioStream);
}
}
Using Robotium for my Android automation I find myself creating the same steps for each test case.
I always need to "Login" and "Logout", I've been trying to create a FunctionsTestClass so I can simply call rLogin(); and rLogout();
Here is an example:
Adding my complete files.
'package com.myproject.mobile.test;
import android.test.ActivityInstrumentationTestCase2;
import android.app.Activity;
import junit.framework.AssertionFailedError;
import com.bitbar.recorder.extensions.ExtSolo;
import com.jayway.android.robotium.solo.By;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
'public class Logout extends ActivityInstrumentationTestCase2<Activity> {
private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.myproject.mobile.MainActivity";
private static Class<?> launchActivityClass;
static {
try {
launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps
// collecting better test execution data during test
// runs
#SuppressWarnings("unchecked")
public Logout() {
super((Class<Activity>) launchActivityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
.getCanonicalName(), getName());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
solo.tearDown();
super.tearDown();
}
public static void logginin() throws Exception {
try {
//enter username
solo.sleep(17000);
throw e;
} catch (Exception e) {
solo.fail(
"com.myproject.mobile.test.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
}
}
}'
Adding my second file
package com.mypackage.mobile.test;
import android.test.ActivityInstrumentationTestCase2;
import android.app.Activity;
import junit.framework.AssertionFailedError;
import com.bitbar.recorder.extensions.ExtSolo;
import com.jayway.android.robotium.solo.By;
import com.mypackage.mobile.test.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
'public class Test extends ActivityInstrumentationTestCase2<Activity> {
private static final String LAUNCHER_ACTIVITY_CLASSNAME = "com.mypackage.mobile.MainActivity";
private static Class<?> launchActivityClass;
static {
try {
launchActivityClass = Class.forName(LAUNCHER_ACTIVITY_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private static ExtSolo solo; // ExtSolo is an extension of Robotium Solo that helps
// collecting better test execution data during test
// runs
#SuppressWarnings("unchecked")
public Test() {
super((Class<Activity>) launchActivityClass);
}
#Override
public void setUp() throws Exception {
super.setUp();
solo = new ExtSolo(getInstrumentation(), getActivity(), this.getClass()
.getCanonicalName(), getName());
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
solo.tearDown();
super.tearDown();
}
public void testRecorded() throws Exception {
try {
Logout.logginin();
} catch (AssertionFailedError e) {
solo.fail(
"com.mypackage.name.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
} catch (Exception e) {
solo.fail(
"com.mypackage.name.MainActivityTest.testRecorded_scr_fail",
e);
throw e;
}
}
}
Updated the bottom two code to reflect my project.
Don't create testcase with name testLoggingin() . Instead of that creat a class having function login(). So that, whenever its needed you can import it and can call the function to login. And you can check conditions using assert.
I'm trying to learn how to use to pool connections so I can get better throughput by not having to open/close channels to a server but I can't seem to get it to work. I had a slightly modified version of my code that worked when I forked a thread and made each thread run a loop to dump data, but now I'm trying to use ThreadPoolExecutor to send jobs vai a single thread and then spawn 2 threads to deal handle the work. My experiment should hopefully show around 2 channels open at any given time(or as many threads as I have) but instead when i change my code I get illegalstateexception: pool not open
I'm really confused if my design of the pool is wrong or my understanding of ThreadPoolExecutor is flawed. My understanding of ThreadPoolExecutor was that it kept the threads alive if there was work to be done and didn't keep killing/respawning them upon each iteration.
Here's the code(you can ignore all the rabbitmq stuff, the gist of it is you need to open a connection to a server, then open a channel. I am trying to open one connection to the server and then a pool of channels that are shared). My idea was to create an instance of the objectpool class and then pass it to a runnable which borrows channels as needed.
Code:
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;
public class PoolExample {
private static ExecutorService executor_worker;
static {
final int numberOfThreads_ThreadPoolExecutor = 2;
executor_worker =
new ThreadPoolExecutor(numberOfThreads_ThreadPoolExecutor, numberOfThreads_ThreadPoolExecutor, 1000, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>());
}
public static void main(String[] args) throws Exception {
System.out.println("starting..");
PoolableObjectFactory<MyPooledObject> factory = new MyPoolableObjectFactory();
ObjectPool<MyPooledObject> pool = new GenericObjectPool<MyPooledObject>(factory);
for (int x = 0; x<500000000; x++) {
executor_worker.submit(new Thread(new MyRunnable(x, pool)));
}
}
}
class MyPooledObject {
//Connection connection;
Channel channel;
public MyPooledObject() throws IOException {
System.out.println("hello world");
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
channel = connection.createChannel();
}
public Channel sing() throws IOException {
//System.out.println("mary had a little lamb");
return channel;
}
public void destroy() {
System.out.println("goodbye cruel world");
}
}
class MyPoolableObjectFactory extends BasePoolableObjectFactory<MyPooledObject> {
#Override
public MyPooledObject makeObject() throws Exception {
return new MyPooledObject();
}
#Override
public void destroyObject(MyPooledObject obj) throws Exception {
obj.destroy();
}
}
class MyRunnable implements Runnable{
protected int x = 0;
protected ObjectPool<MyPooledObject> pool = null;
public MyRunnable(int x, ObjectPool<MyPooledObject> pool) {
// TODO Auto-generated constructor stub
this.x = x;
this.pool = pool;
}
public void run(){
try {
MyPooledObject obj;
obj = pool.borrowObject();
Channel channel = obj.sing();
String message = Integer.toString(x);
channel.basicPublish( "", "task_queue",
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes());
pool.returnObject(obj);
} catch (NoSuchElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
pool.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Any idea what's wrong with my design? or is my entire approach to pool objects flawed?
UPDATE1: as per request here is the stack trace (I get many many of these continuously):
stacktrace:
java.lang.IllegalStateException: Pool not open
at org.apache.commons.pool.BaseObjectPool.assertOpen(BaseObjectPool.java:140)
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1079)
at MyRunnable.run(PoolExample.java:85)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
If it helps, line 85 in my code(where this error is triggered is): obj = pool.borrowObject();
UPDATE2: very odd. I get the error but it does write 2 items to the queue. I don't want to send anyone on a wild goose chase but I'm thinking that means it can successfully borrow objects when its creating them but not when they are being returned to the pool?
UPDATE3: I designed the code so it doesn't go through the middle step I had above. I no longer get the error but it basically does nothing..I launch 10 threads and expect 10 channels but I only get 1 channel for a few seconds then it turns off as well.
code:
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;
public class PoolExample {
private static ExecutorService executor_worker;
static {
final int numberOfThreads_ThreadPoolExecutor = 20;
executor_worker =
new ThreadPoolExecutor(numberOfThreads_ThreadPoolExecutor, numberOfThreads_ThreadPoolExecutor, 1000, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>());
}
public static void main(String[] args) throws Exception {
System.out.println("starting..");
ObjectPool<Channel> pool =
new GenericObjectPool<Channel>(
new ConnectionPoolableObjectFactory(), 5);
for (int x = 0; x<500000000; x++) {
executor_worker.submit(new MyRunnable(x, pool));
}
executor_worker.shutdown();
pool.close();
}
}
class ConnectionPoolableObjectFactory extends BasePoolableObjectFactory<Channel> {
Channel channel;
public ConnectionPoolableObjectFactory() throws IOException {
System.out.println("hello world");
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
channel = connection.createChannel();
}
#Override
public Channel makeObject() throws Exception {
return channel;
}
#Override
public boolean validateObject(Channel channel) {
return channel.isOpen();
}
#Override
public void destroyObject(Channel channel) throws Exception {
channel.close();
}
#Override
public void passivateObject(Channel channel) throws Exception {
//System.out.println("sent back to queue");
}
}
class MyRunnable implements Runnable{
protected int x = 0;
protected ObjectPool<Channel> pool;
public MyRunnable(int x, ObjectPool<Channel> pool) {
// TODO Auto-generated constructor stub
this.x = x;
this.pool = pool;
}
public void run(){
try {
Channel channel = pool.borrowObject();
String message = Integer.toString(x);
channel.basicPublish( "", "task_queue",
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes());
pool.returnObject(channel);
} catch (NoSuchElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have made a program that continuously monitors a log file. But I don't know how to monitor multiple log files. This is what I did to monitor single file. What changes should I make in the following code so that it monitors multiple files also?
package com.read;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FileWatcherTest {
public static void main(String args[]) {
final File fileName = new File("D:/logs/myFile.log");
// monitor a single file
TimerTask fileWatcherTask = new FileWatcher(fileName) {
long addFileLen = fileName.length();
FileChannel channel;
FileLock lock;
String a = "";
String b = "";
#Override
protected void onChange(File file) {
RandomAccessFile access = null;
try {
access = new RandomAccessFile(file, "rw");
channel = access.getChannel();
lock = channel.lock();
if (file.length() < addFileLen) {
access.seek(file.length());
} else {
access.seek(addFileLen);
}
} catch (Exception e) {
e.printStackTrace();
}
String line = null;
try {
while ((line = access.readLine()) != null) {
System.out.println(line);
}
addFileLen = file.length();
} catch (IOException ex) {
Logger.getLogger(FileWatcherTest.class.getName()).log(
Level.SEVERE, null, ex);
}
try {
lock.release();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // Close the file
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer();
// repeat the check every second
timer.schedule(fileWatcherTask, new Date(), 1000);
}
}
package com.read;
import java.util.*;
import java.io.*;
public abstract class FileWatcher extends TimerTask {
private long timeStamp;
private File file;
static String s;
public FileWatcher(File file) {
this.file = file;
this.timeStamp = file.lastModified();
}
public final void run() {
long timeStamp = file.lastModified();
if (this.timeStamp != timeStamp) {
this.timeStamp = timeStamp;
onChange(file);
}
}
protected abstract void onChange(File file);
}
You should use threads. Here's a good tutorial:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
You would do something like:
public class FileWatcherTest {
public static void main(String args[]) {
(new Thread(new FileWatcherRunnable("first.log"))).start();
(new Thread(new FileWatcherRunnable("second.log"))).start();
}
private static class FileWatcherRunnable implements Runnable {
private String logFilePath;
// you should inject the file path of the log file to watch
public FileWatcherRunnable(String logFilePath) {
this.logFilePath = logFilePath;
}
public void run() {
// your code from main goes in here
}
}
}