diff --git a/cpp/jlibmimis/src/main/cpp/mimis.cpp b/cpp/jlibmimis/src/main/cpp/mimis.cpp index 439252c..5e82c03 100644 --- a/cpp/jlibmimis/src/main/cpp/mimis.cpp +++ b/cpp/jlibmimis/src/main/cpp/mimis.cpp @@ -3,87 +3,87 @@ #include bool getProcessEntry32(const char *program, PROCESSENTRY32 *pe32) { - HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); - if (hSnapshot == INVALID_HANDLE_VALUE) { - return false; - } - bool bFound = false; - while (Process32Next(hSnapshot, pe32) != false) { - if (strcmp(program, pe32->szExeFile) == 0) { - bFound = true; - break; - } - } - CloseHandle(hSnapshot); - return bFound; + HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (hSnapshot == INVALID_HANDLE_VALUE) { + return false; + } + bool bFound = false; + while (Process32Next(hSnapshot, pe32) != false) { + if (strcmp(program, pe32->szExeFile) == 0) { + bFound = true; + break; + } + } + CloseHandle(hSnapshot); + return bFound; } bool getProcess(const char *program, HANDLE *hProcess) { - PROCESSENTRY32 *pe32 = new PROCESSENTRY32; - bool bResult = false; - if (getProcessEntry32(program, pe32)) { - *hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32->th32ProcessID); - bResult = true; - } - delete pe32; - return bResult; + PROCESSENTRY32 *pe32 = new PROCESSENTRY32; + bool bResult = false; + if (getProcessEntry32(program, pe32)) { + *hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32->th32ProcessID); + bResult = true; + } + delete pe32; + return bResult; } JNIEXPORT jint JNICALL Java_mimis_util_Native_getHandle(JNIEnv *env, jclass cls, jstring jwindow) { - const char *window = env->GetStringUTFChars(jwindow, 0); - return (int) FindWindow(window, NULL); + const char *window = env->GetStringUTFChars(jwindow, 0); + return (int) FindWindow(window, NULL); } JNIEXPORT jint JNICALL Java_mimis_util_Native_sendMessage(JNIEnv *env, jclass cls, jint handle, jint message, jint wParam, jint lParam) { - return SendMessage((HWND) handle, message, wParam, lParam); + return SendMessage((HWND) handle, message, wParam, lParam); } JNIEXPORT jint JNICALL Java_mimis_util_Native_postMessage(JNIEnv *env, jclass cls, jint handle, jint message, jint wParam, jint lParam) { - return PostMessage((HWND) handle, message, wParam, lParam); + return PostMessage((HWND) handle, message, wParam, lParam); } JNIEXPORT jint JNICALL Java_mimis_util_Native_mapVirtualKey(JNIEnv *env, jclass cls, jint map, jint type) { - return MapVirtualKey(map, type); + return MapVirtualKey(map, type); } JNIEXPORT jboolean JNICALL Java_mimis_util_Native_isRunning(JNIEnv *env, jclass cls, jstring jprogram) { - const char *program = env->GetStringUTFChars(jprogram, 0); - PROCESSENTRY32 *pe32 = new PROCESSENTRY32; - bool bRunning = getProcessEntry32(program, pe32); - delete pe32; - return bRunning; + const char *program = env->GetStringUTFChars(jprogram, 0); + PROCESSENTRY32 *pe32 = new PROCESSENTRY32; + bool bRunning = getProcessEntry32(program, pe32); + delete pe32; + return bRunning; } JNIEXPORT jboolean JNICALL Java_mimis_util_Native_terminate(JNIEnv *env, jclass cls, jstring jprogram) { - const char *program = env->GetStringUTFChars(jprogram, 0); - HANDLE *hProcess = new HANDLE; - bool bResult = false; - if (getProcess(program, hProcess)) { - bResult = TerminateProcess(*hProcess, 0); - } - delete hProcess; - return bResult; + const char *program = env->GetStringUTFChars(jprogram, 0); + HANDLE *hProcess = new HANDLE; + bool bResult = false; + if (getProcess(program, hProcess)) { + bResult = TerminateProcess(*hProcess, 0); + } + delete hProcess; + return bResult; } JNIEXPORT jstring JNICALL Java_mimis_util_Native_getValue(JNIEnv *env, jclass cls, jint registry, jstring jkey, jstring jname) { - const char *key = env->GetStringUTFChars(jkey, 0); - const char *name = env->GetStringUTFChars(jname, 0); - HKEY hKey; - char *value = NULL; - if (RegOpenKey((HKEY) registry, key, &hKey) == ERROR_SUCCESS) { - char nameBuffer[255]; - byte valueBuffer[255]; - DWORD dwNameSize = sizeof(nameBuffer); - DWORD dwValueSize = sizeof(valueBuffer); - int i = 0; - while (RegEnumValue(hKey, i++, nameBuffer, &dwNameSize, NULL, NULL, valueBuffer, &dwValueSize) == ERROR_SUCCESS) { - if (strcmp(name, nameBuffer) == 0) { - value = (char*) valueBuffer; - break; - } - dwNameSize = sizeof(nameBuffer); - } - } - RegCloseKey(hKey); - return env->NewStringUTF(value); + const char *key = env->GetStringUTFChars(jkey, 0); + const char *name = env->GetStringUTFChars(jname, 0); + HKEY hKey; + char *value = NULL; + if (RegOpenKey((HKEY) registry, key, &hKey) == ERROR_SUCCESS) { + char nameBuffer[255]; + byte valueBuffer[255]; + DWORD dwNameSize = sizeof(nameBuffer); + DWORD dwValueSize = sizeof(valueBuffer); + int i = 0; + while (RegEnumValue(hKey, i++, nameBuffer, &dwNameSize, NULL, NULL, valueBuffer, &dwValueSize) == ERROR_SUCCESS) { + if (strcmp(name, nameBuffer) == 0) { + value = (char*) valueBuffer; + break; + } + dwNameSize = sizeof(nameBuffer); + } + } + RegCloseKey(hKey); + return env->NewStringUTF(value); } diff --git a/cpp/jlibmimis/src/main/java/mimis/util/Native.java b/cpp/jlibmimis/src/main/java/mimis/util/Native.java index c29786d..36d6689 100644 --- a/cpp/jlibmimis/src/main/java/mimis/util/Native.java +++ b/cpp/jlibmimis/src/main/java/mimis/util/Native.java @@ -5,7 +5,7 @@ import mimis.value.Windows; public class Native { static { - com.github.boukefalos.jlibloader.Native.load("com.github.boukefalos", "jlibmimis"); + com.github.boukefalos.jlibloader.Native.load("com.github.boukefalos", "jlibmimis"); } public native static int getHandle(String window); diff --git a/cpp/jlibpipe/src/main/c/pipe.c b/cpp/jlibpipe/src/main/c/pipe.c index 1a35caa..d58473b 100644 --- a/cpp/jlibpipe/src/main/c/pipe.c +++ b/cpp/jlibpipe/src/main/c/pipe.c @@ -3,190 +3,190 @@ #include #include "pipe.h" -#define DEBUG 0 +#define DEBUG 0 JNIEXPORT jint JNICALL Java_pipe_Pipe_CreateNamedPipe(JNIEnv *env, - jclass className, jstring sPipeName, jint dwOpenMode, jint dwPipeMode, - jint nMaxInstances, jint nOutBufferSize, jint nInBufferSize, - jint nDefaultTimeOut, jint lpSecurityAttributes) { - HANDLE pipeHandler; - LPCSTR pipeName; - pipeName = (*env)->GetStringUTFChars(env, sPipeName, NULL ); - if (pipeName == NULL ) - return -1; + jclass className, jstring sPipeName, jint dwOpenMode, jint dwPipeMode, + jint nMaxInstances, jint nOutBufferSize, jint nInBufferSize, + jint nDefaultTimeOut, jint lpSecurityAttributes) { + HANDLE pipeHandler; + LPCSTR pipeName; + pipeName = (*env)->GetStringUTFChars(env, sPipeName, NULL ); + if (pipeName == NULL ) + return -1; - if (DEBUG) { - printf("Native: Pipe Name %s\n", pipeName); - printf("Native: dwOpenMode %d\n", dwOpenMode); - printf("Native: dwPipeMode %d\n", dwPipeMode); - printf("Native: nMaxInstances %d\n", nMaxInstances); - printf("Native: nOutBufferSize %d\n", nOutBufferSize); - printf("Native: nInBufferSize %d\n", nInBufferSize); - printf("Native: nDefaultTimeOut %d\n", nDefaultTimeOut); - } + if (DEBUG) { + printf("Native: Pipe Name %s\n", pipeName); + printf("Native: dwOpenMode %d\n", dwOpenMode); + printf("Native: dwPipeMode %d\n", dwPipeMode); + printf("Native: nMaxInstances %d\n", nMaxInstances); + printf("Native: nOutBufferSize %d\n", nOutBufferSize); + printf("Native: nInBufferSize %d\n", nInBufferSize); + printf("Native: nDefaultTimeOut %d\n", nDefaultTimeOut); + } - pipeHandler = CreateNamedPipe((LPCSTR) pipeName, dwOpenMode, dwPipeMode, - nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut, - (LPSECURITY_ATTRIBUTES) lpSecurityAttributes); + pipeHandler = CreateNamedPipe((LPCSTR) pipeName, dwOpenMode, dwPipeMode, + nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut, + (LPSECURITY_ATTRIBUTES) lpSecurityAttributes); - (*env)->ReleaseStringUTFChars(env, sPipeName, pipeName); - return (jint) pipeHandler; + (*env)->ReleaseStringUTFChars(env, sPipeName, pipeName); + return (jint) pipeHandler; } JNIEXPORT jboolean JNICALL Java_pipe_Pipe_ConnectNamedPipe(JNIEnv *env, - jclass className, jint hNamedPipe, jint lpOverlapped) { - BOOL fConnected; - HANDLE pipeHandler = (HANDLE) hNamedPipe; - fConnected = ConnectNamedPipe(pipeHandler, (LPOVERLAPPED) lpOverlapped); - return fConnected; + jclass className, jint hNamedPipe, jint lpOverlapped) { + BOOL fConnected; + HANDLE pipeHandler = (HANDLE) hNamedPipe; + fConnected = ConnectNamedPipe(pipeHandler, (LPOVERLAPPED) lpOverlapped); + return fConnected; } JNIEXPORT jint JNICALL Java_pipe_Pipe_GetLastError(JNIEnv *env, - jclass className) { - DWORD errorNumber = GetLastError(); - return (jint) errorNumber; + jclass className) { + DWORD errorNumber = GetLastError(); + return (jint) errorNumber; } JNIEXPORT jboolean JNICALL Java_pipe_Pipe_CloseHandle(JNIEnv *env, - jclass className, jint hNamedPipe) { - BOOL result; - HANDLE pipeHandler = (HANDLE) hNamedPipe; - result = CloseHandle(pipeHandler); - return result; + jclass className, jint hNamedPipe) { + BOOL result; + HANDLE pipeHandler = (HANDLE) hNamedPipe; + result = CloseHandle(pipeHandler); + return result; } JNIEXPORT jbyteArray JNICALL Java_pipe_Pipe_ReadFile(JNIEnv *env, - jclass className, jint hNamedPipe, jint nNumberOfBytesToRead) { - int bytesRead = 0; - BOOL result; - HANDLE pipeHandler = (HANDLE) hNamedPipe; - LPVOID buffer; - jbyteArray lpBuffer; + jclass className, jint hNamedPipe, jint nNumberOfBytesToRead) { + int bytesRead = 0; + BOOL result; + HANDLE pipeHandler = (HANDLE) hNamedPipe; + LPVOID buffer; + jbyteArray lpBuffer; - buffer = (LPVOID) LocalAlloc(LMEM_ZEROINIT, nNumberOfBytesToRead); + buffer = (LPVOID) LocalAlloc(LMEM_ZEROINIT, nNumberOfBytesToRead); - if (DEBUG) { - printf( - "Native: Before ReadFile pipeHandler %d nNumberOfBytesToRead %d\n", - pipeHandler, nNumberOfBytesToRead); - } - result = ReadFile(pipeHandler, (LPVOID) buffer, - (DWORD) nNumberOfBytesToRead, &bytesRead, (LPOVERLAPPED) 0); - if (result) { - lpBuffer = (*env)->NewByteArray(env, (jsize) bytesRead); - (*env)->SetByteArrayRegion(env, lpBuffer, 0, (jsize) bytesRead, - (jbyte *) buffer); - } else - bytesRead = 0; + if (DEBUG) { + printf( + "Native: Before ReadFile pipeHandler %d nNumberOfBytesToRead %d\n", + pipeHandler, nNumberOfBytesToRead); + } + result = ReadFile(pipeHandler, (LPVOID) buffer, + (DWORD) nNumberOfBytesToRead, &bytesRead, (LPOVERLAPPED) 0); + if (result) { + lpBuffer = (*env)->NewByteArray(env, (jsize) bytesRead); + (*env)->SetByteArrayRegion(env, lpBuffer, 0, (jsize) bytesRead, + (jbyte *) buffer); + } else + bytesRead = 0; - LocalFree(buffer); + LocalFree(buffer); - if (DEBUG) { - printf("Native: After ReadFile BytesRead %d\n", bytesRead); - } - return lpBuffer; + if (DEBUG) { + printf("Native: After ReadFile BytesRead %d\n", bytesRead); + } + return lpBuffer; } JNIEXPORT jint JNICALL Java_pipe_Pipe_WriteFile(JNIEnv *env, jclass className, - jint hNamedPipe, jbyteArray lpBuffer, jint nNumberOfBytesToWrite) { - int bytesWritten = 0; - BOOL result; - HANDLE pipeHandler = (HANDLE) hNamedPipe; - LPVOID buffer; + jint hNamedPipe, jbyteArray lpBuffer, jint nNumberOfBytesToWrite) { + int bytesWritten = 0; + BOOL result; + HANDLE pipeHandler = (HANDLE) hNamedPipe; + LPVOID buffer; - buffer = (LPVOID) LocalAlloc(LMEM_ZEROINIT, nNumberOfBytesToWrite); + buffer = (LPVOID) LocalAlloc(LMEM_ZEROINIT, nNumberOfBytesToWrite); - (*env)->GetByteArrayRegion(env, lpBuffer, 0, nNumberOfBytesToWrite, buffer); - result = WriteFile(pipeHandler, buffer, (DWORD) nNumberOfBytesToWrite, - (LPDWORD) &bytesWritten, (LPOVERLAPPED) 0); - LocalFree(buffer); + (*env)->GetByteArrayRegion(env, lpBuffer, 0, nNumberOfBytesToWrite, buffer); + result = WriteFile(pipeHandler, buffer, (DWORD) nNumberOfBytesToWrite, + (LPDWORD) &bytesWritten, (LPOVERLAPPED) 0); + LocalFree(buffer); - if (DEBUG) { - printf("Native: After WriteFile BytesReadWritten %d\n", bytesWritten); - } + if (DEBUG) { + printf("Native: After WriteFile BytesReadWritten %d\n", bytesWritten); + } - if (!result) { - if (GetLastError() != ERROR_IO_PENDING) - result = 0; - else - result = 1; - } - if (!result) { - bytesWritten = -1; - } - return bytesWritten; + if (!result) { + if (GetLastError() != ERROR_IO_PENDING) + result = 0; + else + result = 1; + } + if (!result) { + bytesWritten = -1; + } + return bytesWritten; } JNIEXPORT jboolean JNICALL Java_pipe_Pipe_FlushFileBuffers(JNIEnv *env, - jclass className, jint hNamedPipe) { - BOOL result; - HANDLE pipeHandler = (HANDLE) hNamedPipe; - result = FlushFileBuffers(pipeHandler); - return result; + jclass className, jint hNamedPipe) { + BOOL result; + HANDLE pipeHandler = (HANDLE) hNamedPipe; + result = FlushFileBuffers(pipeHandler); + return result; } JNIEXPORT jboolean JNICALL Java_pipe_Pipe_DisconnectNamedPipe(JNIEnv *env, - jclass className, jint hNamedPipe) { - BOOL result; - HANDLE pipeHandler = (HANDLE) hNamedPipe; - result = DisconnectNamedPipe(pipeHandler); - return result; + jclass className, jint hNamedPipe) { + BOOL result; + HANDLE pipeHandler = (HANDLE) hNamedPipe; + result = DisconnectNamedPipe(pipeHandler); + return result; } JNIEXPORT jint JNICALL Java_pipe_Pipe_CreateFile(JNIEnv *env, jclass className, - jstring lpFileName, jint dwDesiredAccess, jint dwShareMode, - jint lpSecurityAttributes, jint dwCreationDisposition, - jint dwFlagsAndAttributes, jint hTemplateFile) { - HANDLE pipeHandler; - const jbyte *fileName; - fileName = (*env)->GetStringUTFChars(env, lpFileName, NULL ); - if (fileName == NULL ) - return -1; - pipeHandler = CreateFile((LPCSTR) fileName, (DWORD) dwDesiredAccess, - (DWORD) dwShareMode, (LPSECURITY_ATTRIBUTES) lpSecurityAttributes, - (DWORD) dwCreationDisposition, (DWORD) dwFlagsAndAttributes, - (HANDLE) hTemplateFile); - return (jint) pipeHandler; + jstring lpFileName, jint dwDesiredAccess, jint dwShareMode, + jint lpSecurityAttributes, jint dwCreationDisposition, + jint dwFlagsAndAttributes, jint hTemplateFile) { + HANDLE pipeHandler; + const jbyte *fileName; + fileName = (*env)->GetStringUTFChars(env, lpFileName, NULL ); + if (fileName == NULL ) + return -1; + pipeHandler = CreateFile((LPCSTR) fileName, (DWORD) dwDesiredAccess, + (DWORD) dwShareMode, (LPSECURITY_ATTRIBUTES) lpSecurityAttributes, + (DWORD) dwCreationDisposition, (DWORD) dwFlagsAndAttributes, + (HANDLE) hTemplateFile); + return (jint) pipeHandler; } JNIEXPORT jboolean JNICALL Java_pipe_Pipe_WaitNamedPipe(JNIEnv *env, - jclass className, jstring lpNamedPipeName, jint nTimeOut) { - BOOL result; - const jbyte *pipeName; - pipeName = (*env)->GetStringUTFChars(env, lpNamedPipeName, NULL ); - if (pipeName == NULL ) - return 0; - result = WaitNamedPipe((LPCSTR) pipeName, (DWORD) nTimeOut); - return result; + jclass className, jstring lpNamedPipeName, jint nTimeOut) { + BOOL result; + const jbyte *pipeName; + pipeName = (*env)->GetStringUTFChars(env, lpNamedPipeName, NULL ); + if (pipeName == NULL ) + return 0; + result = WaitNamedPipe((LPCSTR) pipeName, (DWORD) nTimeOut); + return result; } JNIEXPORT jstring JNICALL Java_pipe_Pipe_FormatMessage(JNIEnv *env, - jclass className, jint errorCode) { - LPVOID lpMsgBuf; - LPVOID lpDisplayBuf; - DWORD dw = (DWORD) errorCode; + jclass className, jint errorCode) { + LPVOID lpMsgBuf; + LPVOID lpDisplayBuf; + DWORD dw = (DWORD) errorCode; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, - NULL ); + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM + | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, + NULL ); - lpDisplayBuf = (LPVOID) LocalAlloc(LMEM_ZEROINIT, - (lstrlen((LPCTSTR) lpMsgBuf) + 40) * sizeof(TCHAR)); - StringCchPrintf((LPTSTR) lpDisplayBuf, - LocalSize(lpDisplayBuf) / sizeof(TCHAR), - TEXT("Failed with error %d: %s"), dw, lpMsgBuf); - return (jstring) (*env)->NewStringUTF(env, lpDisplayBuf); + lpDisplayBuf = (LPVOID) LocalAlloc(LMEM_ZEROINIT, + (lstrlen((LPCTSTR) lpMsgBuf) + 40) * sizeof(TCHAR)); + StringCchPrintf((LPTSTR) lpDisplayBuf, + LocalSize(lpDisplayBuf) / sizeof(TCHAR), + TEXT("Failed with error %d: %s"), dw, lpMsgBuf); + return (jstring) (*env)->NewStringUTF(env, lpDisplayBuf); } JNIEXPORT void JNICALL Java_pipe_Pipe_Print(JNIEnv *env, jclass className, - jstring lpMsgBuf) { - const jbyte *str; - str = (*env)->GetStringUTFChars(env, lpMsgBuf, NULL ); - if (str == NULL ) - return; - printf("Native: %s\n", str); - (*env)->ReleaseStringUTFChars(env, lpMsgBuf, str); - return; + jstring lpMsgBuf) { + const jbyte *str; + str = (*env)->GetStringUTFChars(env, lpMsgBuf, NULL ); + if (str == NULL ) + return; + printf("Native: %s\n", str); + (*env)->ReleaseStringUTFChars(env, lpMsgBuf, str); + return; } diff --git a/cpp/jlibpipe/src/main/java/pipe/Pipe.java b/cpp/jlibpipe/src/main/java/pipe/Pipe.java index 2a36d38..e4754aa 100644 --- a/cpp/jlibpipe/src/main/java/pipe/Pipe.java +++ b/cpp/jlibpipe/src/main/java/pipe/Pipe.java @@ -6,51 +6,51 @@ import com.github.boukefalos.jlibloader.Native; * @author Vikram S Khatri vikram.khatri@us.ibm.com */ public class Pipe { - static final int ERROR_PIPE_CONNECTED = 535; - static final int ERROR_BROKEN_PIPE = 109; - static final int PIPE_ACCESS_DUPLEX = 0x00000003; - static final int PIPE_WAIT = 0x00000000; - - static { - Native.load("com.github.boukefalos", "jlibpipe"); - } + static final int ERROR_PIPE_CONNECTED = 535; + static final int ERROR_BROKEN_PIPE = 109; + static final int PIPE_ACCESS_DUPLEX = 0x00000003; + static final int PIPE_WAIT = 0x00000000; + + static { + Native.load("com.github.boukefalos", "jlibpipe"); + } - public static final native int CreateNamedPipe( - String pipeName, - int ppenMode, - int pipeMode, - int maxInstances, - int outBufferSize, - int inBufferSize, - int defaultTimeOut, - int securityAttributes); + public static final native int CreateNamedPipe( + String pipeName, + int ppenMode, + int pipeMode, + int maxInstances, + int outBufferSize, + int inBufferSize, + int defaultTimeOut, + int securityAttributes); - public static final native boolean ConnectNamedPipe(int namedPipeHandle, int overlapped); + public static final native boolean ConnectNamedPipe(int namedPipeHandle, int overlapped); - public static final native int GetLastError(); + public static final native int GetLastError(); - public static final native boolean CloseHandle(int bbject); + public static final native boolean CloseHandle(int bbject); - public static final native byte[] ReadFile(int file, int numberOfBytesToRead); + public static final native byte[] ReadFile(int file, int numberOfBytesToRead); - public static final native int WriteFile(int file, byte[] buffer, int numberOfBytesToWrite); + public static final native int WriteFile(int file, byte[] buffer, int numberOfBytesToWrite); - public static final native boolean FlushFileBuffers(int file); + public static final native boolean FlushFileBuffers(int file); - public static final native boolean DisconnectNamedPipe(int namedPipeHandle); + public static final native boolean DisconnectNamedPipe(int namedPipeHandle); - public static final native int CreateFile( - String fileName, - int desiredAccess, - int shareMode, - int securityAttributes, - int creationDisposition, - int flagsAndAttributes, - int templateFile); + public static final native int CreateFile( + String fileName, + int desiredAccess, + int shareMode, + int securityAttributes, + int creationDisposition, + int flagsAndAttributes, + int templateFile); - public static final native boolean WaitNamedPipe(String namedPipeName, int timeOut); + public static final native boolean WaitNamedPipe(String namedPipeName, int timeOut); - public static final native String FormatMessage(int errorCode); + public static final native String FormatMessage(int errorCode); - public static final native void Print(String message); + public static final native void Print(String message); } diff --git a/cpp/jlibpipe/src/test/java/pipe/Client.java b/cpp/jlibpipe/src/test/java/pipe/Client.java index b36d882..1ef5c26 100644 --- a/cpp/jlibpipe/src/test/java/pipe/Client.java +++ b/cpp/jlibpipe/src/test/java/pipe/Client.java @@ -3,22 +3,22 @@ package pipe; import java.io.RandomAccessFile; public class Client { - public static void main(String[] args) { - try { - // Connect to the pipe - RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\detest", "rw"); - String echoText = "Hello word\n"; + public static void main(String[] args) { + try { + // Connect to the pipe + RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\detest", "rw"); + String echoText = "Hello word\n"; - // write to pipe - pipe.write(echoText.getBytes()); + // write to pipe + pipe.write(echoText.getBytes()); - // read response - String echoResponse = pipe.readLine(); - System.out.println(echoResponse); - pipe.close(); - } catch (Exception e) { - e.printStackTrace(); - } + // read response + String echoResponse = pipe.readLine(); + System.out.println(echoResponse); + pipe.close(); + } catch (Exception e) { + e.printStackTrace(); + } - } + } } diff --git a/cpp/jlibpipe/src/test/java/pipe/TestPipe.java b/cpp/jlibpipe/src/test/java/pipe/TestPipe.java index 46865f9..30b8732 100644 --- a/cpp/jlibpipe/src/test/java/pipe/TestPipe.java +++ b/cpp/jlibpipe/src/test/java/pipe/TestPipe.java @@ -6,81 +6,81 @@ import java.io.InputStream; public class TestPipe { - private int namedPipeHandle; - private String pipeName, srcFile; - private int pipeBuffer = 131072, fileBuffer = 8192; + private int namedPipeHandle; + private String pipeName, srcFile; + private int pipeBuffer = 131072, fileBuffer = 8192; - public TestPipe(String pipeName, String srcFile) { - this.pipeName = pipeName; - this.srcFile = srcFile; - } + public TestPipe(String pipeName, String srcFile) { + this.pipeName = pipeName; + this.srcFile = srcFile; + } - private void log(String message) { - System.out.println(message); - } + private void log(String message) { + System.out.println(message); + } - private boolean createPipe() { - namedPipeHandle = Pipe.CreateNamedPipe( - pipeName, - Pipe.PIPE_ACCESS_DUPLEX, - Pipe.PIPE_WAIT, - 5, - pipeBuffer, - pipeBuffer, - 0xffffffff, - 0); - if (namedPipeHandle == -1) { - log("CreateNamedPipe failed for " + pipeName + " for error Message " + Pipe.FormatMessage(Pipe.GetLastError())); - } else { - log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle); - } - return namedPipeHandle != -1; - } + private boolean createPipe() { + namedPipeHandle = Pipe.CreateNamedPipe( + pipeName, + Pipe.PIPE_ACCESS_DUPLEX, + Pipe.PIPE_WAIT, + 5, + pipeBuffer, + pipeBuffer, + 0xffffffff, + 0); + if (namedPipeHandle == -1) { + log("CreateNamedPipe failed for " + pipeName + " for error Message " + Pipe.FormatMessage(Pipe.GetLastError())); + } else { + log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle); + } + return namedPipeHandle != -1; + } - private boolean connectToPipe() { - log("Waiting for a client to connect to pipe " + pipeName); - boolean connected = Pipe.ConnectNamedPipe(namedPipeHandle, 0); - if (!connected) { - int lastError = Pipe.GetLastError(); - if (lastError == Pipe.ERROR_PIPE_CONNECTED) - connected = true; - } - log((connected ? "Connected to the pipe " : "Falied to connect to the pipe ") + pipeName); - return connected; - } + private boolean connectToPipe() { + log("Waiting for a client to connect to pipe " + pipeName); + boolean connected = Pipe.ConnectNamedPipe(namedPipeHandle, 0); + if (!connected) { + int lastError = Pipe.GetLastError(); + if (lastError == Pipe.ERROR_PIPE_CONNECTED) + connected = true; + } + log((connected ? "Connected to the pipe " : "Falied to connect to the pipe ") + pipeName); + return connected; + } - public void runPipe() { - if (createPipe() && connectToPipe()) { - log("Client connected."); - try { - File f1 = new File(this.srcFile); - InputStream in = new FileInputStream(f1); - log("Sending data to the pipe"); - byte[] buf = new byte[fileBuffer]; - int len, bytesWritten; - while ((len = in.read(buf)) > 0) { - bytesWritten = Pipe.WriteFile(namedPipeHandle, buf, len); - log("Sent " + len + "/" + bytesWritten + " bytes to the pipe"); - if (bytesWritten == -1) { - int errorNumber = Pipe.GetLastError(); - log("Error Writing to pipe " + Pipe.FormatMessage(errorNumber)); - } - } - in.close(); - Pipe.FlushFileBuffers(namedPipeHandle); - Pipe.CloseHandle(namedPipeHandle); - Pipe.DisconnectNamedPipe(namedPipeHandle); - log("Writing to the pipe completed."); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + public void runPipe() { + if (createPipe() && connectToPipe()) { + log("Client connected."); + try { + File f1 = new File(this.srcFile); + InputStream in = new FileInputStream(f1); + log("Sending data to the pipe"); + byte[] buf = new byte[fileBuffer]; + int len, bytesWritten; + while ((len = in.read(buf)) > 0) { + bytesWritten = Pipe.WriteFile(namedPipeHandle, buf, len); + log("Sent " + len + "/" + bytesWritten + " bytes to the pipe"); + if (bytesWritten == -1) { + int errorNumber = Pipe.GetLastError(); + log("Error Writing to pipe " + Pipe.FormatMessage(errorNumber)); + } + } + in.close(); + Pipe.FlushFileBuffers(namedPipeHandle); + Pipe.CloseHandle(namedPipeHandle); + Pipe.DisconnectNamedPipe(namedPipeHandle); + log("Writing to the pipe completed."); + } catch (Exception e) { + e.printStackTrace(); + } + } + } - public static void main(String[] args) { - String pipeName = "\\\\.\\pipe\\detest"; - String fileName = "C:\\Users\\Rik\\Music\\Artists\\+44\\When Your Heart Stops Beating\\+44 - 155.mp3"; - TestPipe testPipe = new TestPipe(pipeName, fileName); - testPipe.runPipe(); - } + public static void main(String[] args) { + String pipeName = "\\\\.\\pipe\\detest"; + String fileName = "C:\\Users\\Rik\\Music\\Artists\\+44\\When Your Heart Stops Beating\\+44 - 155.mp3"; + TestPipe testPipe = new TestPipe(pipeName, fileName); + testPipe.runPipe(); + } } diff --git a/java/base/src/main/java/base/Control.java b/java/base/src/main/java/base/Control.java index ca16751..e48caa9 100644 --- a/java/base/src/main/java/base/Control.java +++ b/java/base/src/main/java/base/Control.java @@ -1,7 +1,7 @@ package base; public interface Control { - public void start(); - public void stop(); - public void exit(); + public void start(); + public void stop(); + public void exit(); } diff --git a/java/base/src/main/java/base/Forwarder.java b/java/base/src/main/java/base/Forwarder.java index a54be61..ccd7e62 100644 --- a/java/base/src/main/java/base/Forwarder.java +++ b/java/base/src/main/java/base/Forwarder.java @@ -1,6 +1,6 @@ package base; public interface Forwarder extends Control { - public void register(Receiver receiver); - public void remove(Receiver receiver); + public void register(Receiver receiver); + public void remove(Receiver receiver); } \ No newline at end of file diff --git a/java/base/src/main/java/base/Receiver.java b/java/base/src/main/java/base/Receiver.java index 31bc1b4..ceb1170 100644 --- a/java/base/src/main/java/base/Receiver.java +++ b/java/base/src/main/java/base/Receiver.java @@ -1,5 +1,5 @@ package base; public interface Receiver { - public void receive(byte[] buffer); + public void receive(byte[] buffer); } diff --git a/java/base/src/main/java/base/Sender.java b/java/base/src/main/java/base/Sender.java index 9464f1d..baaee04 100644 --- a/java/base/src/main/java/base/Sender.java +++ b/java/base/src/main/java/base/Sender.java @@ -3,5 +3,5 @@ package base; import java.io.IOException; public interface Sender extends Control { - public void send(byte[] buffer) throws IOException; + public void send(byte[] buffer) throws IOException; } diff --git a/java/base/src/main/java/base/exception/LoaderException.java b/java/base/src/main/java/base/exception/LoaderException.java index 3ce2772..d0146fa 100644 --- a/java/base/src/main/java/base/exception/LoaderException.java +++ b/java/base/src/main/java/base/exception/LoaderException.java @@ -1,9 +1,9 @@ package base.exception; public class LoaderException extends Exception { - protected static final long serialVersionUID = 1L; + protected static final long serialVersionUID = 1L; - public LoaderException(String message) { - super(message); - } + public LoaderException(String message) { + super(message); + } } diff --git a/java/base/src/main/java/base/loader/AbstractLoader.java b/java/base/src/main/java/base/loader/AbstractLoader.java index b145e17..5dc9775 100644 --- a/java/base/src/main/java/base/loader/AbstractLoader.java +++ b/java/base/src/main/java/base/loader/AbstractLoader.java @@ -19,128 +19,128 @@ import base.server.forwarder.UdpDuplexClientForwarder; import base.server.forwarder.UdpDuplexServerForwarder; public class AbstractLoader { - protected static final String PROPERTIES_FILE = "loader.properties"; - protected static final Properties SERVER = null; + protected static final String PROPERTIES_FILE = "loader.properties"; + protected static final Properties SERVER = null; - protected Logger logger = LoggerFactory.getLogger(AbstractLoader.class); + protected Logger logger = LoggerFactory.getLogger(AbstractLoader.class); protected MutablePicoContainer pico; public AbstractLoader() { - /* Initialise container */ - pico = new DefaultPicoContainer(); - } - - public AbstractLoader(Properties properties) { - this(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static T getLoader() throws LoaderException { - return (T) new AbstractLoader(readProperties(PROPERTIES_FILE)); + /* Initialise container */ + pico = new DefaultPicoContainer(); } - public static Properties readProperties(String propertiesFile) throws LoaderException { - /* Read properties file */ - Properties properties = new Properties(); - try { - properties.load(AbstractLoader.class.getClassLoader().getResourceAsStream(propertiesFile)); - } catch (IOException e) { - throw new LoaderException("Faield to read properties file: " + PROPERTIES_FILE); - } - return properties; - } + public AbstractLoader(Properties properties) { + this(); + } - protected Class getSenderClass(String protocol, String implementation) throws LoaderException { - switch (protocol) { - case "tcp": - switch (implementation) { - case "channel": - return base.server.channel.TcpClient.class; - default: - case "socket": - return base.server.socket.TcpClient.class; - } - case "udp": - return UdpSender.class; - } - throw new LoaderException("Failed to determine "); - } + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static T getLoader() throws LoaderException { + return (T) new AbstractLoader(readProperties(PROPERTIES_FILE)); + } - protected Class getClientForwarderClass(String protocol, String implementation) throws LoaderException { - switch (protocol) { - case "tcp": - switch (implementation) { - case "channel": - return base.server.forwarder.TcpClientChannelForwarder.class; - default: - case "socket": - return base.server.forwarder.TcpClientSocketForwarder.class; - } - case "udp": - return UdpDuplexClientForwarder.class; - } - throw new LoaderException("Failed to determine "); - } + public static Properties readProperties(String propertiesFile) throws LoaderException { + /* Read properties file */ + Properties properties = new Properties(); + try { + properties.load(AbstractLoader.class.getClassLoader().getResourceAsStream(propertiesFile)); + } catch (IOException e) { + throw new LoaderException("Faield to read properties file: " + PROPERTIES_FILE); + } + return properties; + } - protected Class getServerForwarderClass(String protocol, String implementation) throws LoaderException { - switch (protocol) { - case "tcp": - switch (implementation) { - case "channel": - return base.server.forwarder.TcpChannelServerForwarder.class; - default: - case "socket": - return base.server.forwarder.TcpSocketServerForwarder.class; - } - case "udp": - return UdpDuplexServerForwarder.class; - } - throw new LoaderException("Failed to determine "); - } + protected Class getSenderClass(String protocol, String implementation) throws LoaderException { + switch (protocol) { + case "tcp": + switch (implementation) { + case "channel": + return base.server.channel.TcpClient.class; + default: + case "socket": + return base.server.socket.TcpClient.class; + } + case "udp": + return UdpSender.class; + } + throw new LoaderException("Failed to determine "); + } - protected void addClientSender(String protocol, String implementation, String host, int port) throws LoaderException { - Class senderClass = getSenderClass(protocol, implementation); - logger.debug("Adding " + senderClass); - pico.addComponent(Sender.class, senderClass, new Parameter[]{ - new ConstantParameter(host), - new ConstantParameter(port)}); - } + protected Class getClientForwarderClass(String protocol, String implementation) throws LoaderException { + switch (protocol) { + case "tcp": + switch (implementation) { + case "channel": + return base.server.forwarder.TcpClientChannelForwarder.class; + default: + case "socket": + return base.server.forwarder.TcpClientSocketForwarder.class; + } + case "udp": + return UdpDuplexClientForwarder.class; + } + throw new LoaderException("Failed to determine "); + } - protected void addServerSender(String protocol, String implementation, int port) throws LoaderException { - Class senderClass = getSenderClass(protocol, implementation); - logger.debug("Adding " + senderClass); - pico.addComponent(Sender.class, senderClass, new Parameter[]{ - new ConstantParameter(port)}); - } + protected Class getServerForwarderClass(String protocol, String implementation) throws LoaderException { + switch (protocol) { + case "tcp": + switch (implementation) { + case "channel": + return base.server.forwarder.TcpChannelServerForwarder.class; + default: + case "socket": + return base.server.forwarder.TcpSocketServerForwarder.class; + } + case "udp": + return UdpDuplexServerForwarder.class; + } + throw new LoaderException("Failed to determine "); + } - protected void addClientForwarder(String protocol, String implementation, String host, int port) throws LoaderException { - Class forwarderClass = getClientForwarderClass(protocol, implementation); - logger.debug("Adding " + forwarderClass); - pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{ - new ConstantParameter(host), - new ConstantParameter(port)}); - } + protected void addClientSender(String protocol, String implementation, String host, int port) throws LoaderException { + Class senderClass = getSenderClass(protocol, implementation); + logger.debug("Adding " + senderClass); + pico.addComponent(Sender.class, senderClass, new Parameter[]{ + new ConstantParameter(host), + new ConstantParameter(port)}); + } - protected void addClientDuplex(String protocol, String implementation, String host, int port) throws LoaderException { - Class duplexClass = getClientForwarderClass(protocol, implementation); - logger.debug("Adding " + duplexClass); - pico.addComponent(Duplex.class, duplexClass, new Parameter[]{ - new ConstantParameter(host), - new ConstantParameter(port)}); - - } + protected void addServerSender(String protocol, String implementation, int port) throws LoaderException { + Class senderClass = getSenderClass(protocol, implementation); + logger.debug("Adding " + senderClass); + pico.addComponent(Sender.class, senderClass, new Parameter[]{ + new ConstantParameter(port)}); + } - protected void addServerForwarder(String protocol, String implementation, int port) throws LoaderException { - Class forwarderClass = getServerForwarderClass(protocol, implementation); - logger.debug("Adding " + forwarderClass); - pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{ - new ConstantParameter(port)}); - } + protected void addClientForwarder(String protocol, String implementation, String host, int port) throws LoaderException { + Class forwarderClass = getClientForwarderClass(protocol, implementation); + logger.debug("Adding " + forwarderClass); + pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{ + new ConstantParameter(host), + new ConstantParameter(port)}); + } - protected void addServerDuplex(String protocol, String implementation, int port) throws LoaderException { - Class duplexClass = getServerForwarderClass(protocol, implementation); - logger.debug("Adding " + duplexClass); - pico.addComponent(Duplex.class, duplexClass, new Parameter[]{ - new ConstantParameter(port)}); - } + protected void addClientDuplex(String protocol, String implementation, String host, int port) throws LoaderException { + Class duplexClass = getClientForwarderClass(protocol, implementation); + logger.debug("Adding " + duplexClass); + pico.addComponent(Duplex.class, duplexClass, new Parameter[]{ + new ConstantParameter(host), + new ConstantParameter(port)}); + + } + + protected void addServerForwarder(String protocol, String implementation, int port) throws LoaderException { + Class forwarderClass = getServerForwarderClass(protocol, implementation); + logger.debug("Adding " + forwarderClass); + pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{ + new ConstantParameter(port)}); + } + + protected void addServerDuplex(String protocol, String implementation, int port) throws LoaderException { + Class duplexClass = getServerForwarderClass(protocol, implementation); + logger.debug("Adding " + duplexClass); + pico.addComponent(Duplex.class, duplexClass, new Parameter[]{ + new ConstantParameter(port)}); + } } diff --git a/java/base/src/main/java/base/server/channel/TcpClient.java b/java/base/src/main/java/base/server/channel/TcpClient.java index dfbc21b..3c6075d 100644 --- a/java/base/src/main/java/base/server/channel/TcpClient.java +++ b/java/base/src/main/java/base/server/channel/TcpClient.java @@ -18,120 +18,120 @@ import base.work.Work; import base.worker.Worker; public class TcpClient extends Work implements Sender { - protected static final String HOST = "localhost"; - protected static final int BUFFER_SIZE = 1024; + protected static final String HOST = "localhost"; + protected static final int BUFFER_SIZE = 1024; - protected String host; - protected int port; - protected int bufferSize; - protected SocketChannel socketChannel; - protected Selector selector; + protected String host; + protected int port; + protected int bufferSize; + protected SocketChannel socketChannel; + protected Selector selector; protected ArrayList> listenList = new ArrayList>(); public TcpClient(int port) { - this(HOST, port); + this(HOST, port); } - public TcpClient(String host, int port) { - this(host, port, BUFFER_SIZE); - } + public TcpClient(String host, int port) { + this(host, port, BUFFER_SIZE); + } - public TcpClient(String host, int port, int bufferSize) { - this.host = host; - this.port = port; - this.bufferSize = bufferSize; - } + public TcpClient(String host, int port, int bufferSize) { + this.host = host; + this.port = port; + this.bufferSize = bufferSize; + } - public void activate() throws ActivateException { - System.out.println("Client: Activate!"); - try { - InetSocketAddress hostAddress = new InetSocketAddress(host, port); - socketChannel = SocketChannel.open(hostAddress); - socketChannel.configureBlocking(false); - while (!socketChannel.finishConnect()) { - sleep(Worker.SLEEP); - } - selector = Selector.open(); - socketChannel.register(selector, SelectionKey.OP_READ); - synchronized (host) { - host.notifyAll(); - } - } catch (Exception e) { - logger.error("", e); - throw new ActivateException(); - } - super.activate(); - } + public void activate() throws ActivateException { + System.out.println("Client: Activate!"); + try { + InetSocketAddress hostAddress = new InetSocketAddress(host, port); + socketChannel = SocketChannel.open(hostAddress); + socketChannel.configureBlocking(false); + while (!socketChannel.finishConnect()) { + sleep(Worker.SLEEP); + } + selector = Selector.open(); + socketChannel.register(selector, SelectionKey.OP_READ); + synchronized (host) { + host.notifyAll(); + } + } catch (Exception e) { + logger.error("", e); + throw new ActivateException(); + } + super.activate(); + } - public void deactivate() throws DeactivateException { - System.out.println("Client: Deactivate!"); - try { - selector.close(); - socketChannel.close(); - } catch (IOException e) { - throw new DeactivateException(); - } - } + public void deactivate() throws DeactivateException { + System.out.println("Client: Deactivate!"); + try { + selector.close(); + socketChannel.close(); + } catch (IOException e) { + throw new DeactivateException(); + } + } - public void stop() { - super.stop(); - if (selector != null) { - selector.wakeup(); - } - } + public void stop() { + super.stop(); + if (selector != null) { + selector.wakeup(); + } + } - public final void work() { - try { - logger.debug("Client: Waiting for select... "); - logger.debug("Client: Number of selected keys: " + selector.select()); - Set selectionKeySet = selector.selectedKeys(); - Iterator selectionKeyIterator = selectionKeySet.iterator(); + public final void work() { + try { + logger.debug("Client: Waiting for select... "); + logger.debug("Client: Number of selected keys: " + selector.select()); + Set selectionKeySet = selector.selectedKeys(); + Iterator selectionKeyIterator = selectionKeySet.iterator(); - while (selectionKeyIterator.hasNext()) { - SelectionKey selectionKey = selectionKeyIterator.next(); - if (selectionKey.isReadable()) { - ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize); - socketChannel.read(byteBuffer); - byte[] buffer = byteBuffer.array(); - input(buffer); - } else if (selectionKey.isWritable()) { - byte[] buffer; - buffer = (byte[]) selectionKey.attachment(); - ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); - socketChannel.write(byteBuffer); - //selectionKey.cancel(); - socketChannel.register(selector, SelectionKey.OP_READ); - } - selectionKeyIterator.remove(); - } - } catch (Exception e) { - logger.error("", e); - } - } + while (selectionKeyIterator.hasNext()) { + SelectionKey selectionKey = selectionKeyIterator.next(); + if (selectionKey.isReadable()) { + ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize); + socketChannel.read(byteBuffer); + byte[] buffer = byteBuffer.array(); + input(buffer); + } else if (selectionKey.isWritable()) { + byte[] buffer; + buffer = (byte[]) selectionKey.attachment(); + ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); + socketChannel.write(byteBuffer); + //selectionKey.cancel(); + socketChannel.register(selector, SelectionKey.OP_READ); + } + selectionKeyIterator.remove(); + } + } catch (Exception e) { + logger.error("", e); + } + } - protected void input(byte[] buffer) {} + protected void input(byte[] buffer) {} - public void send(byte[] buffer) throws IOException { - if (selector == null) { - try { - synchronized (host) { - host.wait(); - } - } catch (InterruptedException e) {} - } - selector.wakeup(); - socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, buffer); - } + public void send(byte[] buffer) throws IOException { + if (selector == null) { + try { + synchronized (host) { + host.wait(); + } + } catch (InterruptedException e) {} + } + selector.wakeup(); + socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, buffer); + } - public void close() throws IOException { - socketChannel.close(); - } + public void close() throws IOException { + socketChannel.close(); + } - /*public void register(Listen listen) { - listenList.add(listen); - } + /*public void register(Listen listen) { + listenList.add(listen); + } - public void remove(Listen listen) { - listenList.remove(listen); - }*/ + public void remove(Listen listen) { + listenList.remove(listen); + }*/ } \ No newline at end of file diff --git a/java/base/src/main/java/base/server/channel/TcpServer.java b/java/base/src/main/java/base/server/channel/TcpServer.java index 6a8f0b2..c39379b 100644 --- a/java/base/src/main/java/base/server/channel/TcpServer.java +++ b/java/base/src/main/java/base/server/channel/TcpServer.java @@ -20,139 +20,139 @@ import base.server.channel.TcpServerClient; import base.work.Work; public class TcpServer extends Work implements Sender { - protected static final Class CLIENT_CLASS = TcpServerClient.class; - protected static final int BUFFER_SIZE = 1024; + protected static final Class CLIENT_CLASS = TcpServerClient.class; + protected static final int BUFFER_SIZE = 1024; - protected int port; - protected int bufferSize; - protected Constructor clientConstructor; - protected Selector selector; - protected ServerSocketChannel serverSocket; - protected ArrayList clientList; + protected int port; + protected int bufferSize; + protected Constructor clientConstructor; + protected Selector selector; + protected ServerSocketChannel serverSocket; + protected ArrayList clientList; - public TcpServer(int port) { - this(port, CLIENT_CLASS); - } + public TcpServer(int port) { + this(port, CLIENT_CLASS); + } - public TcpServer(int port, Class clientClass) { - this(port, clientClass, BUFFER_SIZE); - } + public TcpServer(int port, Class clientClass) { + this(port, clientClass, BUFFER_SIZE); + } - public TcpServer(int port, Class clientClass, int bufferSize) { - this.port = port; - this.bufferSize = bufferSize; - try { - // Allow dependency injection, constructor arguments - clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, SocketChannel.class, Integer.class); - } catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) { - logger.error("Failed to initialise client constructor", e); - } - clientList = new ArrayList(); - } + public TcpServer(int port, Class clientClass, int bufferSize) { + this.port = port; + this.bufferSize = bufferSize; + try { + // Allow dependency injection, constructor arguments + clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, SocketChannel.class, Integer.class); + } catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) { + logger.error("Failed to initialise client constructor", e); + } + clientList = new ArrayList(); + } - public void activate() throws ActivateException { - System.out.println("Server: Activate!"); - try { - // Get selector - selector = Selector.open(); + public void activate() throws ActivateException { + System.out.println("Server: Activate!"); + try { + // Get selector + selector = Selector.open(); - // Get server socket channel and register with selector - serverSocket = ServerSocketChannel.open(); - InetSocketAddress hostAddress = new InetSocketAddress(port); - serverSocket.bind(hostAddress); - serverSocket.configureBlocking(false); - serverSocket.register(selector, SelectionKey.OP_ACCEPT); - synchronized (clientConstructor) { - clientConstructor.notifyAll(); - } - return; - } catch (BindException e) { - logger.error("Address already in use", e); - } catch (IOException e) { - logger.error("", e); - } - throw new ActivateException(); - } + // Get server socket channel and register with selector + serverSocket = ServerSocketChannel.open(); + InetSocketAddress hostAddress = new InetSocketAddress(port); + serverSocket.bind(hostAddress); + serverSocket.configureBlocking(false); + serverSocket.register(selector, SelectionKey.OP_ACCEPT); + synchronized (clientConstructor) { + clientConstructor.notifyAll(); + } + return; + } catch (BindException e) { + logger.error("Address already in use", e); + } catch (IOException e) { + logger.error("", e); + } + throw new ActivateException(); + } - public void deactivate() throws DeactivateException { - System.out.println("Server: Deactivate!"); - try { - selector.close(); - serverSocket.close(); - } catch (IOException e) { - throw new DeactivateException(); - } finally { - for (TcpServerClient client : clientList) { - client.stop(); - } - } - } + public void deactivate() throws DeactivateException { + System.out.println("Server: Deactivate!"); + try { + selector.close(); + serverSocket.close(); + } catch (IOException e) { + throw new DeactivateException(); + } finally { + for (TcpServerClient client : clientList) { + client.stop(); + } + } + } - public void stop() { - super.stop(); - if (selector != null) { - selector.wakeup(); - } - } + public void stop() { + super.stop(); + if (selector != null) { + selector.wakeup(); + } + } - public void work() { - try { - System.out.println("Server: Waiting for select... "); - System.out.println("Server: Number of selected keys: " + selector.select()); - - Set selectionKeySet = selector.selectedKeys(); - Iterator selectionKeyIterator = selectionKeySet.iterator(); - - while (selectionKeyIterator.hasNext()) { - SelectionKey selectionKey = selectionKeyIterator.next(); - if (selectionKey.isAcceptable()) { - // Accept the new client connection - SocketChannel socketChannel = serverSocket.accept(); - socketChannel.configureBlocking(false); + public void work() { + try { + System.out.println("Server: Waiting for select... "); + System.out.println("Server: Number of selected keys: " + selector.select()); + + Set selectionKeySet = selector.selectedKeys(); + Iterator selectionKeyIterator = selectionKeySet.iterator(); + + while (selectionKeyIterator.hasNext()) { + SelectionKey selectionKey = selectionKeyIterator.next(); + if (selectionKey.isAcceptable()) { + // Accept the new client connection + SocketChannel socketChannel = serverSocket.accept(); + socketChannel.configureBlocking(false); - // Add the new connection to the selector - TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socketChannel, bufferSize); - clientList.add(client); - socketChannel.register(selector, SelectionKey.OP_READ, client); - //initClient(client); - System.out.println("Accepted new connection from client: " + socketChannel); - } else if (selectionKey.isReadable()) { - // Read the data from client - TcpServerClient serverClient = (TcpServerClient) selectionKey.attachment(); - serverClient.readable(); - } else if (selectionKey.isWritable()) { - // Write to client? - } - selectionKeyIterator.remove(); - } - }/* catch (IOException e) {} catch (InstantiationException e) { - logger.error("", e); - } catch (IllegalAccessException e) { - logger.error("", e); - } catch (IllegalArgumentException e) { - logger.error("", e); - } catch (InvocationTargetException e) { - logger.error("", e); - } */catch (Exception e) { - e.printStackTrace(); - } - } + // Add the new connection to the selector + TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socketChannel, bufferSize); + clientList.add(client); + socketChannel.register(selector, SelectionKey.OP_READ, client); + //initClient(client); + System.out.println("Accepted new connection from client: " + socketChannel); + } else if (selectionKey.isReadable()) { + // Read the data from client + TcpServerClient serverClient = (TcpServerClient) selectionKey.attachment(); + serverClient.readable(); + } else if (selectionKey.isWritable()) { + // Write to client? + } + selectionKeyIterator.remove(); + } + }/* catch (IOException e) {} catch (InstantiationException e) { + logger.error("", e); + } catch (IllegalAccessException e) { + logger.error("", e); + } catch (IllegalArgumentException e) { + logger.error("", e); + } catch (InvocationTargetException e) { + logger.error("", e); + } */catch (Exception e) { + e.printStackTrace(); + } + } - protected void initClient(TcpServerClient client) { - try { - client.write(ByteBuffer.wrap(new String("Hi there!").getBytes())); - } catch (IOException e) { - logger.error("", e); - } - } + protected void initClient(TcpServerClient client) { + try { + client.write(ByteBuffer.wrap(new String("Hi there!").getBytes())); + } catch (IOException e) { + logger.error("", e); + } + } - public void send(byte[] buffer) throws IOException { - logger.debug("Number of clients = " + clientList.size()); - for (TcpServerClient client : clientList) { - // Should be dealt with in clients own thread - client.send(buffer); - } - } + public void send(byte[] buffer) throws IOException { + logger.debug("Number of clients = " + clientList.size()); + for (TcpServerClient client : clientList) { + // Should be dealt with in clients own thread + client.send(buffer); + } + } - public void input(TcpServerClient client, byte[] buffer) {} + public void input(TcpServerClient client, byte[] buffer) {} } \ No newline at end of file diff --git a/java/base/src/main/java/base/server/channel/TcpServerClient.java b/java/base/src/main/java/base/server/channel/TcpServerClient.java index 5c7aa79..6082754 100644 --- a/java/base/src/main/java/base/server/channel/TcpServerClient.java +++ b/java/base/src/main/java/base/server/channel/TcpServerClient.java @@ -8,47 +8,47 @@ import base.Sender; import base.work.Listen; public class TcpServerClient extends Listen implements Sender { - protected static final int BUFFER_SIZE = 1024; + protected static final int BUFFER_SIZE = 1024; - protected TcpServer server; - protected SocketChannel socketChannel; - protected int bufferSize; - protected ByteBuffer byteBuffer; + protected TcpServer server; + protected SocketChannel socketChannel; + protected int bufferSize; + protected ByteBuffer byteBuffer; - public TcpServerClient(TcpServer server, SocketChannel socketChannel) { - this(server, socketChannel, BUFFER_SIZE); - } + public TcpServerClient(TcpServer server, SocketChannel socketChannel) { + this(server, socketChannel, BUFFER_SIZE); + } - public TcpServerClient(TcpServer server, SocketChannel socketChannel, Integer bufferSize) { - super(); - this.server = server; - this.socketChannel = socketChannel; - this.bufferSize = bufferSize; - byteBuffer = ByteBuffer.allocate(bufferSize); - } + public TcpServerClient(TcpServer server, SocketChannel socketChannel, Integer bufferSize) { + super(); + this.server = server; + this.socketChannel = socketChannel; + this.bufferSize = bufferSize; + byteBuffer = ByteBuffer.allocate(bufferSize); + } - public void write(ByteBuffer byteBuffer) throws IOException { - socketChannel.write(byteBuffer); - } + public void write(ByteBuffer byteBuffer) throws IOException { + socketChannel.write(byteBuffer); + } - public void readable() throws IOException { - int read; - while (( read = socketChannel.read(byteBuffer)) > 0) { - byteBuffer.flip(); - byte[] buffer = byteBuffer.array(); - input(buffer); - byteBuffer.clear(); - } - if (read < 0) { - socketChannel.close(); - } - } + public void readable() throws IOException { + int read; + while (( read = socketChannel.read(byteBuffer)) > 0) { + byteBuffer.flip(); + byte[] buffer = byteBuffer.array(); + input(buffer); + byteBuffer.clear(); + } + if (read < 0) { + socketChannel.close(); + } + } - public void input(byte[] buffer) { - server.input(this, buffer); - } + public void input(byte[] buffer) { + server.input(this, buffer); + } - public void send(byte[] buffer) throws IOException { - write(ByteBuffer.wrap(buffer)); - } + public void send(byte[] buffer) throws IOException { + write(ByteBuffer.wrap(buffer)); + } } diff --git a/java/base/src/main/java/base/server/datagram/AbstractUdpClient.java b/java/base/src/main/java/base/server/datagram/AbstractUdpClient.java new file mode 100644 index 0000000..9108676 --- /dev/null +++ b/java/base/src/main/java/base/server/datagram/AbstractUdpClient.java @@ -0,0 +1,46 @@ +package base.server.datagram; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.MulticastSocket; + +import base.work.Work; + +public abstract class AbstractUdpClient extends Work { + protected static final int BUFFER_SIZE = 2048; + + protected int bufferSize; + protected MulticastSocket socket; + protected DatagramPacket datagramPacket; + + public AbstractUdpClient() {} + + public AbstractUdpClient(MulticastSocket socket) { + this(socket, BUFFER_SIZE); + } + + public AbstractUdpClient(MulticastSocket socket, int bufferSize) { + this.socket = socket; + this.bufferSize = bufferSize; + byte[] buffer = new byte[bufferSize]; + datagramPacket = new DatagramPacket(buffer, buffer.length); + } + + public void work() { + try { + byte[] buffer = new byte[bufferSize]; + DatagramPacket packet = new DatagramPacket(buffer, buffer.length); + socket.receive(packet); + System.out.println("iets ontvangen!!!!!"); + buffer = packet.getData(); + input(buffer); + } catch (IOException e) {} + } + + public void stop() { + socket.close(); + super.stop(); + } + + protected abstract void input(byte[] buffer); +} diff --git a/java/base/src/main/java/base/server/datagram/UdpDuplexAutoClient.java b/java/base/src/main/java/base/server/datagram/UdpDuplexAutoClient.java new file mode 100644 index 0000000..a3763d5 --- /dev/null +++ b/java/base/src/main/java/base/server/datagram/UdpDuplexAutoClient.java @@ -0,0 +1,17 @@ +package base.server.datagram; + +import java.net.UnknownHostException; + +public class UdpDuplexAutoClient extends UdpDuplexClient { + public UdpDuplexAutoClient(int bindPort, int sendPort) throws UnknownHostException { + super(HOST, bindPort, null, sendPort); + } + + public UdpDuplexAutoClient(String bindHost, int bindPort, int sendPort) throws UnknownHostException { + super(bindHost, bindPort, null, sendPort); + } + + public UdpDuplexAutoClient(String bindHost, int bindPort, int sendPort, int bufferSize) throws UnknownHostException { + super(bindHost, bindPort, null, sendPort, bufferSize); + } +} diff --git a/java/base/src/main/java/base/server/datagram/UdpDuplexClient.java b/java/base/src/main/java/base/server/datagram/UdpDuplexClient.java index 26f27b5..0b8ada8 100644 --- a/java/base/src/main/java/base/server/datagram/UdpDuplexClient.java +++ b/java/base/src/main/java/base/server/datagram/UdpDuplexClient.java @@ -1,22 +1,51 @@ package base.server.datagram; import java.io.IOException; +import java.net.DatagramPacket; +import java.net.UnknownHostException; import base.Sender; public class UdpDuplexClient extends UdpMulticastClient implements Sender { + protected int sendPort; + protected Sender sender; - public UdpDuplexClient(int port) { - super(port); - } + public UdpDuplexClient(int bindPort, String sendHost, int sendPort) throws UnknownHostException { + this(HOST, bindPort, sendHost, sendPort); + } - public void send(byte[] buffer) throws IOException { - // TODO Auto-generated method stub - - } + public UdpDuplexClient(String bindHost, int bindPort, String sendHost, int sendPort) throws UnknownHostException { + this(bindHost, bindPort, sendHost, sendPort, BUFFER_SIZE); + } - protected void input(byte[] buffer) { - // TODO Auto-generated method stub - - } + public UdpDuplexClient(String bindHost, int bindPort, String sendHost, int sendPort, int bufferSize) throws UnknownHostException { + super(bindHost, bindPort, bufferSize); + this.sendPort = sendPort; + if (sendHost != null) { + sender = new UdpSender(sendHost, sendPort); + } + } + + public void work() { + try { + byte[] buffer = new byte[bufferSize]; + DatagramPacket packet = new DatagramPacket(buffer, buffer.length); + socket.receive(packet); + buffer = packet.getData(); + System.out.println("Receive from " + packet.getAddress().getHostAddress()); + if (sender == null) { + String sendHost = packet.getAddress().getHostAddress(); + sender = new UdpSender(sendHost, sendPort); + } + input(buffer); + } catch (IOException e) {} + } + + public void send(byte[] buffer) throws IOException { + if (sender != null) { + sender.send(buffer); + } + } + + public void input(byte[] buffer) {} } diff --git a/java/base/src/main/java/base/server/datagram/UdpDuplexHelper.java b/java/base/src/main/java/base/server/datagram/UdpDuplexHelper.java new file mode 100644 index 0000000..a2c5267 --- /dev/null +++ b/java/base/src/main/java/base/server/datagram/UdpDuplexHelper.java @@ -0,0 +1,19 @@ +package base.server.datagram; + +import java.net.MulticastSocket; + +import base.work.Listen; + +public class UdpDuplexHelper extends AbstractUdpClient { + protected Listen listen; + + public UdpDuplexHelper(Listen listen, MulticastSocket socket) { + super(socket); + this.listen = listen; + } + + public void input(byte[] buffer) { + System.out.println("jajajaja"); + listen.add(buffer); + } +} diff --git a/java/base/src/main/java/base/server/datagram/UdpDuplexServer.java b/java/base/src/main/java/base/server/datagram/UdpDuplexServer.java index bfa1267..cd5d6d9 100644 --- a/java/base/src/main/java/base/server/datagram/UdpDuplexServer.java +++ b/java/base/src/main/java/base/server/datagram/UdpDuplexServer.java @@ -1,9 +1,59 @@ package base.server.datagram; +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; + +import base.exception.worker.ActivateException; +import base.exception.worker.DeactivateException; + public class UdpDuplexServer extends UdpMulticastServer { + protected int bindPort; + protected UdpDuplexHelper helper; - public UdpDuplexServer(int port) { - super(port); - } + public UdpDuplexServer(int sendPort, int bindPort) { + super(sendPort); + this.bindPort = bindPort; + } + public void activate() throws ActivateException { + try { + socket = new MulticastSocket(bindPort); + synchronized (this) { + notifyAll(); + } + helper = new UdpDuplexHelper(this, socket); + helper.start(); + } catch (IOException e) { + throw new ActivateException(); + } + super.activate(); + } + + public void deactivate() throws DeactivateException { + helper.stop(); + super.deactivate(); + } + + public void send(byte[] buffer) throws IOException { + if (socket == null) { + synchronized (this) { + try { + wait(); + } catch (InterruptedException e) { + return; + } + } + } + try { + InetAddress group = InetAddress.getByName(host); + System.out.println("Send to " + host + " " + port); + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port); + socket.send(packet); + } + catch (IOException e) { + logger.error("", e); + } + } } diff --git a/java/base/src/main/java/base/server/datagram/UdpMulticastClient.java b/java/base/src/main/java/base/server/datagram/UdpMulticastClient.java index bcec5d4..f8ced26 100644 --- a/java/base/src/main/java/base/server/datagram/UdpMulticastClient.java +++ b/java/base/src/main/java/base/server/datagram/UdpMulticastClient.java @@ -1,62 +1,42 @@ package base.server.datagram; import java.io.IOException; -import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import base.exception.worker.ActivateException; -import base.work.Work; -public abstract class UdpMulticastClient extends Work { - protected static final String HOST = "239.255.255.255"; - protected static final int BUFFER_SIZE = 2048; +public class UdpMulticastClient extends AbstractUdpClient { + protected static final String HOST = "239.255.255.255"; - protected String host; - protected int port; - protected int bufferSize; - protected MulticastSocket socket; - protected InetAddress group; + protected String host; + protected int port; - public UdpMulticastClient(int port) { - this(HOST, port); - } + public UdpMulticastClient(int port) { + this(HOST, port); + } - public UdpMulticastClient(String host, int port) { - this(host, port, BUFFER_SIZE); - } + public UdpMulticastClient(String host, int port) { + this(host, port, BUFFER_SIZE); + } - public UdpMulticastClient(String host, int port, int bufferSize) { - this.host = host; - this.port = port; - this.bufferSize = BUFFER_SIZE; - } + public UdpMulticastClient(String host, int port, int bufferSize) { + this.host = host; + this.port = port; + this.bufferSize = BUFFER_SIZE; + System.out.println("Client bind: " + host + " " + port); + } - public void work() { - try { - byte[] buffer = new byte[bufferSize]; - DatagramPacket packet = new DatagramPacket(buffer, buffer.length); - socket.receive(packet); - buffer = packet.getData(); - input(buffer); - } catch (IOException e) {} - } + public void activate() throws ActivateException { + try { + socket = new MulticastSocket(port); + InetAddress group = InetAddress.getByName(host); + socket.joinGroup(group); + } catch (IOException e) { + logger.error("", e); + throw new ActivateException(); + } + } - public void activate() throws ActivateException { - try { - socket = new MulticastSocket(port); - group = InetAddress.getByName(host); - socket.joinGroup(group); - } catch (IOException e) { - logger.error("", e); - throw new ActivateException(); - } - } - - public void stop() { - socket.close(); - super.stop(); - } - - protected abstract void input(byte[] buffer); + protected void input(byte[] buffer) {} } diff --git a/java/base/src/main/java/base/server/datagram/UdpMulticastServer.java b/java/base/src/main/java/base/server/datagram/UdpMulticastServer.java index 2510507..621d1b9 100644 --- a/java/base/src/main/java/base/server/datagram/UdpMulticastServer.java +++ b/java/base/src/main/java/base/server/datagram/UdpMulticastServer.java @@ -12,47 +12,39 @@ import base.work.Listen; import base.worker.Worker; public class UdpMulticastServer extends Listen implements Sender { - protected static final String HOST = "239.255.255.255"; + protected static final String HOST = "239.255.255.255"; protected static final int BUFFER_SIZE = 2048; - protected String host; - protected int port; - protected MulticastSocket socket; - //private XX x; + protected String host; + protected int port; + protected MulticastSocket socket; - public UdpMulticastServer(int port) { - this(HOST, port); - } + public UdpMulticastServer(int port) { + this(HOST, port); + } - public UdpMulticastServer(String host, int port) { - super(Worker.Type.BACKGROUND); - this.host = host; - this.port = port; - } + public UdpMulticastServer(String host, int port) { + super(Worker.Type.BACKGROUND); + this.host = host; + this.port = port; + System.out.println("Server send: " + host + " " + port); + } - public void activate() throws ActivateException { - try { - socket = new MulticastSocket(); // optional, add port and receive as well!! - // pass socket directly to Server to establish bidirectional - // couple together capabilities - // listen to datagrams and deal with writing using nio? - //x = new XX(socket); - //x.start(); - } catch (IOException e) { - throw new ActivateException(); - } - super.activate(); - } + public void activate() throws ActivateException { + try { + socket = new MulticastSocket(); + } catch (IOException e) { + throw new ActivateException(); + } + super.activate(); + } - public void deactivate() throws DeactivateException { - socket.close(); - super.deactivate(); - } + public void deactivate() throws DeactivateException { + socket.close(); + super.deactivate(); + } - public void input(byte[] buffer) { - if (socket == null) { - return; - } + public void input(byte[] buffer) { try { InetAddress group = InetAddress.getByName(host); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port); @@ -60,10 +52,10 @@ public class UdpMulticastServer extends Listen implements Sender { } catch (IOException e) { logger.error("", e); - } - } + } + } - public void send(byte[] buffer) throws IOException { - add(buffer); - } + public void send(byte[] buffer) throws IOException { + add(buffer); + } } diff --git a/java/base/src/main/java/base/server/datagram/UdpSender.java b/java/base/src/main/java/base/server/datagram/UdpSender.java index e3e6118..afb5802 100644 --- a/java/base/src/main/java/base/server/datagram/UdpSender.java +++ b/java/base/src/main/java/base/server/datagram/UdpSender.java @@ -13,51 +13,44 @@ import org.slf4j.LoggerFactory; import base.Sender; public class UdpSender implements Sender { - protected static final String HOST = "localhost"; - protected Logger logger = LoggerFactory.getLogger(getClass()); + protected static final String HOST = "localhost"; + protected Logger logger = LoggerFactory.getLogger(getClass()); - protected DatagramSocket datagramSocket; - protected InetAddress inetAddress; - protected int port; + protected DatagramSocket datagramSocket; + protected InetAddress inetAddress; + protected int port; - public UdpSender(int port) throws UnknownHostException { - this(HOST, port); - } + public UdpSender(int port) throws UnknownHostException { + this(HOST, port); + } - public UdpSender(String host, int port) throws UnknownHostException{ - inetAddress = InetAddress.getByName(host); - logger.debug(host); - logger.debug(String.valueOf(port)); - this.port = port; - } + public UdpSender(String host, int port) throws UnknownHostException { + System.out.println("Sender use: " + host + " " + port); + inetAddress = InetAddress.getByName(host); + this.port = port; + try { + datagramSocket = new DatagramSocket(); + } catch (SocketException e) { + logger.error("Failed to create socket", e); + } + } - public void start() { - if (datagramSocket == null) { - try { - datagramSocket = new DatagramSocket(); - } catch (SocketException e) { - logger.error("Failed to create socket", e); - } - } - } + public void start() {} - public void stop() { - if (datagramSocket != null) { - datagramSocket.close(); - } - } + public void stop() { + datagramSocket.close(); + } - public void exit() { - stop(); - } - - public void send(byte[] buffer) { - try { - DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length, inetAddress, port); - datagramSocket.send(datagramPacket); - } catch (IOException e) { - logger.error("Failed to send buffer", e); - } - } + public void exit() { + stop(); + } + public void send(byte[] buffer) { + try { + DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length, inetAddress, port); + datagramSocket.send(datagramPacket); + } catch (IOException e) { + logger.error("Failed to send buffer", e); + } + } } diff --git a/java/base/src/main/java/base/server/datagram/UdpServer.java b/java/base/src/main/java/base/server/datagram/UdpServer.java index 2367f1a..2ebe303 100644 --- a/java/base/src/main/java/base/server/datagram/UdpServer.java +++ b/java/base/src/main/java/base/server/datagram/UdpServer.java @@ -9,56 +9,56 @@ import base.exception.worker.ActivateException; import base.work.Work; public class UdpServer extends Work { - protected static final int BUFFER_SIZE = 1024; - protected static final int TIMEOUT = 1000; + protected static final int BUFFER_SIZE = 1024; + protected static final int TIMEOUT = 1000; - protected int port; - protected int bufferSize; - protected DatagramSocket diagramSocket; + protected int port; + protected int bufferSize; + protected DatagramSocket diagramSocket; - public UdpServer(int port) { - this(port, BUFFER_SIZE); - } + public UdpServer(int port) { + this(port, BUFFER_SIZE); + } - public UdpServer(int port, int bufferSize) { - super(); - this.port = port; - this.bufferSize = bufferSize; - } + public UdpServer(int port, int bufferSize) { + super(); + this.port = port; + this.bufferSize = bufferSize; + } - public void activate() throws ActivateException { - try { - logger.debug("Starting datagram socket on port " + port); - diagramSocket = new DatagramSocket(port); - diagramSocket.setSoTimeout(TIMEOUT); - super.activate(); - } catch (SocketException e) { - logger.error("Failed to initialize socket", e); - throw new ActivateException(); - } - } + public void activate() throws ActivateException { + try { + logger.debug("Starting datagram socket on port " + port); + diagramSocket = new DatagramSocket(port); + diagramSocket.setSoTimeout(TIMEOUT); + super.activate(); + } catch (SocketException e) { + logger.error("Failed to initialize socket", e); + throw new ActivateException(); + } + } - public void stop() { - super.stop(); - if (diagramSocket != null) { - diagramSocket.close(); - } - } + public void stop() { + super.stop(); + if (diagramSocket != null) { + diagramSocket.close(); + } + } - public void work() { - byte[] buffer = new byte[bufferSize]; - DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length); - try { - diagramSocket.receive(datagramPacket); - } catch (SocketException e) { - stop(); - } catch (IOException e) { - logger.error("Failed to receive packet", e); - stop(); - return; - } - input(buffer); - } + public void work() { + byte[] buffer = new byte[bufferSize]; + DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length); + try { + diagramSocket.receive(datagramPacket); + } catch (SocketException e) { + stop(); + } catch (IOException e) { + logger.error("Failed to receive packet", e); + stop(); + return; + } + input(buffer); + } - protected void input(byte[] buffer) {} + protected void input(byte[] buffer) {} } diff --git a/java/base/src/main/java/base/server/datagram/XX.java b/java/base/src/main/java/base/server/datagram/XX.java deleted file mode 100644 index 8832363..0000000 --- a/java/base/src/main/java/base/server/datagram/XX.java +++ /dev/null @@ -1,37 +0,0 @@ -package base.server.datagram; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.MulticastSocket; - -import base.work.Work; - -public class XX extends Work { - - protected int bufferSize = 1024; - private MulticastSocket socket; - private DatagramPacket dgram; - - public XX(MulticastSocket socket) { - this.socket = socket; - byte[] b = new byte[1024]; - dgram = new DatagramPacket(b, b.length); - } - - - public void work() { - try { - socket.receive(dgram); - } catch (IOException e) { - stop(); - } // blocks until a datagram is received - System.err.println("Received " + dgram.getLength() + - " bytes from " + dgram.getAddress()); - dgram.setLength(bufferSize); // must reset length field! - } - - public void stop() { - super.stop(); - socket.close(); - } -} diff --git a/java/base/src/main/java/base/server/forwarder/TcpChannelServerForwarder.java b/java/base/src/main/java/base/server/forwarder/TcpChannelServerForwarder.java index a21c08b..e118225 100644 --- a/java/base/src/main/java/base/server/forwarder/TcpChannelServerForwarder.java +++ b/java/base/src/main/java/base/server/forwarder/TcpChannelServerForwarder.java @@ -8,24 +8,24 @@ import base.server.channel.TcpServer; import base.server.channel.TcpServerClient; public class TcpChannelServerForwarder extends TcpServer implements Duplex { - protected ArrayList receiverList; + protected ArrayList receiverList; - public TcpChannelServerForwarder(int port) { - super(port); - receiverList = new ArrayList(); - } + public TcpChannelServerForwarder(int port) { + super(port); + receiverList = new ArrayList(); + } - public void register(Receiver receiver) { - receiverList.add(receiver); - } + public void register(Receiver receiver) { + receiverList.add(receiver); + } - public void remove(Receiver receiver) { - receiverList.remove(receiver); - } + public void remove(Receiver receiver) { + receiverList.remove(receiver); + } - public void input(TcpServerClient client, byte[] buffer) { - for (Receiver receiver: receiverList) { - receiver.receive(buffer); - } - } + public void input(TcpServerClient client, byte[] buffer) { + for (Receiver receiver: receiverList) { + receiver.receive(buffer); + } + } } diff --git a/java/base/src/main/java/base/server/forwarder/TcpClientChannelForwarder.java b/java/base/src/main/java/base/server/forwarder/TcpClientChannelForwarder.java index eb1b54e..35d3f9b 100644 --- a/java/base/src/main/java/base/server/forwarder/TcpClientChannelForwarder.java +++ b/java/base/src/main/java/base/server/forwarder/TcpClientChannelForwarder.java @@ -8,24 +8,24 @@ import base.server.socket.TcpClient; import base.server.socket.TcpServerClient; public class TcpClientChannelForwarder extends TcpClient implements Duplex { - protected ArrayList receiverList; + protected ArrayList receiverList; - public TcpClientChannelForwarder(String host, int port) { - super(host, port); - receiverList = new ArrayList(); - } + public TcpClientChannelForwarder(String host, int port) { + super(host, port); + receiverList = new ArrayList(); + } - public void register(Receiver receiver) { - receiverList.add(receiver); - } + public void register(Receiver receiver) { + receiverList.add(receiver); + } - public void remove(Receiver receiver) { - receiverList.remove(receiver); - } + public void remove(Receiver receiver) { + receiverList.remove(receiver); + } - public void input(TcpServerClient client, byte[] buffer) { - for (Receiver receiver: receiverList) { - receiver.receive(buffer); - } - } + public void input(TcpServerClient client, byte[] buffer) { + for (Receiver receiver: receiverList) { + receiver.receive(buffer); + } + } } diff --git a/java/base/src/main/java/base/server/forwarder/TcpClientSocketForwarder.java b/java/base/src/main/java/base/server/forwarder/TcpClientSocketForwarder.java index 2a60ca0..42cc5f9 100644 --- a/java/base/src/main/java/base/server/forwarder/TcpClientSocketForwarder.java +++ b/java/base/src/main/java/base/server/forwarder/TcpClientSocketForwarder.java @@ -8,24 +8,24 @@ import base.server.channel.TcpClient; import base.server.channel.TcpServerClient; public class TcpClientSocketForwarder extends TcpClient implements Duplex { - protected ArrayList receiverList; + protected ArrayList receiverList; - public TcpClientSocketForwarder(String host, int port) { - super(host, port); - receiverList = new ArrayList(); - } + public TcpClientSocketForwarder(String host, int port) { + super(host, port); + receiverList = new ArrayList(); + } - public void register(Receiver receiver) { - receiverList.add(receiver); - } + public void register(Receiver receiver) { + receiverList.add(receiver); + } - public void remove(Receiver receiver) { - receiverList.remove(receiver); - } + public void remove(Receiver receiver) { + receiverList.remove(receiver); + } - public void input(TcpServerClient client, byte[] buffer) { - for (Receiver receiver: receiverList) { - receiver.receive(buffer); - } - } + public void input(TcpServerClient client, byte[] buffer) { + for (Receiver receiver: receiverList) { + receiver.receive(buffer); + } + } } diff --git a/java/base/src/main/java/base/server/forwarder/TcpSocketServerForwarder.java b/java/base/src/main/java/base/server/forwarder/TcpSocketServerForwarder.java index 79e8e3b..10d4bfb 100644 --- a/java/base/src/main/java/base/server/forwarder/TcpSocketServerForwarder.java +++ b/java/base/src/main/java/base/server/forwarder/TcpSocketServerForwarder.java @@ -8,24 +8,24 @@ import base.server.socket.TcpServer; import base.server.socket.TcpServerClient; public class TcpSocketServerForwarder extends TcpServer implements Duplex { - protected ArrayList receiverList; + protected ArrayList receiverList; - public TcpSocketServerForwarder(int port) { - super(port); - receiverList = new ArrayList(); - } + public TcpSocketServerForwarder(int port) { + super(port); + receiverList = new ArrayList(); + } - public void register(Receiver receiver) { - receiverList.add(receiver); - } + public void register(Receiver receiver) { + receiverList.add(receiver); + } - public void remove(Receiver receiver) { - receiverList.remove(receiver); - } + public void remove(Receiver receiver) { + receiverList.remove(receiver); + } - public void input(TcpServerClient client, byte[] buffer) { - for (Receiver receiver: receiverList) { - receiver.receive(buffer); - } - } + public void input(TcpServerClient client, byte[] buffer) { + for (Receiver receiver: receiverList) { + receiver.receive(buffer); + } + } } diff --git a/java/base/src/main/java/base/server/forwarder/UdpDuplexClientForwarder.java b/java/base/src/main/java/base/server/forwarder/UdpDuplexClientForwarder.java index 81d80ec..01ee002 100644 --- a/java/base/src/main/java/base/server/forwarder/UdpDuplexClientForwarder.java +++ b/java/base/src/main/java/base/server/forwarder/UdpDuplexClientForwarder.java @@ -1,5 +1,6 @@ package base.server.forwarder; +import java.net.UnknownHostException; import java.util.ArrayList; import base.Duplex; @@ -7,24 +8,24 @@ import base.Receiver; import base.server.datagram.UdpDuplexClient; public class UdpDuplexClientForwarder extends UdpDuplexClient implements Duplex { - protected ArrayList receiverList; + protected ArrayList receiverList; - public UdpDuplexClientForwarder(String host, int port) { - super(port); - receiverList = new ArrayList(); - } + public UdpDuplexClientForwarder(String bindHost, int bindPort, String sendHost, int sendPort) throws UnknownHostException { + super(bindHost, bindPort, sendHost, sendPort); + receiverList = new ArrayList(); + } - public void register(Receiver receiver) { - receiverList.add(receiver); - } + public void register(Receiver receiver) { + receiverList.add(receiver); + } - public void remove(Receiver receiver) { - receiverList.remove(receiver); - } + public void remove(Receiver receiver) { + receiverList.remove(receiver); + } - public void input(byte[] buffer) { - for (Receiver receiver: receiverList) { - receiver.receive(buffer); - } - } + public void input(byte[] buffer) { + for (Receiver receiver: receiverList) { + receiver.receive(buffer); + } + } } diff --git a/java/base/src/main/java/base/server/forwarder/UdpDuplexServerForwarder.java b/java/base/src/main/java/base/server/forwarder/UdpDuplexServerForwarder.java index 24f7c13..57afc3b 100644 --- a/java/base/src/main/java/base/server/forwarder/UdpDuplexServerForwarder.java +++ b/java/base/src/main/java/base/server/forwarder/UdpDuplexServerForwarder.java @@ -7,24 +7,24 @@ import base.Receiver; import base.server.datagram.UdpDuplexServer; public class UdpDuplexServerForwarder extends UdpDuplexServer implements Duplex { - protected ArrayList receiverList; + protected ArrayList receiverList; - public UdpDuplexServerForwarder(int port) { - super(port); - receiverList = new ArrayList(); - } + public UdpDuplexServerForwarder(int port, int listenPort) { + super(port, listenPort); + receiverList = new ArrayList(); + } - public void register(Receiver receiver) { - receiverList.add(receiver); - } + public void register(Receiver receiver) { + receiverList.add(receiver); + } - public void remove(Receiver receiver) { - receiverList.remove(receiver); - } + public void remove(Receiver receiver) { + receiverList.remove(receiver); + } - public void input(byte[] buffer) { - for (Receiver receiver: receiverList) { - receiver.receive(buffer); - } - } + public void input(byte[] buffer) { + for (Receiver receiver: receiverList) { + receiver.receive(buffer); + } + } } diff --git a/java/base/src/main/java/base/server/forwarder/UdpServerForwarder.java b/java/base/src/main/java/base/server/forwarder/UdpServerForwarder.java index fa8e63c..5359b88 100644 --- a/java/base/src/main/java/base/server/forwarder/UdpServerForwarder.java +++ b/java/base/src/main/java/base/server/forwarder/UdpServerForwarder.java @@ -7,24 +7,24 @@ import base.Receiver; import base.server.datagram.UdpServer; public class UdpServerForwarder extends UdpServer implements Forwarder { - protected ArrayList receiverList; + protected ArrayList receiverList; - public UdpServerForwarder(int port) { - super(port); - receiverList = new ArrayList(); - } + public UdpServerForwarder(int port) { + super(port); + receiverList = new ArrayList(); + } - public void register(Receiver receiver) { - receiverList.add(receiver); - } + public void register(Receiver receiver) { + receiverList.add(receiver); + } - public void remove(Receiver receiver) { - receiverList.remove(receiver); - } + public void remove(Receiver receiver) { + receiverList.remove(receiver); + } - public void input(byte[] buffer) { - for (Receiver receiver: receiverList) { - receiver.receive(buffer); - } - } + public void input(byte[] buffer) { + for (Receiver receiver: receiverList) { + receiver.receive(buffer); + } + } } diff --git a/java/base/src/main/java/base/server/receiver/AbstractReceiver.java b/java/base/src/main/java/base/server/receiver/AbstractReceiver.java index 4ae2748..e444e30 100644 --- a/java/base/src/main/java/base/server/receiver/AbstractReceiver.java +++ b/java/base/src/main/java/base/server/receiver/AbstractReceiver.java @@ -8,26 +8,26 @@ import base.Forwarder; import base.Receiver; public abstract class AbstractReceiver implements Receiver, Control { - protected Logger logger = LoggerFactory.getLogger(getClass()); + protected Logger logger = LoggerFactory.getLogger(getClass()); - protected Forwarder forwarder; + protected Forwarder forwarder; - public AbstractReceiver(Forwarder forwarder) { - this.forwarder = forwarder; - forwarder.register(this); - } + public AbstractReceiver(Forwarder forwarder) { + this.forwarder = forwarder; + forwarder.register(this); + } - public void start() { - forwarder.start(); - } + public void start() { + forwarder.start(); + } - public void stop() { - forwarder.stop(); - } + public void stop() { + forwarder.stop(); + } - public void exit() { - forwarder.exit(); - } + public void exit() { + forwarder.exit(); + } - abstract public void receive(byte[] buffer); + abstract public void receive(byte[] buffer); } diff --git a/java/base/src/main/java/base/server/socket/AbstractTcpClient.java b/java/base/src/main/java/base/server/socket/AbstractTcpClient.java index e7168ef..36a537e 100644 --- a/java/base/src/main/java/base/server/socket/AbstractTcpClient.java +++ b/java/base/src/main/java/base/server/socket/AbstractTcpClient.java @@ -10,19 +10,19 @@ import base.exception.worker.DeactivateException; import base.work.Work; public abstract class AbstractTcpClient extends Work implements Sender { - protected static final int BUFFER_SIZE = 1024; + protected static final int BUFFER_SIZE = 1024; - protected Object object = new Object(); - protected int bufferSize; + protected Object object = new Object(); + protected int bufferSize; protected Socket socket; protected InputStream inputStream; protected OutputStream outputStream; public AbstractTcpClient(Integer bufferSize) { - this.bufferSize = bufferSize; - } + this.bufferSize = bufferSize; + } - public boolean active() { + public boolean active() { return super.active() && socket.isConnected(); } @@ -37,36 +37,36 @@ public abstract class AbstractTcpClient extends Work implements Sender { } } - public void exit() { - super.exit(); - try { - socket.close(); - } catch (IOException e) { - logger.error("", e); - } - } + public void exit() { + super.exit(); + try { + socket.close(); + } catch (IOException e) { + logger.error("", e); + } + } public void work() { - byte[] buffer = new byte[bufferSize]; - try { - while (inputStream.read(buffer) > 0) { - input(buffer); - } - } catch (IOException e) { - stop(); - } + byte[] buffer = new byte[bufferSize]; + try { + while (inputStream.read(buffer) > 0) { + input(buffer); + } + } catch (IOException e) { + stop(); + } } protected abstract void input(byte[] buffer); - public void send(byte[] buffer) throws IOException { - if (outputStream == null) { - try { - synchronized (object) { - object.wait(); - } - } catch (InterruptedException e) {} - } - outputStream.write(buffer); - } + public void send(byte[] buffer) throws IOException { + if (outputStream == null) { + try { + synchronized (object) { + object.wait(); + } + } catch (InterruptedException e) {} + } + outputStream.write(buffer); + } } diff --git a/java/base/src/main/java/base/server/socket/TcpClient.java b/java/base/src/main/java/base/server/socket/TcpClient.java index 265bcfb..16f97ae 100644 --- a/java/base/src/main/java/base/server/socket/TcpClient.java +++ b/java/base/src/main/java/base/server/socket/TcpClient.java @@ -8,33 +8,33 @@ import base.Sender; import base.exception.worker.ActivateException; public class TcpClient extends AbstractTcpClient implements Sender { - protected static final String HOST = "localhost"; + protected static final String HOST = "localhost"; - protected String host; + protected String host; protected int port; public TcpClient(int port) { - this(HOST, port); - } + this(HOST, port); + } public TcpClient(String host, int port) { - this(host, port, BUFFER_SIZE); + this(host, port, BUFFER_SIZE); } public TcpClient(String host, int port, int bufferSize) { - super(bufferSize); + super(bufferSize); this.host = host; this.port = port; } - public void activate() throws ActivateException { + public void activate() throws ActivateException { try { socket = new Socket(host, port); inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); synchronized (object) { - object.notifyAll(); - } + object.notifyAll(); + } } catch (UnknownHostException e) { logger.error("", e); throw new ActivateException(); @@ -45,5 +45,5 @@ public class TcpClient extends AbstractTcpClient implements Sender { super.activate(); } - protected void input(byte[] buffer) {} + protected void input(byte[] buffer) {} } \ No newline at end of file diff --git a/java/base/src/main/java/base/server/socket/TcpServer.java b/java/base/src/main/java/base/server/socket/TcpServer.java index f023c4f..449cc97 100644 --- a/java/base/src/main/java/base/server/socket/TcpServer.java +++ b/java/base/src/main/java/base/server/socket/TcpServer.java @@ -12,75 +12,75 @@ import base.exception.worker.DeactivateException; import base.work.Work; public class TcpServer extends Work implements Sender { - protected static final Class CLIENT_CLASS = TcpServerClient.class; + protected static final Class CLIENT_CLASS = TcpServerClient.class; - protected int port; - protected ServerSocket serverSocket; - protected Constructor clientConstructor; - protected ArrayList clientList; + protected int port; + protected ServerSocket serverSocket; + protected Constructor clientConstructor; + protected ArrayList clientList; public TcpServer(int port) { - this(port, CLIENT_CLASS); + this(port, CLIENT_CLASS); } - public TcpServer(int port, Class clientClass) { - this.port = port; - try { - clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, Socket.class); - } catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) { - logger.error("Failed to initialise client constructor"); - } - clientList = new ArrayList(); - } + public TcpServer(int port, Class clientClass) { + this.port = port; + try { + clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, Socket.class); + } catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) { + logger.error("Failed to initialise client constructor"); + } + clientList = new ArrayList(); + } - public void activate() throws ActivateException { - try { - serverSocket = new ServerSocket(port); - } catch (IOException e) { - logger.error("", e); - throw new ActivateException(); - } - } + public void activate() throws ActivateException { + try { + serverSocket = new ServerSocket(port); + } catch (IOException e) { + logger.error("", e); + throw new ActivateException(); + } + } - public void deactivate() throws DeactivateException { - for (TcpServerClient client : clientList) { - client.stop(); - } - } + public void deactivate() throws DeactivateException { + for (TcpServerClient client : clientList) { + client.stop(); + } + } - public void exit() { - super.exit(); - try { - serverSocket.close(); - for (TcpServerClient client : clientList) { - client.exit(); - } - } catch (IOException e) { - logger.error("", e); - } - } + public void exit() { + super.exit(); + try { + serverSocket.close(); + for (TcpServerClient client : clientList) { + client.exit(); + } + } catch (IOException e) { + logger.error("", e); + } + } - public void work() { - try { - Socket socket = serverSocket.accept(); - TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socket); - clientList.add(client); - client.start(); - System.out.println("Accepted new connection from client: " + socket); - } catch (IOException e) { - stop(); - } catch (Exception e) { - logger.error("", e); - } - } + public void work() { + try { + Socket socket = serverSocket.accept(); + TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socket); + clientList.add(client); + client.start(); + System.out.println("Accepted new connection from client: " + socket); + } catch (IOException e) { + stop(); + } catch (Exception e) { + logger.error("", e); + } + } - public void send(byte[] buffer) throws IOException { - logger.debug("Number of clients = " + clientList.size()); - for (TcpServerClient client : clientList) { - // Should be dealt with in clients own thread? - client.send(buffer); - } - } + public void send(byte[] buffer) throws IOException { + logger.debug("Number of clients = " + clientList.size()); + for (TcpServerClient client : clientList) { + // Should be dealt with in clients own thread? + client.send(buffer); + } + } - public void input(TcpServerClient client, byte[] buffer) {} + public void input(TcpServerClient client, byte[] buffer) {} } diff --git a/java/base/src/main/java/base/server/socket/TcpServerClient.java b/java/base/src/main/java/base/server/socket/TcpServerClient.java index 3843211..1c3f1c2 100644 --- a/java/base/src/main/java/base/server/socket/TcpServerClient.java +++ b/java/base/src/main/java/base/server/socket/TcpServerClient.java @@ -6,32 +6,32 @@ import java.net.Socket; import base.exception.worker.ActivateException; public class TcpServerClient extends AbstractTcpClient { - private TcpServer server; + private TcpServer server; public TcpServerClient(TcpServer server, Socket socket) { - this(server, socket, BUFFER_SIZE); + this(server, socket, BUFFER_SIZE); } public TcpServerClient(TcpServer server, Socket socket, Integer bufferSize) { - super(bufferSize); - this.server = server; - this.socket = socket; + super(bufferSize); + this.server = server; + this.socket = socket; } public void activate() throws ActivateException { - try { - inputStream = socket.getInputStream(); - outputStream = socket.getOutputStream(); - synchronized (object) { - object.notifyAll(); - } - } catch (IOException e) { - logger.error("", e); - throw new ActivateException(); - } + try { + inputStream = socket.getInputStream(); + outputStream = socket.getOutputStream(); + synchronized (object) { + object.notifyAll(); + } + } catch (IOException e) { + logger.error("", e); + throw new ActivateException(); + } } - public void input(byte[] buffer) { - server.input(this, buffer); - } + public void input(byte[] buffer) { + server.input(this, buffer); + } } diff --git a/java/base/src/main/java/base/util/ArrayCycle.java b/java/base/src/main/java/base/util/ArrayCycle.java index 72df2ac..3de85c7 100644 --- a/java/base/src/main/java/base/util/ArrayCycle.java +++ b/java/base/src/main/java/base/util/ArrayCycle.java @@ -8,7 +8,7 @@ public class ArrayCycle extends CopyOnWriteArrayList { protected int index = 0; @SuppressWarnings("unchecked") - public ArrayCycle(E... elementArray) { + public ArrayCycle(E... elementArray) { if (elementArray != null) { for (E element : elementArray) { add(element); diff --git a/java/base/src/main/java/base/util/Buffer.java b/java/base/src/main/java/base/util/Buffer.java index 31c890c..c210967 100644 --- a/java/base/src/main/java/base/util/Buffer.java +++ b/java/base/src/main/java/base/util/Buffer.java @@ -1,41 +1,41 @@ package base.util; public class Buffer { - protected byte[] elements; - protected int capacity; - protected int index; - protected int size; + protected byte[] elements; + protected int capacity; + protected int index; + protected int size; - public Buffer(int capacity) { - this.elements = new byte[capacity]; - this.capacity = capacity; - index = 0; - size = 0; - } + public Buffer(int capacity) { + this.elements = new byte[capacity]; + this.capacity = capacity; + index = 0; + size = 0; + } - public synchronized void add(byte... elements) { - for (byte element : elements) { - this.elements[index++ % capacity] = element; - if (size < capacity) { - ++size; - } - } - } + public synchronized void add(byte... elements) { + for (byte element : elements) { + this.elements[index++ % capacity] = element; + if (size < capacity) { + ++size; + } + } + } - public synchronized void write(byte[] elements, int offset, int length) { - for (int i = offset; i < length; ++i) { - this.elements[index++ % capacity] = elements[i]; - if (size < capacity) { - ++size; - } - } - } + public synchronized void write(byte[] elements, int offset, int length) { + for (int i = offset; i < length; ++i) { + this.elements[index++ % capacity] = elements[i]; + if (size < capacity) { + ++size; + } + } + } - public synchronized byte[] get() { - byte[] elements = new byte[size]; - for (int i = 0; i < size; i++) { - elements[i] = this.elements[(index + i) % size]; - } - return elements; - } + public synchronized byte[] get() { + byte[] elements = new byte[size]; + for (int i = 0; i < size; i++) { + elements[i] = this.elements[(index + i) % size]; + } + return elements; + } } diff --git a/java/base/src/main/java/base/util/Bufferable.java b/java/base/src/main/java/base/util/Bufferable.java index 5249edf..0479817 100644 --- a/java/base/src/main/java/base/util/Bufferable.java +++ b/java/base/src/main/java/base/util/Bufferable.java @@ -1,6 +1,6 @@ package base.util; public interface Bufferable { - public void load(); - public void unload(); + public void load(); + public void unload(); } diff --git a/java/base/src/main/java/base/util/BufferedArrayCycle.java b/java/base/src/main/java/base/util/BufferedArrayCycle.java index 589bd09..0bcc11b 100644 --- a/java/base/src/main/java/base/util/BufferedArrayCycle.java +++ b/java/base/src/main/java/base/util/BufferedArrayCycle.java @@ -1,37 +1,37 @@ package base.util; public class BufferedArrayCycle extends ArrayCycle { - protected static final long serialVersionUID = 1L; + protected static final long serialVersionUID = 1L; - protected ArrayCycle buffer; - protected int before; - protected int after; - protected int indexFirst; - protected int indexLast; - //protected int indexBuffer; - //protected Bufferable[] bufferableArray; + protected ArrayCycle buffer; + protected int before; + protected int after; + protected int indexFirst; + protected int indexLast; + //protected int indexBuffer; + //protected Bufferable[] bufferableArray; - @SuppressWarnings("unchecked") - public BufferedArrayCycle(int before, int after) { - this.before = before; - this.after = after; - indexFirst = 0; - indexLast = 0; - //bufferableArray = new Bufferable[before + after + 1]; - //buffer = new ArrayCycle(); - - } + @SuppressWarnings("unchecked") + public BufferedArrayCycle(int before, int after) { + this.before = before; + this.after = after; + indexFirst = 0; + indexLast = 0; + //bufferableArray = new Bufferable[before + after + 1]; + //buffer = new ArrayCycle(); + + } public E previous() { - get(indexFirst).unload(); + get(indexFirst).unload(); indexFirst = previous(indexFirst); indexLast = previous(indexLast); get(indexLast).load(); // eerste before weg - // eerste after wordt huidig - - // voeg laatste after toe + // eerste after wordt huidig + + // voeg laatste after toe return current(); } @@ -40,35 +40,35 @@ public class BufferedArrayCycle extends ArrayCycle { // eerste before weg - // eerste after wordt huidig - - // voeg laatste after toe - + // eerste after wordt huidig + + // voeg laatste after toe + return size() == 0 ? null : get(index); } protected int previous(int index) { if (--index < 0) { - index = Math.max(0, size() - 1); + index = Math.max(0, size() - 1); } return index; } protected int next(int index) { - System.out.println(index); + System.out.println(index); if (++index >= size()) { - index = 0; + index = 0; } return index; } - public static void main(String[] args) { - BufferedArrayCycle bac = new BufferedArrayCycle(2, 3); - for (int i = 1; i <= 10; ++i) { - bac.add(new Dummy(i)); - } - bac.remove(0); - System.out.println(bac.get(2).id); - } + public static void main(String[] args) { + BufferedArrayCycle bac = new BufferedArrayCycle(2, 3); + for (int i = 1; i <= 10; ++i) { + bac.add(new Dummy(i)); + } + bac.remove(0); + System.out.println(bac.get(2).id); + } } \ No newline at end of file diff --git a/java/base/src/main/java/base/util/Dummy.java b/java/base/src/main/java/base/util/Dummy.java index e23ec10..911a4ee 100644 --- a/java/base/src/main/java/base/util/Dummy.java +++ b/java/base/src/main/java/base/util/Dummy.java @@ -1,18 +1,18 @@ package base.util; public class Dummy implements Bufferable { - public int id; - - public Dummy(int id) { - this.id = id; - } + public int id; + + public Dummy(int id) { + this.id = id; + } - public void load() { - System.out.println("Dummy #" + id + ": load()"); - } + public void load() { + System.out.println("Dummy #" + id + ": load()"); + } - public void unload() { - System.out.println("Dummy #" + id + ": load()"); - } + public void unload() { + System.out.println("Dummy #" + id + ": load()"); + } } diff --git a/java/base/src/main/java/base/work/Listen.java b/java/base/src/main/java/base/work/Listen.java index a6692fb..c323c4c 100644 --- a/java/base/src/main/java/base/work/Listen.java +++ b/java/base/src/main/java/base/work/Listen.java @@ -15,95 +15,94 @@ import base.worker.pool.ListenerPool; import base.worker.pool.PooledListener; public abstract class Listen extends Work implements Listener { - protected static final Worker.Type WORKER_TYPE = Worker.Type.DIRECT; + protected static final Worker.Type WORKER_TYPE = Worker.Type.DIRECT; protected Listener listener; protected Worker.Type workerType; public Queue queue; public Listen() { - this(WORKER_TYPE); + this(WORKER_TYPE); } - protected Listen(Worker.Type workerType) { - this.workerType = workerType; - switch (workerType) { - case DIRECT: - return; - case FOREGROUND: - listener = new ForegroundListener(this); - break; - default: - listener = new BackgroundListener(this); - break; - } + protected Listen(Worker.Type workerType) { + this.workerType = workerType; + switch (workerType) { + case DIRECT: + return; + case FOREGROUND: + listener = new ForegroundListener(this); + break; + default: + listener = new BackgroundListener(this); + break; + } queue = new ConcurrentLinkedQueue(); - } + } - protected Listen(Worker worker) { - this.worker = worker; + protected Listen(Worker worker) { + this.worker = worker; queue = new ConcurrentLinkedQueue(); - } + } - protected Listen(ListenerPool listenerPool) { - listener = new PooledListener(this); - listenerPool.add((PooledListener) listener); + protected Listen(ListenerPool listenerPool) { + listener = new PooledListener(this); + listenerPool.add((PooledListener) listener); queue = new ConcurrentLinkedQueue(); - } + } public synchronized void add(E element) { - if (workerType.equals(Worker.Type.DIRECT)) { - input(element); - } else { - listener.add(element); - } + if (workerType.equals(Worker.Type.DIRECT)) { + input(element); + } else { + listener.add(element); + } } public void start() { - if (workerType.equals(Worker.Type.DIRECT)) { - try { - activate(); - } catch (ActivateException e) { - logger.error("Failed to start directly", e); - } - } else { - super.start(); - } + if (workerType.equals(Worker.Type.DIRECT)) { + try { + activate(); + } catch (ActivateException e) { + logger.error("Failed to start directly", e); + } + } else { + super.start(); + } } public void stop() { - super.stop(); - synchronized (this) { - notifyAll(); - } + super.stop(); + synchronized (this) { + notifyAll(); + } } - public void work() { + public void work() { while (!queue.isEmpty()) { - logger.debug("Listen: work() > input"); + logger.debug("Listen: work() > input"); input(queue.poll()); } synchronized (this) { - logger.debug("Listen: work() > wait"); - try { + logger.debug("Listen: work() > wait"); + try { wait(); } catch (InterruptedException e) {} - logger.debug("Listen: work() > notified"); + logger.debug("Listen: work() > notified"); } - } + } - public void input(Object object) { - // This lookup should be cached - MethodType methodType = MethodType.methodType(void.class, object.getClass()); - MethodHandles.Lookup lookup = MethodHandles.lookup(); - MethodHandle methodHandle; - try { - methodHandle = lookup.findVirtual(getClass(), "input", methodType); - methodHandle.invoke(this, object); - } catch (Exception e) { - logger.error("", e); - } catch (Throwable e) { - logger.error("", e); - } - } + public void input(Object object) { + MethodType methodType = MethodType.methodType(void.class, object.getClass()); + MethodHandles.Lookup lookup = MethodHandles.lookup(); + MethodHandle methodHandle; + try { + methodHandle = lookup.findVirtual(getClass(), "input", methodType); + methodHandle.invoke(this, object); + } catch (Exception e) { + logger.error("", e); + } catch (Throwable e) { + logger.error("", e); + } + } } diff --git a/java/base/src/main/java/base/work/Work.java b/java/base/src/main/java/base/work/Work.java index cf3d4ea..2ee9928 100644 --- a/java/base/src/main/java/base/work/Work.java +++ b/java/base/src/main/java/base/work/Work.java @@ -13,61 +13,61 @@ import base.worker.pool.PooledWorker; import base.worker.pool.WorkerPool; public abstract class Work implements Control { - protected static final Worker.Type WORKER_TYPE = Worker.Type.BACKGROUND; + protected static final Worker.Type WORKER_TYPE = Worker.Type.BACKGROUND; protected Logger logger = LoggerFactory.getLogger(getClass()); - protected Worker worker; + protected Worker worker; - protected Work() { - this(WORKER_TYPE); - } + protected Work() { + this(WORKER_TYPE); + } - protected Work(Worker.Type workerType) { - switch (workerType) { - case FOREGROUND: - worker = new DirectWorker(this); - break; - default: - worker = new ThreadWorker(this); - break; - } - } + protected Work(Worker.Type workerType) { + switch (workerType) { + case FOREGROUND: + worker = new DirectWorker(this); + break; + default: + worker = new ThreadWorker(this); + break; + } + } - protected Work(Worker worker) { - this.worker = worker; - } + protected Work(Worker worker) { + this.worker = worker; + } - protected Work(WorkerPool workerPool) { - worker = new PooledWorker(this); - workerPool.add((PooledWorker) worker); - } + protected Work(WorkerPool workerPool) { + worker = new PooledWorker(this); + workerPool.add((PooledWorker) worker); + } - protected void sleep(int time) { - worker.sleep(time); - } + protected void sleep(int time) { + worker.sleep(time); + } - public void start() { - logger.debug("Work: start()"); - worker.start(); - } + public void start() { + logger.debug("Work: start()"); + worker.start(); + } - public void stop() { - logger.debug("Work: stop()"); - worker.stop(); - } + public void stop() { + logger.debug("Work: stop()"); + worker.stop(); + } - public boolean active() { - logger.debug("Work: active()"); - return worker.active(); - } + public boolean active() { + logger.debug("Work: active()"); + return worker.active(); + } - public void exit() { - logger.debug("Work: exit()"); - worker.exit(); - } + public void exit() { + logger.debug("Work: exit()"); + worker.exit(); + } - public void activate() throws ActivateException {} - public void deactivate() throws DeactivateException {} - public abstract void work(); + public void activate() throws ActivateException {} + public void deactivate() throws DeactivateException {} + public abstract void work(); } diff --git a/java/base/src/main/java/base/worker/BackgroundListener.java b/java/base/src/main/java/base/worker/BackgroundListener.java index 2c388b2..f0b1fe2 100644 --- a/java/base/src/main/java/base/worker/BackgroundListener.java +++ b/java/base/src/main/java/base/worker/BackgroundListener.java @@ -4,19 +4,19 @@ import base.work.Listen; import base.worker.pool.Listener; public class BackgroundListener extends ThreadWorker implements Listener { - protected Listen listen; + protected Listen listen; - public BackgroundListener(Listen listen) { - super(listen); - this.listen = listen; - } + public BackgroundListener(Listen listen) { + super(listen); + this.listen = listen; + } - public BackgroundListener(Listen listen, boolean start) { - super(listen); - } + public BackgroundListener(Listen listen, boolean start) { + super(listen); + } - public void add(E element) { - listen.queue.add(element); - listen.notify(); - } + public void add(E element) { + listen.queue.add(element); + listen.notify(); + } } diff --git a/java/base/src/main/java/base/worker/DirectIntervalWorker.java b/java/base/src/main/java/base/worker/DirectIntervalWorker.java index 1bc7dd8..b1f9507 100644 --- a/java/base/src/main/java/base/worker/DirectIntervalWorker.java +++ b/java/base/src/main/java/base/worker/DirectIntervalWorker.java @@ -3,12 +3,12 @@ package base.worker; import base.work.Work; public class DirectIntervalWorker extends ThreadIntervalWorker { - public DirectIntervalWorker(Work work, int interval) { - super(work, false); - this.interval = interval; - } + public DirectIntervalWorker(Work work, int interval) { + super(work, false); + this.interval = interval; + } - public DirectIntervalWorker(IntervalWork intervalWork) { - super(intervalWork); - } + public DirectIntervalWorker(IntervalWork intervalWork) { + super(intervalWork); + } } diff --git a/java/base/src/main/java/base/worker/DirectWorker.java b/java/base/src/main/java/base/worker/DirectWorker.java index bf01b50..e58f529 100644 --- a/java/base/src/main/java/base/worker/DirectWorker.java +++ b/java/base/src/main/java/base/worker/DirectWorker.java @@ -3,7 +3,7 @@ package base.worker; import base.work.Work; public class DirectWorker extends ThreadWorker { - public DirectWorker(Work work) { - super(work, false); - } + public DirectWorker(Work work) { + super(work, false); + } } \ No newline at end of file diff --git a/java/base/src/main/java/base/worker/ForegroundListener.java b/java/base/src/main/java/base/worker/ForegroundListener.java index 79e2f4e..b3696cd 100644 --- a/java/base/src/main/java/base/worker/ForegroundListener.java +++ b/java/base/src/main/java/base/worker/ForegroundListener.java @@ -4,7 +4,7 @@ import base.work.Listen; import base.worker.pool.Listener; public class ForegroundListener extends BackgroundListener implements Listener { - public ForegroundListener(Listen listen) { - super(listen, false); - } + public ForegroundListener(Listen listen) { + super(listen, false); + } } \ No newline at end of file diff --git a/java/base/src/main/java/base/worker/IntervalWork.java b/java/base/src/main/java/base/worker/IntervalWork.java index a365436..fb09f8e 100644 --- a/java/base/src/main/java/base/worker/IntervalWork.java +++ b/java/base/src/main/java/base/worker/IntervalWork.java @@ -3,35 +3,35 @@ package base.worker; import base.work.Work; public abstract class IntervalWork extends Work { - protected IntervalWork() { - this(WORKER_TYPE); - } + protected IntervalWork() { + this(WORKER_TYPE); + } - protected IntervalWork(int interval) { - this(WORKER_TYPE, interval); - } + protected IntervalWork(int interval) { + this(WORKER_TYPE, interval); + } - protected IntervalWork(Worker.Type workerType) { - switch (workerType) { - case FOREGROUND: - worker = new DirectIntervalWorker(this); - break; - default: - case BACKGROUND: - worker = new ThreadIntervalWorker(this); - break; - } - } + protected IntervalWork(Worker.Type workerType) { + switch (workerType) { + case FOREGROUND: + worker = new DirectIntervalWorker(this); + break; + default: + case BACKGROUND: + worker = new ThreadIntervalWorker(this); + break; + } + } - protected IntervalWork(Worker.Type workerType, int interval) { - switch (workerType) { - case FOREGROUND: - worker = new DirectIntervalWorker(this, interval); - break; - default: - case BACKGROUND: - worker = new ThreadIntervalWorker(this, interval); - break; - } - } + protected IntervalWork(Worker.Type workerType, int interval) { + switch (workerType) { + case FOREGROUND: + worker = new DirectIntervalWorker(this, interval); + break; + default: + case BACKGROUND: + worker = new ThreadIntervalWorker(this, interval); + break; + } + } } diff --git a/java/base/src/main/java/base/worker/ThreadIntervalWorker.java b/java/base/src/main/java/base/worker/ThreadIntervalWorker.java index 367cacd..9f41310 100644 --- a/java/base/src/main/java/base/worker/ThreadIntervalWorker.java +++ b/java/base/src/main/java/base/worker/ThreadIntervalWorker.java @@ -6,41 +6,41 @@ import java.util.TimerTask; import base.work.Work; public class ThreadIntervalWorker extends ThreadWorker { - protected static final int INTERVAL = 500; - protected int interval; + protected static final int INTERVAL = 500; + protected int interval; public ThreadIntervalWorker(Work work) { - super(work); - interval = INTERVAL; - } + super(work); + interval = INTERVAL; + } public ThreadIntervalWorker(Work work, boolean thread) { - super(work, thread); - interval = INTERVAL; - } + super(work, thread); + interval = INTERVAL; + } - public ThreadIntervalWorker(Work work, int interval) { - super(work); - this.interval = interval; - } + public ThreadIntervalWorker(Work work, int interval) { + super(work); + this.interval = interval; + } - protected Timer timer; + protected Timer timer; public synchronized void start(boolean thread) { if (!active) { activate = true; timer = new Timer(); timer.schedule(new TimerTask() { - public void run() { - Worker worker = ThreadIntervalWorker.this; - worker.runActivate(); - worker.runDeactivate(); - worker.runWork(); - }}, 0, interval); - active = true; + public void run() { + Worker worker = ThreadIntervalWorker.this; + worker.runActivate(); + worker.runDeactivate(); + worker.runWork(); + }}, 0, interval); + active = true; } if (!thread) { - try { + try { synchronized (this) { wait(); } @@ -52,7 +52,7 @@ public class ThreadIntervalWorker extends ThreadWorker { public synchronized void stop() { if (active) { - timer.cancel(); + timer.cancel(); deactivate = true; run(); notifyAll(); diff --git a/java/base/src/main/java/base/worker/ThreadWorker.java b/java/base/src/main/java/base/worker/ThreadWorker.java index aee836d..5711172 100644 --- a/java/base/src/main/java/base/worker/ThreadWorker.java +++ b/java/base/src/main/java/base/worker/ThreadWorker.java @@ -8,15 +8,15 @@ public class ThreadWorker extends Worker implements Runnable { protected boolean thread = true; public ThreadWorker(Work work, boolean thread) { - this(work); - this.thread = thread; - } + this(work); + this.thread = thread; + } - public ThreadWorker(Work work) { - super(work); - } + public ThreadWorker(Work work) { + super(work); + } - public synchronized void start(boolean thread) { + public synchronized void start(boolean thread) { if (!active) { activate = true; } @@ -30,11 +30,11 @@ public class ThreadWorker extends Worker implements Runnable { run(); } } else { - notifyAll(); + notifyAll(); } } - public synchronized void start() { + public synchronized void start() { start(thread); } diff --git a/java/base/src/main/java/base/worker/Worker.java b/java/base/src/main/java/base/worker/Worker.java index af85571..9dcf368 100644 --- a/java/base/src/main/java/base/worker/Worker.java +++ b/java/base/src/main/java/base/worker/Worker.java @@ -8,9 +8,9 @@ import base.exception.worker.DeactivateException; import base.work.Work; public abstract class Worker { - public enum Type { - DIRECT, FOREGROUND, BACKGROUND, POOLED - } + public enum Type { + DIRECT, FOREGROUND, BACKGROUND, POOLED + } public static final int SLEEP = 100; @@ -23,30 +23,30 @@ public abstract class Worker { protected Work work; - public Worker(Work work) { - this.work = work; - logger = LoggerFactory.getLogger(work.getClass()); - } + public Worker(Work work) { + this.work = work; + logger = LoggerFactory.getLogger(work.getClass()); + } public boolean active() { - logger.debug("Worker: active()"); + logger.debug("Worker: active()"); return deactivate || active; } public final void run() { - logger.debug("Worker: run()"); + logger.debug("Worker: run()"); while (run || deactivate) { - runActivate(); - runDeactivate(); - runWork(); + runActivate(); + runDeactivate(); + runWork(); } } - public void runActivate() { - if (activate && !active) { - logger.debug("Worker: runActivate()"); + public void runActivate() { + if (activate && !active) { + logger.debug("Worker: runActivate()"); try { - work.activate(); + work.activate(); active = true; } catch (ActivateException e) { logger.error("", e); @@ -57,8 +57,8 @@ public abstract class Worker { } public void runDeactivate() { - if (deactivate && active) { - logger.debug("Worker: runDeactivate()"); + if (deactivate && active) { + logger.debug("Worker: runDeactivate()"); try { work.deactivate(); } catch (DeactivateException e) { @@ -72,11 +72,11 @@ public abstract class Worker { public void runWork() { if (active) { - logger.debug("Worker: runWork() > work"); - work.work(); + logger.debug("Worker: runWork() > work"); + work.work(); } else if (run) { try { - logger.debug("Worker: runWork() > wait"); + logger.debug("Worker: runWork() > wait"); synchronized (this) { wait(); } @@ -100,15 +100,15 @@ public abstract class Worker { } } - public abstract void start(); + public abstract void start(); - public void stop() { - logger.debug("Worker: stop()"); + public void stop() { + logger.debug("Worker: stop()"); if (active && !activate) { deactivate = true; } activate = false; - } + } abstract public void exit(); } diff --git a/java/base/src/main/java/base/worker/pool/Listener.java b/java/base/src/main/java/base/worker/pool/Listener.java index 581b695..baf7fdc 100644 --- a/java/base/src/main/java/base/worker/pool/Listener.java +++ b/java/base/src/main/java/base/worker/pool/Listener.java @@ -1,5 +1,5 @@ package base.worker.pool; public interface Listener { - public void add(E element); + public void add(E element); } diff --git a/java/base/src/main/java/base/worker/pool/ListenerPool.java b/java/base/src/main/java/base/worker/pool/ListenerPool.java index 8f9e266..ddc5d31 100644 --- a/java/base/src/main/java/base/worker/pool/ListenerPool.java +++ b/java/base/src/main/java/base/worker/pool/ListenerPool.java @@ -7,32 +7,32 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; public class ListenerPool { - protected int poolSize; - protected BlockingQueue> queue; - protected ExecutorService executorService; + protected int poolSize; + protected BlockingQueue> queue; + protected ExecutorService executorService; - public ListenerPool(int poolSize) { - this.poolSize = poolSize; - queue = new LinkedBlockingQueue>(); - executorService = Executors.newFixedThreadPool(poolSize); - } + public ListenerPool(int poolSize) { + this.poolSize = poolSize; + queue = new LinkedBlockingQueue>(); + executorService = Executors.newFixedThreadPool(poolSize); + } - public PooledListener add(PooledListener listener) { - listener.setPoolQueue(queue); - return listener; - } + public PooledListener add(PooledListener listener) { + listener.setPoolQueue(queue); + return listener; + } - public void start() { - for (int i = 0; i < poolSize; ++i) { - Runnable runnable = new ListenerPoolRunnable(queue, i); - executorService.execute(runnable); - } - } + public void start() { + for (int i = 0; i < poolSize; ++i) { + Runnable runnable = new ListenerPoolRunnable(queue, i); + executorService.execute(runnable); + } + } - public void await() { - try { - executorService.awaitTermination(0, TimeUnit.SECONDS); - } catch (InterruptedException e) {} - } - + public void await() { + try { + executorService.awaitTermination(0, TimeUnit.SECONDS); + } catch (InterruptedException e) {} + } + } diff --git a/java/base/src/main/java/base/worker/pool/ListenerPoolRunnable.java b/java/base/src/main/java/base/worker/pool/ListenerPoolRunnable.java index ab60177..4de651e 100644 --- a/java/base/src/main/java/base/worker/pool/ListenerPoolRunnable.java +++ b/java/base/src/main/java/base/worker/pool/ListenerPoolRunnable.java @@ -3,22 +3,22 @@ package base.worker.pool; import java.util.concurrent.BlockingQueue; class ListenerPoolRunnable implements Runnable { - protected BlockingQueue> queue; - protected int id; + protected BlockingQueue> queue; + protected int id; - public ListenerPoolRunnable(BlockingQueue> queue, int id) { - this.queue = queue; - this.id = id; - } + public ListenerPoolRunnable(BlockingQueue> queue, int id) { + this.queue = queue; + this.id = id; + } - public void run() { - try { - while (true) { - System.out.println("Thread #" + id + " waiting..."); - Wrapper wrapper = queue.take(); - wrapper.deliver(); - Thread.sleep((int) (Math.random() * 1000)); - } - } catch (InterruptedException e) {} - } + public void run() { + try { + while (true) { + System.out.println("Thread #" + id + " waiting..."); + Wrapper wrapper = queue.take(); + wrapper.deliver(); + Thread.sleep((int) (Math.random() * 1000)); + } + } catch (InterruptedException e) {} + } } \ No newline at end of file diff --git a/java/base/src/main/java/base/worker/pool/PooledListener.java b/java/base/src/main/java/base/worker/pool/PooledListener.java index 8b458a1..3d79a8f 100644 --- a/java/base/src/main/java/base/worker/pool/PooledListener.java +++ b/java/base/src/main/java/base/worker/pool/PooledListener.java @@ -5,24 +5,24 @@ import java.util.concurrent.BlockingQueue; import base.work.Listen; public class PooledListener extends PooledWorker implements Listener { - protected BlockingQueue> poolQueue; - protected Listen listen; + protected BlockingQueue> poolQueue; + protected Listen listen; public PooledListener(Listen listen) { - super(listen); - this.listen = listen; - } - - public void setPoolQueue(BlockingQueue> poolQueue) { - this.poolQueue = poolQueue; - } - - public synchronized void add(E element) { - Wrapper wrapper = new Wrapper(this, element); - poolQueue.add(wrapper); + super(listen); + this.listen = listen; } - void input(E element) { - listen.input(element); - } + public void setPoolQueue(BlockingQueue> poolQueue) { + this.poolQueue = poolQueue; + } + + public synchronized void add(E element) { + Wrapper wrapper = new Wrapper(this, element); + poolQueue.add(wrapper); + } + + void input(E element) { + listen.input(element); + } } \ No newline at end of file diff --git a/java/base/src/main/java/base/worker/pool/PooledWorker.java b/java/base/src/main/java/base/worker/pool/PooledWorker.java index e68cc8a..a943835 100644 --- a/java/base/src/main/java/base/worker/pool/PooledWorker.java +++ b/java/base/src/main/java/base/worker/pool/PooledWorker.java @@ -6,44 +6,44 @@ import base.work.Work; import base.worker.Worker; public class PooledWorker extends Worker { - protected BlockingQueue activateQueue; - protected BlockingQueue deactivateQueue; + protected BlockingQueue activateQueue; + protected BlockingQueue deactivateQueue; - public PooledWorker(Work work) { - super(work); - } + public PooledWorker(Work work) { + super(work); + } - public void setActivateQueue(BlockingQueue activateQueue) { - this.activateQueue = activateQueue; - } + public void setActivateQueue(BlockingQueue activateQueue) { + this.activateQueue = activateQueue; + } - public void setDeactivateQueue(BlockingQueue deactivateQueue) { - this.deactivateQueue = deactivateQueue; - } + public void setDeactivateQueue(BlockingQueue deactivateQueue) { + this.deactivateQueue = deactivateQueue; + } - public void start() { + public void start() { if (!active) { activate = true; } if (!run) { run = true; } - try { - deactivateQueue.remove(this); - activateQueue.put(this); - } catch (InterruptedException e) {} - } + try { + deactivateQueue.remove(this); + activateQueue.put(this); + } catch (InterruptedException e) {} + } - public void stop() { - System.out.println("stop!! " + active); + public void stop() { + System.out.println("stop!! " + active); if (active) { deactivate = true; } - activateQueue.remove(this); - deactivateQueue.add(this); - } + activateQueue.remove(this); + deactivateQueue.add(this); + } - public void exit() { - stop(); - } + public void exit() { + stop(); + } } diff --git a/java/base/src/main/java/base/worker/pool/WorkerPool.java b/java/base/src/main/java/base/worker/pool/WorkerPool.java index a8bdb8c..cdd880d 100644 --- a/java/base/src/main/java/base/worker/pool/WorkerPool.java +++ b/java/base/src/main/java/base/worker/pool/WorkerPool.java @@ -9,34 +9,34 @@ import base.util.ArrayCycle; import base.worker.Worker; public class WorkerPool { - protected int poolSize; - protected BlockingQueue activateQueue; - protected BlockingQueue deactivateQueue; - protected ArrayCycle workerCycle; - protected ExecutorService executorService; + protected int poolSize; + protected BlockingQueue activateQueue; + protected BlockingQueue deactivateQueue; + protected ArrayCycle workerCycle; + protected ExecutorService executorService; - public WorkerPool(int poolSize) { - this.poolSize = poolSize; - activateQueue = new LinkedBlockingQueue(); - deactivateQueue = new LinkedBlockingQueue(); - workerCycle = new ArrayCycle(); - executorService = Executors.newFixedThreadPool(poolSize); - } + public WorkerPool(int poolSize) { + this.poolSize = poolSize; + activateQueue = new LinkedBlockingQueue(); + deactivateQueue = new LinkedBlockingQueue(); + workerCycle = new ArrayCycle(); + executorService = Executors.newFixedThreadPool(poolSize); + } - public void start() { - for (int i = 0; i < poolSize; ++i) { - Runnable runnable = new WorkerPoolRunnable(activateQueue, deactivateQueue, workerCycle, i + 1); - executorService.execute(runnable); - } - } + public void start() { + for (int i = 0; i < poolSize; ++i) { + Runnable runnable = new WorkerPoolRunnable(activateQueue, deactivateQueue, workerCycle, i + 1); + executorService.execute(runnable); + } + } - public void stop() { - // Must be graceful - executorService.shutdownNow(); - } + public void stop() { + // Must be graceful + executorService.shutdownNow(); + } - public void add(PooledWorker worker) { - worker.setActivateQueue(activateQueue); - worker.setDeactivateQueue(deactivateQueue); - } + public void add(PooledWorker worker) { + worker.setActivateQueue(activateQueue); + worker.setDeactivateQueue(deactivateQueue); + } } diff --git a/java/base/src/main/java/base/worker/pool/WorkerPoolRunnable.java b/java/base/src/main/java/base/worker/pool/WorkerPoolRunnable.java index 67c1886..a843d5b 100644 --- a/java/base/src/main/java/base/worker/pool/WorkerPoolRunnable.java +++ b/java/base/src/main/java/base/worker/pool/WorkerPoolRunnable.java @@ -6,36 +6,36 @@ import base.util.ArrayCycle; import base.worker.Worker; public class WorkerPoolRunnable implements Runnable { - protected BlockingQueue activateQueue; - protected BlockingQueue deactivateQueue; - protected ArrayCycle workerCycle; - protected int id; + protected BlockingQueue activateQueue; + protected BlockingQueue deactivateQueue; + protected ArrayCycle workerCycle; + protected int id; - public WorkerPoolRunnable(BlockingQueue activateQueue, BlockingQueue deactivateQueue, ArrayCycle workerCycle, int id) { - this.activateQueue = activateQueue; - this.deactivateQueue = deactivateQueue; - this.workerCycle = workerCycle; - this.id = id; - } + public WorkerPoolRunnable(BlockingQueue activateQueue, BlockingQueue deactivateQueue, ArrayCycle workerCycle, int id) { + this.activateQueue = activateQueue; + this.deactivateQueue = deactivateQueue; + this.workerCycle = workerCycle; + this.id = id; + } - public void run() { - while (true) { - if (!deactivateQueue.isEmpty()) { - try { - Worker worker = deactivateQueue.take(); - worker.runDeactivate(); - workerCycle.remove(worker); - } catch (InterruptedException e) {} - } else if (!activateQueue.isEmpty() || workerCycle.isEmpty()) { - try { - Worker worker = activateQueue.take(); - worker.runActivate(); - workerCycle.add(worker); - } catch (InterruptedException e) {} - } else { - Worker worker = workerCycle.next(); - worker.runWork(); - } - } - } + public void run() { + while (true) { + if (!deactivateQueue.isEmpty()) { + try { + Worker worker = deactivateQueue.take(); + worker.runDeactivate(); + workerCycle.remove(worker); + } catch (InterruptedException e) {} + } else if (!activateQueue.isEmpty() || workerCycle.isEmpty()) { + try { + Worker worker = activateQueue.take(); + worker.runActivate(); + workerCycle.add(worker); + } catch (InterruptedException e) {} + } else { + Worker worker = workerCycle.next(); + worker.runWork(); + } + } + } } diff --git a/java/base/src/main/java/base/worker/pool/Wrapper.java b/java/base/src/main/java/base/worker/pool/Wrapper.java index f62ce74..a78dbaa 100644 --- a/java/base/src/main/java/base/worker/pool/Wrapper.java +++ b/java/base/src/main/java/base/worker/pool/Wrapper.java @@ -2,15 +2,15 @@ package base.worker.pool; class Wrapper { - protected PooledListener listener; - protected E element; + protected PooledListener listener; + protected E element; - public Wrapper(PooledListener listener, E element) { - this.listener = listener; - this.element = element; - } + public Wrapper(PooledListener listener, E element) { + this.listener = listener; + this.element = element; + } - public void deliver() { - listener.input(element); - } + public void deliver() { + listener.input(element); + } } \ No newline at end of file diff --git a/java/base/src/test/java/junit/AllTests.java b/java/base/src/test/java/junit/AllTests.java index 3c105e3..d42cc63 100644 --- a/java/base/src/test/java/junit/AllTests.java +++ b/java/base/src/test/java/junit/AllTests.java @@ -6,10 +6,10 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ - TestTcpSocketCommunication.class, - TestTcpChannelCommunication.class, - TestUdpUnicastCommunication.class, - TestUdpMulticastCommunication.class + TestTcpSocketCommunication.class, + TestTcpChannelCommunication.class, + TestUdpUnicastCommunication.class, + TestUdpMulticastCommunication.class }) public class AllTests {} diff --git a/java/base/src/test/java/junit/TestTcpChannelCommunication.java b/java/base/src/test/java/junit/TestTcpChannelCommunication.java index 5492c23..8ab1ba4 100644 --- a/java/base/src/test/java/junit/TestTcpChannelCommunication.java +++ b/java/base/src/test/java/junit/TestTcpChannelCommunication.java @@ -12,83 +12,83 @@ import base.server.channel.TcpServer; import base.server.channel.TcpServerClient; public class TestTcpChannelCommunication { - protected TestTcpServer server; - protected TestTcpClient client; + protected TestTcpServer server; + protected TestTcpClient client; - @Before - public void setUp() throws Exception { - server = new TestTcpServer(1234); - server.start(); - client = new TestTcpClient(1234); - client.start(); - } + @Before + public void setUp() throws Exception { + server = new TestTcpServer(1234); + server.start(); + client = new TestTcpClient(1234); + client.start(); + } - @After - public void tearDown() throws Exception { - client.exit(); - server.exit(); + @After + public void tearDown() throws Exception { + client.exit(); + server.exit(); - // Should add blocking stop and exit to worker - while (client.active() || server.active()) { - Thread.sleep(100); - } - } + // Should add blocking stop and exit to worker + while (client.active() || server.active()) { + Thread.sleep(100); + } + } - @Test - public void testSendClientToServer() throws Exception { - String message = "test"; - client.send(message.getBytes()); - synchronized (server) { - server.wait(2000); - } - byte[] buffer = server.buffer; - assertNotNull("Received input", buffer); - assertEquals("Message intact", message, new String(buffer).trim()); - } + @Test + public void testSendClientToServer() throws Exception { + String message = "test"; + client.send(message.getBytes()); + synchronized (server) { + server.wait(2000); + } + byte[] buffer = server.buffer; + assertNotNull("Received input", buffer); + assertEquals("Message intact", message, new String(buffer).trim()); + } - @Test - public void testSendServerToClient() throws Exception { - // If client can send, connection has been established - client.send("init".getBytes()); + @Test + public void testSendServerToClient() throws Exception { + // If client can send, connection has been established + client.send("init".getBytes()); - String message = "test"; - server.send(message.getBytes()); - synchronized (client) { - client.wait(2000); - } - byte[] buffer = client.buffer; - assertNotNull("Received input", buffer); - assertEquals("Message intact", message, new String(buffer).trim()); - } + String message = "test"; + server.send(message.getBytes()); + synchronized (client) { + client.wait(2000); + } + byte[] buffer = client.buffer; + assertNotNull("Received input", buffer); + assertEquals("Message intact", message, new String(buffer).trim()); + } - class TestTcpServer extends TcpServer { - public byte[] buffer; + class TestTcpServer extends TcpServer { + public byte[] buffer; - public TestTcpServer(int port) { - super(port); - } + public TestTcpServer(int port) { + super(port); + } - public void input(TcpServerClient client, byte[] buffer) { - this.buffer = buffer; - synchronized (this) { - notifyAll(); - } - } - } + public void input(TcpServerClient client, byte[] buffer) { + this.buffer = buffer; + synchronized (this) { + notifyAll(); + } + } + } - class TestTcpClient extends TcpClient { - public byte[] buffer; + class TestTcpClient extends TcpClient { + public byte[] buffer; - public TestTcpClient(int port) { - super(port); - } + public TestTcpClient(int port) { + super(port); + } - protected void input(byte[] buffer) { - this.buffer = buffer; - synchronized (this) { - notifyAll(); - } - } - - } + protected void input(byte[] buffer) { + this.buffer = buffer; + synchronized (this) { + notifyAll(); + } + } + + } } diff --git a/java/base/src/test/java/junit/TestTcpSocketCommunication.java b/java/base/src/test/java/junit/TestTcpSocketCommunication.java index 879b45a..801b86f 100644 --- a/java/base/src/test/java/junit/TestTcpSocketCommunication.java +++ b/java/base/src/test/java/junit/TestTcpSocketCommunication.java @@ -12,82 +12,82 @@ import base.server.socket.TcpServer; import base.server.socket.TcpServerClient; public class TestTcpSocketCommunication { - protected TestTcpServer server; - protected TestTcpClient client; + protected TestTcpServer server; + protected TestTcpClient client; - @Before - public void setUp() throws Exception { - server = new TestTcpServer(1234); - server.start(); - client = new TestTcpClient(1234); - client.start(); - } + @Before + public void setUp() throws Exception { + server = new TestTcpServer(1234); + server.start(); + client = new TestTcpClient(1234); + client.start(); + } - @After - public void tearDown() throws Exception { - client.exit(); - server.exit(); + @After + public void tearDown() throws Exception { + client.exit(); + server.exit(); - // Should add blocking stop and exit to worker - while (client.active() || server.active()) { - Thread.sleep(100); - } - } + // Should add blocking stop and exit to worker + while (client.active() || server.active()) { + Thread.sleep(100); + } + } - @Test - public void testSendClientToServer() throws Exception { - String message = "test"; - client.send(message.getBytes()); - synchronized (server) { - server.wait(2000); - } - byte[] buffer = server.buffer; - assertNotNull("Received input", buffer); - assertEquals("Message intact", message, new String(buffer).trim()); - } + @Test + public void testSendClientToServer() throws Exception { + String message = "test"; + client.send(message.getBytes()); + synchronized (server) { + server.wait(2000); + } + byte[] buffer = server.buffer; + assertNotNull("Received input", buffer); + assertEquals("Message intact", message, new String(buffer).trim()); + } - @Test - public void testSendServerToClient() throws Exception { - // If client can send, connection has been established - client.send("init".getBytes()); + @Test + public void testSendServerToClient() throws Exception { + // If client can send, connection has been established + client.send("init".getBytes()); - String message = "test"; - server.send(message.getBytes()); - synchronized (client) { - client.wait(2000); - } - byte[] buffer = client.buffer; - assertNotNull("Received input", buffer); - assertEquals("Message intact", message, new String(buffer).trim()); - } + String message = "test"; + server.send(message.getBytes()); + synchronized (client) { + client.wait(2000); + } + byte[] buffer = client.buffer; + assertNotNull("Received input", buffer); + assertEquals("Message intact", message, new String(buffer).trim()); + } - class TestTcpServer extends TcpServer { - public byte[] buffer; + class TestTcpServer extends TcpServer { + public byte[] buffer; - public TestTcpServer(int port) { - super(port); - } + public TestTcpServer(int port) { + super(port); + } - public void input(TcpServerClient client, byte[] buffer) { - this.buffer = buffer; - synchronized (this) { - notifyAll(); - } - } - } + public void input(TcpServerClient client, byte[] buffer) { + this.buffer = buffer; + synchronized (this) { + notifyAll(); + } + } + } - class TestTcpClient extends TcpClient { - public byte[] buffer; + class TestTcpClient extends TcpClient { + public byte[] buffer; - public TestTcpClient(int port) { - super(port); - } + public TestTcpClient(int port) { + super(port); + } - protected void input(byte[] buffer) { - this.buffer = buffer; - synchronized (this) { - notifyAll(); - } - } - } + protected void input(byte[] buffer) { + this.buffer = buffer; + synchronized (this) { + notifyAll(); + } + } + } } diff --git a/java/base/src/test/java/junit/TestUdpDuplexCommunication.java b/java/base/src/test/java/junit/TestUdpDuplexCommunication.java new file mode 100644 index 0000000..e406529 --- /dev/null +++ b/java/base/src/test/java/junit/TestUdpDuplexCommunication.java @@ -0,0 +1,96 @@ +package junit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.net.UnknownHostException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import base.server.datagram.UdpDuplexAutoClient; +import base.server.datagram.UdpDuplexServer; + +public class TestUdpDuplexCommunication { + protected TestUdpDuplexServer server; + protected TestUdpDuplexClient client; + + @Before + public void setUp() throws Exception { + server = new TestUdpDuplexServer(1234, 1235); + server.start(); + client = new TestUdpDuplexClient(1234, 1235); + client.start(); + } + + @After + public void tearDown() throws Exception { + client.exit(); + server.exit(); + + // Should add blocking stop and exit to worker + while (client.active() || server.active()) { + Thread.sleep(1000); + } + } + + @Test + public void testServerToClientCommunication() throws Exception { + String message = "test"; + server.send(message.getBytes()); + System.err.println("send"); + synchronized (client) { + client.wait(2000); + } + byte[] buffer = client.buffer; + assertNotNull("Received input", buffer); + assertEquals("Message intact", message, new String(buffer).trim()); + } + + @Test + public void testClientToServerCommunication() throws Exception { + // Let client discover server address + testServerToClientCommunication(); + + String message = "test"; + client.send(message.getBytes()); + System.err.println("send"); + synchronized (server) { + server.wait(2000); + } + byte[] buffer = server.buffer; + assertNotNull("Received input", buffer); + assertEquals("Message intact", message, new String(buffer).trim()); + } + + public class TestUdpDuplexServer extends UdpDuplexServer { + public byte[] buffer; + + public TestUdpDuplexServer(int sendPort, int bindPort) { + super(sendPort, bindPort); + } + + public void input(byte[] buffer) { + this.buffer = buffer; + synchronized (this) { + notifyAll(); + } + } + } + + class TestUdpDuplexClient extends UdpDuplexAutoClient { + public byte[] buffer; + + public TestUdpDuplexClient(int bindPort, int sendPort) throws UnknownHostException { + super(bindPort, sendPort); + } + + public void input(byte[] buffer) { + this.buffer = buffer; + synchronized (this) { + notifyAll(); + } + } + } +} diff --git a/java/base/src/test/java/junit/TestUdpMulticastCommunication.java b/java/base/src/test/java/junit/TestUdpMulticastCommunication.java index b9df364..4088324 100644 --- a/java/base/src/test/java/junit/TestUdpMulticastCommunication.java +++ b/java/base/src/test/java/junit/TestUdpMulticastCommunication.java @@ -11,53 +11,53 @@ import base.server.datagram.UdpMulticastClient; import base.server.datagram.UdpMulticastServer; public class TestUdpMulticastCommunication { - protected UdpMulticastServer server; - protected TestUdpMulticastClient client; + protected UdpMulticastServer server; + protected TestUdpMulticastClient client; - @Before - public void setUp() throws Exception { - server = new UdpMulticastServer(1234); - server.start(); - client = new TestUdpMulticastClient(1234); - client.start(); - } + @Before + public void setUp() throws Exception { + server = new UdpMulticastServer(1234); + server.start(); + client = new TestUdpMulticastClient(1234); + client.start(); + } - @After - public void tearDown() throws Exception { - client.exit(); - server.exit(); + @After + public void tearDown() throws Exception { + client.exit(); + server.exit(); - // Should add blocking stop and exit to worker - while (client.active() || server.active()) { - Thread.sleep(1000); - } - } + // Should add blocking stop and exit to worker + while (client.active() || server.active()) { + Thread.sleep(1000); + } + } - @Test - public void testServerToClientCommunication() throws Exception { - String message = "test"; - server.send(message.getBytes()); - System.err.println("send"); - synchronized (client) { - client.wait(2000); - } - byte[] buffer = client.buffer; - assertNotNull("Received input", buffer); - assertEquals("Message intact", message, new String(buffer).trim()); - } + @Test + public void testServerToClientCommunication() throws Exception { + String message = "test"; + server.send(message.getBytes()); + System.err.println("send"); + synchronized (client) { + client.wait(2000); + } + byte[] buffer = client.buffer; + assertNotNull("Received input", buffer); + assertEquals("Message intact", message, new String(buffer).trim()); + } - class TestUdpMulticastClient extends UdpMulticastClient { - public byte[] buffer; + class TestUdpMulticastClient extends UdpMulticastClient { + public byte[] buffer; - public TestUdpMulticastClient(int port) { - super(port); - } + public TestUdpMulticastClient(int port) { + super(port); + } - protected void input(byte[] buffer) { - this.buffer = buffer; - synchronized (this) { - notifyAll(); - } - } - } + public void input(byte[] buffer) { + this.buffer = buffer; + synchronized (this) { + notifyAll(); + } + } + } } diff --git a/java/base/src/test/java/junit/TestUdpUnicastCommunication.java b/java/base/src/test/java/junit/TestUdpUnicastCommunication.java index 136ef47..35c6596 100644 --- a/java/base/src/test/java/junit/TestUdpUnicastCommunication.java +++ b/java/base/src/test/java/junit/TestUdpUnicastCommunication.java @@ -11,51 +11,51 @@ import base.server.datagram.UdpSender; import base.server.datagram.UdpServer; public class TestUdpUnicastCommunication { - protected TestUdpServer server; - protected UdpSender sender; + protected TestUdpServer server; + protected UdpSender sender; - @Before - public void setUp() throws Exception { - server = new TestUdpServer(1234); - server.start(); - sender = new UdpSender(1234); - } + @Before + public void setUp() throws Exception { + server = new TestUdpServer(1234); + server.start(); + sender = new UdpSender(1234); + } - @After - public void tearDown() throws Exception { - server.exit(); + @After + public void tearDown() throws Exception { + server.exit(); - // Should add blocking stop and exit to worker - while (server.active()) { - Thread.sleep(100); - } - } + // Should add blocking stop and exit to worker + while (server.active()) { + Thread.sleep(100); + } + } - @Test - public void testSendClientToServer() throws Exception { - String message = "test"; - sender.send(message.getBytes()); - synchronized (server) { - server.wait(2000); - } - byte[] buffer = server.buffer; - assertNotNull("Received input", buffer); - assertEquals("Message intact", message, new String(buffer).trim()); - } + @Test + public void testSendClientToServer() throws Exception { + String message = "test"; + sender.send(message.getBytes()); + synchronized (server) { + server.wait(2000); + } + byte[] buffer = server.buffer; + assertNotNull("Received input", buffer); + assertEquals("Message intact", message, new String(buffer).trim()); + } - class TestUdpServer extends UdpServer { - public byte[] buffer; + class TestUdpServer extends UdpServer { + public byte[] buffer; - public TestUdpServer(int port) { - super(port); - } + public TestUdpServer(int port) { + super(port); + } - @Override - protected void input(byte[] buffer) { - this.buffer = buffer; - synchronized (this) { - notifyAll(); - } - } - } + @Override + protected void input(byte[] buffer) { + this.buffer = buffer; + synchronized (this) { + notifyAll(); + } + } + } } diff --git a/java/base/src/test/java/test/Test.java b/java/base/src/test/java/test/Test.java index 1bb755f..7e1b0b8 100644 --- a/java/base/src/test/java/test/Test.java +++ b/java/base/src/test/java/test/Test.java @@ -5,50 +5,50 @@ import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; public class Test { - public static void main(String[] args) { - try { - new Test().start(); - } catch (Throwable e) { - e.printStackTrace(); - } - } + public static void main(String[] args) { + try { + new Test().start(); + } catch (Throwable e) { + e.printStackTrace(); + } + } - private void start() throws Throwable { - input((Object) new A()); - input((Object) new B()); - input((Object) new String[] {"a", "b"}); - } + private void start() throws Throwable { + input((Object) new A()); + input((Object) new B()); + input((Object) new String[] {"a", "b"}); + } - public void input(Object object) throws Throwable { - System.out.println("Object"); - MethodType methodType = MethodType.methodType(void.class, object.getClass()); - MethodHandles.Lookup lookup = MethodHandles.lookup(); - MethodHandle methodHandle = lookup.findVirtual(getClass(), "input", methodType); - try { - methodHandle.invoke(this, object); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - System.exit(1); - } - } + public void input(Object object) throws Throwable { + System.out.println("Object"); + MethodType methodType = MethodType.methodType(void.class, object.getClass()); + MethodHandles.Lookup lookup = MethodHandles.lookup(); + MethodHandle methodHandle = lookup.findVirtual(getClass(), "input", methodType); + try { + methodHandle.invoke(this, object); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + System.exit(1); + } + } - public void input(A object) { - System.out.println("A"); - } + public void input(A object) { + System.out.println("A"); + } - public void input(B object) { - System.out.println("B"); - } + public void input(B object) { + System.out.println("B"); + } - public void input(String[] object) { - System.out.println("String[]"); - } + public void input(String[] object) { + System.out.println("String[]"); + } - public class A { - - } + public class A { + + } - public class B { - - } + public class B { + + } } diff --git a/java/base/src/test/java/worker/TestDirectWork.java b/java/base/src/test/java/worker/TestDirectWork.java index b736f2c..63671d9 100644 --- a/java/base/src/test/java/worker/TestDirectWork.java +++ b/java/base/src/test/java/worker/TestDirectWork.java @@ -4,12 +4,12 @@ import worker.dummy.DummyWork; public class TestDirectWork { - public static void main(String[] args) { - DummyWork work = new DummyWork(1); - work.setWork(100); - work.start(); - try { - Thread.sleep(10000); - } catch (InterruptedException e) {} - } + public static void main(String[] args) { + DummyWork work = new DummyWork(1); + work.setWork(100); + work.start(); + try { + Thread.sleep(10000); + } catch (InterruptedException e) {} + } } diff --git a/java/base/src/test/java/worker/TestIntervalWork.java b/java/base/src/test/java/worker/TestIntervalWork.java index 6ac9f7d..93ad699 100644 --- a/java/base/src/test/java/worker/TestIntervalWork.java +++ b/java/base/src/test/java/worker/TestIntervalWork.java @@ -4,15 +4,15 @@ import worker.dummy.DummyIntervalWork; import base.work.Work; public class TestIntervalWork { - public static void main(String[] args) { - Work work = new DummyIntervalWork(500); - for (int i = 0; i < 10; ++i) { - work.start(); - System.out.println("--"); - try { - Thread.sleep(1000); - } catch (InterruptedException e) {} - work.stop(); - } - } + public static void main(String[] args) { + Work work = new DummyIntervalWork(500); + for (int i = 0; i < 10; ++i) { + work.start(); + System.out.println("--"); + try { + Thread.sleep(1000); + } catch (InterruptedException e) {} + work.stop(); + } + } } diff --git a/java/base/src/test/java/worker/TestListen.java b/java/base/src/test/java/worker/TestListen.java index bbc9ccc..b9728d6 100644 --- a/java/base/src/test/java/worker/TestListen.java +++ b/java/base/src/test/java/worker/TestListen.java @@ -3,17 +3,17 @@ package worker; import worker.dummy.DummyListen; public class TestListen { - public static void main(String[] args) { - DummyListen listen = new DummyListen(0); - listen.start(); - for (int i = 0; i < 10; ++i) { - listen.add(i); - try { - Thread.sleep(1000); - } catch (InterruptedException e) {} - } - try { - Thread.sleep(10000); - } catch (InterruptedException e) {} - } + public static void main(String[] args) { + DummyListen listen = new DummyListen(0); + listen.start(); + for (int i = 0; i < 10; ++i) { + listen.add(i); + try { + Thread.sleep(1000); + } catch (InterruptedException e) {} + } + try { + Thread.sleep(10000); + } catch (InterruptedException e) {} + } } diff --git a/java/base/src/test/java/worker/TestPooledListen.java b/java/base/src/test/java/worker/TestPooledListen.java index 1f88322..32c35a5 100644 --- a/java/base/src/test/java/worker/TestPooledListen.java +++ b/java/base/src/test/java/worker/TestPooledListen.java @@ -8,31 +8,31 @@ import worker.dummy.DummyListen; import base.worker.pool.ListenerPool; public class TestPooledListen { - protected int id; + protected int id; - public TestPooledListen(int id) { - this.id = id; - } + public TestPooledListen(int id) { + this.id = id; + } - public void input(Integer element) { - System.out.println("#" + id + ": " + element); - } + public void input(Integer element) { + System.out.println("#" + id + ": " + element); + } public static void main(String[] args) { - ListenerPool listenerPool = new ListenerPool(5); - List> listenList = new ArrayList>(); - for (int i = 0; i < 20; ++i) { - DummyListen listen = new DummyListen(listenerPool, i + 1); - listenList.add(listen); - } - listenerPool.start(); + ListenerPool listenerPool = new ListenerPool(5); + List> listenList = new ArrayList>(); + for (int i = 0; i < 20; ++i) { + DummyListen listen = new DummyListen(listenerPool, i + 1); + listenList.add(listen); + } + listenerPool.start(); - System.out.println("Starting to give out elements!"); - for (int i = 0; i < 100; ++i) { - DummyListen randomListen = listenList.get((new Random()).nextInt(listenList.size())); - randomListen.add(i); - } + System.out.println("Starting to give out elements!"); + for (int i = 0; i < 100; ++i) { + DummyListen randomListen = listenList.get((new Random()).nextInt(listenList.size())); + randomListen.add(i); + } - //listenerPool.await(); + //listenerPool.await(); } } diff --git a/java/base/src/test/java/worker/TestPooledWork.java b/java/base/src/test/java/worker/TestPooledWork.java index aa932fd..04dd8d1 100644 --- a/java/base/src/test/java/worker/TestPooledWork.java +++ b/java/base/src/test/java/worker/TestPooledWork.java @@ -9,37 +9,37 @@ import base.work.Work; import base.worker.pool.WorkerPool; public class TestPooledWork { - public static void main(String[] args) { - WorkerPool workerPool = new WorkerPool(3); + public static void main(String[] args) { + WorkerPool workerPool = new WorkerPool(3); - List workList = new ArrayList(); - for (int i = 0; i < 10; ++i) { - DummyWork work = new DummyWork(workerPool, i + 1); - workList.add(work); - } - workerPool.start(); + List workList = new ArrayList(); + for (int i = 0; i < 10; ++i) { + DummyWork work = new DummyWork(workerPool, i + 1); + workList.add(work); + } + workerPool.start(); - System.out.println("Starting work!"); - ArrayList activeWorkList = new ArrayList(); - for (int i = 0; i < 8; ++i) { - DummyWork work = workList.get((new Random()).nextInt(workList.size())); - work.setWork(1000); - work.start(); - activeWorkList.add(work); - } - try { - Thread.sleep(2000); - } catch (InterruptedException e) {} - int i = 0; - for (Work work : activeWorkList) { - if (++i > 5) { - break; - } - work.stop(); - } - try { - Thread.sleep(100000); - } catch (InterruptedException e) {} - System.exit(0); - } + System.out.println("Starting work!"); + ArrayList activeWorkList = new ArrayList(); + for (int i = 0; i < 8; ++i) { + DummyWork work = workList.get((new Random()).nextInt(workList.size())); + work.setWork(1000); + work.start(); + activeWorkList.add(work); + } + try { + Thread.sleep(2000); + } catch (InterruptedException e) {} + int i = 0; + for (Work work : activeWorkList) { + if (++i > 5) { + break; + } + work.stop(); + } + try { + Thread.sleep(100000); + } catch (InterruptedException e) {} + System.exit(0); + } } diff --git a/java/base/src/test/java/worker/dummy/DummyIntervalWork.java b/java/base/src/test/java/worker/dummy/DummyIntervalWork.java index 5bc9bba..706fa08 100644 --- a/java/base/src/test/java/worker/dummy/DummyIntervalWork.java +++ b/java/base/src/test/java/worker/dummy/DummyIntervalWork.java @@ -3,11 +3,11 @@ package worker.dummy; import base.worker.IntervalWork; public class DummyIntervalWork extends IntervalWork { - public DummyIntervalWork(int interval) { - super(interval); - } + public DummyIntervalWork(int interval) { + super(interval); + } - public void work() { - System.out.println(":-)"); - } + public void work() { + System.out.println(":-)"); + } } \ No newline at end of file diff --git a/java/base/src/test/java/worker/dummy/DummyListen.java b/java/base/src/test/java/worker/dummy/DummyListen.java index e9822f7..704cd55 100644 --- a/java/base/src/test/java/worker/dummy/DummyListen.java +++ b/java/base/src/test/java/worker/dummy/DummyListen.java @@ -4,23 +4,23 @@ import base.work.Listen; import base.worker.pool.ListenerPool; public class DummyListen extends Listen { - protected int id; + protected int id; - public DummyListen(ListenerPool listenerPool, int id) { - super(listenerPool); - this.id = id; - } + public DummyListen(ListenerPool listenerPool, int id) { + super(listenerPool); + this.id = id; + } - public DummyListen(int id) { - super(); - this.id = id; - } + public DummyListen(int id) { + super(); + this.id = id; + } - public void input(Integer input) { - System.out.println("#" + id + ", input = " + input); - } + public void input(Integer input) { + System.out.println("#" + id + ", input = " + input); + } - public void input(byte[] input) { - System.out.println("#" + id + ", input = " + new String(input).trim()); - } + public void input(byte[] input) { + System.out.println("#" + id + ", input = " + new String(input).trim()); + } } diff --git a/java/base/src/test/java/worker/dummy/DummyWork.java b/java/base/src/test/java/worker/dummy/DummyWork.java index 4dbf7da..e2d9839 100644 --- a/java/base/src/test/java/worker/dummy/DummyWork.java +++ b/java/base/src/test/java/worker/dummy/DummyWork.java @@ -6,37 +6,37 @@ import base.work.Work; import base.worker.pool.WorkerPool; public class DummyWork extends Work { - protected int id; - protected volatile int work; + protected int id; + protected volatile int work; - public DummyWork(int id) { - super(); - this.id = id; - } + public DummyWork(int id) { + super(); + this.id = id; + } - public DummyWork(WorkerPool workerPool, int id) { - super(workerPool); - this.id = id; - } + public DummyWork(WorkerPool workerPool, int id) { + super(workerPool); + this.id = id; + } - public void setWork(int work) { - System.out.println("#" + id + ", set work @ " + work); - this.work = work; - } + public void setWork(int work) { + System.out.println("#" + id + ", set work @ " + work); + this.work = work; + } - public void work() { - System.out.println("#" + id + ", work = " + work); - if (--work < 1) { - stop(); - } - sleep(300); - } + public void work() { + System.out.println("#" + id + ", work = " + work); + if (--work < 1) { + stop(); + } + sleep(300); + } - public void activate() throws ActivateException { - System.out.println("#" + id + ", activating..."); - } + public void activate() throws ActivateException { + System.out.println("#" + id + ", activating..."); + } - public void deactivate() throws DeactivateException { - System.out.println("#" + id + ", deactivating..."); - } + public void deactivate() throws DeactivateException { + System.out.println("#" + id + ", deactivating..."); + } } diff --git a/java/mimis/src/main/java/mimis/Component.java b/java/mimis/src/main/java/mimis/Component.java index e66fcc1..8c6c873 100644 --- a/java/mimis/src/main/java/mimis/Component.java +++ b/java/mimis/src/main/java/mimis/Component.java @@ -41,14 +41,14 @@ public abstract class Component extends Listen { } public Component(Type type) { - super(type); - } + super(type); + } public Component(String title) { this.title = title; } - public void setRouter(Router router) { + public void setRouter(Router router) { this.router = router; } diff --git a/java/mimis/src/main/java/mimis/Main.java b/java/mimis/src/main/java/mimis/Main.java index 89e5096..ae24de0 100644 --- a/java/mimis/src/main/java/mimis/Main.java +++ b/java/mimis/src/main/java/mimis/Main.java @@ -41,21 +41,21 @@ public class Main extends Mimis { } public static Component[] getApplications() { - return getComponents(mimis.application.Application.class); + return getComponents(mimis.application.Application.class); } public static Component[] getDevices() { - return getComponents(mimis.device.Device.class); + return getComponents(mimis.device.Device.class); } public static Component[] getComponents(Class clazz) { - ArrayList componentList = new ArrayList(); - for (Object object : ServiceLoader.load(clazz)) { - if (object instanceof Component) { - componentList.add((Component) object); - } - } - return componentList.toArray(new Component[]{}); + ArrayList componentList = new ArrayList(); + for (Object object : ServiceLoader.load(clazz)) { + if (object instanceof Component) { + componentList.add((Component) object); + } + } + return componentList.toArray(new Component[]{}); } public Main() { @@ -106,8 +106,8 @@ public class Main extends Mimis { case PREVIOUS: applicationManager.currentChanged(); break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/Mimis.java b/java/mimis/src/main/java/mimis/Mimis.java index 8d430a0..4705286 100644 --- a/java/mimis/src/main/java/mimis/Mimis.java +++ b/java/mimis/src/main/java/mimis/Mimis.java @@ -35,7 +35,7 @@ public abstract class Mimis extends Component { protected ArrayCycle componentCycle; public Mimis(Component... currentArray) { - super(Worker.Type.FOREGROUND); + super(Worker.Type.FOREGROUND); this.currentArray = initialize(false, currentArray); componentCycle = new ArrayCycle(currentArray); router = new Router(); @@ -91,8 +91,8 @@ public abstract class Mimis extends Component { case EXIT: exit(); break; - default: - break; + default: + break; } } } \ No newline at end of file diff --git a/java/mimis/src/main/java/mimis/application/cmd/windows/gomplayer/GomPlayerApplication.java b/java/mimis/src/main/java/mimis/application/cmd/windows/gomplayer/GomPlayerApplication.java index 53d43d2..7ed66bc 100644 --- a/java/mimis/src/main/java/mimis/application/cmd/windows/gomplayer/GomPlayerApplication.java +++ b/java/mimis/src/main/java/mimis/application/cmd/windows/gomplayer/GomPlayerApplication.java @@ -73,8 +73,8 @@ public class GomPlayerApplication extends WindowsApplication { case PREVIOUS: seekWork.start(Amount.MEDIUM, -1); break; - default: - break; + default: + break; } } @@ -100,8 +100,8 @@ public class GomPlayerApplication extends WindowsApplication { case FULLSCREEN: command(0x8154); break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/application/cmd/windows/photoviewer/PhotoViewerApplication.java b/java/mimis/src/main/java/mimis/application/cmd/windows/photoviewer/PhotoViewerApplication.java index 99581d7..fea63f7 100644 --- a/java/mimis/src/main/java/mimis/application/cmd/windows/photoviewer/PhotoViewerApplication.java +++ b/java/mimis/src/main/java/mimis/application/cmd/windows/photoviewer/PhotoViewerApplication.java @@ -57,8 +57,8 @@ public class PhotoViewerApplication extends WindowsApplication { case VOLUME_DOWN: zoomWork.start(-1); break; - default: - break; + default: + break; } } @@ -108,8 +108,8 @@ public class PhotoViewerApplication extends WindowsApplication { end(Action.FULLSCREEN); }*/ break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/application/cmd/windows/winamp/WinampApplication.java b/java/mimis/src/main/java/mimis/application/cmd/windows/winamp/WinampApplication.java index fcd266c..5f5ecf7 100644 --- a/java/mimis/src/main/java/mimis/application/cmd/windows/winamp/WinampApplication.java +++ b/java/mimis/src/main/java/mimis/application/cmd/windows/winamp/WinampApplication.java @@ -92,8 +92,8 @@ public class WinampApplication extends WindowsApplication { case REWIND: seekWork.start(-1); break; - default: - break; + default: + break; } } @@ -150,8 +150,8 @@ public class WinampApplication extends WindowsApplication { system(Command.System.MAXIMIZE); command(WINAMP_VISPLUGIN); break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/application/cmd/windows/wmp/WMPApplication.java b/java/mimis/src/main/java/mimis/application/cmd/windows/wmp/WMPApplication.java index 821bfd9..c724af7 100644 --- a/java/mimis/src/main/java/mimis/application/cmd/windows/wmp/WMPApplication.java +++ b/java/mimis/src/main/java/mimis/application/cmd/windows/wmp/WMPApplication.java @@ -66,9 +66,9 @@ public class WMPApplication extends WindowsApplication { break; case REPEAT: command(18843); - break; - default: - break; + break; + default: + break; } } @@ -85,8 +85,8 @@ public class WMPApplication extends WindowsApplication { case VOLUME_DOWN: volumeWork.stop(); break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/application/itunes/iTunesApplication.java b/java/mimis/src/main/java/mimis/application/itunes/iTunesApplication.java index 83b9226..458ce70 100644 --- a/java/mimis/src/main/java/mimis/application/itunes/iTunesApplication.java +++ b/java/mimis/src/main/java/mimis/application/itunes/iTunesApplication.java @@ -108,8 +108,8 @@ public class iTunesApplication extends Component implements Application, iTunesE case VOLUME_DOWN: volumeWork.start(-VOLUME_CHANGE_RATE); break; - default: - break; + default: + break; } } @@ -151,8 +151,8 @@ public class iTunesApplication extends Component implements Application, iTunesE case DISLIKE: iTunes.playlistAddCurrentTrack(PLAYLIST_DISLIKE); break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/application/lirc/ipod/iPodApplication.java b/java/mimis/src/main/java/mimis/application/lirc/ipod/iPodApplication.java index bb69c4f..38b47f2 100644 --- a/java/mimis/src/main/java/mimis/application/lirc/ipod/iPodApplication.java +++ b/java/mimis/src/main/java/mimis/application/lirc/ipod/iPodApplication.java @@ -62,8 +62,8 @@ public class iPodApplication extends LircApplication { logger.error("", e); } break; - default: - break; + default: + break; } } @@ -84,8 +84,8 @@ public class iPodApplication extends LircApplication { case VOLUME_DOWN: volumeWork.stop(); break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/application/mpc/MPCApplication.java b/java/mimis/src/main/java/mimis/application/mpc/MPCApplication.java index 22a2980..41fdfa9 100644 --- a/java/mimis/src/main/java/mimis/application/mpc/MPCApplication.java +++ b/java/mimis/src/main/java/mimis/application/mpc/MPCApplication.java @@ -52,8 +52,8 @@ public class MPCApplication extends WindowsApplication { case VOLUME_DOWN: volumeWork.start(-1); break; - default: - break; + default: + break; } } @@ -83,8 +83,8 @@ public class MPCApplication extends WindowsApplication { case FULLSCREEN: command(830); break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/application/vlc/VLCApplication.java b/java/mimis/src/main/java/mimis/application/vlc/VLCApplication.java index 1f2edfd..4ac3643 100644 --- a/java/mimis/src/main/java/mimis/application/vlc/VLCApplication.java +++ b/java/mimis/src/main/java/mimis/application/vlc/VLCApplication.java @@ -108,8 +108,8 @@ public class VLCApplication extends CMDApplication { case REWIND: seekWorker.start(Amount.SMALL, "-"); break; - default: - break; + default: + break; } } catch (ActivateException e) { logger.error("", e); @@ -148,8 +148,8 @@ public class VLCApplication extends CMDApplication { case REPEAT: command("command=pl_repeat"); break; - default: - break; + default: + break; } } diff --git a/java/mimis/src/main/java/mimis/device/lirc/LircDevice.java b/java/mimis/src/main/java/mimis/device/lirc/LircDevice.java index 1aae55d..16d9b4a 100644 --- a/java/mimis/src/main/java/mimis/device/lirc/LircDevice.java +++ b/java/mimis/src/main/java/mimis/device/lirc/LircDevice.java @@ -105,8 +105,8 @@ public class LircDevice extends CMDApplication implements Device, LircButtonList case END: route(new Release(button)); break; - default: - break; + default: + break; } if (general) { diff --git a/java/mimis/src/main/java/mimis/device/lirc/LircService.java b/java/mimis/src/main/java/mimis/device/lirc/LircService.java index 2131fdd..0defe31 100644 --- a/java/mimis/src/main/java/mimis/device/lirc/LircService.java +++ b/java/mimis/src/main/java/mimis/device/lirc/LircService.java @@ -47,8 +47,8 @@ public class LircService extends TcpClient { protected String send; public static void main(String[] args) { - LircService lircService = new LircService(); - lircService.start(); + LircService lircService = new LircService(); + lircService.start(); } public LircService() { @@ -72,7 +72,7 @@ public class LircService extends TcpClient { public void activate() throws ActivateException { - super.activate(); + super.activate(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); printWriter = new PrintWriter(outputStream); } diff --git a/java/mimis/src/main/java/mimis/device/wiimote/WiimoteDevice.java b/java/mimis/src/main/java/mimis/device/wiimote/WiimoteDevice.java index e319602..7dde851 100644 --- a/java/mimis/src/main/java/mimis/device/wiimote/WiimoteDevice.java +++ b/java/mimis/src/main/java/mimis/device/wiimote/WiimoteDevice.java @@ -76,7 +76,7 @@ public class WiimoteDevice extends Component implements Device, GestureListener /* Worker */ public void activate() throws ActivateException { - if (wiimote == null) { + if (wiimote == null) { motionDevice.setRouter(router); motionDevice.start(); parser(Action.ADD, taskMapCycle.player); @@ -170,8 +170,8 @@ public class WiimoteDevice extends Component implements Device, GestureListener gestureDevice.loadGesture("tmp/gesture #" + gestureId); } break; - default: - break; + default: + break; } } @@ -189,8 +189,8 @@ public class WiimoteDevice extends Component implements Device, GestureListener logger.debug("Gesture close release"); gestureDevice.close(Signal.END); break; - default: - break; + default: + break; } } @@ -211,9 +211,9 @@ public class WiimoteDevice extends Component implements Device, GestureListener /* Listeners */ public void onButtonsEvent(WiimoteButtonsEvent event) { - if (!active()) { - return; - } + if (!active()) { + return; + } int pressed = event.getButtonsJustPressed() - event.getButtonsHeld(); int released = event.getButtonsJustReleased(); try { @@ -230,9 +230,9 @@ public class WiimoteDevice extends Component implements Device, GestureListener } public void onMotionSensingEvent(MotionSensingEvent event) { - if (!active()) { - return; - } + if (!active()) { + return; + } gestureDevice.add(event.getGforce()); motionDevice.add(event); } diff --git a/java/mimis/src/main/java/mimis/device/wiimote/WiimoteService.java b/java/mimis/src/main/java/mimis/device/wiimote/WiimoteService.java index f7c86e0..9b87b2a 100644 --- a/java/mimis/src/main/java/mimis/device/wiimote/WiimoteService.java +++ b/java/mimis/src/main/java/mimis/device/wiimote/WiimoteService.java @@ -47,7 +47,7 @@ public class WiimoteService extends WiiUseApiManager implements WiimoteListener public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(WiimoteService.class); for (Wiimote wm : WiiUseApiManager.getWiimotes(1, false)) { - logger.debug("" + wm.getId()); + logger.debug("" + wm.getId()); } } @@ -95,7 +95,7 @@ public class WiimoteService extends WiiUseApiManager implements WiimoteListener } public void onButtonsEvent(WiimoteButtonsEvent event) { - getWiimoteDevice(event).onButtonsEvent(event); + getWiimoteDevice(event).onButtonsEvent(event); } public void onMotionSensingEvent(MotionSensingEvent event) { diff --git a/java/mimis/src/main/java/mimis/device/wiimote/motion/MotionDevice.java b/java/mimis/src/main/java/mimis/device/wiimote/motion/MotionDevice.java index 245fffe..89d26fd 100644 --- a/java/mimis/src/main/java/mimis/device/wiimote/motion/MotionDevice.java +++ b/java/mimis/src/main/java/mimis/device/wiimote/motion/MotionDevice.java @@ -93,8 +93,8 @@ public class MotionDevice extends Component { case SCREEN_DOWN: wiimoteDevice.begin(Action.LOAD); break; - default: - break; + default: + break; } } else if (button instanceof NumberButton) { NumberButton numberButton = (NumberButton) button; @@ -140,8 +140,8 @@ public class MotionDevice extends Component { replay = true; replayWork.start(); break; - default: - break; + default: + break; } } } diff --git a/java/mimis/src/main/java/mimis/util/swing/HoldButton.java b/java/mimis/src/main/java/mimis/util/swing/HoldButton.java index 16df195..76ac6c2 100644 --- a/java/mimis/src/main/java/mimis/util/swing/HoldButton.java +++ b/java/mimis/src/main/java/mimis/util/swing/HoldButton.java @@ -28,22 +28,22 @@ public class HoldButton extends JButton implements MouseListener { public HoldButton(HoldButtonListener holdButtonListener) { this.holdButtonListener = holdButtonListener; - addMouseListener(this); + addMouseListener(this); } public void mousePressed(MouseEvent event) { - if (event.getButton() == MouseEvent.BUTTON1) { - holdButtonListener.buttonPressed(this); - } + if (event.getButton() == MouseEvent.BUTTON1) { + holdButtonListener.buttonPressed(this); + } } public void mouseReleased(MouseEvent event) { - if (event.getButton() == MouseEvent.BUTTON1) { - holdButtonListener.buttonReleased(this); - } + if (event.getButton() == MouseEvent.BUTTON1) { + holdButtonListener.buttonReleased(this); + } } - public void mouseClicked(MouseEvent event) {} - public void mouseEntered(MouseEvent event) {} - public void mouseExited(MouseEvent event) {} + public void mouseClicked(MouseEvent event) {} + public void mouseEntered(MouseEvent event) {} + public void mouseExited(MouseEvent event) {} } diff --git a/java/sound/src/main/java/old/Converter.java b/java/sound/src/main/java/old/Converter.java index 4a82dc7..fdbf3ee 100644 --- a/java/sound/src/main/java/old/Converter.java +++ b/java/sound/src/main/java/old/Converter.java @@ -16,172 +16,172 @@ import base.work.Work; import com.Ostermiller.util.CircularByteBuffer; public class Converter extends Work { - public static final String COMMAND = "lame --mp3input --cbr %s - - --quiet"; - public static final int BYTES = 4096; // bytes - public static final int BUFFER = 30000; // milliseconds - public static final int BUFFERING = 1000; // milliseconds + public static final String COMMAND = "lame --mp3input --cbr %s - - --quiet"; + public static final int BYTES = 4096; // bytes + public static final int BUFFER = 30000; // milliseconds + public static final int BUFFERING = 1000; // milliseconds - protected int targetRate; - protected int rate; - protected int buffer; - protected boolean convert; + protected int targetRate; + protected int rate; + protected int buffer; + protected boolean convert; - protected Process process; - protected InputStream sourceInputStream, processInputStream, inputStream; - protected OutputStream processOutputStream; - protected CircularByteBuffer circularByteBuffer; - protected BufferWorker bufferWorker; + protected Process process; + protected InputStream sourceInputStream, processInputStream, inputStream; + protected OutputStream processOutputStream; + protected CircularByteBuffer circularByteBuffer; + protected BufferWorker bufferWorker; - public Converter(InputStream inputStream) { - this(inputStream, -1); - } + public Converter(InputStream inputStream) { + this(inputStream, -1); + } - public Converter(InputStream inputStream, int targetRate) { - super(); - this.sourceInputStream = inputStream; - this.targetRate = targetRate; - bufferWorker = new BufferWorker(); - convert = false; - } - + public Converter(InputStream inputStream, int targetRate) { + super(); + this.sourceInputStream = inputStream; + this.targetRate = targetRate; + bufferWorker = new BufferWorker(); + convert = false; + } + public void exit() { super.exit(); bufferWorker.exit(); } - public synchronized void activate() throws ActivateException { - /* Read bitrate */ - BufferedInputStream bufferedInputStream = new BufferedInputStream(sourceInputStream); - Bitstream bitStream = new Bitstream(bufferedInputStream); - try { - rate = bitStream.readFrame().bitrate() / 1000; - buffer = BUFFER * rate / 8; - } catch (BitstreamException e) { - logger.error("", e); - throw new ActivateException(); - } + public synchronized void activate() throws ActivateException { + /* Read bitrate */ + BufferedInputStream bufferedInputStream = new BufferedInputStream(sourceInputStream); + Bitstream bitStream = new Bitstream(bufferedInputStream); + try { + rate = bitStream.readFrame().bitrate() / 1000; + buffer = BUFFER * rate / 8; + } catch (BitstreamException e) { + logger.error("", e); + throw new ActivateException(); + } - /* Check for need to convert */ - if (targetRate < 0 || rate == targetRate) { - logger.debug("No conversion required"); - inputStream = sourceInputStream; - } else { - logger.debug("Converting from " + rate + "kbps to " + targetRate + "kbps"); - try { - String command = String.format(COMMAND, rate > targetRate ? "-B " + targetRate : "-F -b " + targetRate); - logger.debug("Starting process: " + command); - process = Runtime.getRuntime().exec(command); - processInputStream = process.getInputStream(); - processOutputStream = process.getOutputStream(); + /* Check for need to convert */ + if (targetRate < 0 || rate == targetRate) { + logger.debug("No conversion required"); + inputStream = sourceInputStream; + } else { + logger.debug("Converting from " + rate + "kbps to " + targetRate + "kbps"); + try { + String command = String.format(COMMAND, rate > targetRate ? "-B " + targetRate : "-F -b " + targetRate); + logger.debug("Starting process: " + command); + process = Runtime.getRuntime().exec(command); + processInputStream = process.getInputStream(); + processOutputStream = process.getOutputStream(); - /* Buffer output */ - circularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); - inputStream = circularByteBuffer.getInputStream(); - bufferWorker.start(); - convert = true; - } catch (IOException e) { - logger.error("", e); - throw new ActivateException(); - } - } - super.activate(); - notifyAll(); - } + /* Buffer output */ + circularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); + inputStream = circularByteBuffer.getInputStream(); + bufferWorker.start(); + convert = true; + } catch (IOException e) { + logger.error("", e); + throw new ActivateException(); + } + } + super.activate(); + notifyAll(); + } - public void deactivate() throws DeactivateException { - super.deactivate(); - try { - sourceInputStream.close(); - bufferWorker.stop(); - if (convert) { - circularByteBuffer.clear(); - convert = false; - } - inputStream.close(); - } catch (IOException e) { - logger.error("", e); - throw new DeactivateException(); - } - } + public void deactivate() throws DeactivateException { + super.deactivate(); + try { + sourceInputStream.close(); + bufferWorker.stop(); + if (convert) { + circularByteBuffer.clear(); + convert = false; + } + inputStream.close(); + } catch (IOException e) { + logger.error("", e); + throw new DeactivateException(); + } + } - public void work() { - if (!convert) { - try { - synchronized (this) { - wait(); - } - } catch (InterruptedException e) { - logger.error("", e); - } - return; - } - byte[] bytes = new byte[BYTES]; - int read = 0; - try { - logger.debug("Writing input to process"); - // Should be interrupted by stop()/exit() - while ((read = sourceInputStream.read(bytes)) > 0) { - /* Limit buffer size */ - while (inputStream.available() > buffer) { - int progress = (int) ((1 - (inputStream.available() - buffer) / (float) buffer) * 100); - logger.trace("Waiting for buffer to empty: " + progress + "%"); - sleep(BUFFERING); - } - processOutputStream.write(bytes, 0, read); - } - processOutputStream.close(); - logger.debug("Stopped writing input to process"); - process.waitFor(); - logger.debug("Process finished"); - } catch (IOException e) { - } catch (InterruptedException e) { - logger.error("", e); - } - stop(); - } + public void work() { + if (!convert) { + try { + synchronized (this) { + wait(); + } + } catch (InterruptedException e) { + logger.error("", e); + } + return; + } + byte[] bytes = new byte[BYTES]; + int read = 0; + try { + logger.debug("Writing input to process"); + // Should be interrupted by stop()/exit() + while ((read = sourceInputStream.read(bytes)) > 0) { + /* Limit buffer size */ + while (inputStream.available() > buffer) { + int progress = (int) ((1 - (inputStream.available() - buffer) / (float) buffer) * 100); + logger.trace("Waiting for buffer to empty: " + progress + "%"); + sleep(BUFFERING); + } + processOutputStream.write(bytes, 0, read); + } + processOutputStream.close(); + logger.debug("Stopped writing input to process"); + process.waitFor(); + logger.debug("Process finished"); + } catch (IOException e) { + } catch (InterruptedException e) { + logger.error("", e); + } + stop(); + } - public synchronized InputStream getInputStream() { - if (!active()) { - start(); - try { - wait(); - } catch (InterruptedException e) { - logger.error("", e); - } - } - return inputStream; - } + public synchronized InputStream getInputStream() { + if (!active()) { + start(); + try { + wait(); + } catch (InterruptedException e) { + logger.error("", e); + } + } + return inputStream; + } - public synchronized void setInputStream(InputStream inputStream) { - this.inputStream = inputStream; - } + public synchronized void setInputStream(InputStream inputStream) { + this.inputStream = inputStream; + } - class BufferWorker extends Work { - public void work() { - byte[] bytes = new byte[BYTES]; - int read = 0; - try { - OutputStream bufferOutputStream = circularByteBuffer.getOutputStream(); - logger.debug("Start buffering process output"); - while ((read = processInputStream.read(bytes, 0, BYTES)) > 0) { - bufferOutputStream.write(bytes, 0, read); - } - logger.debug("Finished buffering process output"); - bufferOutputStream.close(); - } catch (IOException e) {} - stop(); - } - } + class BufferWorker extends Work { + public void work() { + byte[] bytes = new byte[BYTES]; + int read = 0; + try { + OutputStream bufferOutputStream = circularByteBuffer.getOutputStream(); + logger.debug("Start buffering process output"); + while ((read = processInputStream.read(bytes, 0, BYTES)) > 0) { + bufferOutputStream.write(bytes, 0, read); + } + logger.debug("Finished buffering process output"); + bufferOutputStream.close(); + } catch (IOException e) {} + stop(); + } + } - public static void main(String[] args) { - Mp3 mp3 = new Mp3(new File("stream.mp3"), 128); - InputStream inputStream = mp3.getInputStream(); + public static void main(String[] args) { + Mp3 mp3 = new Mp3(new File("stream.mp3"), 128); + InputStream inputStream = mp3.getInputStream(); - /* Play */ - //Utils.play(inputStream); + /* Play */ + //Utils.play(inputStream); - /* Write to file */ - Utils.write(inputStream, new File("output.mp3")); - mp3.exit(); - } + /* Write to file */ + Utils.write(inputStream, new File("output.mp3")); + mp3.exit(); + } } diff --git a/java/sound/src/main/java/old/List.java b/java/sound/src/main/java/old/List.java index 9f681c7..1d49985 100644 --- a/java/sound/src/main/java/old/List.java +++ b/java/sound/src/main/java/old/List.java @@ -17,185 +17,185 @@ import com.Ostermiller.util.CircularByteBuffer; import com.Ostermiller.util.CircularObjectBuffer; public class List extends Work { - public static final int STEP = 80; // milliseconds - public static final int RATE = 192; // kbps - public static final int OVERLAP = 20000; // milliseconds + public static final int STEP = 80; // milliseconds + public static final int RATE = 192; // kbps + public static final int OVERLAP = 20000; // milliseconds - protected File file; - protected String[] fileArray; + protected File file; + protected String[] fileArray; - protected int rate; - protected int chunk; - protected int overlap; - protected byte[] bytes; - protected boolean next; - protected Mp3 mp3, nextMp3; + protected int rate; + protected int chunk; + protected int overlap; + protected byte[] bytes; + protected boolean next; + protected Mp3 mp3, nextMp3; - protected InputStream mp3InputStream; - protected OutputStream audioOutputStream; - protected CircularByteBuffer circularByteBuffer; - protected CircularObjectBuffer circularStringBuffer; + protected InputStream mp3InputStream; + protected OutputStream audioOutputStream; + protected CircularByteBuffer circularByteBuffer; + protected CircularObjectBuffer circularStringBuffer; - public List(File file) { - this(file, RATE); - } + public List(File file) { + this(file, RATE); + } - public List(File file, int rate) { - this.file = file; - this.rate = rate; - chunk = STEP * rate / 8; - overlap = OVERLAP * RATE / 8; - bytes = new byte[chunk]; - next = true; - } + public List(File file, int rate) { + this.file = file; + this.rate = rate; + chunk = STEP * rate / 8; + overlap = OVERLAP * RATE / 8; + bytes = new byte[chunk]; + next = true; + } - public void exit() { - super.exit(); - if (mp3 != null) { - mp3.exit(); - } - if (nextMp3 != null) { - nextMp3.exit(); - } - } + public void exit() { + super.exit(); + if (mp3 != null) { + mp3.exit(); + } + if (nextMp3 != null) { + nextMp3.exit(); + } + } - public synchronized void activate() throws ActivateException { - try { - Scanner scanner = new Scanner(file); - ArrayList fileList = new ArrayList(); - while (scanner.hasNextLine()) { - fileList.add(scanner.nextLine()); - } - scanner.close(); - if (fileList.size() > 0) { - fileArray = fileList.toArray(new String[0]); + public synchronized void activate() throws ActivateException { + try { + Scanner scanner = new Scanner(file); + ArrayList fileList = new ArrayList(); + while (scanner.hasNextLine()) { + fileList.add(scanner.nextLine()); + } + scanner.close(); + if (fileList.size() > 0) { + fileArray = fileList.toArray(new String[0]); - circularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); - audioOutputStream = circularByteBuffer.getOutputStream(); + circularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); + audioOutputStream = circularByteBuffer.getOutputStream(); - circularStringBuffer = new CircularObjectBuffer(CircularByteBuffer.INFINITE_SIZE); - setNext(); - super.activate(); - notifyAll(); - return; - } - } catch (FileNotFoundException e) { - logger.error("", e); - } - throw new ActivateException(); - } + circularStringBuffer = new CircularObjectBuffer(CircularByteBuffer.INFINITE_SIZE); + setNext(); + super.activate(); + notifyAll(); + return; + } + } catch (FileNotFoundException e) { + logger.error("", e); + } + throw new ActivateException(); + } - public synchronized void work() { - try { - int left = chunk; - while (left > 0) { - /* Check for need to load next mp3 */ - int available = mp3InputStream == null ? -1 : mp3InputStream.available(); - boolean expect = mp3 == null ? false : mp3.active(); + public synchronized void work() { + try { + int left = chunk; + while (left > 0) { + /* Check for need to load next mp3 */ + int available = mp3InputStream == null ? -1 : mp3InputStream.available(); + boolean expect = mp3 == null ? false : mp3.active(); - /* Act when no more data is expected */ - if (!expect) { - if (available < overlap) { - setNext(); - next = false; - nextMp3.start(); - } - if (available < 1) { - swap(); - } - } + /* Act when no more data is expected */ + if (!expect) { + if (available < overlap) { + setNext(); + next = false; + nextMp3.start(); + } + if (available < 1) { + swap(); + } + } - /* Transfer data */ - int read = mp3InputStream.read(bytes, 0, left); - left -= read; - audioOutputStream.write(bytes, 0, read); - } - } catch (IOException e) { - /* Swap to next if stream has stopped */ - setNext(); - swap(); - } catch (IllegalStateException e) { - logger.error("", e); - } - sleep(STEP); - } + /* Transfer data */ + int read = mp3InputStream.read(bytes, 0, left); + left -= read; + audioOutputStream.write(bytes, 0, read); + } + } catch (IOException e) { + /* Swap to next if stream has stopped */ + setNext(); + swap(); + } catch (IllegalStateException e) { + logger.error("", e); + } + sleep(STEP); + } - protected File getRandomFile() { - return new File(fileArray[(int) (Math.random() * fileArray.length)]); - } + protected File getRandomFile() { + return new File(fileArray[(int) (Math.random() * fileArray.length)]); + } - public synchronized void setNext() { - if (nextMp3 == null) { - logger.debug("Initialize next mp3"); - nextMp3 = new Mp3(getRandomFile(), rate); - } else if (next) { - logger.debug("Load next mp3"); - nextMp3.setFile(getRandomFile()); - } - } + public synchronized void setNext() { + if (nextMp3 == null) { + logger.debug("Initialize next mp3"); + nextMp3 = new Mp3(getRandomFile(), rate); + } else if (next) { + logger.debug("Load next mp3"); + nextMp3.setFile(getRandomFile()); + } + } - public synchronized void next() { - logger.debug("Stop current mp3"); - mp3.stop(); - } + public synchronized void next() { + logger.debug("Stop current mp3"); + mp3.stop(); + } - public void swap() { - logger.debug("Swap to next mp3"); - Mp3 swapMp3 = mp3; - mp3 = nextMp3; - nextMp3 = swapMp3; - next = true; + public void swap() { + logger.debug("Swap to next mp3"); + Mp3 swapMp3 = mp3; + mp3 = nextMp3; + nextMp3 = swapMp3; + next = true; - /* Swap stream and announce title */ - mp3InputStream = mp3.getInputStream(); - try { - circularStringBuffer.write(mp3.getTitle()); - } catch (BufferOverflowException e) { - logger.error("", e); - } catch (IllegalStateException e) { - logger.error("", e); - } catch (InterruptedException e) { - logger.error("", e); - } - } + /* Swap stream and announce title */ + mp3InputStream = mp3.getInputStream(); + try { + circularStringBuffer.write(mp3.getTitle()); + } catch (BufferOverflowException e) { + logger.error("", e); + } catch (IllegalStateException e) { + logger.error("", e); + } catch (InterruptedException e) { + logger.error("", e); + } + } - public synchronized InputStream getInputStream() { - if (circularByteBuffer == null) { - start(); - try { - wait(); - } catch (InterruptedException e) { - logger.error("", e); - } - } - return circularByteBuffer.getInputStream(); - } + public synchronized InputStream getInputStream() { + if (circularByteBuffer == null) { + start(); + try { + wait(); + } catch (InterruptedException e) { + logger.error("", e); + } + } + return circularByteBuffer.getInputStream(); + } - public synchronized CircularObjectBuffer getMetaBuffer() { - if (circularStringBuffer == null) { - start(); - try { - wait(); - } catch (InterruptedException e) { - logger.error("", e); - } - } - return circularStringBuffer; - } + public synchronized CircularObjectBuffer getMetaBuffer() { + if (circularStringBuffer == null) { + start(); + try { + wait(); + } catch (InterruptedException e) { + logger.error("", e); + } + } + return circularStringBuffer; + } - public static void main(String[] args) throws Exception { - int rate = 192; - List list = new List(new File(List.class.getClassLoader().getResource("txt/mp3").toURI()), rate); - Shoutcast shoutcast = new Shoutcast(rate, 9876); - - shoutcast.setInputStream(list.getInputStream()); - shoutcast.setMetaBuffer(list.getMetaBuffer()); - shoutcast.start(); - while (true) { - try { - Thread.sleep(15000); - list.next(); - } catch (InterruptedException e) {} - } - } + public static void main(String[] args) throws Exception { + int rate = 192; + List list = new List(new File(List.class.getClassLoader().getResource("txt/mp3").toURI()), rate); + Shoutcast shoutcast = new Shoutcast(rate, 9876); + + shoutcast.setInputStream(list.getInputStream()); + shoutcast.setMetaBuffer(list.getMetaBuffer()); + shoutcast.start(); + while (true) { + try { + Thread.sleep(15000); + list.next(); + } catch (InterruptedException e) {} + } + } } diff --git a/java/sound/src/main/java/old/Mp3.java b/java/sound/src/main/java/old/Mp3.java index 589d35e..de90aff 100644 --- a/java/sound/src/main/java/old/Mp3.java +++ b/java/sound/src/main/java/old/Mp3.java @@ -12,69 +12,69 @@ import sound.util.Utils; import base.exception.worker.ActivateException; public class Mp3 extends Converter { - protected File file; - protected String title; + protected File file; + protected String title; - public Mp3(File file) { - this(file, -1); - } + public Mp3(File file) { + this(file, -1); + } - public Mp3(File file, int targetRate) { - super(null, targetRate); - setFile(file); - title = ""; - } + public Mp3(File file, int targetRate) { + super(null, targetRate); + setFile(file); + title = ""; + } - public synchronized void activate() throws ActivateException { - /* Open file */ - try { - sourceInputStream = new FileInputStream(file); - } catch (FileNotFoundException e) { - logger.error("", e); - throw new ActivateException(); - } + public synchronized void activate() throws ActivateException { + /* Open file */ + try { + sourceInputStream = new FileInputStream(file); + } catch (FileNotFoundException e) { + logger.error("", e); + throw new ActivateException(); + } - /* Read ID3V2 tags */ - try { - MP3File mp3File = new MP3File(file); - String album = clean(mp3File.getID3v2Tag().getAlbumTitle()); - String artist = clean(mp3File.getID3v2Tag().getLeadArtist()); - String track = clean(mp3File.getID3v2Tag().getSongTitle()); - if (album.isEmpty()) { - title = String.format("%s - %s", artist, track, album); - } else { - title = String.format("%s - %s {%s}", artist, track, album); - } - logger.debug("Title: " + title); - } catch (IOException e) { - logger.error("", e); - } catch (TagException e) { - logger.error("", e); - } - try { - sourceInputStream.skip(100000); - } catch (IOException e) {} - super.activate(); - } + /* Read ID3V2 tags */ + try { + MP3File mp3File = new MP3File(file); + String album = clean(mp3File.getID3v2Tag().getAlbumTitle()); + String artist = clean(mp3File.getID3v2Tag().getLeadArtist()); + String track = clean(mp3File.getID3v2Tag().getSongTitle()); + if (album.isEmpty()) { + title = String.format("%s - %s", artist, track, album); + } else { + title = String.format("%s - %s {%s}", artist, track, album); + } + logger.debug("Title: " + title); + } catch (IOException e) { + logger.error("", e); + } catch (TagException e) { + logger.error("", e); + } + try { + sourceInputStream.skip(100000); + } catch (IOException e) {} + super.activate(); + } - protected String clean(String input) { - String output = input.replace("\0", ""); - return output.replace("ÿþ", ""); - } + protected String clean(String input) { + String output = input.replace("\0", ""); + return output.replace("ÿþ", ""); + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setFile(File file) { - this.file = file; - } + public void setFile(File file) { + this.file = file; + } - public static void main(String[] args) { - final Mp3 mp3 = new Mp3(new File("input.mp3"), 128); - Utils.write(mp3.getInputStream(), new File("one.mp3")); - mp3.setFile(new File("stream.mp3")); - Utils.write(mp3.getInputStream(), new File("two.mp3")); - mp3.exit(); - } + public static void main(String[] args) { + final Mp3 mp3 = new Mp3(new File("input.mp3"), 128); + Utils.write(mp3.getInputStream(), new File("one.mp3")); + mp3.setFile(new File("stream.mp3")); + Utils.write(mp3.getInputStream(), new File("two.mp3")); + mp3.exit(); + } } diff --git a/java/sound/src/main/java/old/Transducer.java b/java/sound/src/main/java/old/Transducer.java index 071bb91..64c4a01 100644 --- a/java/sound/src/main/java/old/Transducer.java +++ b/java/sound/src/main/java/old/Transducer.java @@ -4,13 +4,13 @@ import sound.Consumer; import sound.Producer; public abstract class Transducer implements Consumer, Producer { - public int rate; + public int rate; - public Transducer(Producer producer) { - //setProducer(producer); - } + public Transducer(Producer producer) { + //setProducer(producer); + } - public int getRate() { - return rate; - } + public int getRate() { + return rate; + } } diff --git a/java/sound/src/main/java/pipe/Client.java b/java/sound/src/main/java/pipe/Client.java index b36d882..1ef5c26 100644 --- a/java/sound/src/main/java/pipe/Client.java +++ b/java/sound/src/main/java/pipe/Client.java @@ -3,22 +3,22 @@ package pipe; import java.io.RandomAccessFile; public class Client { - public static void main(String[] args) { - try { - // Connect to the pipe - RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\detest", "rw"); - String echoText = "Hello word\n"; + public static void main(String[] args) { + try { + // Connect to the pipe + RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\detest", "rw"); + String echoText = "Hello word\n"; - // write to pipe - pipe.write(echoText.getBytes()); + // write to pipe + pipe.write(echoText.getBytes()); - // read response - String echoResponse = pipe.readLine(); - System.out.println(echoResponse); - pipe.close(); - } catch (Exception e) { - e.printStackTrace(); - } + // read response + String echoResponse = pipe.readLine(); + System.out.println(echoResponse); + pipe.close(); + } catch (Exception e) { + e.printStackTrace(); + } - } + } } diff --git a/java/sound/src/main/java/pipe/Pipe.java b/java/sound/src/main/java/pipe/Pipe.java index c74b90f..3bb3805 100644 --- a/java/sound/src/main/java/pipe/Pipe.java +++ b/java/sound/src/main/java/pipe/Pipe.java @@ -4,51 +4,51 @@ package pipe; * @author Vikram S Khatri vikram.khatri@us.ibm.com */ public class Pipe { - static final int ERROR_PIPE_CONNECTED = 535; - static final int ERROR_BROKEN_PIPE = 109; - static final int PIPE_ACCESS_DUPLEX = 0x00000003; - static final int PIPE_WAIT = 0x00000000; - - static { - System.loadLibrary("pipe"); - } + static final int ERROR_PIPE_CONNECTED = 535; + static final int ERROR_BROKEN_PIPE = 109; + static final int PIPE_ACCESS_DUPLEX = 0x00000003; + static final int PIPE_WAIT = 0x00000000; + + static { + System.loadLibrary("pipe"); + } - public static final native int CreateNamedPipe( - String pipeName, - int ppenMode, - int pipeMode, - int maxInstances, - int outBufferSize, - int inBufferSize, - int defaultTimeOut, - int securityAttributes); + public static final native int CreateNamedPipe( + String pipeName, + int ppenMode, + int pipeMode, + int maxInstances, + int outBufferSize, + int inBufferSize, + int defaultTimeOut, + int securityAttributes); - public static final native boolean ConnectNamedPipe(int namedPipeHandle, int overlapped); + public static final native boolean ConnectNamedPipe(int namedPipeHandle, int overlapped); - public static final native int GetLastError(); + public static final native int GetLastError(); - public static final native boolean CloseHandle(int bbject); + public static final native boolean CloseHandle(int bbject); - public static final native byte[] ReadFile(int file, int numberOfBytesToRead); + public static final native byte[] ReadFile(int file, int numberOfBytesToRead); - public static final native int WriteFile(int file, byte[] buffer, int numberOfBytesToWrite); + public static final native int WriteFile(int file, byte[] buffer, int numberOfBytesToWrite); - public static final native boolean FlushFileBuffers(int file); + public static final native boolean FlushFileBuffers(int file); - public static final native boolean DisconnectNamedPipe(int namedPipeHandle); + public static final native boolean DisconnectNamedPipe(int namedPipeHandle); - public static final native int CreateFile( - String fileName, - int desiredAccess, - int shareMode, - int securityAttributes, - int creationDisposition, - int flagsAndAttributes, - int templateFile); + public static final native int CreateFile( + String fileName, + int desiredAccess, + int shareMode, + int securityAttributes, + int creationDisposition, + int flagsAndAttributes, + int templateFile); - public static final native boolean WaitNamedPipe(String namedPipeName, int timeOut); + public static final native boolean WaitNamedPipe(String namedPipeName, int timeOut); - public static final native String FormatMessage(int errorCode); + public static final native String FormatMessage(int errorCode); - public static final native void Print(String message); + public static final native void Print(String message); } diff --git a/java/sound/src/main/java/pipe/TestPipe.java b/java/sound/src/main/java/pipe/TestPipe.java index b1e1e32..9d1ec66 100644 --- a/java/sound/src/main/java/pipe/TestPipe.java +++ b/java/sound/src/main/java/pipe/TestPipe.java @@ -6,82 +6,82 @@ import java.io.InputStream; public class TestPipe { - private int namedPipeHandle; - private String pipeName, srcFile; - private int pipeBuffer = 131072, fileBuffer = 8192; + private int namedPipeHandle; + private String pipeName, srcFile; + private int pipeBuffer = 131072, fileBuffer = 8192; - public TestPipe(String pipeName, String srcFile) { - this.pipeName = pipeName; - this.srcFile = srcFile; - } + public TestPipe(String pipeName, String srcFile) { + this.pipeName = pipeName; + this.srcFile = srcFile; + } - private void log(String message) { - System.out.println(message); - } + private void log(String message) { + System.out.println(message); + } - private boolean createPipe() { - namedPipeHandle = Pipe.CreateNamedPipe( - pipeName, - Pipe.PIPE_ACCESS_DUPLEX, - Pipe.PIPE_WAIT, - 5, - pipeBuffer, - pipeBuffer, - 0xffffffff, - 0); - if (namedPipeHandle == -1) { - log("CreateNamedPipe failed for " + pipeName + " for error Message " + Pipe.FormatMessage(Pipe.GetLastError())); - } else { - log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle); - } - return namedPipeHandle != -1; - } + private boolean createPipe() { + namedPipeHandle = Pipe.CreateNamedPipe( + pipeName, + Pipe.PIPE_ACCESS_DUPLEX, + Pipe.PIPE_WAIT, + 5, + pipeBuffer, + pipeBuffer, + 0xffffffff, + 0); + if (namedPipeHandle == -1) { + log("CreateNamedPipe failed for " + pipeName + " for error Message " + Pipe.FormatMessage(Pipe.GetLastError())); + } else { + log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle); + } + return namedPipeHandle != -1; + } - private boolean connectToPipe() { - log("Waiting for a client to connect to pipe " + pipeName); - boolean connected = Pipe.ConnectNamedPipe(namedPipeHandle, 0); - if (!connected) { - int lastError = Pipe.GetLastError(); - if (lastError == Pipe.ERROR_PIPE_CONNECTED) - connected = true; - } - log((connected ? "Connected to the pipe " : "Falied to connect to the pipe ") + pipeName); - return connected; - } + private boolean connectToPipe() { + log("Waiting for a client to connect to pipe " + pipeName); + boolean connected = Pipe.ConnectNamedPipe(namedPipeHandle, 0); + if (!connected) { + int lastError = Pipe.GetLastError(); + if (lastError == Pipe.ERROR_PIPE_CONNECTED) + connected = true; + } + log((connected ? "Connected to the pipe " : "Falied to connect to the pipe ") + pipeName); + return connected; + } - public void runPipe() { - if (createPipe() && connectToPipe()) { - log("Client connected."); - try { - File f1 = new File(this.srcFile); - InputStream in = new FileInputStream(f1); - log("Sending data to the pipe"); - byte[] buf = new byte[fileBuffer]; - int len, bytesWritten; - while ((len = in.read(buf)) > 0) { - bytesWritten = Pipe.WriteFile(namedPipeHandle, buf, len); - log("Sent " + len + "/" + bytesWritten + " bytes to the pipe"); - if (bytesWritten == -1) { - int errorNumber = Pipe.GetLastError(); - log("Error Writing to pipe " + Pipe.FormatMessage(errorNumber)); - } - } - in.close(); - Pipe.FlushFileBuffers(namedPipeHandle); - Pipe.CloseHandle(namedPipeHandle); - Pipe.DisconnectNamedPipe(namedPipeHandle); - log("Writing to the pipe completed."); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + public void runPipe() { + if (createPipe() && connectToPipe()) { + log("Client connected."); + try { + File f1 = new File(this.srcFile); + InputStream in = new FileInputStream(f1); + log("Sending data to the pipe"); + byte[] buf = new byte[fileBuffer]; + int len, bytesWritten; + while ((len = in.read(buf)) > 0) { + bytesWritten = Pipe.WriteFile(namedPipeHandle, buf, len); + log("Sent " + len + "/" + bytesWritten + " bytes to the pipe"); + if (bytesWritten == -1) { + int errorNumber = Pipe.GetLastError(); + log("Error Writing to pipe " + Pipe.FormatMessage(errorNumber)); + } + } + in.close(); + Pipe.FlushFileBuffers(namedPipeHandle); + Pipe.CloseHandle(namedPipeHandle); + Pipe.DisconnectNamedPipe(namedPipeHandle); + log("Writing to the pipe completed."); + } catch (Exception e) { + e.printStackTrace(); + } + } + } - public static void main(String[] args) { - String pipeName = "\\\\.\\pipe\\detest"; - String fileName = "txt/bla.txt"; - //fileName = "C:\\Users\\Rik\\Music\\Artists\\+44\\When Your Heart Stops Beating\\+44 - 155.mp3"; - TestPipe testPipe = new TestPipe(pipeName, fileName); - testPipe.runPipe(); - } + public static void main(String[] args) { + String pipeName = "\\\\.\\pipe\\detest"; + String fileName = "txt/bla.txt"; + //fileName = "C:\\Users\\Rik\\Music\\Artists\\+44\\When Your Heart Stops Beating\\+44 - 155.mp3"; + TestPipe testPipe = new TestPipe(pipeName, fileName); + testPipe.runPipe(); + } } diff --git a/java/sound/src/main/java/sound/Consumer.java b/java/sound/src/main/java/sound/Consumer.java index 9174078..dddd96e 100644 --- a/java/sound/src/main/java/sound/Consumer.java +++ b/java/sound/src/main/java/sound/Consumer.java @@ -1,7 +1,7 @@ package sound; public interface Consumer { - public void start(Producer producer); - public void stop(); - public void exit(); + public void start(Producer producer); + public void stop(); + public void exit(); } diff --git a/java/sound/src/main/java/sound/Format.java b/java/sound/src/main/java/sound/Format.java index c24c3d3..5fa89af 100644 --- a/java/sound/src/main/java/sound/Format.java +++ b/java/sound/src/main/java/sound/Format.java @@ -3,11 +3,11 @@ package sound; import javax.sound.sampled.AudioFormat; public interface Format extends Cloneable { - public interface Standard extends Format { - public AudioFormat getAudioFormat(); - } + public interface Standard extends Format { + public AudioFormat getAudioFormat(); + } - public interface Mp3 extends Format { - public int getRate(); - } + public interface Mp3 extends Format { + public int getRate(); + } } \ No newline at end of file diff --git a/java/sound/src/main/java/sound/Producer.java b/java/sound/src/main/java/sound/Producer.java index c25eb48..bbabccd 100644 --- a/java/sound/src/main/java/sound/Producer.java +++ b/java/sound/src/main/java/sound/Producer.java @@ -3,8 +3,8 @@ package sound; import java.io.InputStream; public interface Producer extends Format { - public InputStream getInputStream(); - public void start(); - public void stop(); - public void exit(); + public InputStream getInputStream(); + public void start(); + public void stop(); + public void exit(); } \ No newline at end of file diff --git a/java/sound/src/main/java/sound/Source.java b/java/sound/src/main/java/sound/Source.java index 2dd7e4e..6380a6d 100644 --- a/java/sound/src/main/java/sound/Source.java +++ b/java/sound/src/main/java/sound/Source.java @@ -19,143 +19,143 @@ import base.exception.worker.DeactivateException; import base.work.Work; public class Source implements Consumer { - protected Logger logger = LoggerFactory.getLogger(getClass()); + protected Logger logger = LoggerFactory.getLogger(getClass()); - protected static final int BUFFER_SIZE = 1024 * 4; // in bytes - protected static final int FRAMES = 10; // count + protected static final int BUFFER_SIZE = 1024 * 4; // in bytes + protected static final int FRAMES = 10; // count - protected String name; - protected Producer producer; - protected InputStream producerInputStream; - protected Work work; + protected String name; + protected Producer producer; + protected InputStream producerInputStream; + protected Work work; - public Source(String name) throws LineUnavailableException { - this.name = name; - } + public Source(String name) throws LineUnavailableException { + this.name = name; + } - public void start() { - if (work != null) { - work.start(); - } - } + public void start() { + if (work != null) { + work.start(); + } + } - public void start(Producer producer) { - this.producer = producer; - producerInputStream = producer.getInputStream(); - if (work != null) { - work.exit(); - } - if (producer instanceof Format.Standard) { - logger.debug("Format.Standard"); - work = new DefaultWorker((Format.Standard) producer); - } else if (producer instanceof Format.Mp3) { - logger.debug("Format.Mp3"); - work = new Mp3Worker((Format.Mp3) producer); - } - start(); - } + public void start(Producer producer) { + this.producer = producer; + producerInputStream = producer.getInputStream(); + if (work != null) { + work.exit(); + } + if (producer instanceof Format.Standard) { + logger.debug("Format.Standard"); + work = new DefaultWorker((Format.Standard) producer); + } else if (producer instanceof Format.Mp3) { + logger.debug("Format.Mp3"); + work = new Mp3Worker((Format.Mp3) producer); + } + start(); + } - public void stop() { - if (work != null) { - work.stop(); - } - } + public void stop() { + if (work != null) { + work.stop(); + } + } - public void exit() { - if (work != null) { - work.exit(); - } - } + public void exit() { + if (work != null) { + work.exit(); + } + } - protected class DefaultWorker extends Work { - protected Format.Standard format; - protected SourceDataLine line; + protected class DefaultWorker extends Work { + protected Format.Standard format; + protected SourceDataLine line; - public DefaultWorker(Format.Standard format) { - this.format = format; - } + public DefaultWorker(Format.Standard format) { + this.format = format; + } - public void activate() throws ActivateException { - AudioFormat audioFormat = format.getAudioFormat(); - try { - if (line == null) { - line = Tool.getSourceDataLine(name, audioFormat); - } - if (!line.isOpen()) { - line.open(); - } - } catch (LineUnavailableException e) { - logger.error("", e); - throw new ActivateException(); - } - if (!line.isRunning()) { - line.start(); - } - super.activate(); - } + public void activate() throws ActivateException { + AudioFormat audioFormat = format.getAudioFormat(); + try { + if (line == null) { + line = Tool.getSourceDataLine(name, audioFormat); + } + if (!line.isOpen()) { + line.open(); + } + } catch (LineUnavailableException e) { + logger.error("", e); + throw new ActivateException(); + } + if (!line.isRunning()) { + line.start(); + } + super.activate(); + } - public void deactivate() throws DeactivateException { - super.deactivate(); - line.flush(); - } + public void deactivate() throws DeactivateException { + super.deactivate(); + line.flush(); + } - public void exit() { - super.exit(); - line.close(); - } + public void exit() { + super.exit(); + line.close(); + } - public void work() { - try { - byte[] buffer = new byte[BUFFER_SIZE]; - int read = producerInputStream.read(buffer, 0, buffer.length); - if (read > 0) { - line.write(buffer, 0, read); - } else { - exit(); - } - } catch (IOException e) { - logger.error("", e); - exit(); - } - } - } + public void work() { + try { + byte[] buffer = new byte[BUFFER_SIZE]; + int read = producerInputStream.read(buffer, 0, buffer.length); + if (read > 0) { + line.write(buffer, 0, read); + } else { + exit(); + } + } catch (IOException e) { + logger.error("", e); + exit(); + } + } + } - protected class Mp3Worker extends Work { - protected Format.Mp3 format; - protected Player player; + protected class Mp3Worker extends Work { + protected Format.Mp3 format; + protected Player player; - public Mp3Worker(Format.Mp3 format) { - this.format = format; - } + public Mp3Worker(Format.Mp3 format) { + this.format = format; + } - public void activate() throws ActivateException { - producer.start(); - super.activate(); - } + public void activate() throws ActivateException { + producer.start(); + super.activate(); + } - public void deactivate() throws DeactivateException { - super.deactivate(); - producer.stop(); - } + public void deactivate() throws DeactivateException { + super.deactivate(); + producer.stop(); + } - public void exit() { - super.exit(); - player.close(); - } + public void exit() { + super.exit(); + player.close(); + } - public void work() { - try { - if (player == null) { - player = new Player(producerInputStream); - sleep(100); - } - player.play(FRAMES); - } catch (JavaLayerException e) { - logger.error("", e); - } - if (player.isComplete()) { - stop(); - } - } - } + public void work() { + try { + if (player == null) { + player = new Player(producerInputStream); + sleep(100); + } + player.play(FRAMES); + } catch (JavaLayerException e) { + logger.error("", e); + } + if (player.isComplete()) { + stop(); + } + } + } } diff --git a/java/sound/src/main/java/sound/consumer/Port.java b/java/sound/src/main/java/sound/consumer/Port.java index 2e0951c..83111b2 100644 --- a/java/sound/src/main/java/sound/consumer/Port.java +++ b/java/sound/src/main/java/sound/consumer/Port.java @@ -19,103 +19,103 @@ import base.exception.worker.DeactivateException; import base.work.Work; public class Port extends Work implements Consumer { - protected static final int BUFFER_SIZE = 1024 * 4; // in bytes + protected static final int BUFFER_SIZE = 1024 * 4; // in bytes - protected String device; - protected Producer producer; - protected Process process; - protected InputStream producerInputStream; - protected OutputStream processOutputStream; - protected ProcessBuilder processBuilder; + protected String device; + protected Producer producer; + protected Process process; + protected InputStream producerInputStream; + protected OutputStream processOutputStream; + protected ProcessBuilder processBuilder; - public Port() { - this("0"); - } + public Port() { + this("0"); + } - public Port(String device) { - this.device = device; - } + public Port(String device) { + this.device = device; + } - public void start(Producer producer) { - start(producer); - } + public void start(Producer producer) { + start(producer); + } @SuppressWarnings("static-access") - public void start(Producer producer, boolean thread) { - this.producer = producer; - producerInputStream = producer.getInputStream(); - - String command = ""; - if (producer instanceof Standard) { - AudioFormat audioFormat = ((Standard) producer).getAudioFormat(); - SoxBuilder.addFile(File.setType(Type.STANDARD).setOptions(audioFormat)); - } else if (producer instanceof Format.Mp3) { - SoxBuilder.addFile(File.setType(Type.STANDARD).setOption(File.Format.MP3)); - } - command = SoxBuilder - .setOption(Option.QUIET) - .addFile(File.setType(Type.DEVICE)) - .build(); + public void start(Producer producer, boolean thread) { + this.producer = producer; + producerInputStream = producer.getInputStream(); + + String command = ""; + if (producer instanceof Standard) { + AudioFormat audioFormat = ((Standard) producer).getAudioFormat(); + SoxBuilder.addFile(File.setType(Type.STANDARD).setOptions(audioFormat)); + } else if (producer instanceof Format.Mp3) { + SoxBuilder.addFile(File.setType(Type.STANDARD).setOption(File.Format.MP3)); + } + command = SoxBuilder + .setOption(Option.QUIET) + .addFile(File.setType(Type.DEVICE)) + .build(); - logger.debug(String.format("Build process (\"%s\")", command)); - processBuilder = new ProcessBuilder(command.split(" ")); - processBuilder.environment().put("AUDIODEV", device); + logger.debug(String.format("Build process (\"%s\")", command)); + processBuilder = new ProcessBuilder(command.split(" ")); + processBuilder.environment().put("AUDIODEV", device); - start(); - } + start(); + } - public void activate() throws ActivateException { - producer.start(); - if (process == null) { - try { - process = processBuilder.start(); - } catch (IOException e) { - logger.error("", e); - throw new ActivateException(); - } - processOutputStream = process.getOutputStream(); - } + public void activate() throws ActivateException { + producer.start(); + if (process == null) { + try { + process = processBuilder.start(); + } catch (IOException e) { + logger.error("", e); + throw new ActivateException(); + } + processOutputStream = process.getOutputStream(); + } super.activate(); } public void deactivate() throws DeactivateException { - super.deactivate(); - try { - processOutputStream.flush(); - } catch (IOException e) { - logger.error("", e); - throw new DeactivateException(); - } + super.deactivate(); + try { + processOutputStream.flush(); + } catch (IOException e) { + logger.error("", e); + throw new DeactivateException(); + } } public void exit() { - try { - logger.debug("close process output stream"); - processOutputStream.close(); + try { + logger.debug("close process output stream"); + processOutputStream.close(); - logger.debug("wait for process to terminate"); - process.waitFor(); - } catch (IOException e) { - logger.error("", e); - } catch (InterruptedException e) { - logger.error("", e); - } finally { - process = null; - } + logger.debug("wait for process to terminate"); + process.waitFor(); + } catch (IOException e) { + logger.error("", e); + } catch (InterruptedException e) { + logger.error("", e); + } finally { + process = null; + } } - public void work() { - try { - byte[] buffer = new byte[BUFFER_SIZE]; - int read = producerInputStream.read(buffer, 0, buffer.length); - if (read > 0) { - processOutputStream.write(buffer, 0, read); - } else { - exit(); - } - } catch (IOException e) { - logger.error("", e); - exit(); - } - } + public void work() { + try { + byte[] buffer = new byte[BUFFER_SIZE]; + int read = producerInputStream.read(buffer, 0, buffer.length); + if (read > 0) { + processOutputStream.write(buffer, 0, read); + } else { + exit(); + } + } catch (IOException e) { + logger.error("", e); + exit(); + } + } } diff --git a/java/sound/src/main/java/sound/consumer/Shoutcast.java b/java/sound/src/main/java/sound/consumer/Shoutcast.java index a6b056b..a87a78a 100644 --- a/java/sound/src/main/java/sound/consumer/Shoutcast.java +++ b/java/sound/src/main/java/sound/consumer/Shoutcast.java @@ -25,272 +25,272 @@ import base.work.Work; import com.Ostermiller.util.CircularObjectBuffer; public class Shoutcast extends Work implements Consumer { - public static final int PORT = 9876; - public static final int RATE = 192; // in kbps - public static final int META = 8192; // in bytes - public static final int STEP = 80; // in milliseconds - public static final int BUFFER = 2000; // in bytes - public static final int BUFFERING = 500; // in milliseconds - public static final String DATA = "StreamTitle='%s';StreamUrl='%s';"; - protected int rate; - protected int port; - protected Server server; - protected HashMap headerMap; - protected ConcurrentLinkedQueue clientList; - protected InputStream producerInputStream; - protected int chunk; - protected Buffer buffer; - protected byte[] bytes; - protected Data data; - protected String metaData; - private CircularObjectBuffer circularStringBuffer; + public static final int PORT = 9876; + public static final int RATE = 192; // in kbps + public static final int META = 8192; // in bytes + public static final int STEP = 80; // in milliseconds + public static final int BUFFER = 2000; // in bytes + public static final int BUFFERING = 500; // in milliseconds + public static final String DATA = "StreamTitle='%s';StreamUrl='%s';"; + protected int rate; + protected int port; + protected Server server; + protected HashMap headerMap; + protected ConcurrentLinkedQueue clientList; + protected InputStream producerInputStream; + protected int chunk; + protected Buffer buffer; + protected byte[] bytes; + protected Data data; + protected String metaData; + private CircularObjectBuffer circularStringBuffer; - public Shoutcast() { - this(RATE, PORT); - } + public Shoutcast() { + this(RATE, PORT); + } - public Shoutcast(int rate) { - this(rate, PORT); - } + public Shoutcast(int rate) { + this(rate, PORT); + } - public Shoutcast(int rate, int port) { - this.rate = rate; - this.port = port; - clientList = new ConcurrentLinkedQueue(); - metaData = ""; + public Shoutcast(int rate, int port) { + this.rate = rate; + this.port = port; + clientList = new ConcurrentLinkedQueue(); + metaData = ""; - chunk = STEP * rate / 8; - bytes = new byte[chunk]; - buffer = new Buffer(BUFFER * rate / 8); + chunk = STEP * rate / 8; + bytes = new byte[chunk]; + buffer = new Buffer(BUFFER * rate / 8); - headerMap = new HashMap(); - headerMap.put("icy-notice1", "This stream requires Winamp"); - headerMap.put("icy-notice2", "Java SHOUTcast Server"); - headerMap.put("icy-name", "Java Radio"); - headerMap.put("icy-genre", "Java"); - headerMap.put("icy-url", "http://localhost"); - headerMap.put("content-type:", "audio/mpeg"); - headerMap.put("icy-pub", "0"); - headerMap.put("icy-metaint", String.valueOf(META)); - headerMap.put("icy-br", String.valueOf(rate)); - } + headerMap = new HashMap(); + headerMap.put("icy-notice1", "This stream requires Winamp"); + headerMap.put("icy-notice2", "Java SHOUTcast Server"); + headerMap.put("icy-name", "Java Radio"); + headerMap.put("icy-genre", "Java"); + headerMap.put("icy-url", "http://localhost"); + headerMap.put("content-type:", "audio/mpeg"); + headerMap.put("icy-pub", "0"); + headerMap.put("icy-metaint", String.valueOf(META)); + headerMap.put("icy-br", String.valueOf(rate)); + } - public void activate() throws ActivateException { - logger.trace("Activate Server"); - server = new Server(port); - server.start(); - super.activate(); - } + public void activate() throws ActivateException { + logger.trace("Activate Server"); + server = new Server(port); + server.start(); + super.activate(); + } - public boolean active() { - return server.active(); - } + public boolean active() { + return server.active(); + } - public void deactivate() throws DeactivateException { - super.deactivate(); - server.stop(); - } + public void deactivate() throws DeactivateException { + super.deactivate(); + server.stop(); + } - public void work() { - int progress; - try { - int read = 0; - if (producerInputStream != null) { - while (producerInputStream.available() < buffer.capacity) { - progress = (int) (producerInputStream.available() / (buffer.capacity / 100.0F)); - logger.debug("Filling buffer: " + progress + "%"); - sleep(BUFFERING); - } - read = producerInputStream.read(bytes); - } - data = new Data(bytes, read); - buffer.write(bytes, 0, read); - } catch (IOException e) { - logger.error(e.getMessage()); - } + public void work() { + int progress; + try { + int read = 0; + if (producerInputStream != null) { + while (producerInputStream.available() < buffer.capacity) { + progress = (int) (producerInputStream.available() / (buffer.capacity / 100.0F)); + logger.debug("Filling buffer: " + progress + "%"); + sleep(BUFFERING); + } + read = producerInputStream.read(bytes); + } + data = new Data(bytes, read); + buffer.write(bytes, 0, read); + } catch (IOException e) { + logger.error(e.getMessage()); + } - for (Client client : clientList) { - if (client.active) { - client.add(data); - } - } - sleep(STEP); - } + for (Client client : clientList) { + if (client.active) { + client.add(data); + } + } + sleep(STEP); + } - public void setMetaBuffer(CircularObjectBuffer circularStringBuffer) { - logger.debug("Set meta input stream"); - this.circularStringBuffer = circularStringBuffer; - } + public void setMetaBuffer(CircularObjectBuffer circularStringBuffer) { + logger.debug("Set meta input stream"); + this.circularStringBuffer = circularStringBuffer; + } - public void setMeta(String meta) { - logger.debug("Set meta string: " + meta); - metaData = meta; - } + public void setMeta(String meta) { + logger.debug("Set meta string: " + meta); + metaData = meta; + } - protected class Client extends Listen { - protected Socket socket; - protected InputStream inputStream; - protected OutputStream outputStream; - protected boolean writeMeta; - protected int untilMeta; - protected boolean active; + protected class Client extends Listen { + protected Socket socket; + protected InputStream inputStream; + protected OutputStream outputStream; + protected boolean writeMeta; + protected int untilMeta; + protected boolean active; - public Client(Socket socket) throws IOException { - this.socket = socket; - inputStream = socket.getInputStream(); - outputStream = socket.getOutputStream(); - active = false; - clientList.add(this); - } + public Client(Socket socket) throws IOException { + this.socket = socket; + inputStream = socket.getInputStream(); + outputStream = socket.getOutputStream(); + active = false; + clientList.add(this); + } - public void activate() throws ActivateException { - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - try { - String line; - while ((line = bufferedReader.readLine()) != null) { - if (line.startsWith("Icy-MetaData")) { - writeMeta = Integer.valueOf(line.substring(line.indexOf(":") + 1).trim()).intValue() == 1; - untilMeta = META; - } else if (line.equals("")) { - break; - } - } - logger.debug(String.format("Client accept meta: %s", Boolean.valueOf(writeMeta))); + public void activate() throws ActivateException { + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + try { + String line; + while ((line = bufferedReader.readLine()) != null) { + if (line.startsWith("Icy-MetaData")) { + writeMeta = Integer.valueOf(line.substring(line.indexOf(":") + 1).trim()).intValue() == 1; + untilMeta = META; + } else if (line.equals("")) { + break; + } + } + logger.debug(String.format("Client accept meta: %s", Boolean.valueOf(writeMeta))); - OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); - outputStreamWriter.write("ICY 200 OK\r\n"); - for (Entry header : headerMap.entrySet()) { - outputStreamWriter.write(String.format("%s: %s\r\n", header.getKey(), header.getValue())); - } - outputStreamWriter.write("\r\n"); - outputStreamWriter.flush(); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); + outputStreamWriter.write("ICY 200 OK\r\n"); + for (Entry header : headerMap.entrySet()) { + outputStreamWriter.write(String.format("%s: %s\r\n", header.getKey(), header.getValue())); + } + outputStreamWriter.write("\r\n"); + outputStreamWriter.flush(); - add(new Data(buffer.get())); - active = true; - } catch (IOException e) { - logger.error(e.getMessage()); - throw new ActivateException(); - } - super.activate(); - } + add(new Data(buffer.get())); + active = true; + } catch (IOException e) { + logger.error(e.getMessage()); + throw new ActivateException(); + } + super.activate(); + } - public void exit() { - logger.debug("Client exit"); - super.exit(); - clientList.remove(this); - try { - inputStream.close(); - outputStream.close(); - socket.close(); - } catch (IOException e) { - logger.error(e.getMessage()); - } - } + public void exit() { + logger.debug("Client exit"); + super.exit(); + clientList.remove(this); + try { + inputStream.close(); + outputStream.close(); + socket.close(); + } catch (IOException e) { + logger.error(e.getMessage()); + } + } - public void input(Data data) { - try { - byte[] bytes = data.get(); - if (writeMeta) { - int offset = 0; - while (data.length() - offset >= untilMeta) { - outputStream.write(bytes, offset, untilMeta); - writeMeta(); - offset += untilMeta; - untilMeta = META; - } - int length = data.length() - offset; - outputStream.write(bytes, offset, length); - untilMeta -= length; - } else { - outputStream.write(bytes); - } - } catch (SocketException e) { - exit(); - } catch (IOException e) { - exit(); - } - } + public void input(Data data) { + try { + byte[] bytes = data.get(); + if (writeMeta) { + int offset = 0; + while (data.length() - offset >= untilMeta) { + outputStream.write(bytes, offset, untilMeta); + writeMeta(); + offset += untilMeta; + untilMeta = META; + } + int length = data.length() - offset; + outputStream.write(bytes, offset, length); + untilMeta -= length; + } else { + outputStream.write(bytes); + } + } catch (SocketException e) { + exit(); + } catch (IOException e) { + exit(); + } + } - protected void writeMeta() throws IOException { - if ((circularStringBuffer != null) - && (circularStringBuffer.getAvailable() > 0)) { - try { - String newMetaData = circularStringBuffer.read(); - if (!newMetaData.isEmpty() && !newMetaData.equals(metaData)) { - metaData = newMetaData; - } - } catch (InterruptedException e) { - logger.error(e.getMessage()); - } - } + protected void writeMeta() throws IOException { + if ((circularStringBuffer != null) + && (circularStringBuffer.getAvailable() > 0)) { + try { + String newMetaData = circularStringBuffer.read(); + if (!newMetaData.isEmpty() && !newMetaData.equals(metaData)) { + metaData = newMetaData; + } + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } - String meta = String.format("StreamTitle='%s';StreamUrl='%s';", metaData, "???"); - byte[] metaBytes = meta.getBytes(); + String meta = String.format("StreamTitle='%s';StreamUrl='%s';", metaData, "???"); + byte[] metaBytes = meta.getBytes(); - int length = (int) Math.ceil(metaBytes.length / 16.0F); - outputStream.write(length); - outputStream.write(metaBytes); + int length = (int) Math.ceil(metaBytes.length / 16.0F); + outputStream.write(length); + outputStream.write(metaBytes); - int padding = 16 * length - metaBytes.length; - outputStream.write(new byte[padding], 0, padding); - } - } + int padding = 16 * length - metaBytes.length; + outputStream.write(new byte[padding], 0, padding); + } + } - protected class Server extends Work { - protected int port; - protected ServerSocket serverSocket; + protected class Server extends Work { + protected int port; + protected ServerSocket serverSocket; - public Server(int port) { - this.port = port; - } + public Server(int port) { + this.port = port; + } - public boolean active() { - return serverSocket.isClosed() ? false : true; - } + public boolean active() { + return serverSocket.isClosed() ? false : true; + } - public void activate() throws ActivateException { - try { - serverSocket = new ServerSocket(port); - logger.debug("Server listening at port " + port); - } catch (IOException e) { - logger.error("", e); - throw new ActivateException(); - } - super.activate(); - } + public void activate() throws ActivateException { + try { + serverSocket = new ServerSocket(port); + logger.debug("Server listening at port " + port); + } catch (IOException e) { + logger.error("", e); + throw new ActivateException(); + } + super.activate(); + } - public void work() { - try { - Socket socket = serverSocket.accept(); - logger.trace("Client connected: " + socket.getInetAddress().toString()); - Shoutcast.Client client = new Shoutcast.Client(socket); - client.start(); - } catch (IOException e) { - logger.error(e.getMessage()); - } - } + public void work() { + try { + Socket socket = serverSocket.accept(); + logger.trace("Client connected: " + socket.getInetAddress().toString()); + Shoutcast.Client client = new Shoutcast.Client(socket); + client.start(); + } catch (IOException e) { + logger.error(e.getMessage()); + } + } - public void deactivate() throws DeactivateException { - logger.debug("Server deactivate"); - super.deactivate(); - try { - serverSocket.close(); - } catch (IOException e) { - logger.error(e.getMessage()); - } - for (Shoutcast.Client client : clientList) { - client.stop(); - } - } - } + public void deactivate() throws DeactivateException { + logger.debug("Server deactivate"); + super.deactivate(); + try { + serverSocket.close(); + } catch (IOException e) { + logger.error(e.getMessage()); + } + for (Shoutcast.Client client : clientList) { + client.stop(); + } + } + } - public void start(Producer producer) { - producerInputStream = producer.getInputStream(); - producer.start(); - super.start(); - } + public void start(Producer producer) { + producerInputStream = producer.getInputStream(); + producer.start(); + super.start(); + } - public void setInputStream(InputStream inputStream) { - producerInputStream = inputStream; - } + public void setInputStream(InputStream inputStream) { + producerInputStream = inputStream; + } } diff --git a/java/sound/src/main/java/sound/data/Data.java b/java/sound/src/main/java/sound/data/Data.java index d66cb3b..645cccc 100644 --- a/java/sound/src/main/java/sound/data/Data.java +++ b/java/sound/src/main/java/sound/data/Data.java @@ -1,23 +1,23 @@ package sound.data; public class Data { - protected byte[] bytes; - protected int length; + protected byte[] bytes; + protected int length; - public Data(byte[] bytes) { - this(bytes, bytes.length); - } + public Data(byte[] bytes) { + this(bytes, bytes.length); + } - public Data(byte[] bytes, int length) { - this.bytes = bytes; - this.length = length; - } + public Data(byte[] bytes, int length) { + this.bytes = bytes; + this.length = length; + } - public byte[] get() { - return this.bytes; - } + public byte[] get() { + return this.bytes; + } - public int length() { - return this.length; - } + public int length() { + return this.length; + } } \ No newline at end of file diff --git a/java/sound/src/main/java/sound/producer/Stream.java b/java/sound/src/main/java/sound/producer/Stream.java index 3503ac1..efa3dab 100644 --- a/java/sound/src/main/java/sound/producer/Stream.java +++ b/java/sound/src/main/java/sound/producer/Stream.java @@ -18,183 +18,183 @@ import com.Ostermiller.util.CircularByteBuffer; import com.Ostermiller.util.CircularObjectBuffer; public class Stream extends Work implements Producer, Format.Mp3 { - public static final int STEP = 80; // in milliseconds + public static final int STEP = 80; // in milliseconds - protected String http; - protected Socket socket; - protected InputStream socketInputStream; - protected OutputStreamWriter socketOutputStreamWriter; - protected HoardedInputStream hoardedInputStream; - protected int meta; - protected int rate; - protected int chunk; - protected int untilMeta; - protected CircularByteBuffer audioCircularByteBuffer; - protected CircularObjectBuffer metaCircularObjectBuffer; - protected String metaData; + protected String http; + protected Socket socket; + protected InputStream socketInputStream; + protected OutputStreamWriter socketOutputStreamWriter; + protected HoardedInputStream hoardedInputStream; + protected int meta; + protected int rate; + protected int chunk; + protected int untilMeta; + protected CircularByteBuffer audioCircularByteBuffer; + protected CircularObjectBuffer metaCircularObjectBuffer; + protected String metaData; - public Stream(String http) { - super(); - this.http = http; - meta = -1; - rate = -1; - audioCircularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); - metaCircularObjectBuffer = new CircularObjectBuffer(); - } + public Stream(String http) { + super(); + this.http = http; + meta = -1; + rate = -1; + audioCircularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); + metaCircularObjectBuffer = new CircularObjectBuffer(); + } - protected void connect(URL url) { - try { - /* Open socket communication */ - socket = new Socket(url.getHost(), url.getPort()); - socketInputStream = socket.getInputStream(); - socketOutputStreamWriter = new OutputStreamWriter(socket.getOutputStream()); + protected void connect(URL url) { + try { + /* Open socket communication */ + socket = new Socket(url.getHost(), url.getPort()); + socketInputStream = socket.getInputStream(); + socketOutputStreamWriter = new OutputStreamWriter(socket.getOutputStream()); - /* Write stream request */ - if (url.getFile().equals("")) { - socketOutputStreamWriter.write("GET / HTTP/1.1\r\n"); - } else { - socketOutputStreamWriter.write("GET " + url.getFile() + " HTTP/1.1\r\n"); - } - socketOutputStreamWriter.write("Host: " + url.getHost() + "\r\n"); - //socketOutputStreamWriter.write("Icy-MetaData: 1\r\n"); - socketOutputStreamWriter.write("Connection: close\r\n"); - socketOutputStreamWriter.write("\r\n"); - socketOutputStreamWriter.flush(); - } catch (IOException e) { - e.printStackTrace(); - } - } + /* Write stream request */ + if (url.getFile().equals("")) { + socketOutputStreamWriter.write("GET / HTTP/1.1\r\n"); + } else { + socketOutputStreamWriter.write("GET " + url.getFile() + " HTTP/1.1\r\n"); + } + socketOutputStreamWriter.write("Host: " + url.getHost() + "\r\n"); + //socketOutputStreamWriter.write("Icy-MetaData: 1\r\n"); + socketOutputStreamWriter.write("Connection: close\r\n"); + socketOutputStreamWriter.write("\r\n"); + socketOutputStreamWriter.flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } - public void activate() throws ActivateException { - try { - /* Initialize connection */ - URL url = new URL(http); + public void activate() throws ActivateException { + try { + /* Initialize connection */ + URL url = new URL(http); - /* Parse headers */ - connect(url); - InputStreamReader inputStreamReader = new InputStreamReader(socketInputStream); - StringBuffer stringBuffer = new StringBuffer(); - char character; - int skip = 0; - while ((character = (char) inputStreamReader.read()) > 0) { - ++skip; - if (character == '\n') { - /* Fetch relevant headers */ - String line = stringBuffer.toString().trim(); - if (line.startsWith("icy-metaint")) { - meta = Integer.valueOf(line.substring(line.indexOf(":") + 1).trim()); - } else if (line.startsWith("icy-br")) { - rate = Integer.valueOf(line.substring(line.indexOf(":") + 1).trim()); - } else if (line.equals("")) { - break; - } - stringBuffer = new StringBuffer(); - } else { - stringBuffer.append(character); - } - } - inputStreamReader.close(); + /* Parse headers */ + connect(url); + InputStreamReader inputStreamReader = new InputStreamReader(socketInputStream); + StringBuffer stringBuffer = new StringBuffer(); + char character; + int skip = 0; + while ((character = (char) inputStreamReader.read()) > 0) { + ++skip; + if (character == '\n') { + /* Fetch relevant headers */ + String line = stringBuffer.toString().trim(); + if (line.startsWith("icy-metaint")) { + meta = Integer.valueOf(line.substring(line.indexOf(":") + 1).trim()); + } else if (line.startsWith("icy-br")) { + rate = Integer.valueOf(line.substring(line.indexOf(":") + 1).trim()); + } else if (line.equals("")) { + break; + } + stringBuffer = new StringBuffer(); + } else { + stringBuffer.append(character); + } + } + inputStreamReader.close(); - /* Reconnect to bypass pre-buffering problems */ - connect(url); - socketInputStream = socket.getInputStream(); - socketInputStream.skip(skip); - } catch (IOException e) { - e.printStackTrace(); - } catch (NumberFormatException e) { - e.printStackTrace(); - } + /* Reconnect to bypass pre-buffering problems */ + connect(url); + socketInputStream = socket.getInputStream(); + socketInputStream.skip(skip); + } catch (IOException e) { + e.printStackTrace(); + } catch (NumberFormatException e) { + e.printStackTrace(); + } - /* Calculate streaming parameters */ - //untilMeta = meta; - chunk = STEP * rate / 8; - super.activate(); - } + /* Calculate streaming parameters */ + //untilMeta = meta; + chunk = STEP * rate / 8; + super.activate(); + } - public void deactivate() throws DeactivateException { - super.deactivate(); - audioCircularByteBuffer.clear(); - metaCircularObjectBuffer.clear(); - try { - hoardedInputStream.clear(); - } catch (IOException e) { - logger.error("", e); - throw new DeactivateException(); - } - } + public void deactivate() throws DeactivateException { + super.deactivate(); + audioCircularByteBuffer.clear(); + metaCircularObjectBuffer.clear(); + try { + hoardedInputStream.clear(); + } catch (IOException e) { + logger.error("", e); + throw new DeactivateException(); + } + } - public void work() { - int left = chunk; + public void work() { + int left = chunk; - /* Handle media at appropriate times * - while (meta > 0 && left >= untilMeta) { - stream(untilMeta); - left -= untilMeta; - meta(); - untilMeta = meta; - }*/ + /* Handle media at appropriate times * + while (meta > 0 && left >= untilMeta) { + stream(untilMeta); + left -= untilMeta; + meta(); + untilMeta = meta; + }*/ - /* Stream at fixed rate */ - stream(left); - //untilMeta -= left; - sleep(STEP); - } + /* Stream at fixed rate */ + stream(left); + //untilMeta -= left; + sleep(STEP); + } - protected void stream(int length) { - try { - byte[] bytes = new byte[length]; - int read = 0; - while (length > 0 && (read = socketInputStream.read(bytes)) > 0) { - length -= read; - audioCircularByteBuffer.getOutputStream().write(bytes); - } - } catch (IOException e) { - logger.error(e.getMessage()); - stop(); - } - } + protected void stream(int length) { + try { + byte[] bytes = new byte[length]; + int read = 0; + while (length > 0 && (read = socketInputStream.read(bytes)) > 0) { + length -= read; + audioCircularByteBuffer.getOutputStream().write(bytes); + } + } catch (IOException e) { + logger.error(e.getMessage()); + stop(); + } + } - protected void meta() { - try { - /* Retrieve data length */ - byte[] data = new byte[1]; - socketInputStream.read(data); + protected void meta() { + try { + /* Retrieve data length */ + byte[] data = new byte[1]; + socketInputStream.read(data); - int length = 16 * data[0]; - data = new byte[length]; - socketInputStream.read(data); + int length = 16 * data[0]; + data = new byte[length]; + socketInputStream.read(data); - /* Check for new data */ - String newMetaData = new String(data); - if (!newMetaData.isEmpty() && !newMetaData.equals(metaData)) { - metaData = newMetaData; - metaCircularObjectBuffer.write(new String(data)); - logger.debug("data: " + metaData); - } - return; - } catch (IOException e) { - logger.error("", e); - } catch (IllegalStateException e) { - logger.error("", e); - } catch (InterruptedException e) { - logger.error("", e); - } - stop(); - return; - } + /* Check for new data */ + String newMetaData = new String(data); + if (!newMetaData.isEmpty() && !newMetaData.equals(metaData)) { + metaData = newMetaData; + metaCircularObjectBuffer.write(new String(data)); + logger.debug("data: " + metaData); + } + return; + } catch (IOException e) { + logger.error("", e); + } catch (IllegalStateException e) { + logger.error("", e); + } catch (InterruptedException e) { + logger.error("", e); + } + stop(); + return; + } - public InputStream getInputStream() { - if (hoardedInputStream == null) { - hoardedInputStream = new HoardedInputStream(audioCircularByteBuffer.getInputStream()); - } - return hoardedInputStream; - } + public InputStream getInputStream() { + if (hoardedInputStream == null) { + hoardedInputStream = new HoardedInputStream(audioCircularByteBuffer.getInputStream()); + } + return hoardedInputStream; + } - public CircularObjectBuffer getMetaBufferStream() { - return metaCircularObjectBuffer; - } + public CircularObjectBuffer getMetaBufferStream() { + return metaCircularObjectBuffer; + } - public int getRate() { - return rate; - } + public int getRate() { + return rate; + } } diff --git a/java/sound/src/main/java/sound/producer/Target.java b/java/sound/src/main/java/sound/producer/Target.java index e752e5d..e8b1412 100644 --- a/java/sound/src/main/java/sound/producer/Target.java +++ b/java/sound/src/main/java/sound/producer/Target.java @@ -16,82 +16,82 @@ import sound.stream.HoardedInputStream; import sound.util.Tool; public class Target implements Producer, Format.Standard { - protected Logger logger = LoggerFactory.getLogger(getClass()); + protected Logger logger = LoggerFactory.getLogger(getClass()); - protected Standard format; + protected Standard format; - protected TargetDataLine line; - protected InputStream targetInputStream; - protected HoardedInputStream hoardedInputStream; + protected TargetDataLine line; + protected InputStream targetInputStream; + protected HoardedInputStream hoardedInputStream; - protected AudioFormat audioFormat; + protected AudioFormat audioFormat; - public Target(String name) throws LineUnavailableException { - logger.debug(String.format("Target \"%s\" without format", name)); - line = Tool.getTargetDataLine(name); - audioFormat = line.getFormat(); - targetInputStream = new TargetInputStream(); - } + public Target(String name) throws LineUnavailableException { + logger.debug(String.format("Target \"%s\" without format", name)); + line = Tool.getTargetDataLine(name); + audioFormat = line.getFormat(); + targetInputStream = new TargetInputStream(); + } - public Target(String name, AudioFormat audioFormat) throws LineUnavailableException { - logger.debug(String.format("Target \"%s\" with format: %s", name, audioFormat)); - this.audioFormat = audioFormat; - line = Tool.getTargetDataLine(name, audioFormat); - targetInputStream = new TargetInputStream(); - } + public Target(String name, AudioFormat audioFormat) throws LineUnavailableException { + logger.debug(String.format("Target \"%s\" with format: %s", name, audioFormat)); + this.audioFormat = audioFormat; + line = Tool.getTargetDataLine(name, audioFormat); + targetInputStream = new TargetInputStream(); + } - public AudioFormat getAudioFormat() { - return audioFormat; - } + public AudioFormat getAudioFormat() { + return audioFormat; + } - public InputStream getInputStream() { - return targetInputStream; - } + public InputStream getInputStream() { + return targetInputStream; + } - public class TargetInputStream extends InputStream { - protected boolean open; + public class TargetInputStream extends InputStream { + protected boolean open; - public TargetInputStream() { - open = false; - } + public TargetInputStream() { + open = false; + } - public int read() throws IOException { - start(); - byte[] buffer = new byte[1]; - line.read(buffer, 0, 1); - return (int) buffer[0]; - } + public int read() throws IOException { + start(); + byte[] buffer = new byte[1]; + line.read(buffer, 0, 1); + return (int) buffer[0]; + } - public int read(byte[] buffer, int offset, int length) { - start(); - line.read(buffer, offset, length); - return length; - } + public int read(byte[] buffer, int offset, int length) { + start(); + line.read(buffer, offset, length); + return length; + } - public int available() { - start(); - return line.available(); - } - } + public int available() { + start(); + return line.available(); + } + } - public void start() { - if (!line.isOpen()) { - try { - line.open(); - } catch (LineUnavailableException e) { - logger.error("", e); - } - } - if (!line.isRunning()) { - line.start(); - } - } + public void start() { + if (!line.isOpen()) { + try { + line.open(); + } catch (LineUnavailableException e) { + logger.error("", e); + } + } + if (!line.isRunning()) { + line.start(); + } + } - public void stop() { - line.flush(); - } + public void stop() { + line.flush(); + } - public void exit() { - line.close(); - } + public void exit() { + line.close(); + } } diff --git a/java/sound/src/main/java/sound/stream/HoardedInputStream.java b/java/sound/src/main/java/sound/stream/HoardedInputStream.java index beb941c..bc94391 100644 --- a/java/sound/src/main/java/sound/stream/HoardedInputStream.java +++ b/java/sound/src/main/java/sound/stream/HoardedInputStream.java @@ -8,69 +8,69 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HoardedInputStream extends BufferedInputStream { - protected Logger logger = LoggerFactory.getLogger(getClass()); + protected Logger logger = LoggerFactory.getLogger(getClass()); protected static final int SLEEP = 500; // in milliseconds - protected static final int BUFFER_SIZE = 30000; // in bytes - protected static final int MINIMUM_SIZE = 1000; // in bytes + protected static final int BUFFER_SIZE = 30000; // in bytes + protected static final int MINIMUM_SIZE = 1000; // in bytes - protected int bufferSize; - protected int minimumSize; - protected boolean hoard; + protected int bufferSize; + protected int minimumSize; + protected boolean hoard; - public HoardedInputStream(InputStream inputStream) { - this(inputStream, BUFFER_SIZE, MINIMUM_SIZE); - } + public HoardedInputStream(InputStream inputStream) { + this(inputStream, BUFFER_SIZE, MINIMUM_SIZE); + } - public HoardedInputStream(InputStream inputStream, int bufferSize) { - super(inputStream, bufferSize); - this.bufferSize = bufferSize; - hoard = true; - } - - public HoardedInputStream(InputStream inputStream, int bufferSize, int minimumSize) { - this(inputStream, bufferSize); - this.minimumSize = minimumSize; - } + public HoardedInputStream(InputStream inputStream, int bufferSize) { + super(inputStream, bufferSize); + this.bufferSize = bufferSize; + hoard = true; + } + + public HoardedInputStream(InputStream inputStream, int bufferSize, int minimumSize) { + this(inputStream, bufferSize); + this.minimumSize = minimumSize; + } - public int read() throws IOException { - hoard(); - byte[] buffer = new byte[1]; - in.read(buffer, 0, 1); - return (int) buffer[0]; - } + public int read() throws IOException { + hoard(); + byte[] buffer = new byte[1]; + in.read(buffer, 0, 1); + return (int) buffer[0]; + } - public int read(byte[] buffer, int offset, int length) throws IOException { - hoard(); - in.read(buffer, offset, length); - return length; - } + public int read(byte[] buffer, int offset, int length) throws IOException { + hoard(); + in.read(buffer, offset, length); + return length; + } - public void hoard() throws IOException { - int available = available(); - if (hoard && available < MINIMUM_SIZE) { - long time = System.currentTimeMillis(); - do { - try { - Thread.sleep(SLEEP); - } catch (InterruptedException e) { - logger.warn("", e); - } - } while (available() < BUFFER_SIZE); - logger.debug(String.format("Buffered %d bytes in %s milliseconds", BUFFER_SIZE - available, System.currentTimeMillis() - time)); - } - } + public void hoard() throws IOException { + int available = available(); + if (hoard && available < MINIMUM_SIZE) { + long time = System.currentTimeMillis(); + do { + try { + Thread.sleep(SLEEP); + } catch (InterruptedException e) { + logger.warn("", e); + } + } while (available() < BUFFER_SIZE); + logger.debug(String.format("Buffered %d bytes in %s milliseconds", BUFFER_SIZE - available, System.currentTimeMillis() - time)); + } + } - public void clear() throws IOException { - this.buf = new byte[buf.length]; - reset(); - } + public void clear() throws IOException { + this.buf = new byte[buf.length]; + reset(); + } - public void drain() { - drain(true); - } + public void drain() { + drain(true); + } - public void drain(boolean drain) { - hoard = !drain; - } + public void drain(boolean drain) { + hoard = !drain; + } } diff --git a/java/sound/src/main/java/sound/util/Buffer.java b/java/sound/src/main/java/sound/util/Buffer.java index 419ceaa..2beb9fc 100644 --- a/java/sound/src/main/java/sound/util/Buffer.java +++ b/java/sound/src/main/java/sound/util/Buffer.java @@ -1,41 +1,41 @@ package sound.util; public class Buffer { - protected byte[] elements; - public int capacity; - protected int index; - protected int size; + protected byte[] elements; + public int capacity; + protected int index; + protected int size; - public Buffer(int capacity) { - elements = new byte[capacity]; - this.capacity = capacity; - index = 0; - size = 0; - } + public Buffer(int capacity) { + elements = new byte[capacity]; + this.capacity = capacity; + index = 0; + size = 0; + } - public synchronized void add(byte[] elements) { - for (byte element : elements) { - elements[index++ % capacity] = element; - if (size < capacity) { - ++size; - } - } - } + public synchronized void add(byte[] elements) { + for (byte element : elements) { + elements[index++ % capacity] = element; + if (size < capacity) { + ++size; + } + } + } - public synchronized void write(byte[] elements, int offset, int length) { - for (int i = offset; i < length; ++i) { - this.elements[(index++ % capacity)] = elements[i]; - if (size < capacity) { - ++size; - } - } - } + public synchronized void write(byte[] elements, int offset, int length) { + for (int i = offset; i < length; ++i) { + this.elements[(index++ % capacity)] = elements[i]; + if (size < capacity) { + ++size; + } + } + } - public synchronized byte[] get() { - byte[] elements = new byte[size]; - for (int i = 0; i < size; i++) { - elements[i] = elements[((index + i) % size)]; - } - return elements; - } + public synchronized byte[] get() { + byte[] elements = new byte[size]; + for (int i = 0; i < size; i++) { + elements[i] = elements[((index + i) % size)]; + } + return elements; + } } \ No newline at end of file diff --git a/java/sound/src/main/java/sound/util/SoxBuilder.java b/java/sound/src/main/java/sound/util/SoxBuilder.java index 9870d50..4e3f1ef 100644 --- a/java/sound/src/main/java/sound/util/SoxBuilder.java +++ b/java/sound/src/main/java/sound/util/SoxBuilder.java @@ -9,313 +9,313 @@ import sound.util.SoxBuilder.Option.Combine; import sound.util.SoxBuilder.Option.Replay; public final class SoxBuilder { - protected static SoxBuilder instance; - protected static HashMap optionMap; - protected static String files; - protected static String effects; + protected static SoxBuilder instance; + protected static HashMap optionMap; + protected static String files; + protected static String effects; - static { - instance = new SoxBuilder(); - reset(); - } + static { + instance = new SoxBuilder(); + reset(); + } - public static void reset() { - optionMap = new HashMap(); - files = ""; - effects = ""; - } + public static void reset() { + optionMap = new HashMap(); + files = ""; + effects = ""; + } - public static SoxBuilder setOption(Option option, String value) { - optionMap.put(option.getCode(), value); - return instance; - } + public static SoxBuilder setOption(Option option, String value) { + optionMap.put(option.getCode(), value); + return instance; + } - public static SoxBuilder setOption(Option option) { - return SoxBuilder.setOption(option, ""); - } + public static SoxBuilder setOption(Option option) { + return SoxBuilder.setOption(option, ""); + } - public static SoxBuilder setOption(Option option, int value) { - return SoxBuilder.setOption(option, String.valueOf(value)); - } + public static SoxBuilder setOption(Option option, int value) { + return SoxBuilder.setOption(option, String.valueOf(value)); + } - public static SoxBuilder setOption(Option option, Combine combine) { - return SoxBuilder.setOption(option, combine.getCode()); - } + public static SoxBuilder setOption(Option option, Combine combine) { + return SoxBuilder.setOption(option, combine.getCode()); + } - public static SoxBuilder setOption(Combine combine) { - return SoxBuilder.setOption(Option.COMBINE, combine); - } + public static SoxBuilder setOption(Combine combine) { + return SoxBuilder.setOption(Option.COMBINE, combine); + } - public static SoxBuilder setOption(Option option, Replay replay) { - return SoxBuilder.setOption(option, replay.toString().toLowerCase()); - } + public static SoxBuilder setOption(Option option, Replay replay) { + return SoxBuilder.setOption(option, replay.toString().toLowerCase()); + } - public static SoxBuilder setOption(Replay replay) { - return SoxBuilder.setOption(Option.REPLAY, replay); - } + public static SoxBuilder setOption(Replay replay) { + return SoxBuilder.setOption(Option.REPLAY, replay); + } - public static SoxBuilder addFile(File file) { - files = String.format("%s %s", files, file.build()); - return instance; - } + public static SoxBuilder addFile(File file) { + files = String.format("%s %s", files, file.build()); + return instance; + } - public static SoxBuilder addEffect(Effect effect) { - effects = String.format("%s %s", effects, effect.build()); - return instance; - } + public static SoxBuilder addEffect(Effect effect) { + effects = String.format("%s %s", effects, effect.build()); + return instance; + } - public String build() { - String build = "sox"; - for (Entry entry : optionMap.entrySet()) { - String value = entry.getValue(); - if (value.equals("")) { - build = String.format("%s %s", build, entry.getKey()); - } else { - String option = String.format("%s %s", entry.getKey(), value); - build = String.format("%s %s", build, option); - } - } - build = String.format("%s%s%s", build, files, effects); - reset(); - return build; - } + public String build() { + String build = "sox"; + for (Entry entry : optionMap.entrySet()) { + String value = entry.getValue(); + if (value.equals("")) { + build = String.format("%s %s", build, entry.getKey()); + } else { + String option = String.format("%s %s", entry.getKey(), value); + build = String.format("%s %s", build, option); + } + } + build = String.format("%s%s%s", build, files, effects); + reset(); + return build; + } - public enum Environment { - AUDIODRIVER, AUDIODEV - } + public enum Environment { + AUDIODRIVER, AUDIODEV + } - public enum Option { - BUFFER ("--buffer"), // default=8192 - INPUT_BUFFER ("--input-buffer"), - CLOBBER ("--clobber"), - COMBINE ("--combine"), // |Combine| - NO_DITHER ("--no-dither"), // (-D) - EFFECTS_FILE ("--efects-file"), - GUARD ("--guard"), // (-G) - MIX ("-m"), // (--combine mix) - MERGE ("-M"), // (--combine merge) - MAGIC ("--magic"), - MULTI_THREADED ("--multi-threaded"), - SINGLE_THREADED ("--single-threaded"), - NORM ("--norm"), // [=dB-level] - PLAY_RATE_ARG ("--play-rate-arg"), - QUIET ("--no-show-progress"), // (-q) - REPEATABLE ("-R"), - REPLAY ("--replay-gain"), // |Replay| - MULTIPLY ("-T"), // (--combine multiply) - TEMP ("--temp"); + public enum Option { + BUFFER ("--buffer"), // default=8192 + INPUT_BUFFER ("--input-buffer"), + CLOBBER ("--clobber"), + COMBINE ("--combine"), // |Combine| + NO_DITHER ("--no-dither"), // (-D) + EFFECTS_FILE ("--efects-file"), + GUARD ("--guard"), // (-G) + MIX ("-m"), // (--combine mix) + MERGE ("-M"), // (--combine merge) + MAGIC ("--magic"), + MULTI_THREADED ("--multi-threaded"), + SINGLE_THREADED ("--single-threaded"), + NORM ("--norm"), // [=dB-level] + PLAY_RATE_ARG ("--play-rate-arg"), + QUIET ("--no-show-progress"), // (-q) + REPEATABLE ("-R"), + REPLAY ("--replay-gain"), // |Replay| + MULTIPLY ("-T"), // (--combine multiply) + TEMP ("--temp"); - protected String code; + protected String code; - private Option(String code) { - this.code = code; - } - - public String getCode() { - return code; - } + private Option(String code) { + this.code = code; + } + + public String getCode() { + return code; + } - public enum Combine { - CONCATENATE ("concatenate"), - MERGE ("merge"), // (-M) - MIX ("mix"), // (-m) - MIX_POWER ("mix-power"), - MULTIPLY ("multiply"), // (-T) - SEQUENCE ("sequence"); + public enum Combine { + CONCATENATE ("concatenate"), + MERGE ("merge"), // (-M) + MIX ("mix"), // (-m) + MIX_POWER ("mix-power"), + MULTIPLY ("multiply"), // (-T) + SEQUENCE ("sequence"); - protected String code; + protected String code; - private Combine(String code) { - this.code = code; - } - - public String getCode() { - return code; - } - } - - public enum Replay { - TRACK, ALBUM, OFF - } - } + private Combine(String code) { + this.code = code; + } + + public String getCode() { + return code; + } + } + + public enum Replay { + TRACK, ALBUM, OFF + } + } - public static class File { - protected static File instance; + public static class File { + protected static File instance; - protected static HashMap optionMap; - protected static Type type; + protected static HashMap optionMap; + protected static Type type; - static { - instance = new File(); - reset(); - } + static { + instance = new File(); + reset(); + } - public static void reset() { - optionMap = new HashMap(); - type = Type.PIPE; - } - - public static File setOption(Option option, String value) { - optionMap.put(option.getCode(), value); - return instance; - } + public static void reset() { + optionMap = new HashMap(); + type = Type.PIPE; + } + + public static File setOption(Option option, String value) { + optionMap.put(option.getCode(), value); + return instance; + } - public static File setOption(Option option) { - return File.setOption(option, ""); - } + public static File setOption(Option option) { + return File.setOption(option, ""); + } - public static File setOption(Option option, int value) { - return File.setOption(option, String.valueOf(value)); - } + public static File setOption(Option option, int value) { + return File.setOption(option, String.valueOf(value)); + } - public static File setOption(Option option, Encoding encoding) { - return File.setOption(option, encoding.getCode()); - } + public static File setOption(Option option, Encoding encoding) { + return File.setOption(option, encoding.getCode()); + } - public static File setOption(Encoding encoding) { - return File.setOption(Option.ENCODING, encoding); - } + public static File setOption(Encoding encoding) { + return File.setOption(Option.ENCODING, encoding); + } - public static File setOption(Option option, Format format) { - return File.setOption(option, format.toString().toLowerCase()); - } + public static File setOption(Option option, Format format) { + return File.setOption(option, format.toString().toLowerCase()); + } - public static File setOption( Format format) { - return File.setOption(Option.FORMAT, format); - } + public static File setOption( Format format) { + return File.setOption(Option.FORMAT, format); + } - public static File setOption(Option option, Endian endian) { - return File.setOption(option, endian.toString().toLowerCase()); - } + public static File setOption(Option option, Endian endian) { + return File.setOption(option, endian.toString().toLowerCase()); + } - public static File setOption(Endian endian) { - return File.setOption(Option.ENDIAN, endian); - } - - public File setOptions(AudioFormat audioFormat) { - setOption(Option.CHANNELS, audioFormat.getChannels()); - setOption(Option.RATE, String.format("%sk", String.valueOf(audioFormat.getSampleRate() / 1000f))); - AudioFormat.Encoding encoding = audioFormat.getEncoding(); - int bits = audioFormat.getSampleSizeInBits(); - if (encoding.equals(AudioFormat.Encoding.ALAW)) { - setOption(Format.AL); - setOption(Encoding.A_LAW); - } else if (encoding.equals(AudioFormat.Encoding.ULAW)) { - setOption(Format.UL); - setOption(Encoding.U_LAW); - } else if (encoding.equals(AudioFormat.Encoding.PCM_SIGNED)) { - setOption(Format.valueOf(String.format("S%d", bits))); - setOption(Encoding.SIGNED_INTEGER); - } else if (encoding.equals(AudioFormat.Encoding.PCM_UNSIGNED)) { - setOption(Format.valueOf(String.format("U%d", bits))); - setOption(Encoding.UNSIGNED_INTEGER); - } - setOption(audioFormat.isBigEndian() ? Endian.BIG : Endian.LITTLE); - return instance; - } + public static File setOption(Endian endian) { + return File.setOption(Option.ENDIAN, endian); + } + + public File setOptions(AudioFormat audioFormat) { + setOption(Option.CHANNELS, audioFormat.getChannels()); + setOption(Option.RATE, String.format("%sk", String.valueOf(audioFormat.getSampleRate() / 1000f))); + AudioFormat.Encoding encoding = audioFormat.getEncoding(); + int bits = audioFormat.getSampleSizeInBits(); + if (encoding.equals(AudioFormat.Encoding.ALAW)) { + setOption(Format.AL); + setOption(Encoding.A_LAW); + } else if (encoding.equals(AudioFormat.Encoding.ULAW)) { + setOption(Format.UL); + setOption(Encoding.U_LAW); + } else if (encoding.equals(AudioFormat.Encoding.PCM_SIGNED)) { + setOption(Format.valueOf(String.format("S%d", bits))); + setOption(Encoding.SIGNED_INTEGER); + } else if (encoding.equals(AudioFormat.Encoding.PCM_UNSIGNED)) { + setOption(Format.valueOf(String.format("U%d", bits))); + setOption(Encoding.UNSIGNED_INTEGER); + } + setOption(audioFormat.isBigEndian() ? Endian.BIG : Endian.LITTLE); + return instance; + } - public static File setType(Type type) { - File.type = type; - return instance; - } + public static File setType(Type type) { + File.type = type; + return instance; + } - public String build() { - String build = type.getCode(); - for (Entry entry : optionMap.entrySet()) { - String value = entry.getValue(); - if (value.equals("")) { - build = String.format("%s %s", entry.getKey(), build); - } else { - String option = String.format("%s %s", entry.getKey(), value); - build = String.format("%s %s", option, build); - } - } - reset(); - return build; - } + public String build() { + String build = type.getCode(); + for (Entry entry : optionMap.entrySet()) { + String value = entry.getValue(); + if (value.equals("")) { + build = String.format("%s %s", entry.getKey(), build); + } else { + String option = String.format("%s %s", entry.getKey(), value); + build = String.format("%s %s", option, build); + } + } + reset(); + return build; + } - public enum Option { - BITS ("--bits"), // (-b) - CHANNELS ("--channels"), // (-c) - ENCODING ("--encoding"), // (-e), |Encoding| - NO_GLOB ("--no-glob"), - RATE ("--rate"), // (-r) - FORMAT ("--type"), // (-t), |Format| - ENDIAN ("--endian"), // (-L, -B, -x), |Endian| - REVERSE_NIBBLES ("--reverse-nibbles"), // (-N) - REVERSE_BITS ("--reverse-bits"), // (-X) - /* Input only */ - IGNORE_LENGTH ("--ignore-length"), - VOLUME ("--volume"), // (-v) - /* Output only */ - ADD_COMMENT ("--add-comment"), - COMMENT ("--comment"), - COMMENT_FILE ("--comment-file"), - COMPRESSION ("--compression"); // -C - - protected String code; + public enum Option { + BITS ("--bits"), // (-b) + CHANNELS ("--channels"), // (-c) + ENCODING ("--encoding"), // (-e), |Encoding| + NO_GLOB ("--no-glob"), + RATE ("--rate"), // (-r) + FORMAT ("--type"), // (-t), |Format| + ENDIAN ("--endian"), // (-L, -B, -x), |Endian| + REVERSE_NIBBLES ("--reverse-nibbles"), // (-N) + REVERSE_BITS ("--reverse-bits"), // (-X) + /* Input only */ + IGNORE_LENGTH ("--ignore-length"), + VOLUME ("--volume"), // (-v) + /* Output only */ + ADD_COMMENT ("--add-comment"), + COMMENT ("--comment"), + COMMENT_FILE ("--comment-file"), + COMPRESSION ("--compression"); // -C + + protected String code; - private Option(String code) { - this.code = code; - } + private Option(String code) { + this.code = code; + } - public String getCode() { - return code; - } - } + public String getCode() { + return code; + } + } - public enum Encoding { - SIGNED_INTEGER ("signed-integer"), // PCM data stored as signed integers - UNSIGNED_INTEGER ("unsigned-integer"), // PCM data stored as unsigned integers - FLOATING_POINT ("floating-point"), // PCM data stored as single precision (32-bit) or double precision (64-bit) floating-point numbers - A_LAW ("a-lawW"), // International telephony standard for logarithmic encoding to 8 bits per sample (~13-bit PCM) - U_LAW ("u-law"), // North American telephony standard for logarithmic encoding to 8 bits per sample (~14-bit PCM) - MU_LAW ("mu-law"), // alias for u-law (~14-bit PCM) - OKI_ADPCM ("oki-adpcm"), // OKI (VOX, Dialogic or Intel) 4-bit ADPCM (~12-bit PCM) - IMA_ADPCM ("ima-adpcm"), // IMA (DVI) 4-bit ADPCM (~13-bit PCM) - MS_ADPCM ("ms-adpcm"), // Microsoft 4-bit ADPCM (~14-bit PCM) - GSM_FULL_RATE ("gsm-full-rate"); // Several audio formats used for digital wireless telephone calls + public enum Encoding { + SIGNED_INTEGER ("signed-integer"), // PCM data stored as signed integers + UNSIGNED_INTEGER ("unsigned-integer"), // PCM data stored as unsigned integers + FLOATING_POINT ("floating-point"), // PCM data stored as single precision (32-bit) or double precision (64-bit) floating-point numbers + A_LAW ("a-lawW"), // International telephony standard for logarithmic encoding to 8 bits per sample (~13-bit PCM) + U_LAW ("u-law"), // North American telephony standard for logarithmic encoding to 8 bits per sample (~14-bit PCM) + MU_LAW ("mu-law"), // alias for u-law (~14-bit PCM) + OKI_ADPCM ("oki-adpcm"), // OKI (VOX, Dialogic or Intel) 4-bit ADPCM (~12-bit PCM) + IMA_ADPCM ("ima-adpcm"), // IMA (DVI) 4-bit ADPCM (~13-bit PCM) + MS_ADPCM ("ms-adpcm"), // Microsoft 4-bit ADPCM (~14-bit PCM) + GSM_FULL_RATE ("gsm-full-rate"); // Several audio formats used for digital wireless telephone calls - protected String code; + protected String code; - private Encoding(String code) { - this.code = code; - } + private Encoding(String code) { + this.code = code; + } - public String getCode() { - return code; - } - } + public String getCode() { + return code; + } + } - public enum Format { - AIF, AIFC, AIFF, AIFFC, AL, AMB, AMR, ANY, ARL, AU, AVR, BIN, CAF, CDDA, CDR, CVS, CVSD, CVU, DAT, DVMS, EDU, F32, F64, FAP, FLAC, FSSD, GSM, GSRT, HCOM, HTK, IMA, IRCAM, LA, LPC, LPC10, LU, M3U, M4A, MAT, MAT4, MAT5, MAUD, MP2, MP3, MP4, NIST, OGG, PAF, PLS, PRC, PVF, RAW, S16, S24, S32, S8, SD2, SDS, SF, SLN, SMP, SND, SNDR, SNDT, SOU, SOX, SPH, TXW, U16, U24, U32, U8, UL, VMS, VOC, VORBIS, VOX, W64, WAV, WAVPCM, WV, WVE, XA, XI; - } + public enum Format { + AIF, AIFC, AIFF, AIFFC, AL, AMB, AMR, ANY, ARL, AU, AVR, BIN, CAF, CDDA, CDR, CVS, CVSD, CVU, DAT, DVMS, EDU, F32, F64, FAP, FLAC, FSSD, GSM, GSRT, HCOM, HTK, IMA, IRCAM, LA, LPC, LPC10, LU, M3U, M4A, MAT, MAT4, MAT5, MAUD, MP2, MP3, MP4, NIST, OGG, PAF, PLS, PRC, PVF, RAW, S16, S24, S32, S8, SD2, SDS, SF, SLN, SMP, SND, SNDR, SNDT, SOU, SOX, SPH, TXW, U16, U24, U32, U8, UL, VMS, VOC, VORBIS, VOX, W64, WAV, WAVPCM, WV, WVE, XA, XI; + } - public enum Endian { - LITTLE, BIG, SWAP; - } + public enum Endian { + LITTLE, BIG, SWAP; + } - public enum Type { - STANDARD ("-"), // -t must be given - PIPE ("-p"), // (--sox-pipe) - DEVICE ("-d"), // (--default-device) - NULL ("-n"); // (--null) + public enum Type { + STANDARD ("-"), // -t must be given + PIPE ("-p"), // (--sox-pipe) + DEVICE ("-d"), // (--default-device) + NULL ("-n"); // (--null) - protected String code; - - private Type(String code) { - this.code = code; - } - - public String getCode() { - return code; - } - } - } + protected String code; + + private Type(String code) { + this.code = code; + } + + public String getCode() { + return code; + } + } + } - public class Effect { - public String build() { - return null; - } - } + public class Effect { + public String build() { + return null; + } + } } diff --git a/java/sound/src/main/java/sound/util/Tool.java b/java/sound/src/main/java/sound/util/Tool.java index 22d5076..d5a654f 100644 --- a/java/sound/src/main/java/sound/util/Tool.java +++ b/java/sound/src/main/java/sound/util/Tool.java @@ -18,7 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Tool { - protected static Logger logger = LoggerFactory.getLogger(Tool.class); + protected static Logger logger = LoggerFactory.getLogger(Tool.class); protected static HashMap> targetMap; protected static HashMap> sourceMap; @@ -27,114 +27,114 @@ public class Tool { protected static ArrayList targetList; protected static ArrayList sourceList; - static { - Tool tool = new Tool(); + static { + Tool tool = new Tool(); - targetMap = new HashMap>(); - sourceMap = new HashMap>(); - targetList = new ArrayList(); - sourceList = new ArrayList(); - portList = new ArrayList(); + targetMap = new HashMap>(); + sourceMap = new HashMap>(); + targetList = new ArrayList(); + sourceList = new ArrayList(); + portList = new ArrayList(); - for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) { - String name = mixerInfo.getName(); - Mixer mixer = AudioSystem.getMixer(mixerInfo); - - for (Line.Info lineInfo : mixer.getSourceLineInfo()) { - String lineClassName = lineInfo.getLineClass().getName(); - if (lineClassName.equals("javax.sound.sampled.SourceDataLine")) { - if (mixer.isLineSupported(lineInfo)) { - logger.debug(" " + name); - sourceMap.put(name, tool.new Device(mixer, lineInfo)); - } - } - } - for (Line.Info lineInfo : mixer.getTargetLineInfo()) { - String lineClassName = lineInfo.getLineClass().getName(); - if (lineClassName.equals("javax.sound.sampled.TargetDataLine")) { - if (mixer.isLineSupported(lineInfo)) { - logger.debug(" " + name); - targetMap.put(name, tool.new Device(mixer, lineInfo)); - } - } else if (lineClassName.equals("javax.sound.sampled.Port")) { - name = name.substring(5); - try { - Port port = (Port) mixer.getLine(lineInfo); - Port.Info portInfo = (Info) port.getLineInfo(); - if (!targetMap.containsKey(name) || portInfo.equals(Port.Info.LINE_OUT) || portInfo.equals(Port.Info.SPEAKER)) { - logger.debug(" " + name); - portList.add(name); - } - } catch (LineUnavailableException e) { - logger.error("", e); - } - } - } - } - } + for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) { + String name = mixerInfo.getName(); + Mixer mixer = AudioSystem.getMixer(mixerInfo); + + for (Line.Info lineInfo : mixer.getSourceLineInfo()) { + String lineClassName = lineInfo.getLineClass().getName(); + if (lineClassName.equals("javax.sound.sampled.SourceDataLine")) { + if (mixer.isLineSupported(lineInfo)) { + logger.debug(" " + name); + sourceMap.put(name, tool.new Device(mixer, lineInfo)); + } + } + } + for (Line.Info lineInfo : mixer.getTargetLineInfo()) { + String lineClassName = lineInfo.getLineClass().getName(); + if (lineClassName.equals("javax.sound.sampled.TargetDataLine")) { + if (mixer.isLineSupported(lineInfo)) { + logger.debug(" " + name); + targetMap.put(name, tool.new Device(mixer, lineInfo)); + } + } else if (lineClassName.equals("javax.sound.sampled.Port")) { + name = name.substring(5); + try { + Port port = (Port) mixer.getLine(lineInfo); + Port.Info portInfo = (Info) port.getLineInfo(); + if (!targetMap.containsKey(name) || portInfo.equals(Port.Info.LINE_OUT) || portInfo.equals(Port.Info.SPEAKER)) { + logger.debug(" " + name); + portList.add(name); + } + } catch (LineUnavailableException e) { + logger.error("", e); + } + } + } + } + } - public static String[] getTargets() { - return targetMap.keySet().toArray(new String[0]); - } + public static String[] getTargets() { + return targetMap.keySet().toArray(new String[0]); + } - public static String[] getSources() { - return sourceMap.keySet().toArray(new String[0]); - } + public static String[] getSources() { + return sourceMap.keySet().toArray(new String[0]); + } - public static String[] getPorts() { - return portList.toArray(new String[0]); - } + public static String[] getPorts() { + return portList.toArray(new String[0]); + } - public static TargetDataLine getTargetDataLine(String name) throws LineUnavailableException { - if (targetMap.containsKey(name)) { - return targetMap.get(name).getLine(); - } else { - throw new LineUnavailableException(); - } - } + public static TargetDataLine getTargetDataLine(String name) throws LineUnavailableException { + if (targetMap.containsKey(name)) { + return targetMap.get(name).getLine(); + } else { + throw new LineUnavailableException(); + } + } - public static TargetDataLine getTargetDataLine(String name, AudioFormat audioFormat) throws LineUnavailableException { - if (targetMap.containsKey(name)) { - return targetMap.get(name).getLine(audioFormat); - } else { - throw new LineUnavailableException(); - } - } + public static TargetDataLine getTargetDataLine(String name, AudioFormat audioFormat) throws LineUnavailableException { + if (targetMap.containsKey(name)) { + return targetMap.get(name).getLine(audioFormat); + } else { + throw new LineUnavailableException(); + } + } - public static SourceDataLine getSourceDataLine(String name) throws LineUnavailableException { - if (sourceMap.containsKey(name)) { - return sourceMap.get(name).getLine(); - } else { - throw new LineUnavailableException(); - } - } + public static SourceDataLine getSourceDataLine(String name) throws LineUnavailableException { + if (sourceMap.containsKey(name)) { + return sourceMap.get(name).getLine(); + } else { + throw new LineUnavailableException(); + } + } - public static SourceDataLine getSourceDataLine(String name, AudioFormat audioFormat) throws LineUnavailableException { - if (sourceMap.containsKey(name)) { - return sourceMap.get(name).getLine(audioFormat); - } else { - throw new LineUnavailableException(); - } - } + public static SourceDataLine getSourceDataLine(String name, AudioFormat audioFormat) throws LineUnavailableException { + if (sourceMap.containsKey(name)) { + return sourceMap.get(name).getLine(audioFormat); + } else { + throw new LineUnavailableException(); + } + } - public class Device { - protected Mixer mixer; - protected Line.Info lineInfo; + public class Device { + protected Mixer mixer; + protected Line.Info lineInfo; - public Device(Mixer mixer, Line.Info lineInfo) { - this.mixer = mixer; - this.lineInfo = lineInfo; - } + public Device(Mixer mixer, Line.Info lineInfo) { + this.mixer = mixer; + this.lineInfo = lineInfo; + } - @SuppressWarnings("unchecked") - public T getLine() throws LineUnavailableException { - return (T) mixer.getLine(lineInfo); - } + @SuppressWarnings("unchecked") + public T getLine() throws LineUnavailableException { + return (T) mixer.getLine(lineInfo); + } - @SuppressWarnings("unchecked") - public T getLine(AudioFormat audioFormat) throws LineUnavailableException { - DataLine.Info dataLineInfo = new DataLine.Info(lineInfo.getLineClass(), audioFormat); - return (T) mixer.getLine(dataLineInfo); - } - } + @SuppressWarnings("unchecked") + public T getLine(AudioFormat audioFormat) throws LineUnavailableException { + DataLine.Info dataLineInfo = new DataLine.Info(lineInfo.getLineClass(), audioFormat); + return (T) mixer.getLine(dataLineInfo); + } + } } diff --git a/java/sound/src/main/java/sound/util/Utils.java b/java/sound/src/main/java/sound/util/Utils.java index 32100d8..8aeb57e 100644 --- a/java/sound/src/main/java/sound/util/Utils.java +++ b/java/sound/src/main/java/sound/util/Utils.java @@ -11,29 +11,29 @@ import javazoom.jl.decoder.JavaLayerException; import javazoom.jl.player.Player; public class Utils { - public static final int BUFFER = 2048; // bytes + public static final int BUFFER = 2048; // bytes - public static void play(InputStream inputStream) { - try { - new Player(new BufferedInputStream(inputStream)).play(); - } catch (JavaLayerException e) { - e.printStackTrace(); - } - } + public static void play(InputStream inputStream) { + try { + new Player(new BufferedInputStream(inputStream)).play(); + } catch (JavaLayerException e) { + e.printStackTrace(); + } + } - public static void write(InputStream inputStream, File file) { - byte[] bytes = new byte[BUFFER]; - int read = 0; - try { - FileOutputStream fileOutputStream = new FileOutputStream(file); - while ((read = inputStream.read(bytes)) > 0) { - fileOutputStream.write(bytes, 0, read); - } - fileOutputStream.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } + public static void write(InputStream inputStream, File file) { + byte[] bytes = new byte[BUFFER]; + int read = 0; + try { + FileOutputStream fileOutputStream = new FileOutputStream(file); + while ((read = inputStream.read(bytes)) > 0) { + fileOutputStream.write(bytes, 0, read); + } + fileOutputStream.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/java/sound/src/main/java/test/Test.java b/java/sound/src/main/java/test/Test.java index 5d1632c..9c0cda3 100644 --- a/java/sound/src/main/java/test/Test.java +++ b/java/sound/src/main/java/test/Test.java @@ -10,31 +10,31 @@ import sound.consumer.Shoutcast; import sound.producer.Stream; public class Test { - public static void main(String[] args) { - AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 48000f, 16, 2, 4, 48000f, true); - try { - //Producer p1 = new Target("Line-In (Creative SB X-Fi)"); - //Producer p2 = new Target("Line 1 (Virtual Audio Cable)", audioFormat); - //p2.start(); - Producer p3 = new Stream("http://ics2gss.omroep.nl:80/3fm-bb-mp3"); - Producer p4 = new Stream("http://sc7.mystreamserver.com:8004"); + public static void main(String[] args) { + AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 48000f, 16, 2, 4, 48000f, true); + try { + //Producer p1 = new Target("Line-In (Creative SB X-Fi)"); + //Producer p2 = new Target("Line 1 (Virtual Audio Cable)", audioFormat); + //p2.start(); + Producer p3 = new Stream("http://ics2gss.omroep.nl:80/3fm-bb-mp3"); + Producer p4 = new Stream("http://sc7.mystreamserver.com:8004"); - Consumer c1 = new Source("Java Sound Audio Engine"); - Consumer c2 = new Port("Speakers (Creative SB X-Fi)"); - Consumer c3 = new Shoutcast(); - //Consumer c4 = new Player(); - //Consumer c5 = new Writer(new File("stream.out")); + Consumer c1 = new Source("Java Sound Audio Engine"); + Consumer c2 = new Port("Speakers (Creative SB X-Fi)"); + Consumer c3 = new Shoutcast(); + //Consumer c4 = new Player(); + //Consumer c5 = new Writer(new File("stream.out")); - //Utils.write(p3.getInputStream(), new File("stream.out")); - //Utils.play(p3.getInputStream()); - c3.start(p4); + //Utils.write(p3.getInputStream(), new File("stream.out")); + //Utils.play(p3.getInputStream()); + c3.start(p4); - //while (true) { - //Thread.sleep(300000); - //c1.stop(); - //} - } catch (Exception e) { - e.printStackTrace(); - } - } + //while (true) { + //Thread.sleep(300000); + //c1.stop(); + //} + } catch (Exception e) { + e.printStackTrace(); + } + } } \ No newline at end of file diff --git a/java/sound/src/main/java/test/lines/Main.java b/java/sound/src/main/java/test/lines/Main.java index be6bbc2..8c392ee 100644 --- a/java/sound/src/main/java/test/lines/Main.java +++ b/java/sound/src/main/java/test/lines/Main.java @@ -9,26 +9,26 @@ import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; public class Main { - public static void main(String[] args) { - System.out.println(System.getProperty("javax.sound.sampled.SourceDataLine")); + public static void main(String[] args) { + System.out.println(System.getProperty("javax.sound.sampled.SourceDataLine")); - new AudioFormat(44100, 16, 2, true, false); + new AudioFormat(44100, 16, 2, true, false); - for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) { - Mixer mixer = AudioSystem.getMixer(mixerInfo); - for (Line.Info lineInfo : mixer.getTargetLineInfo()) { - try { - Line line = mixer.getLine(lineInfo); - if (mixer.isLineSupported(lineInfo)) { - if (line instanceof TargetDataLine) { - new TargetLine(mixer, (TargetDataLine) line); - }/* else if (line instanceof SourceDataLine) { - new SourceLine(mixer, (SourceDataLine) line); - }*/ - } - } catch (LineUnavailableException e) {} - } + for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) { + Mixer mixer = AudioSystem.getMixer(mixerInfo); + for (Line.Info lineInfo : mixer.getTargetLineInfo()) { + try { + Line line = mixer.getLine(lineInfo); + if (mixer.isLineSupported(lineInfo)) { + if (line instanceof TargetDataLine) { + new TargetLine(mixer, (TargetDataLine) line); + }/* else if (line instanceof SourceDataLine) { + new SourceLine(mixer, (SourceDataLine) line); + }*/ + } + } catch (LineUnavailableException e) {} + } - } - } + } + } } diff --git a/java/sound/src/main/java/test/lines/SourceLine.java b/java/sound/src/main/java/test/lines/SourceLine.java index ede5969..cb6a157 100644 --- a/java/sound/src/main/java/test/lines/SourceLine.java +++ b/java/sound/src/main/java/test/lines/SourceLine.java @@ -4,16 +4,16 @@ import javax.sound.sampled.Mixer; import javax.sound.sampled.SourceDataLine; public class SourceLine { - //private Mixer mixer; - private SourceDataLine line; + //private Mixer mixer; + private SourceDataLine line; - public SourceLine(Mixer mixer, SourceDataLine line) { - //this.mixer = mixer; - this.line = line; - System.out.println("SOURCE " + mixer.getMixerInfo().getName() + " || " + line.getLineInfo()); - } + public SourceLine(Mixer mixer, SourceDataLine line) { + //this.mixer = mixer; + this.line = line; + System.out.println("SOURCE " + mixer.getMixerInfo().getName() + " || " + line.getLineInfo()); + } - public int write(byte[] bytes, int offset, int length) { - return line.write(bytes, offset, length); - } + public int write(byte[] bytes, int offset, int length) { + return line.write(bytes, offset, length); + } } diff --git a/java/sound/src/main/java/test/lines/TargetLine.java b/java/sound/src/main/java/test/lines/TargetLine.java index e1e7823..e442304 100644 --- a/java/sound/src/main/java/test/lines/TargetLine.java +++ b/java/sound/src/main/java/test/lines/TargetLine.java @@ -4,16 +4,16 @@ import javax.sound.sampled.Mixer; import javax.sound.sampled.TargetDataLine; public class TargetLine { - //private Mixer mixer; - private TargetDataLine line; + //private Mixer mixer; + private TargetDataLine line; - public TargetLine(Mixer mixer, TargetDataLine line) { - //this.mixer = mixer; - this.line = line; - System.out.println("TARGET " + mixer.getMixerInfo().getName() + " || " + line.getLineInfo()); - } + public TargetLine(Mixer mixer, TargetDataLine line) { + //this.mixer = mixer; + this.line = line; + System.out.println("TARGET " + mixer.getMixerInfo().getName() + " || " + line.getLineInfo()); + } - public int read(byte[] bytes, int offset, int length) { - return line.read(bytes, offset, length); - } + public int read(byte[] bytes, int offset, int length) { + return line.read(bytes, offset, length); + } } diff --git a/java/test/src/main/java/jni/TestNative.java b/java/test/src/main/java/jni/TestNative.java index 70ebdda..a00a8be 100644 --- a/java/test/src/main/java/jni/TestNative.java +++ b/java/test/src/main/java/jni/TestNative.java @@ -4,7 +4,7 @@ import mimis.util.Native; import mimis.value.Registry; public class TestNative { - public static void main(String[] args) { - System.out.println(Native.getValue(Registry.CURRENT_USER, "Software\\LIRC", "password")); + public static void main(String[] args) { + System.out.println(Native.getValue(Registry.CURRENT_USER, "Software\\LIRC", "password")); } } \ No newline at end of file diff --git a/java/test/src/main/java/jni/TestWiiuse.java b/java/test/src/main/java/jni/TestWiiuse.java index eb18253..8902657 100644 --- a/java/test/src/main/java/jni/TestWiiuse.java +++ b/java/test/src/main/java/jni/TestWiiuse.java @@ -4,6 +4,6 @@ import wiiusej.WiiUseApiManager; public class TestWiiuse { public static void main(String[] args) { - WiiUseApiManager.getWiimotes(0, false); + WiiUseApiManager.getWiimotes(0, false); } } \ No newline at end of file diff --git a/java/test/src/main/java/jni/TestXinput.java b/java/test/src/main/java/jni/TestXinput.java index cdbb39b..4a9e378 100644 --- a/java/test/src/main/java/jni/TestXinput.java +++ b/java/test/src/main/java/jni/TestXinput.java @@ -3,7 +3,7 @@ package jni; import de.hardcode.jxinput.JXInputManager; public class TestXinput { - public static void main(String[] args) { - System.out.println(JXInputManager.getNumberOfDevices()); - } + public static void main(String[] args) { + System.out.println(JXInputManager.getNumberOfDevices()); + } } \ No newline at end of file diff --git a/java/test/src/main/java/jni/TestiTunes.java b/java/test/src/main/java/jni/TestiTunes.java index b7e9db2..9e72429 100644 --- a/java/test/src/main/java/jni/TestiTunes.java +++ b/java/test/src/main/java/jni/TestiTunes.java @@ -3,9 +3,9 @@ package jni; import com.dt.iTunesController.iTunes; public class TestiTunes { - public static void main(String[] args) { - iTunes iTunes = new iTunes(); - iTunes.connect(); - iTunes.playPause(); - } + public static void main(String[] args) { + iTunes iTunes = new iTunes(); + iTunes.connect(); + iTunes.playPause(); + } } \ No newline at end of file diff --git a/java/test/src/main/java/test/CustomAppender.java b/java/test/src/main/java/test/CustomAppender.java index 1e694f8..890541f 100644 --- a/java/test/src/main/java/test/CustomAppender.java +++ b/java/test/src/main/java/test/CustomAppender.java @@ -4,24 +4,24 @@ import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; public class CustomAppender extends AppenderSkeleton { - protected int bla = 9999; - - public void setBla(int bla) { - this.bla = bla; - } + protected int bla = 9999; + + public void setBla(int bla) { + this.bla = bla; + } - public int getBla() { - return bla; - } + public int getBla() { + return bla; + } - public boolean requiresLayout() { - return true; - } + public boolean requiresLayout() { + return true; + } - public void close() {} + public void close() {} - protected void append(LoggingEvent loggingEvent) { - System.out.print(layout.format(loggingEvent)); - } + protected void append(LoggingEvent loggingEvent) { + System.out.print(layout.format(loggingEvent)); + } }