Snapshot, replace tabs with spaces
This commit is contained in:
@@ -3,87 +3,87 @@
|
|||||||
#include <tlhelp32.h>
|
#include <tlhelp32.h>
|
||||||
|
|
||||||
bool getProcessEntry32(const char *program, PROCESSENTRY32 *pe32) {
|
bool getProcessEntry32(const char *program, PROCESSENTRY32 *pe32) {
|
||||||
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
||||||
if (hSnapshot == INVALID_HANDLE_VALUE) {
|
if (hSnapshot == INVALID_HANDLE_VALUE) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
bool bFound = false;
|
bool bFound = false;
|
||||||
while (Process32Next(hSnapshot, pe32) != false) {
|
while (Process32Next(hSnapshot, pe32) != false) {
|
||||||
if (strcmp(program, pe32->szExeFile) == 0) {
|
if (strcmp(program, pe32->szExeFile) == 0) {
|
||||||
bFound = true;
|
bFound = true;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
CloseHandle(hSnapshot);
|
CloseHandle(hSnapshot);
|
||||||
return bFound;
|
return bFound;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool getProcess(const char *program, HANDLE *hProcess) {
|
bool getProcess(const char *program, HANDLE *hProcess) {
|
||||||
PROCESSENTRY32 *pe32 = new PROCESSENTRY32;
|
PROCESSENTRY32 *pe32 = new PROCESSENTRY32;
|
||||||
bool bResult = false;
|
bool bResult = false;
|
||||||
if (getProcessEntry32(program, pe32)) {
|
if (getProcessEntry32(program, pe32)) {
|
||||||
*hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32->th32ProcessID);
|
*hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32->th32ProcessID);
|
||||||
bResult = true;
|
bResult = true;
|
||||||
}
|
}
|
||||||
delete pe32;
|
delete pe32;
|
||||||
return bResult;
|
return bResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL Java_mimis_util_Native_getHandle(JNIEnv *env, jclass cls, jstring jwindow) {
|
JNIEXPORT jint JNICALL Java_mimis_util_Native_getHandle(JNIEnv *env, jclass cls, jstring jwindow) {
|
||||||
const char *window = env->GetStringUTFChars(jwindow, 0);
|
const char *window = env->GetStringUTFChars(jwindow, 0);
|
||||||
return (int) FindWindow(window, NULL);
|
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) {
|
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) {
|
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) {
|
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) {
|
JNIEXPORT jboolean JNICALL Java_mimis_util_Native_isRunning(JNIEnv *env, jclass cls, jstring jprogram) {
|
||||||
const char *program = env->GetStringUTFChars(jprogram, 0);
|
const char *program = env->GetStringUTFChars(jprogram, 0);
|
||||||
PROCESSENTRY32 *pe32 = new PROCESSENTRY32;
|
PROCESSENTRY32 *pe32 = new PROCESSENTRY32;
|
||||||
bool bRunning = getProcessEntry32(program, pe32);
|
bool bRunning = getProcessEntry32(program, pe32);
|
||||||
delete pe32;
|
delete pe32;
|
||||||
return bRunning;
|
return bRunning;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL Java_mimis_util_Native_terminate(JNIEnv *env, jclass cls, jstring jprogram) {
|
JNIEXPORT jboolean JNICALL Java_mimis_util_Native_terminate(JNIEnv *env, jclass cls, jstring jprogram) {
|
||||||
const char *program = env->GetStringUTFChars(jprogram, 0);
|
const char *program = env->GetStringUTFChars(jprogram, 0);
|
||||||
HANDLE *hProcess = new HANDLE;
|
HANDLE *hProcess = new HANDLE;
|
||||||
bool bResult = false;
|
bool bResult = false;
|
||||||
if (getProcess(program, hProcess)) {
|
if (getProcess(program, hProcess)) {
|
||||||
bResult = TerminateProcess(*hProcess, 0);
|
bResult = TerminateProcess(*hProcess, 0);
|
||||||
}
|
}
|
||||||
delete hProcess;
|
delete hProcess;
|
||||||
return bResult;
|
return bResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jstring JNICALL Java_mimis_util_Native_getValue(JNIEnv *env, jclass cls, jint registry, jstring jkey, jstring jname) {
|
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 *key = env->GetStringUTFChars(jkey, 0);
|
||||||
const char *name = env->GetStringUTFChars(jname, 0);
|
const char *name = env->GetStringUTFChars(jname, 0);
|
||||||
HKEY hKey;
|
HKEY hKey;
|
||||||
char *value = NULL;
|
char *value = NULL;
|
||||||
if (RegOpenKey((HKEY) registry, key, &hKey) == ERROR_SUCCESS) {
|
if (RegOpenKey((HKEY) registry, key, &hKey) == ERROR_SUCCESS) {
|
||||||
char nameBuffer[255];
|
char nameBuffer[255];
|
||||||
byte valueBuffer[255];
|
byte valueBuffer[255];
|
||||||
DWORD dwNameSize = sizeof(nameBuffer);
|
DWORD dwNameSize = sizeof(nameBuffer);
|
||||||
DWORD dwValueSize = sizeof(valueBuffer);
|
DWORD dwValueSize = sizeof(valueBuffer);
|
||||||
int i = 0;
|
int i = 0;
|
||||||
while (RegEnumValue(hKey, i++, nameBuffer, &dwNameSize, NULL, NULL, valueBuffer, &dwValueSize) == ERROR_SUCCESS) {
|
while (RegEnumValue(hKey, i++, nameBuffer, &dwNameSize, NULL, NULL, valueBuffer, &dwValueSize) == ERROR_SUCCESS) {
|
||||||
if (strcmp(name, nameBuffer) == 0) {
|
if (strcmp(name, nameBuffer) == 0) {
|
||||||
value = (char*) valueBuffer;
|
value = (char*) valueBuffer;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
dwNameSize = sizeof(nameBuffer);
|
dwNameSize = sizeof(nameBuffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RegCloseKey(hKey);
|
RegCloseKey(hKey);
|
||||||
return env->NewStringUTF(value);
|
return env->NewStringUTF(value);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import mimis.value.Windows;
|
|||||||
|
|
||||||
public class Native {
|
public class Native {
|
||||||
static {
|
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);
|
public native static int getHandle(String window);
|
||||||
|
|||||||
@@ -3,190 +3,190 @@
|
|||||||
#include <jni.h>
|
#include <jni.h>
|
||||||
#include "pipe.h"
|
#include "pipe.h"
|
||||||
|
|
||||||
#define DEBUG 0
|
#define DEBUG 0
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL Java_pipe_Pipe_CreateNamedPipe(JNIEnv *env,
|
JNIEXPORT jint JNICALL Java_pipe_Pipe_CreateNamedPipe(JNIEnv *env,
|
||||||
jclass className, jstring sPipeName, jint dwOpenMode, jint dwPipeMode,
|
jclass className, jstring sPipeName, jint dwOpenMode, jint dwPipeMode,
|
||||||
jint nMaxInstances, jint nOutBufferSize, jint nInBufferSize,
|
jint nMaxInstances, jint nOutBufferSize, jint nInBufferSize,
|
||||||
jint nDefaultTimeOut, jint lpSecurityAttributes) {
|
jint nDefaultTimeOut, jint lpSecurityAttributes) {
|
||||||
HANDLE pipeHandler;
|
HANDLE pipeHandler;
|
||||||
LPCSTR pipeName;
|
LPCSTR pipeName;
|
||||||
pipeName = (*env)->GetStringUTFChars(env, sPipeName, NULL );
|
pipeName = (*env)->GetStringUTFChars(env, sPipeName, NULL );
|
||||||
if (pipeName == NULL )
|
if (pipeName == NULL )
|
||||||
return -1;
|
return -1;
|
||||||
|
|
||||||
if (DEBUG) {
|
if (DEBUG) {
|
||||||
printf("Native: Pipe Name %s\n", pipeName);
|
printf("Native: Pipe Name %s\n", pipeName);
|
||||||
printf("Native: dwOpenMode %d\n", dwOpenMode);
|
printf("Native: dwOpenMode %d\n", dwOpenMode);
|
||||||
printf("Native: dwPipeMode %d\n", dwPipeMode);
|
printf("Native: dwPipeMode %d\n", dwPipeMode);
|
||||||
printf("Native: nMaxInstances %d\n", nMaxInstances);
|
printf("Native: nMaxInstances %d\n", nMaxInstances);
|
||||||
printf("Native: nOutBufferSize %d\n", nOutBufferSize);
|
printf("Native: nOutBufferSize %d\n", nOutBufferSize);
|
||||||
printf("Native: nInBufferSize %d\n", nInBufferSize);
|
printf("Native: nInBufferSize %d\n", nInBufferSize);
|
||||||
printf("Native: nDefaultTimeOut %d\n", nDefaultTimeOut);
|
printf("Native: nDefaultTimeOut %d\n", nDefaultTimeOut);
|
||||||
}
|
}
|
||||||
|
|
||||||
pipeHandler = CreateNamedPipe((LPCSTR) pipeName, dwOpenMode, dwPipeMode,
|
pipeHandler = CreateNamedPipe((LPCSTR) pipeName, dwOpenMode, dwPipeMode,
|
||||||
nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut,
|
nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut,
|
||||||
(LPSECURITY_ATTRIBUTES) lpSecurityAttributes);
|
(LPSECURITY_ATTRIBUTES) lpSecurityAttributes);
|
||||||
|
|
||||||
(*env)->ReleaseStringUTFChars(env, sPipeName, pipeName);
|
(*env)->ReleaseStringUTFChars(env, sPipeName, pipeName);
|
||||||
return (jint) pipeHandler;
|
return (jint) pipeHandler;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_ConnectNamedPipe(JNIEnv *env,
|
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_ConnectNamedPipe(JNIEnv *env,
|
||||||
jclass className, jint hNamedPipe, jint lpOverlapped) {
|
jclass className, jint hNamedPipe, jint lpOverlapped) {
|
||||||
BOOL fConnected;
|
BOOL fConnected;
|
||||||
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
||||||
fConnected = ConnectNamedPipe(pipeHandler, (LPOVERLAPPED) lpOverlapped);
|
fConnected = ConnectNamedPipe(pipeHandler, (LPOVERLAPPED) lpOverlapped);
|
||||||
return fConnected;
|
return fConnected;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL Java_pipe_Pipe_GetLastError(JNIEnv *env,
|
JNIEXPORT jint JNICALL Java_pipe_Pipe_GetLastError(JNIEnv *env,
|
||||||
jclass className) {
|
jclass className) {
|
||||||
DWORD errorNumber = GetLastError();
|
DWORD errorNumber = GetLastError();
|
||||||
return (jint) errorNumber;
|
return (jint) errorNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_CloseHandle(JNIEnv *env,
|
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_CloseHandle(JNIEnv *env,
|
||||||
jclass className, jint hNamedPipe) {
|
jclass className, jint hNamedPipe) {
|
||||||
BOOL result;
|
BOOL result;
|
||||||
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
||||||
result = CloseHandle(pipeHandler);
|
result = CloseHandle(pipeHandler);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jbyteArray JNICALL Java_pipe_Pipe_ReadFile(JNIEnv *env,
|
JNIEXPORT jbyteArray JNICALL Java_pipe_Pipe_ReadFile(JNIEnv *env,
|
||||||
jclass className, jint hNamedPipe, jint nNumberOfBytesToRead) {
|
jclass className, jint hNamedPipe, jint nNumberOfBytesToRead) {
|
||||||
int bytesRead = 0;
|
int bytesRead = 0;
|
||||||
BOOL result;
|
BOOL result;
|
||||||
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
||||||
LPVOID buffer;
|
LPVOID buffer;
|
||||||
jbyteArray lpBuffer;
|
jbyteArray lpBuffer;
|
||||||
|
|
||||||
buffer = (LPVOID) LocalAlloc(LMEM_ZEROINIT, nNumberOfBytesToRead);
|
buffer = (LPVOID) LocalAlloc(LMEM_ZEROINIT, nNumberOfBytesToRead);
|
||||||
|
|
||||||
if (DEBUG) {
|
if (DEBUG) {
|
||||||
printf(
|
printf(
|
||||||
"Native: Before ReadFile pipeHandler %d nNumberOfBytesToRead %d\n",
|
"Native: Before ReadFile pipeHandler %d nNumberOfBytesToRead %d\n",
|
||||||
pipeHandler, nNumberOfBytesToRead);
|
pipeHandler, nNumberOfBytesToRead);
|
||||||
}
|
}
|
||||||
result = ReadFile(pipeHandler, (LPVOID) buffer,
|
result = ReadFile(pipeHandler, (LPVOID) buffer,
|
||||||
(DWORD) nNumberOfBytesToRead, &bytesRead, (LPOVERLAPPED) 0);
|
(DWORD) nNumberOfBytesToRead, &bytesRead, (LPOVERLAPPED) 0);
|
||||||
if (result) {
|
if (result) {
|
||||||
lpBuffer = (*env)->NewByteArray(env, (jsize) bytesRead);
|
lpBuffer = (*env)->NewByteArray(env, (jsize) bytesRead);
|
||||||
(*env)->SetByteArrayRegion(env, lpBuffer, 0, (jsize) bytesRead,
|
(*env)->SetByteArrayRegion(env, lpBuffer, 0, (jsize) bytesRead,
|
||||||
(jbyte *) buffer);
|
(jbyte *) buffer);
|
||||||
} else
|
} else
|
||||||
bytesRead = 0;
|
bytesRead = 0;
|
||||||
|
|
||||||
LocalFree(buffer);
|
LocalFree(buffer);
|
||||||
|
|
||||||
if (DEBUG) {
|
if (DEBUG) {
|
||||||
printf("Native: After ReadFile BytesRead %d\n", bytesRead);
|
printf("Native: After ReadFile BytesRead %d\n", bytesRead);
|
||||||
}
|
}
|
||||||
return lpBuffer;
|
return lpBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL Java_pipe_Pipe_WriteFile(JNIEnv *env, jclass className,
|
JNIEXPORT jint JNICALL Java_pipe_Pipe_WriteFile(JNIEnv *env, jclass className,
|
||||||
jint hNamedPipe, jbyteArray lpBuffer, jint nNumberOfBytesToWrite) {
|
jint hNamedPipe, jbyteArray lpBuffer, jint nNumberOfBytesToWrite) {
|
||||||
int bytesWritten = 0;
|
int bytesWritten = 0;
|
||||||
BOOL result;
|
BOOL result;
|
||||||
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
||||||
LPVOID buffer;
|
LPVOID buffer;
|
||||||
|
|
||||||
buffer = (LPVOID) LocalAlloc(LMEM_ZEROINIT, nNumberOfBytesToWrite);
|
buffer = (LPVOID) LocalAlloc(LMEM_ZEROINIT, nNumberOfBytesToWrite);
|
||||||
|
|
||||||
(*env)->GetByteArrayRegion(env, lpBuffer, 0, nNumberOfBytesToWrite, buffer);
|
(*env)->GetByteArrayRegion(env, lpBuffer, 0, nNumberOfBytesToWrite, buffer);
|
||||||
result = WriteFile(pipeHandler, buffer, (DWORD) nNumberOfBytesToWrite,
|
result = WriteFile(pipeHandler, buffer, (DWORD) nNumberOfBytesToWrite,
|
||||||
(LPDWORD) &bytesWritten, (LPOVERLAPPED) 0);
|
(LPDWORD) &bytesWritten, (LPOVERLAPPED) 0);
|
||||||
LocalFree(buffer);
|
LocalFree(buffer);
|
||||||
|
|
||||||
if (DEBUG) {
|
if (DEBUG) {
|
||||||
printf("Native: After WriteFile BytesReadWritten %d\n", bytesWritten);
|
printf("Native: After WriteFile BytesReadWritten %d\n", bytesWritten);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!result) {
|
if (!result) {
|
||||||
if (GetLastError() != ERROR_IO_PENDING)
|
if (GetLastError() != ERROR_IO_PENDING)
|
||||||
result = 0;
|
result = 0;
|
||||||
else
|
else
|
||||||
result = 1;
|
result = 1;
|
||||||
}
|
}
|
||||||
if (!result) {
|
if (!result) {
|
||||||
bytesWritten = -1;
|
bytesWritten = -1;
|
||||||
}
|
}
|
||||||
return bytesWritten;
|
return bytesWritten;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_FlushFileBuffers(JNIEnv *env,
|
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_FlushFileBuffers(JNIEnv *env,
|
||||||
jclass className, jint hNamedPipe) {
|
jclass className, jint hNamedPipe) {
|
||||||
BOOL result;
|
BOOL result;
|
||||||
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
||||||
result = FlushFileBuffers(pipeHandler);
|
result = FlushFileBuffers(pipeHandler);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_DisconnectNamedPipe(JNIEnv *env,
|
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_DisconnectNamedPipe(JNIEnv *env,
|
||||||
jclass className, jint hNamedPipe) {
|
jclass className, jint hNamedPipe) {
|
||||||
BOOL result;
|
BOOL result;
|
||||||
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
HANDLE pipeHandler = (HANDLE) hNamedPipe;
|
||||||
result = DisconnectNamedPipe(pipeHandler);
|
result = DisconnectNamedPipe(pipeHandler);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jint JNICALL Java_pipe_Pipe_CreateFile(JNIEnv *env, jclass className,
|
JNIEXPORT jint JNICALL Java_pipe_Pipe_CreateFile(JNIEnv *env, jclass className,
|
||||||
jstring lpFileName, jint dwDesiredAccess, jint dwShareMode,
|
jstring lpFileName, jint dwDesiredAccess, jint dwShareMode,
|
||||||
jint lpSecurityAttributes, jint dwCreationDisposition,
|
jint lpSecurityAttributes, jint dwCreationDisposition,
|
||||||
jint dwFlagsAndAttributes, jint hTemplateFile) {
|
jint dwFlagsAndAttributes, jint hTemplateFile) {
|
||||||
HANDLE pipeHandler;
|
HANDLE pipeHandler;
|
||||||
const jbyte *fileName;
|
const jbyte *fileName;
|
||||||
fileName = (*env)->GetStringUTFChars(env, lpFileName, NULL );
|
fileName = (*env)->GetStringUTFChars(env, lpFileName, NULL );
|
||||||
if (fileName == NULL )
|
if (fileName == NULL )
|
||||||
return -1;
|
return -1;
|
||||||
pipeHandler = CreateFile((LPCSTR) fileName, (DWORD) dwDesiredAccess,
|
pipeHandler = CreateFile((LPCSTR) fileName, (DWORD) dwDesiredAccess,
|
||||||
(DWORD) dwShareMode, (LPSECURITY_ATTRIBUTES) lpSecurityAttributes,
|
(DWORD) dwShareMode, (LPSECURITY_ATTRIBUTES) lpSecurityAttributes,
|
||||||
(DWORD) dwCreationDisposition, (DWORD) dwFlagsAndAttributes,
|
(DWORD) dwCreationDisposition, (DWORD) dwFlagsAndAttributes,
|
||||||
(HANDLE) hTemplateFile);
|
(HANDLE) hTemplateFile);
|
||||||
return (jint) pipeHandler;
|
return (jint) pipeHandler;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_WaitNamedPipe(JNIEnv *env,
|
JNIEXPORT jboolean JNICALL Java_pipe_Pipe_WaitNamedPipe(JNIEnv *env,
|
||||||
jclass className, jstring lpNamedPipeName, jint nTimeOut) {
|
jclass className, jstring lpNamedPipeName, jint nTimeOut) {
|
||||||
BOOL result;
|
BOOL result;
|
||||||
const jbyte *pipeName;
|
const jbyte *pipeName;
|
||||||
pipeName = (*env)->GetStringUTFChars(env, lpNamedPipeName, NULL );
|
pipeName = (*env)->GetStringUTFChars(env, lpNamedPipeName, NULL );
|
||||||
if (pipeName == NULL )
|
if (pipeName == NULL )
|
||||||
return 0;
|
return 0;
|
||||||
result = WaitNamedPipe((LPCSTR) pipeName, (DWORD) nTimeOut);
|
result = WaitNamedPipe((LPCSTR) pipeName, (DWORD) nTimeOut);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT jstring JNICALL Java_pipe_Pipe_FormatMessage(JNIEnv *env,
|
JNIEXPORT jstring JNICALL Java_pipe_Pipe_FormatMessage(JNIEnv *env,
|
||||||
jclass className, jint errorCode) {
|
jclass className, jint errorCode) {
|
||||||
LPVOID lpMsgBuf;
|
LPVOID lpMsgBuf;
|
||||||
LPVOID lpDisplayBuf;
|
LPVOID lpDisplayBuf;
|
||||||
DWORD dw = (DWORD) errorCode;
|
DWORD dw = (DWORD) errorCode;
|
||||||
|
|
||||||
FormatMessage(
|
FormatMessage(
|
||||||
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
|
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
|
||||||
| FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw,
|
| FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw,
|
||||||
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0,
|
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0,
|
||||||
NULL );
|
NULL );
|
||||||
|
|
||||||
lpDisplayBuf = (LPVOID) LocalAlloc(LMEM_ZEROINIT,
|
lpDisplayBuf = (LPVOID) LocalAlloc(LMEM_ZEROINIT,
|
||||||
(lstrlen((LPCTSTR) lpMsgBuf) + 40) * sizeof(TCHAR));
|
(lstrlen((LPCTSTR) lpMsgBuf) + 40) * sizeof(TCHAR));
|
||||||
StringCchPrintf((LPTSTR) lpDisplayBuf,
|
StringCchPrintf((LPTSTR) lpDisplayBuf,
|
||||||
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
|
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
|
||||||
TEXT("Failed with error %d: %s"), dw, lpMsgBuf);
|
TEXT("Failed with error %d: %s"), dw, lpMsgBuf);
|
||||||
return (jstring) (*env)->NewStringUTF(env, lpDisplayBuf);
|
return (jstring) (*env)->NewStringUTF(env, lpDisplayBuf);
|
||||||
}
|
}
|
||||||
|
|
||||||
JNIEXPORT void JNICALL Java_pipe_Pipe_Print(JNIEnv *env, jclass className,
|
JNIEXPORT void JNICALL Java_pipe_Pipe_Print(JNIEnv *env, jclass className,
|
||||||
jstring lpMsgBuf) {
|
jstring lpMsgBuf) {
|
||||||
const jbyte *str;
|
const jbyte *str;
|
||||||
str = (*env)->GetStringUTFChars(env, lpMsgBuf, NULL );
|
str = (*env)->GetStringUTFChars(env, lpMsgBuf, NULL );
|
||||||
if (str == NULL )
|
if (str == NULL )
|
||||||
return;
|
return;
|
||||||
printf("Native: %s\n", str);
|
printf("Native: %s\n", str);
|
||||||
(*env)->ReleaseStringUTFChars(env, lpMsgBuf, str);
|
(*env)->ReleaseStringUTFChars(env, lpMsgBuf, str);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,51 +6,51 @@ import com.github.boukefalos.jlibloader.Native;
|
|||||||
* @author Vikram S Khatri vikram.khatri@us.ibm.com
|
* @author Vikram S Khatri vikram.khatri@us.ibm.com
|
||||||
*/
|
*/
|
||||||
public class Pipe {
|
public class Pipe {
|
||||||
static final int ERROR_PIPE_CONNECTED = 535;
|
static final int ERROR_PIPE_CONNECTED = 535;
|
||||||
static final int ERROR_BROKEN_PIPE = 109;
|
static final int ERROR_BROKEN_PIPE = 109;
|
||||||
static final int PIPE_ACCESS_DUPLEX = 0x00000003;
|
static final int PIPE_ACCESS_DUPLEX = 0x00000003;
|
||||||
static final int PIPE_WAIT = 0x00000000;
|
static final int PIPE_WAIT = 0x00000000;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
Native.load("com.github.boukefalos", "jlibpipe");
|
Native.load("com.github.boukefalos", "jlibpipe");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final native int CreateNamedPipe(
|
public static final native int CreateNamedPipe(
|
||||||
String pipeName,
|
String pipeName,
|
||||||
int ppenMode,
|
int ppenMode,
|
||||||
int pipeMode,
|
int pipeMode,
|
||||||
int maxInstances,
|
int maxInstances,
|
||||||
int outBufferSize,
|
int outBufferSize,
|
||||||
int inBufferSize,
|
int inBufferSize,
|
||||||
int defaultTimeOut,
|
int defaultTimeOut,
|
||||||
int securityAttributes);
|
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(
|
public static final native int CreateFile(
|
||||||
String fileName,
|
String fileName,
|
||||||
int desiredAccess,
|
int desiredAccess,
|
||||||
int shareMode,
|
int shareMode,
|
||||||
int securityAttributes,
|
int securityAttributes,
|
||||||
int creationDisposition,
|
int creationDisposition,
|
||||||
int flagsAndAttributes,
|
int flagsAndAttributes,
|
||||||
int templateFile);
|
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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,22 +3,22 @@ package pipe;
|
|||||||
import java.io.RandomAccessFile;
|
import java.io.RandomAccessFile;
|
||||||
|
|
||||||
public class Client {
|
public class Client {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
try {
|
try {
|
||||||
// Connect to the pipe
|
// Connect to the pipe
|
||||||
RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\detest", "rw");
|
RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\detest", "rw");
|
||||||
String echoText = "Hello word\n";
|
String echoText = "Hello word\n";
|
||||||
|
|
||||||
// write to pipe
|
// write to pipe
|
||||||
pipe.write(echoText.getBytes());
|
pipe.write(echoText.getBytes());
|
||||||
|
|
||||||
// read response
|
// read response
|
||||||
String echoResponse = pipe.readLine();
|
String echoResponse = pipe.readLine();
|
||||||
System.out.println(echoResponse);
|
System.out.println(echoResponse);
|
||||||
pipe.close();
|
pipe.close();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,81 +6,81 @@ import java.io.InputStream;
|
|||||||
|
|
||||||
public class TestPipe {
|
public class TestPipe {
|
||||||
|
|
||||||
private int namedPipeHandle;
|
private int namedPipeHandle;
|
||||||
private String pipeName, srcFile;
|
private String pipeName, srcFile;
|
||||||
private int pipeBuffer = 131072, fileBuffer = 8192;
|
private int pipeBuffer = 131072, fileBuffer = 8192;
|
||||||
|
|
||||||
public TestPipe(String pipeName, String srcFile) {
|
public TestPipe(String pipeName, String srcFile) {
|
||||||
this.pipeName = pipeName;
|
this.pipeName = pipeName;
|
||||||
this.srcFile = srcFile;
|
this.srcFile = srcFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void log(String message) {
|
private void log(String message) {
|
||||||
System.out.println(message);
|
System.out.println(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean createPipe() {
|
private boolean createPipe() {
|
||||||
namedPipeHandle = Pipe.CreateNamedPipe(
|
namedPipeHandle = Pipe.CreateNamedPipe(
|
||||||
pipeName,
|
pipeName,
|
||||||
Pipe.PIPE_ACCESS_DUPLEX,
|
Pipe.PIPE_ACCESS_DUPLEX,
|
||||||
Pipe.PIPE_WAIT,
|
Pipe.PIPE_WAIT,
|
||||||
5,
|
5,
|
||||||
pipeBuffer,
|
pipeBuffer,
|
||||||
pipeBuffer,
|
pipeBuffer,
|
||||||
0xffffffff,
|
0xffffffff,
|
||||||
0);
|
0);
|
||||||
if (namedPipeHandle == -1) {
|
if (namedPipeHandle == -1) {
|
||||||
log("CreateNamedPipe failed for " + pipeName + " for error Message " + Pipe.FormatMessage(Pipe.GetLastError()));
|
log("CreateNamedPipe failed for " + pipeName + " for error Message " + Pipe.FormatMessage(Pipe.GetLastError()));
|
||||||
} else {
|
} else {
|
||||||
log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle);
|
log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle);
|
||||||
}
|
}
|
||||||
return namedPipeHandle != -1;
|
return namedPipeHandle != -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean connectToPipe() {
|
private boolean connectToPipe() {
|
||||||
log("Waiting for a client to connect to pipe " + pipeName);
|
log("Waiting for a client to connect to pipe " + pipeName);
|
||||||
boolean connected = Pipe.ConnectNamedPipe(namedPipeHandle, 0);
|
boolean connected = Pipe.ConnectNamedPipe(namedPipeHandle, 0);
|
||||||
if (!connected) {
|
if (!connected) {
|
||||||
int lastError = Pipe.GetLastError();
|
int lastError = Pipe.GetLastError();
|
||||||
if (lastError == Pipe.ERROR_PIPE_CONNECTED)
|
if (lastError == Pipe.ERROR_PIPE_CONNECTED)
|
||||||
connected = true;
|
connected = true;
|
||||||
}
|
}
|
||||||
log((connected ? "Connected to the pipe " : "Falied to connect to the pipe ") + pipeName);
|
log((connected ? "Connected to the pipe " : "Falied to connect to the pipe ") + pipeName);
|
||||||
return connected;
|
return connected;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void runPipe() {
|
public void runPipe() {
|
||||||
if (createPipe() && connectToPipe()) {
|
if (createPipe() && connectToPipe()) {
|
||||||
log("Client connected.");
|
log("Client connected.");
|
||||||
try {
|
try {
|
||||||
File f1 = new File(this.srcFile);
|
File f1 = new File(this.srcFile);
|
||||||
InputStream in = new FileInputStream(f1);
|
InputStream in = new FileInputStream(f1);
|
||||||
log("Sending data to the pipe");
|
log("Sending data to the pipe");
|
||||||
byte[] buf = new byte[fileBuffer];
|
byte[] buf = new byte[fileBuffer];
|
||||||
int len, bytesWritten;
|
int len, bytesWritten;
|
||||||
while ((len = in.read(buf)) > 0) {
|
while ((len = in.read(buf)) > 0) {
|
||||||
bytesWritten = Pipe.WriteFile(namedPipeHandle, buf, len);
|
bytesWritten = Pipe.WriteFile(namedPipeHandle, buf, len);
|
||||||
log("Sent " + len + "/" + bytesWritten + " bytes to the pipe");
|
log("Sent " + len + "/" + bytesWritten + " bytes to the pipe");
|
||||||
if (bytesWritten == -1) {
|
if (bytesWritten == -1) {
|
||||||
int errorNumber = Pipe.GetLastError();
|
int errorNumber = Pipe.GetLastError();
|
||||||
log("Error Writing to pipe " + Pipe.FormatMessage(errorNumber));
|
log("Error Writing to pipe " + Pipe.FormatMessage(errorNumber));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
in.close();
|
in.close();
|
||||||
Pipe.FlushFileBuffers(namedPipeHandle);
|
Pipe.FlushFileBuffers(namedPipeHandle);
|
||||||
Pipe.CloseHandle(namedPipeHandle);
|
Pipe.CloseHandle(namedPipeHandle);
|
||||||
Pipe.DisconnectNamedPipe(namedPipeHandle);
|
Pipe.DisconnectNamedPipe(namedPipeHandle);
|
||||||
log("Writing to the pipe completed.");
|
log("Writing to the pipe completed.");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
String pipeName = "\\\\.\\pipe\\detest";
|
String pipeName = "\\\\.\\pipe\\detest";
|
||||||
String fileName = "C:\\Users\\Rik\\Music\\Artists\\+44\\When Your Heart Stops Beating\\+44 - 155.mp3";
|
String fileName = "C:\\Users\\Rik\\Music\\Artists\\+44\\When Your Heart Stops Beating\\+44 - 155.mp3";
|
||||||
TestPipe testPipe = new TestPipe(pipeName, fileName);
|
TestPipe testPipe = new TestPipe(pipeName, fileName);
|
||||||
testPipe.runPipe();
|
testPipe.runPipe();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package base;
|
package base;
|
||||||
|
|
||||||
public interface Control {
|
public interface Control {
|
||||||
public void start();
|
public void start();
|
||||||
public void stop();
|
public void stop();
|
||||||
public void exit();
|
public void exit();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package base;
|
package base;
|
||||||
|
|
||||||
public interface Forwarder extends Control {
|
public interface Forwarder extends Control {
|
||||||
public void register(Receiver receiver);
|
public void register(Receiver receiver);
|
||||||
public void remove(Receiver receiver);
|
public void remove(Receiver receiver);
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
package base;
|
package base;
|
||||||
|
|
||||||
public interface Receiver {
|
public interface Receiver {
|
||||||
public void receive(byte[] buffer);
|
public void receive(byte[] buffer);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,5 +3,5 @@ package base;
|
|||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
public interface Sender extends Control {
|
public interface Sender extends Control {
|
||||||
public void send(byte[] buffer) throws IOException;
|
public void send(byte[] buffer) throws IOException;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
package base.exception;
|
package base.exception;
|
||||||
|
|
||||||
public class LoaderException extends Exception {
|
public class LoaderException extends Exception {
|
||||||
protected static final long serialVersionUID = 1L;
|
protected static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
public LoaderException(String message) {
|
public LoaderException(String message) {
|
||||||
super(message);
|
super(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,128 +19,128 @@ import base.server.forwarder.UdpDuplexClientForwarder;
|
|||||||
import base.server.forwarder.UdpDuplexServerForwarder;
|
import base.server.forwarder.UdpDuplexServerForwarder;
|
||||||
|
|
||||||
public class AbstractLoader<T> {
|
public class AbstractLoader<T> {
|
||||||
protected static final String PROPERTIES_FILE = "loader.properties";
|
protected static final String PROPERTIES_FILE = "loader.properties";
|
||||||
protected static final Properties SERVER = null;
|
protected static final Properties SERVER = null;
|
||||||
|
|
||||||
protected Logger logger = LoggerFactory.getLogger(AbstractLoader.class);
|
protected Logger logger = LoggerFactory.getLogger(AbstractLoader.class);
|
||||||
protected MutablePicoContainer pico;
|
protected MutablePicoContainer pico;
|
||||||
|
|
||||||
public AbstractLoader() {
|
public AbstractLoader() {
|
||||||
/* Initialise container */
|
/* Initialise container */
|
||||||
pico = new DefaultPicoContainer();
|
pico = new DefaultPicoContainer();
|
||||||
}
|
|
||||||
|
|
||||||
public AbstractLoader(Properties properties) {
|
|
||||||
this();
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
|
||||||
public static <T> T getLoader() throws LoaderException {
|
|
||||||
return (T) new AbstractLoader(readProperties(PROPERTIES_FILE));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Properties readProperties(String propertiesFile) throws LoaderException {
|
public AbstractLoader(Properties properties) {
|
||||||
/* Read properties file */
|
this();
|
||||||
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<?> getSenderClass(String protocol, String implementation) throws LoaderException {
|
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||||
switch (protocol) {
|
public static <T> T getLoader() throws LoaderException {
|
||||||
case "tcp":
|
return (T) new AbstractLoader(readProperties(PROPERTIES_FILE));
|
||||||
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 <Sender>");
|
|
||||||
}
|
|
||||||
|
|
||||||
protected Class<?> getClientForwarderClass(String protocol, String implementation) throws LoaderException {
|
public static Properties readProperties(String propertiesFile) throws LoaderException {
|
||||||
switch (protocol) {
|
/* Read properties file */
|
||||||
case "tcp":
|
Properties properties = new Properties();
|
||||||
switch (implementation) {
|
try {
|
||||||
case "channel":
|
properties.load(AbstractLoader.class.getClassLoader().getResourceAsStream(propertiesFile));
|
||||||
return base.server.forwarder.TcpClientChannelForwarder.class;
|
} catch (IOException e) {
|
||||||
default:
|
throw new LoaderException("Faield to read properties file: " + PROPERTIES_FILE);
|
||||||
case "socket":
|
}
|
||||||
return base.server.forwarder.TcpClientSocketForwarder.class;
|
return properties;
|
||||||
}
|
}
|
||||||
case "udp":
|
|
||||||
return UdpDuplexClientForwarder.class;
|
|
||||||
}
|
|
||||||
throw new LoaderException("Failed to determine <Forwarder>");
|
|
||||||
}
|
|
||||||
|
|
||||||
protected Class<?> getServerForwarderClass(String protocol, String implementation) throws LoaderException {
|
protected Class<?> getSenderClass(String protocol, String implementation) throws LoaderException {
|
||||||
switch (protocol) {
|
switch (protocol) {
|
||||||
case "tcp":
|
case "tcp":
|
||||||
switch (implementation) {
|
switch (implementation) {
|
||||||
case "channel":
|
case "channel":
|
||||||
return base.server.forwarder.TcpChannelServerForwarder.class;
|
return base.server.channel.TcpClient.class;
|
||||||
default:
|
default:
|
||||||
case "socket":
|
case "socket":
|
||||||
return base.server.forwarder.TcpSocketServerForwarder.class;
|
return base.server.socket.TcpClient.class;
|
||||||
}
|
}
|
||||||
case "udp":
|
case "udp":
|
||||||
return UdpDuplexServerForwarder.class;
|
return UdpSender.class;
|
||||||
}
|
}
|
||||||
throw new LoaderException("Failed to determine <Forwarder>");
|
throw new LoaderException("Failed to determine <Sender>");
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void addClientSender(String protocol, String implementation, String host, int port) throws LoaderException {
|
protected Class<?> getClientForwarderClass(String protocol, String implementation) throws LoaderException {
|
||||||
Class<?> senderClass = getSenderClass(protocol, implementation);
|
switch (protocol) {
|
||||||
logger.debug("Adding " + senderClass);
|
case "tcp":
|
||||||
pico.addComponent(Sender.class, senderClass, new Parameter[]{
|
switch (implementation) {
|
||||||
new ConstantParameter(host),
|
case "channel":
|
||||||
new ConstantParameter(port)});
|
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 <Forwarder>");
|
||||||
|
}
|
||||||
|
|
||||||
protected void addServerSender(String protocol, String implementation, int port) throws LoaderException {
|
protected Class<?> getServerForwarderClass(String protocol, String implementation) throws LoaderException {
|
||||||
Class<?> senderClass = getSenderClass(protocol, implementation);
|
switch (protocol) {
|
||||||
logger.debug("Adding " + senderClass);
|
case "tcp":
|
||||||
pico.addComponent(Sender.class, senderClass, new Parameter[]{
|
switch (implementation) {
|
||||||
new ConstantParameter(port)});
|
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 <Forwarder>");
|
||||||
|
}
|
||||||
|
|
||||||
protected void addClientForwarder(String protocol, String implementation, String host, int port) throws LoaderException {
|
protected void addClientSender(String protocol, String implementation, String host, int port) throws LoaderException {
|
||||||
Class<?> forwarderClass = getClientForwarderClass(protocol, implementation);
|
Class<?> senderClass = getSenderClass(protocol, implementation);
|
||||||
logger.debug("Adding " + forwarderClass);
|
logger.debug("Adding " + senderClass);
|
||||||
pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{
|
pico.addComponent(Sender.class, senderClass, new Parameter[]{
|
||||||
new ConstantParameter(host),
|
new ConstantParameter(host),
|
||||||
new ConstantParameter(port)});
|
new ConstantParameter(port)});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void addClientDuplex(String protocol, String implementation, String host, int port) throws LoaderException {
|
protected void addServerSender(String protocol, String implementation, int port) throws LoaderException {
|
||||||
Class<?> duplexClass = getClientForwarderClass(protocol, implementation);
|
Class<?> senderClass = getSenderClass(protocol, implementation);
|
||||||
logger.debug("Adding " + duplexClass);
|
logger.debug("Adding " + senderClass);
|
||||||
pico.addComponent(Duplex.class, duplexClass, new Parameter[]{
|
pico.addComponent(Sender.class, senderClass, new Parameter[]{
|
||||||
new ConstantParameter(host),
|
new ConstantParameter(port)});
|
||||||
new ConstantParameter(port)});
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
protected void addServerForwarder(String protocol, String implementation, int port) throws LoaderException {
|
protected void addClientForwarder(String protocol, String implementation, String host, int port) throws LoaderException {
|
||||||
Class<?> forwarderClass = getServerForwarderClass(protocol, implementation);
|
Class<?> forwarderClass = getClientForwarderClass(protocol, implementation);
|
||||||
logger.debug("Adding " + forwarderClass);
|
logger.debug("Adding " + forwarderClass);
|
||||||
pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{
|
pico.addComponent(Forwarder.class, forwarderClass, new Parameter[]{
|
||||||
new ConstantParameter(port)});
|
new ConstantParameter(host),
|
||||||
}
|
new ConstantParameter(port)});
|
||||||
|
}
|
||||||
|
|
||||||
protected void addServerDuplex(String protocol, String implementation, int port) throws LoaderException {
|
protected void addClientDuplex(String protocol, String implementation, String host, int port) throws LoaderException {
|
||||||
Class<?> duplexClass = getServerForwarderClass(protocol, implementation);
|
Class<?> duplexClass = getClientForwarderClass(protocol, implementation);
|
||||||
logger.debug("Adding " + duplexClass);
|
logger.debug("Adding " + duplexClass);
|
||||||
pico.addComponent(Duplex.class, duplexClass, new Parameter[]{
|
pico.addComponent(Duplex.class, duplexClass, new Parameter[]{
|
||||||
new ConstantParameter(port)});
|
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)});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,120 +18,120 @@ import base.work.Work;
|
|||||||
import base.worker.Worker;
|
import base.worker.Worker;
|
||||||
|
|
||||||
public class TcpClient extends Work implements Sender {
|
public class TcpClient extends Work implements Sender {
|
||||||
protected static final String HOST = "localhost";
|
protected static final String HOST = "localhost";
|
||||||
protected static final int BUFFER_SIZE = 1024;
|
protected static final int BUFFER_SIZE = 1024;
|
||||||
|
|
||||||
protected String host;
|
protected String host;
|
||||||
protected int port;
|
protected int port;
|
||||||
protected int bufferSize;
|
protected int bufferSize;
|
||||||
protected SocketChannel socketChannel;
|
protected SocketChannel socketChannel;
|
||||||
protected Selector selector;
|
protected Selector selector;
|
||||||
protected ArrayList<Listen<byte[]>> listenList = new ArrayList<Listen<byte[]>>();
|
protected ArrayList<Listen<byte[]>> listenList = new ArrayList<Listen<byte[]>>();
|
||||||
|
|
||||||
public TcpClient(int port) {
|
public TcpClient(int port) {
|
||||||
this(HOST, port);
|
this(HOST, port);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TcpClient(String host, int 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) {
|
public TcpClient(String host, int port, int bufferSize) {
|
||||||
this.host = host;
|
this.host = host;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
this.bufferSize = bufferSize;
|
this.bufferSize = bufferSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
System.out.println("Client: Activate!");
|
System.out.println("Client: Activate!");
|
||||||
try {
|
try {
|
||||||
InetSocketAddress hostAddress = new InetSocketAddress(host, port);
|
InetSocketAddress hostAddress = new InetSocketAddress(host, port);
|
||||||
socketChannel = SocketChannel.open(hostAddress);
|
socketChannel = SocketChannel.open(hostAddress);
|
||||||
socketChannel.configureBlocking(false);
|
socketChannel.configureBlocking(false);
|
||||||
while (!socketChannel.finishConnect()) {
|
while (!socketChannel.finishConnect()) {
|
||||||
sleep(Worker.SLEEP);
|
sleep(Worker.SLEEP);
|
||||||
}
|
}
|
||||||
selector = Selector.open();
|
selector = Selector.open();
|
||||||
socketChannel.register(selector, SelectionKey.OP_READ);
|
socketChannel.register(selector, SelectionKey.OP_READ);
|
||||||
synchronized (host) {
|
synchronized (host) {
|
||||||
host.notifyAll();
|
host.notifyAll();
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
super.activate();
|
super.activate();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deactivate() throws DeactivateException {
|
public void deactivate() throws DeactivateException {
|
||||||
System.out.println("Client: Deactivate!");
|
System.out.println("Client: Deactivate!");
|
||||||
try {
|
try {
|
||||||
selector.close();
|
selector.close();
|
||||||
socketChannel.close();
|
socketChannel.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new DeactivateException();
|
throw new DeactivateException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
super.stop();
|
super.stop();
|
||||||
if (selector != null) {
|
if (selector != null) {
|
||||||
selector.wakeup();
|
selector.wakeup();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void work() {
|
public final void work() {
|
||||||
try {
|
try {
|
||||||
logger.debug("Client: Waiting for select... ");
|
logger.debug("Client: Waiting for select... ");
|
||||||
logger.debug("Client: Number of selected keys: " + selector.select());
|
logger.debug("Client: Number of selected keys: " + selector.select());
|
||||||
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
|
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
|
||||||
Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
|
Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
|
||||||
|
|
||||||
while (selectionKeyIterator.hasNext()) {
|
while (selectionKeyIterator.hasNext()) {
|
||||||
SelectionKey selectionKey = selectionKeyIterator.next();
|
SelectionKey selectionKey = selectionKeyIterator.next();
|
||||||
if (selectionKey.isReadable()) {
|
if (selectionKey.isReadable()) {
|
||||||
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
|
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
|
||||||
socketChannel.read(byteBuffer);
|
socketChannel.read(byteBuffer);
|
||||||
byte[] buffer = byteBuffer.array();
|
byte[] buffer = byteBuffer.array();
|
||||||
input(buffer);
|
input(buffer);
|
||||||
} else if (selectionKey.isWritable()) {
|
} else if (selectionKey.isWritable()) {
|
||||||
byte[] buffer;
|
byte[] buffer;
|
||||||
buffer = (byte[]) selectionKey.attachment();
|
buffer = (byte[]) selectionKey.attachment();
|
||||||
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
|
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
|
||||||
socketChannel.write(byteBuffer);
|
socketChannel.write(byteBuffer);
|
||||||
//selectionKey.cancel();
|
//selectionKey.cancel();
|
||||||
socketChannel.register(selector, SelectionKey.OP_READ);
|
socketChannel.register(selector, SelectionKey.OP_READ);
|
||||||
}
|
}
|
||||||
selectionKeyIterator.remove();
|
selectionKeyIterator.remove();
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void input(byte[] buffer) {}
|
protected void input(byte[] buffer) {}
|
||||||
|
|
||||||
public void send(byte[] buffer) throws IOException {
|
public void send(byte[] buffer) throws IOException {
|
||||||
if (selector == null) {
|
if (selector == null) {
|
||||||
try {
|
try {
|
||||||
synchronized (host) {
|
synchronized (host) {
|
||||||
host.wait();
|
host.wait();
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
selector.wakeup();
|
selector.wakeup();
|
||||||
socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, buffer);
|
socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void close() throws IOException {
|
public void close() throws IOException {
|
||||||
socketChannel.close();
|
socketChannel.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
/*public void register(Listen<byte[]> listen) {
|
/*public void register(Listen<byte[]> listen) {
|
||||||
listenList.add(listen);
|
listenList.add(listen);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void remove(Listen<byte[]> listen) {
|
public void remove(Listen<byte[]> listen) {
|
||||||
listenList.remove(listen);
|
listenList.remove(listen);
|
||||||
}*/
|
}*/
|
||||||
}
|
}
|
||||||
@@ -20,139 +20,139 @@ import base.server.channel.TcpServerClient;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public class TcpServer extends Work implements Sender {
|
public class TcpServer extends Work implements Sender {
|
||||||
protected static final Class<?> CLIENT_CLASS = TcpServerClient.class;
|
protected static final Class<?> CLIENT_CLASS = TcpServerClient.class;
|
||||||
protected static final int BUFFER_SIZE = 1024;
|
protected static final int BUFFER_SIZE = 1024;
|
||||||
|
|
||||||
protected int port;
|
protected int port;
|
||||||
protected int bufferSize;
|
protected int bufferSize;
|
||||||
protected Constructor<?> clientConstructor;
|
protected Constructor<?> clientConstructor;
|
||||||
protected Selector selector;
|
protected Selector selector;
|
||||||
protected ServerSocketChannel serverSocket;
|
protected ServerSocketChannel serverSocket;
|
||||||
protected ArrayList<TcpServerClient> clientList;
|
protected ArrayList<TcpServerClient> clientList;
|
||||||
|
|
||||||
public TcpServer(int port) {
|
public TcpServer(int port) {
|
||||||
this(port, CLIENT_CLASS);
|
this(port, CLIENT_CLASS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TcpServer(int port, Class<?> clientClass) {
|
public TcpServer(int port, Class<?> clientClass) {
|
||||||
this(port, clientClass, BUFFER_SIZE);
|
this(port, clientClass, BUFFER_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TcpServer(int port, Class<?> clientClass, int bufferSize) {
|
public TcpServer(int port, Class<?> clientClass, int bufferSize) {
|
||||||
this.port = port;
|
this.port = port;
|
||||||
this.bufferSize = bufferSize;
|
this.bufferSize = bufferSize;
|
||||||
try {
|
try {
|
||||||
// Allow dependency injection, constructor arguments
|
// Allow dependency injection, constructor arguments
|
||||||
clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, SocketChannel.class, Integer.class);
|
clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, SocketChannel.class, Integer.class);
|
||||||
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
|
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
|
||||||
logger.error("Failed to initialise client constructor", e);
|
logger.error("Failed to initialise client constructor", e);
|
||||||
}
|
}
|
||||||
clientList = new ArrayList<TcpServerClient>();
|
clientList = new ArrayList<TcpServerClient>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
System.out.println("Server: Activate!");
|
System.out.println("Server: Activate!");
|
||||||
try {
|
try {
|
||||||
// Get selector
|
// Get selector
|
||||||
selector = Selector.open();
|
selector = Selector.open();
|
||||||
|
|
||||||
// Get server socket channel and register with selector
|
// Get server socket channel and register with selector
|
||||||
serverSocket = ServerSocketChannel.open();
|
serverSocket = ServerSocketChannel.open();
|
||||||
InetSocketAddress hostAddress = new InetSocketAddress(port);
|
InetSocketAddress hostAddress = new InetSocketAddress(port);
|
||||||
serverSocket.bind(hostAddress);
|
serverSocket.bind(hostAddress);
|
||||||
serverSocket.configureBlocking(false);
|
serverSocket.configureBlocking(false);
|
||||||
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
|
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
|
||||||
synchronized (clientConstructor) {
|
synchronized (clientConstructor) {
|
||||||
clientConstructor.notifyAll();
|
clientConstructor.notifyAll();
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
} catch (BindException e) {
|
} catch (BindException e) {
|
||||||
logger.error("Address already in use", e);
|
logger.error("Address already in use", e);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deactivate() throws DeactivateException {
|
public void deactivate() throws DeactivateException {
|
||||||
System.out.println("Server: Deactivate!");
|
System.out.println("Server: Deactivate!");
|
||||||
try {
|
try {
|
||||||
selector.close();
|
selector.close();
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new DeactivateException();
|
throw new DeactivateException();
|
||||||
} finally {
|
} finally {
|
||||||
for (TcpServerClient client : clientList) {
|
for (TcpServerClient client : clientList) {
|
||||||
client.stop();
|
client.stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
super.stop();
|
super.stop();
|
||||||
if (selector != null) {
|
if (selector != null) {
|
||||||
selector.wakeup();
|
selector.wakeup();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void work() {
|
public void work() {
|
||||||
try {
|
try {
|
||||||
System.out.println("Server: Waiting for select... ");
|
System.out.println("Server: Waiting for select... ");
|
||||||
System.out.println("Server: Number of selected keys: " + selector.select());
|
System.out.println("Server: Number of selected keys: " + selector.select());
|
||||||
|
|
||||||
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
|
Set<SelectionKey> selectionKeySet = selector.selectedKeys();
|
||||||
Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
|
Iterator<SelectionKey> selectionKeyIterator = selectionKeySet.iterator();
|
||||||
|
|
||||||
while (selectionKeyIterator.hasNext()) {
|
while (selectionKeyIterator.hasNext()) {
|
||||||
SelectionKey selectionKey = selectionKeyIterator.next();
|
SelectionKey selectionKey = selectionKeyIterator.next();
|
||||||
if (selectionKey.isAcceptable()) {
|
if (selectionKey.isAcceptable()) {
|
||||||
// Accept the new client connection
|
// Accept the new client connection
|
||||||
SocketChannel socketChannel = serverSocket.accept();
|
SocketChannel socketChannel = serverSocket.accept();
|
||||||
socketChannel.configureBlocking(false);
|
socketChannel.configureBlocking(false);
|
||||||
|
|
||||||
// Add the new connection to the selector
|
// Add the new connection to the selector
|
||||||
TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socketChannel, bufferSize);
|
TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socketChannel, bufferSize);
|
||||||
clientList.add(client);
|
clientList.add(client);
|
||||||
socketChannel.register(selector, SelectionKey.OP_READ, client);
|
socketChannel.register(selector, SelectionKey.OP_READ, client);
|
||||||
//initClient(client);
|
//initClient(client);
|
||||||
System.out.println("Accepted new connection from client: " + socketChannel);
|
System.out.println("Accepted new connection from client: " + socketChannel);
|
||||||
} else if (selectionKey.isReadable()) {
|
} else if (selectionKey.isReadable()) {
|
||||||
// Read the data from client
|
// Read the data from client
|
||||||
TcpServerClient serverClient = (TcpServerClient) selectionKey.attachment();
|
TcpServerClient serverClient = (TcpServerClient) selectionKey.attachment();
|
||||||
serverClient.readable();
|
serverClient.readable();
|
||||||
} else if (selectionKey.isWritable()) {
|
} else if (selectionKey.isWritable()) {
|
||||||
// Write to client?
|
// Write to client?
|
||||||
}
|
}
|
||||||
selectionKeyIterator.remove();
|
selectionKeyIterator.remove();
|
||||||
}
|
}
|
||||||
}/* catch (IOException e) {} catch (InstantiationException e) {
|
}/* catch (IOException e) {} catch (InstantiationException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
} catch (IllegalAccessException e) {
|
} catch (IllegalAccessException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
} catch (InvocationTargetException e) {
|
} catch (InvocationTargetException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
} */catch (Exception e) {
|
} */catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void initClient(TcpServerClient client) {
|
protected void initClient(TcpServerClient client) {
|
||||||
try {
|
try {
|
||||||
client.write(ByteBuffer.wrap(new String("Hi there!").getBytes()));
|
client.write(ByteBuffer.wrap(new String("Hi there!").getBytes()));
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void send(byte[] buffer) throws IOException {
|
public void send(byte[] buffer) throws IOException {
|
||||||
logger.debug("Number of clients = " + clientList.size());
|
logger.debug("Number of clients = " + clientList.size());
|
||||||
for (TcpServerClient client : clientList) {
|
for (TcpServerClient client : clientList) {
|
||||||
// Should be dealt with in clients own thread
|
// Should be dealt with in clients own thread
|
||||||
client.send(buffer);
|
client.send(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(TcpServerClient client, byte[] buffer) {}
|
public void input(TcpServerClient client, byte[] buffer) {}
|
||||||
}
|
}
|
||||||
@@ -8,47 +8,47 @@ import base.Sender;
|
|||||||
import base.work.Listen;
|
import base.work.Listen;
|
||||||
|
|
||||||
public class TcpServerClient extends Listen<byte[]> implements Sender {
|
public class TcpServerClient extends Listen<byte[]> implements Sender {
|
||||||
protected static final int BUFFER_SIZE = 1024;
|
protected static final int BUFFER_SIZE = 1024;
|
||||||
|
|
||||||
protected TcpServer server;
|
protected TcpServer server;
|
||||||
protected SocketChannel socketChannel;
|
protected SocketChannel socketChannel;
|
||||||
protected int bufferSize;
|
protected int bufferSize;
|
||||||
protected ByteBuffer byteBuffer;
|
protected ByteBuffer byteBuffer;
|
||||||
|
|
||||||
public TcpServerClient(TcpServer server, SocketChannel socketChannel) {
|
public TcpServerClient(TcpServer server, SocketChannel socketChannel) {
|
||||||
this(server, socketChannel, BUFFER_SIZE);
|
this(server, socketChannel, BUFFER_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TcpServerClient(TcpServer server, SocketChannel socketChannel, Integer bufferSize) {
|
public TcpServerClient(TcpServer server, SocketChannel socketChannel, Integer bufferSize) {
|
||||||
super();
|
super();
|
||||||
this.server = server;
|
this.server = server;
|
||||||
this.socketChannel = socketChannel;
|
this.socketChannel = socketChannel;
|
||||||
this.bufferSize = bufferSize;
|
this.bufferSize = bufferSize;
|
||||||
byteBuffer = ByteBuffer.allocate(bufferSize);
|
byteBuffer = ByteBuffer.allocate(bufferSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void write(ByteBuffer byteBuffer) throws IOException {
|
public void write(ByteBuffer byteBuffer) throws IOException {
|
||||||
socketChannel.write(byteBuffer);
|
socketChannel.write(byteBuffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void readable() throws IOException {
|
public void readable() throws IOException {
|
||||||
int read;
|
int read;
|
||||||
while (( read = socketChannel.read(byteBuffer)) > 0) {
|
while (( read = socketChannel.read(byteBuffer)) > 0) {
|
||||||
byteBuffer.flip();
|
byteBuffer.flip();
|
||||||
byte[] buffer = byteBuffer.array();
|
byte[] buffer = byteBuffer.array();
|
||||||
input(buffer);
|
input(buffer);
|
||||||
byteBuffer.clear();
|
byteBuffer.clear();
|
||||||
}
|
}
|
||||||
if (read < 0) {
|
if (read < 0) {
|
||||||
socketChannel.close();
|
socketChannel.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(byte[] buffer) {
|
public void input(byte[] buffer) {
|
||||||
server.input(this, buffer);
|
server.input(this, buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void send(byte[] buffer) throws IOException {
|
public void send(byte[] buffer) throws IOException {
|
||||||
write(ByteBuffer.wrap(buffer));
|
write(ByteBuffer.wrap(buffer));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +1,51 @@
|
|||||||
package base.server.datagram;
|
package base.server.datagram;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.DatagramPacket;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
|
||||||
import base.Sender;
|
import base.Sender;
|
||||||
|
|
||||||
public class UdpDuplexClient extends UdpMulticastClient implements Sender {
|
public class UdpDuplexClient extends UdpMulticastClient implements Sender {
|
||||||
|
protected int sendPort;
|
||||||
|
protected Sender sender;
|
||||||
|
|
||||||
public UdpDuplexClient(int port) {
|
public UdpDuplexClient(int bindPort, String sendHost, int sendPort) throws UnknownHostException {
|
||||||
super(port);
|
this(HOST, bindPort, sendHost, sendPort);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void send(byte[] buffer) throws IOException {
|
public UdpDuplexClient(String bindHost, int bindPort, String sendHost, int sendPort) throws UnknownHostException {
|
||||||
// TODO Auto-generated method stub
|
this(bindHost, bindPort, sendHost, sendPort, BUFFER_SIZE);
|
||||||
|
}
|
||||||
}
|
|
||||||
|
|
||||||
protected void input(byte[] buffer) {
|
public UdpDuplexClient(String bindHost, int bindPort, String sendHost, int sendPort, int bufferSize) throws UnknownHostException {
|
||||||
// TODO Auto-generated method stub
|
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) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package base.server.datagram;
|
||||||
|
|
||||||
|
import java.net.MulticastSocket;
|
||||||
|
|
||||||
|
import base.work.Listen;
|
||||||
|
|
||||||
|
public class UdpDuplexHelper extends AbstractUdpClient {
|
||||||
|
protected Listen<byte[]> listen;
|
||||||
|
|
||||||
|
public UdpDuplexHelper(Listen<byte[]> listen, MulticastSocket socket) {
|
||||||
|
super(socket);
|
||||||
|
this.listen = listen;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void input(byte[] buffer) {
|
||||||
|
System.out.println("jajajaja");
|
||||||
|
listen.add(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,59 @@
|
|||||||
package base.server.datagram;
|
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 {
|
public class UdpDuplexServer extends UdpMulticastServer {
|
||||||
|
protected int bindPort;
|
||||||
|
protected UdpDuplexHelper helper;
|
||||||
|
|
||||||
public UdpDuplexServer(int port) {
|
public UdpDuplexServer(int sendPort, int bindPort) {
|
||||||
super(port);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,62 +1,42 @@
|
|||||||
package base.server.datagram;
|
package base.server.datagram;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.DatagramPacket;
|
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.MulticastSocket;
|
import java.net.MulticastSocket;
|
||||||
|
|
||||||
import base.exception.worker.ActivateException;
|
import base.exception.worker.ActivateException;
|
||||||
import base.work.Work;
|
|
||||||
|
|
||||||
public abstract class UdpMulticastClient extends Work {
|
public class UdpMulticastClient extends AbstractUdpClient {
|
||||||
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 String host;
|
||||||
protected int port;
|
protected int port;
|
||||||
protected int bufferSize;
|
|
||||||
protected MulticastSocket socket;
|
|
||||||
protected InetAddress group;
|
|
||||||
|
|
||||||
public UdpMulticastClient(int port) {
|
public UdpMulticastClient(int port) {
|
||||||
this(HOST, port);
|
this(HOST, port);
|
||||||
}
|
}
|
||||||
|
|
||||||
public UdpMulticastClient(String host, int port) {
|
public UdpMulticastClient(String host, int port) {
|
||||||
this(host, port, BUFFER_SIZE);
|
this(host, port, BUFFER_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
public UdpMulticastClient(String host, int port, int bufferSize) {
|
public UdpMulticastClient(String host, int port, int bufferSize) {
|
||||||
this.host = host;
|
this.host = host;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
this.bufferSize = BUFFER_SIZE;
|
this.bufferSize = BUFFER_SIZE;
|
||||||
}
|
System.out.println("Client bind: " + host + " " + port);
|
||||||
|
}
|
||||||
|
|
||||||
public void work() {
|
public void activate() throws ActivateException {
|
||||||
try {
|
try {
|
||||||
byte[] buffer = new byte[bufferSize];
|
socket = new MulticastSocket(port);
|
||||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
|
InetAddress group = InetAddress.getByName(host);
|
||||||
socket.receive(packet);
|
socket.joinGroup(group);
|
||||||
buffer = packet.getData();
|
} catch (IOException e) {
|
||||||
input(buffer);
|
logger.error("", e);
|
||||||
} catch (IOException e) {}
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
protected void input(byte[] buffer) {}
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,47 +12,39 @@ import base.work.Listen;
|
|||||||
import base.worker.Worker;
|
import base.worker.Worker;
|
||||||
|
|
||||||
public class UdpMulticastServer extends Listen<byte[]> implements Sender {
|
public class UdpMulticastServer extends Listen<byte[]> 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 static final int BUFFER_SIZE = 2048;
|
||||||
|
|
||||||
protected String host;
|
protected String host;
|
||||||
protected int port;
|
protected int port;
|
||||||
protected MulticastSocket socket;
|
protected MulticastSocket socket;
|
||||||
//private XX x;
|
|
||||||
|
|
||||||
public UdpMulticastServer(int port) {
|
public UdpMulticastServer(int port) {
|
||||||
this(HOST, port);
|
this(HOST, port);
|
||||||
}
|
}
|
||||||
|
|
||||||
public UdpMulticastServer(String host, int port) {
|
public UdpMulticastServer(String host, int port) {
|
||||||
super(Worker.Type.BACKGROUND);
|
super(Worker.Type.BACKGROUND);
|
||||||
this.host = host;
|
this.host = host;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
}
|
System.out.println("Server send: " + host + " " + port);
|
||||||
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
try {
|
try {
|
||||||
socket = new MulticastSocket(); // optional, add port and receive as well!!
|
socket = new MulticastSocket();
|
||||||
// pass socket directly to Server to establish bidirectional
|
} catch (IOException e) {
|
||||||
// couple together capabilities
|
throw new ActivateException();
|
||||||
// listen to datagrams and deal with writing using nio?
|
}
|
||||||
//x = new XX(socket);
|
super.activate();
|
||||||
//x.start();
|
}
|
||||||
} catch (IOException e) {
|
|
||||||
throw new ActivateException();
|
|
||||||
}
|
|
||||||
super.activate();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void deactivate() throws DeactivateException {
|
public void deactivate() throws DeactivateException {
|
||||||
socket.close();
|
socket.close();
|
||||||
super.deactivate();
|
super.deactivate();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(byte[] buffer) {
|
public void input(byte[] buffer) {
|
||||||
if (socket == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
InetAddress group = InetAddress.getByName(host);
|
InetAddress group = InetAddress.getByName(host);
|
||||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
|
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
|
||||||
@@ -60,10 +52,10 @@ public class UdpMulticastServer extends Listen<byte[]> implements Sender {
|
|||||||
}
|
}
|
||||||
catch (IOException e) {
|
catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void send(byte[] buffer) throws IOException {
|
public void send(byte[] buffer) throws IOException {
|
||||||
add(buffer);
|
add(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,51 +13,44 @@ import org.slf4j.LoggerFactory;
|
|||||||
import base.Sender;
|
import base.Sender;
|
||||||
|
|
||||||
public class UdpSender implements Sender {
|
public class UdpSender implements Sender {
|
||||||
protected static final String HOST = "localhost";
|
protected static final String HOST = "localhost";
|
||||||
protected Logger logger = LoggerFactory.getLogger(getClass());
|
protected Logger logger = LoggerFactory.getLogger(getClass());
|
||||||
|
|
||||||
protected DatagramSocket datagramSocket;
|
protected DatagramSocket datagramSocket;
|
||||||
protected InetAddress inetAddress;
|
protected InetAddress inetAddress;
|
||||||
protected int port;
|
protected int port;
|
||||||
|
|
||||||
public UdpSender(int port) throws UnknownHostException {
|
public UdpSender(int port) throws UnknownHostException {
|
||||||
this(HOST, port);
|
this(HOST, port);
|
||||||
}
|
}
|
||||||
|
|
||||||
public UdpSender(String host, int port) throws UnknownHostException{
|
public UdpSender(String host, int port) throws UnknownHostException {
|
||||||
inetAddress = InetAddress.getByName(host);
|
System.out.println("Sender use: " + host + " " + port);
|
||||||
logger.debug(host);
|
inetAddress = InetAddress.getByName(host);
|
||||||
logger.debug(String.valueOf(port));
|
this.port = port;
|
||||||
this.port = port;
|
try {
|
||||||
}
|
datagramSocket = new DatagramSocket();
|
||||||
|
} catch (SocketException e) {
|
||||||
|
logger.error("Failed to create socket", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void start() {
|
public void start() {}
|
||||||
if (datagramSocket == null) {
|
|
||||||
try {
|
|
||||||
datagramSocket = new DatagramSocket();
|
|
||||||
} catch (SocketException e) {
|
|
||||||
logger.error("Failed to create socket", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
if (datagramSocket != null) {
|
datagramSocket.close();
|
||||||
datagramSocket.close();
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
stop();
|
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 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,56 +9,56 @@ import base.exception.worker.ActivateException;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public class UdpServer extends Work {
|
public class UdpServer extends Work {
|
||||||
protected static final int BUFFER_SIZE = 1024;
|
protected static final int BUFFER_SIZE = 1024;
|
||||||
protected static final int TIMEOUT = 1000;
|
protected static final int TIMEOUT = 1000;
|
||||||
|
|
||||||
protected int port;
|
protected int port;
|
||||||
protected int bufferSize;
|
protected int bufferSize;
|
||||||
protected DatagramSocket diagramSocket;
|
protected DatagramSocket diagramSocket;
|
||||||
|
|
||||||
public UdpServer(int port) {
|
public UdpServer(int port) {
|
||||||
this(port, BUFFER_SIZE);
|
this(port, BUFFER_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
public UdpServer(int port, int bufferSize) {
|
public UdpServer(int port, int bufferSize) {
|
||||||
super();
|
super();
|
||||||
this.port = port;
|
this.port = port;
|
||||||
this.bufferSize = bufferSize;
|
this.bufferSize = bufferSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
try {
|
try {
|
||||||
logger.debug("Starting datagram socket on port " + port);
|
logger.debug("Starting datagram socket on port " + port);
|
||||||
diagramSocket = new DatagramSocket(port);
|
diagramSocket = new DatagramSocket(port);
|
||||||
diagramSocket.setSoTimeout(TIMEOUT);
|
diagramSocket.setSoTimeout(TIMEOUT);
|
||||||
super.activate();
|
super.activate();
|
||||||
} catch (SocketException e) {
|
} catch (SocketException e) {
|
||||||
logger.error("Failed to initialize socket", e);
|
logger.error("Failed to initialize socket", e);
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
super.stop();
|
super.stop();
|
||||||
if (diagramSocket != null) {
|
if (diagramSocket != null) {
|
||||||
diagramSocket.close();
|
diagramSocket.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void work() {
|
public void work() {
|
||||||
byte[] buffer = new byte[bufferSize];
|
byte[] buffer = new byte[bufferSize];
|
||||||
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
|
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
|
||||||
try {
|
try {
|
||||||
diagramSocket.receive(datagramPacket);
|
diagramSocket.receive(datagramPacket);
|
||||||
} catch (SocketException e) {
|
} catch (SocketException e) {
|
||||||
stop();
|
stop();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("Failed to receive packet", e);
|
logger.error("Failed to receive packet", e);
|
||||||
stop();
|
stop();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
input(buffer);
|
input(buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void input(byte[] buffer) {}
|
protected void input(byte[] buffer) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,24 +8,24 @@ import base.server.channel.TcpServer;
|
|||||||
import base.server.channel.TcpServerClient;
|
import base.server.channel.TcpServerClient;
|
||||||
|
|
||||||
public class TcpChannelServerForwarder extends TcpServer implements Duplex {
|
public class TcpChannelServerForwarder extends TcpServer implements Duplex {
|
||||||
protected ArrayList<Receiver> receiverList;
|
protected ArrayList<Receiver> receiverList;
|
||||||
|
|
||||||
public TcpChannelServerForwarder(int port) {
|
public TcpChannelServerForwarder(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
receiverList = new ArrayList<Receiver>();
|
receiverList = new ArrayList<Receiver>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void register(Receiver receiver) {
|
public void register(Receiver receiver) {
|
||||||
receiverList.add(receiver);
|
receiverList.add(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void remove(Receiver receiver) {
|
public void remove(Receiver receiver) {
|
||||||
receiverList.remove(receiver);
|
receiverList.remove(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(TcpServerClient client, byte[] buffer) {
|
public void input(TcpServerClient client, byte[] buffer) {
|
||||||
for (Receiver receiver: receiverList) {
|
for (Receiver receiver: receiverList) {
|
||||||
receiver.receive(buffer);
|
receiver.receive(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,24 +8,24 @@ import base.server.socket.TcpClient;
|
|||||||
import base.server.socket.TcpServerClient;
|
import base.server.socket.TcpServerClient;
|
||||||
|
|
||||||
public class TcpClientChannelForwarder extends TcpClient implements Duplex {
|
public class TcpClientChannelForwarder extends TcpClient implements Duplex {
|
||||||
protected ArrayList<Receiver> receiverList;
|
protected ArrayList<Receiver> receiverList;
|
||||||
|
|
||||||
public TcpClientChannelForwarder(String host, int port) {
|
public TcpClientChannelForwarder(String host, int port) {
|
||||||
super(host, port);
|
super(host, port);
|
||||||
receiverList = new ArrayList<Receiver>();
|
receiverList = new ArrayList<Receiver>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void register(Receiver receiver) {
|
public void register(Receiver receiver) {
|
||||||
receiverList.add(receiver);
|
receiverList.add(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void remove(Receiver receiver) {
|
public void remove(Receiver receiver) {
|
||||||
receiverList.remove(receiver);
|
receiverList.remove(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(TcpServerClient client, byte[] buffer) {
|
public void input(TcpServerClient client, byte[] buffer) {
|
||||||
for (Receiver receiver: receiverList) {
|
for (Receiver receiver: receiverList) {
|
||||||
receiver.receive(buffer);
|
receiver.receive(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,24 +8,24 @@ import base.server.channel.TcpClient;
|
|||||||
import base.server.channel.TcpServerClient;
|
import base.server.channel.TcpServerClient;
|
||||||
|
|
||||||
public class TcpClientSocketForwarder extends TcpClient implements Duplex {
|
public class TcpClientSocketForwarder extends TcpClient implements Duplex {
|
||||||
protected ArrayList<Receiver> receiverList;
|
protected ArrayList<Receiver> receiverList;
|
||||||
|
|
||||||
public TcpClientSocketForwarder(String host, int port) {
|
public TcpClientSocketForwarder(String host, int port) {
|
||||||
super(host, port);
|
super(host, port);
|
||||||
receiverList = new ArrayList<Receiver>();
|
receiverList = new ArrayList<Receiver>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void register(Receiver receiver) {
|
public void register(Receiver receiver) {
|
||||||
receiverList.add(receiver);
|
receiverList.add(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void remove(Receiver receiver) {
|
public void remove(Receiver receiver) {
|
||||||
receiverList.remove(receiver);
|
receiverList.remove(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(TcpServerClient client, byte[] buffer) {
|
public void input(TcpServerClient client, byte[] buffer) {
|
||||||
for (Receiver receiver: receiverList) {
|
for (Receiver receiver: receiverList) {
|
||||||
receiver.receive(buffer);
|
receiver.receive(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,24 +8,24 @@ import base.server.socket.TcpServer;
|
|||||||
import base.server.socket.TcpServerClient;
|
import base.server.socket.TcpServerClient;
|
||||||
|
|
||||||
public class TcpSocketServerForwarder extends TcpServer implements Duplex {
|
public class TcpSocketServerForwarder extends TcpServer implements Duplex {
|
||||||
protected ArrayList<Receiver> receiverList;
|
protected ArrayList<Receiver> receiverList;
|
||||||
|
|
||||||
public TcpSocketServerForwarder(int port) {
|
public TcpSocketServerForwarder(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
receiverList = new ArrayList<Receiver>();
|
receiverList = new ArrayList<Receiver>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void register(Receiver receiver) {
|
public void register(Receiver receiver) {
|
||||||
receiverList.add(receiver);
|
receiverList.add(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void remove(Receiver receiver) {
|
public void remove(Receiver receiver) {
|
||||||
receiverList.remove(receiver);
|
receiverList.remove(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(TcpServerClient client, byte[] buffer) {
|
public void input(TcpServerClient client, byte[] buffer) {
|
||||||
for (Receiver receiver: receiverList) {
|
for (Receiver receiver: receiverList) {
|
||||||
receiver.receive(buffer);
|
receiver.receive(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package base.server.forwarder;
|
package base.server.forwarder;
|
||||||
|
|
||||||
|
import java.net.UnknownHostException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
|
||||||
import base.Duplex;
|
import base.Duplex;
|
||||||
@@ -7,24 +8,24 @@ import base.Receiver;
|
|||||||
import base.server.datagram.UdpDuplexClient;
|
import base.server.datagram.UdpDuplexClient;
|
||||||
|
|
||||||
public class UdpDuplexClientForwarder extends UdpDuplexClient implements Duplex {
|
public class UdpDuplexClientForwarder extends UdpDuplexClient implements Duplex {
|
||||||
protected ArrayList<Receiver> receiverList;
|
protected ArrayList<Receiver> receiverList;
|
||||||
|
|
||||||
public UdpDuplexClientForwarder(String host, int port) {
|
public UdpDuplexClientForwarder(String bindHost, int bindPort, String sendHost, int sendPort) throws UnknownHostException {
|
||||||
super(port);
|
super(bindHost, bindPort, sendHost, sendPort);
|
||||||
receiverList = new ArrayList<Receiver>();
|
receiverList = new ArrayList<Receiver>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void register(Receiver receiver) {
|
public void register(Receiver receiver) {
|
||||||
receiverList.add(receiver);
|
receiverList.add(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void remove(Receiver receiver) {
|
public void remove(Receiver receiver) {
|
||||||
receiverList.remove(receiver);
|
receiverList.remove(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(byte[] buffer) {
|
public void input(byte[] buffer) {
|
||||||
for (Receiver receiver: receiverList) {
|
for (Receiver receiver: receiverList) {
|
||||||
receiver.receive(buffer);
|
receiver.receive(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,24 +7,24 @@ import base.Receiver;
|
|||||||
import base.server.datagram.UdpDuplexServer;
|
import base.server.datagram.UdpDuplexServer;
|
||||||
|
|
||||||
public class UdpDuplexServerForwarder extends UdpDuplexServer implements Duplex {
|
public class UdpDuplexServerForwarder extends UdpDuplexServer implements Duplex {
|
||||||
protected ArrayList<Receiver> receiverList;
|
protected ArrayList<Receiver> receiverList;
|
||||||
|
|
||||||
public UdpDuplexServerForwarder(int port) {
|
public UdpDuplexServerForwarder(int port, int listenPort) {
|
||||||
super(port);
|
super(port, listenPort);
|
||||||
receiverList = new ArrayList<Receiver>();
|
receiverList = new ArrayList<Receiver>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void register(Receiver receiver) {
|
public void register(Receiver receiver) {
|
||||||
receiverList.add(receiver);
|
receiverList.add(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void remove(Receiver receiver) {
|
public void remove(Receiver receiver) {
|
||||||
receiverList.remove(receiver);
|
receiverList.remove(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(byte[] buffer) {
|
public void input(byte[] buffer) {
|
||||||
for (Receiver receiver: receiverList) {
|
for (Receiver receiver: receiverList) {
|
||||||
receiver.receive(buffer);
|
receiver.receive(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,24 +7,24 @@ import base.Receiver;
|
|||||||
import base.server.datagram.UdpServer;
|
import base.server.datagram.UdpServer;
|
||||||
|
|
||||||
public class UdpServerForwarder extends UdpServer implements Forwarder {
|
public class UdpServerForwarder extends UdpServer implements Forwarder {
|
||||||
protected ArrayList<Receiver> receiverList;
|
protected ArrayList<Receiver> receiverList;
|
||||||
|
|
||||||
public UdpServerForwarder(int port) {
|
public UdpServerForwarder(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
receiverList = new ArrayList<Receiver>();
|
receiverList = new ArrayList<Receiver>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void register(Receiver receiver) {
|
public void register(Receiver receiver) {
|
||||||
receiverList.add(receiver);
|
receiverList.add(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void remove(Receiver receiver) {
|
public void remove(Receiver receiver) {
|
||||||
receiverList.remove(receiver);
|
receiverList.remove(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(byte[] buffer) {
|
public void input(byte[] buffer) {
|
||||||
for (Receiver receiver: receiverList) {
|
for (Receiver receiver: receiverList) {
|
||||||
receiver.receive(buffer);
|
receiver.receive(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,26 +8,26 @@ import base.Forwarder;
|
|||||||
import base.Receiver;
|
import base.Receiver;
|
||||||
|
|
||||||
public abstract class AbstractReceiver implements Receiver, Control {
|
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) {
|
public AbstractReceiver(Forwarder forwarder) {
|
||||||
this.forwarder = forwarder;
|
this.forwarder = forwarder;
|
||||||
forwarder.register(this);
|
forwarder.register(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() {
|
public void start() {
|
||||||
forwarder.start();
|
forwarder.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
forwarder.stop();
|
forwarder.stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
forwarder.exit();
|
forwarder.exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract public void receive(byte[] buffer);
|
abstract public void receive(byte[] buffer);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,19 +10,19 @@ import base.exception.worker.DeactivateException;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public abstract class AbstractTcpClient extends Work implements Sender {
|
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 Object object = new Object();
|
||||||
protected int bufferSize;
|
protected int bufferSize;
|
||||||
protected Socket socket;
|
protected Socket socket;
|
||||||
protected InputStream inputStream;
|
protected InputStream inputStream;
|
||||||
protected OutputStream outputStream;
|
protected OutputStream outputStream;
|
||||||
|
|
||||||
public AbstractTcpClient(Integer bufferSize) {
|
public AbstractTcpClient(Integer bufferSize) {
|
||||||
this.bufferSize = bufferSize;
|
this.bufferSize = bufferSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean active() {
|
public boolean active() {
|
||||||
return super.active() && socket.isConnected();
|
return super.active() && socket.isConnected();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,36 +37,36 @@ public abstract class AbstractTcpClient extends Work implements Sender {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
super.exit();
|
super.exit();
|
||||||
try {
|
try {
|
||||||
socket.close();
|
socket.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void work() {
|
public void work() {
|
||||||
byte[] buffer = new byte[bufferSize];
|
byte[] buffer = new byte[bufferSize];
|
||||||
try {
|
try {
|
||||||
while (inputStream.read(buffer) > 0) {
|
while (inputStream.read(buffer) > 0) {
|
||||||
input(buffer);
|
input(buffer);
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected abstract void input(byte[] buffer);
|
protected abstract void input(byte[] buffer);
|
||||||
|
|
||||||
public void send(byte[] buffer) throws IOException {
|
public void send(byte[] buffer) throws IOException {
|
||||||
if (outputStream == null) {
|
if (outputStream == null) {
|
||||||
try {
|
try {
|
||||||
synchronized (object) {
|
synchronized (object) {
|
||||||
object.wait();
|
object.wait();
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
outputStream.write(buffer);
|
outputStream.write(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,33 +8,33 @@ import base.Sender;
|
|||||||
import base.exception.worker.ActivateException;
|
import base.exception.worker.ActivateException;
|
||||||
|
|
||||||
public class TcpClient extends AbstractTcpClient implements Sender {
|
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;
|
protected int port;
|
||||||
|
|
||||||
public TcpClient(int port) {
|
public TcpClient(int port) {
|
||||||
this(HOST, port);
|
this(HOST, port);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TcpClient(String host, int 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) {
|
public TcpClient(String host, int port, int bufferSize) {
|
||||||
super(bufferSize);
|
super(bufferSize);
|
||||||
this.host = host;
|
this.host = host;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
try {
|
try {
|
||||||
socket = new Socket(host, port);
|
socket = new Socket(host, port);
|
||||||
inputStream = socket.getInputStream();
|
inputStream = socket.getInputStream();
|
||||||
outputStream = socket.getOutputStream();
|
outputStream = socket.getOutputStream();
|
||||||
synchronized (object) {
|
synchronized (object) {
|
||||||
object.notifyAll();
|
object.notifyAll();
|
||||||
}
|
}
|
||||||
} catch (UnknownHostException e) {
|
} catch (UnknownHostException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
@@ -45,5 +45,5 @@ public class TcpClient extends AbstractTcpClient implements Sender {
|
|||||||
super.activate();
|
super.activate();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void input(byte[] buffer) {}
|
protected void input(byte[] buffer) {}
|
||||||
}
|
}
|
||||||
@@ -12,75 +12,75 @@ import base.exception.worker.DeactivateException;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public class TcpServer extends Work implements Sender {
|
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 int port;
|
||||||
protected ServerSocket serverSocket;
|
protected ServerSocket serverSocket;
|
||||||
protected Constructor<?> clientConstructor;
|
protected Constructor<?> clientConstructor;
|
||||||
protected ArrayList<TcpServerClient> clientList;
|
protected ArrayList<TcpServerClient> clientList;
|
||||||
|
|
||||||
public TcpServer(int port) {
|
public TcpServer(int port) {
|
||||||
this(port, CLIENT_CLASS);
|
this(port, CLIENT_CLASS);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TcpServer(int port, Class<?> clientClass) {
|
public TcpServer(int port, Class<?> clientClass) {
|
||||||
this.port = port;
|
this.port = port;
|
||||||
try {
|
try {
|
||||||
clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, Socket.class);
|
clientConstructor = Class.forName(clientClass.getName()).getConstructor(TcpServer.class, Socket.class);
|
||||||
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
|
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
|
||||||
logger.error("Failed to initialise client constructor");
|
logger.error("Failed to initialise client constructor");
|
||||||
}
|
}
|
||||||
clientList = new ArrayList<TcpServerClient>();
|
clientList = new ArrayList<TcpServerClient>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
try {
|
try {
|
||||||
serverSocket = new ServerSocket(port);
|
serverSocket = new ServerSocket(port);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deactivate() throws DeactivateException {
|
public void deactivate() throws DeactivateException {
|
||||||
for (TcpServerClient client : clientList) {
|
for (TcpServerClient client : clientList) {
|
||||||
client.stop();
|
client.stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
super.exit();
|
super.exit();
|
||||||
try {
|
try {
|
||||||
serverSocket.close();
|
serverSocket.close();
|
||||||
for (TcpServerClient client : clientList) {
|
for (TcpServerClient client : clientList) {
|
||||||
client.exit();
|
client.exit();
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void work() {
|
public void work() {
|
||||||
try {
|
try {
|
||||||
Socket socket = serverSocket.accept();
|
Socket socket = serverSocket.accept();
|
||||||
TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socket);
|
TcpServerClient client = (TcpServerClient) clientConstructor.newInstance(this, socket);
|
||||||
clientList.add(client);
|
clientList.add(client);
|
||||||
client.start();
|
client.start();
|
||||||
System.out.println("Accepted new connection from client: " + socket);
|
System.out.println("Accepted new connection from client: " + socket);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
stop();
|
stop();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void send(byte[] buffer) throws IOException {
|
public void send(byte[] buffer) throws IOException {
|
||||||
logger.debug("Number of clients = " + clientList.size());
|
logger.debug("Number of clients = " + clientList.size());
|
||||||
for (TcpServerClient client : clientList) {
|
for (TcpServerClient client : clientList) {
|
||||||
// Should be dealt with in clients own thread?
|
// Should be dealt with in clients own thread?
|
||||||
client.send(buffer);
|
client.send(buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(TcpServerClient client, byte[] buffer) {}
|
public void input(TcpServerClient client, byte[] buffer) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,32 +6,32 @@ import java.net.Socket;
|
|||||||
import base.exception.worker.ActivateException;
|
import base.exception.worker.ActivateException;
|
||||||
|
|
||||||
public class TcpServerClient extends AbstractTcpClient {
|
public class TcpServerClient extends AbstractTcpClient {
|
||||||
private TcpServer server;
|
private TcpServer server;
|
||||||
|
|
||||||
public TcpServerClient(TcpServer server, Socket socket) {
|
public TcpServerClient(TcpServer server, Socket socket) {
|
||||||
this(server, socket, BUFFER_SIZE);
|
this(server, socket, BUFFER_SIZE);
|
||||||
}
|
}
|
||||||
|
|
||||||
public TcpServerClient(TcpServer server, Socket socket, Integer bufferSize) {
|
public TcpServerClient(TcpServer server, Socket socket, Integer bufferSize) {
|
||||||
super(bufferSize);
|
super(bufferSize);
|
||||||
this.server = server;
|
this.server = server;
|
||||||
this.socket = socket;
|
this.socket = socket;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
try {
|
try {
|
||||||
inputStream = socket.getInputStream();
|
inputStream = socket.getInputStream();
|
||||||
outputStream = socket.getOutputStream();
|
outputStream = socket.getOutputStream();
|
||||||
synchronized (object) {
|
synchronized (object) {
|
||||||
object.notifyAll();
|
object.notifyAll();
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(byte[] buffer) {
|
public void input(byte[] buffer) {
|
||||||
server.input(this, buffer);
|
server.input(this, buffer);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ public class ArrayCycle<E> extends CopyOnWriteArrayList<E> {
|
|||||||
protected int index = 0;
|
protected int index = 0;
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public ArrayCycle(E... elementArray) {
|
public ArrayCycle(E... elementArray) {
|
||||||
if (elementArray != null) {
|
if (elementArray != null) {
|
||||||
for (E element : elementArray) {
|
for (E element : elementArray) {
|
||||||
add(element);
|
add(element);
|
||||||
|
|||||||
@@ -1,41 +1,41 @@
|
|||||||
package base.util;
|
package base.util;
|
||||||
|
|
||||||
public class Buffer {
|
public class Buffer {
|
||||||
protected byte[] elements;
|
protected byte[] elements;
|
||||||
protected int capacity;
|
protected int capacity;
|
||||||
protected int index;
|
protected int index;
|
||||||
protected int size;
|
protected int size;
|
||||||
|
|
||||||
public Buffer(int capacity) {
|
public Buffer(int capacity) {
|
||||||
this.elements = new byte[capacity];
|
this.elements = new byte[capacity];
|
||||||
this.capacity = capacity;
|
this.capacity = capacity;
|
||||||
index = 0;
|
index = 0;
|
||||||
size = 0;
|
size = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void add(byte... elements) {
|
public synchronized void add(byte... elements) {
|
||||||
for (byte element : elements) {
|
for (byte element : elements) {
|
||||||
this.elements[index++ % capacity] = element;
|
this.elements[index++ % capacity] = element;
|
||||||
if (size < capacity) {
|
if (size < capacity) {
|
||||||
++size;
|
++size;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void write(byte[] elements, int offset, int length) {
|
public synchronized void write(byte[] elements, int offset, int length) {
|
||||||
for (int i = offset; i < length; ++i) {
|
for (int i = offset; i < length; ++i) {
|
||||||
this.elements[index++ % capacity] = elements[i];
|
this.elements[index++ % capacity] = elements[i];
|
||||||
if (size < capacity) {
|
if (size < capacity) {
|
||||||
++size;
|
++size;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized byte[] get() {
|
public synchronized byte[] get() {
|
||||||
byte[] elements = new byte[size];
|
byte[] elements = new byte[size];
|
||||||
for (int i = 0; i < size; i++) {
|
for (int i = 0; i < size; i++) {
|
||||||
elements[i] = this.elements[(index + i) % size];
|
elements[i] = this.elements[(index + i) % size];
|
||||||
}
|
}
|
||||||
return elements;
|
return elements;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package base.util;
|
package base.util;
|
||||||
|
|
||||||
public interface Bufferable {
|
public interface Bufferable {
|
||||||
public void load();
|
public void load();
|
||||||
public void unload();
|
public void unload();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,37 @@
|
|||||||
package base.util;
|
package base.util;
|
||||||
|
|
||||||
public class BufferedArrayCycle<E extends Bufferable> extends ArrayCycle<E> {
|
public class BufferedArrayCycle<E extends Bufferable> extends ArrayCycle<E> {
|
||||||
protected static final long serialVersionUID = 1L;
|
protected static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
protected ArrayCycle<? extends Bufferable> buffer;
|
protected ArrayCycle<? extends Bufferable> buffer;
|
||||||
protected int before;
|
protected int before;
|
||||||
protected int after;
|
protected int after;
|
||||||
protected int indexFirst;
|
protected int indexFirst;
|
||||||
protected int indexLast;
|
protected int indexLast;
|
||||||
//protected int indexBuffer;
|
//protected int indexBuffer;
|
||||||
//protected Bufferable[] bufferableArray;
|
//protected Bufferable[] bufferableArray;
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public BufferedArrayCycle(int before, int after) {
|
public BufferedArrayCycle(int before, int after) {
|
||||||
this.before = before;
|
this.before = before;
|
||||||
this.after = after;
|
this.after = after;
|
||||||
indexFirst = 0;
|
indexFirst = 0;
|
||||||
indexLast = 0;
|
indexLast = 0;
|
||||||
//bufferableArray = new Bufferable[before + after + 1];
|
//bufferableArray = new Bufferable[before + after + 1];
|
||||||
//buffer = new ArrayCycle<Bufferable>();
|
//buffer = new ArrayCycle<Bufferable>();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public E previous() {
|
public E previous() {
|
||||||
get(indexFirst).unload();
|
get(indexFirst).unload();
|
||||||
indexFirst = previous(indexFirst);
|
indexFirst = previous(indexFirst);
|
||||||
indexLast = previous(indexLast);
|
indexLast = previous(indexLast);
|
||||||
get(indexLast).load();
|
get(indexLast).load();
|
||||||
// eerste before weg
|
// eerste before weg
|
||||||
|
|
||||||
// eerste after wordt huidig
|
// eerste after wordt huidig
|
||||||
|
|
||||||
// voeg laatste after toe
|
// voeg laatste after toe
|
||||||
|
|
||||||
return current();
|
return current();
|
||||||
}
|
}
|
||||||
@@ -40,35 +40,35 @@ public class BufferedArrayCycle<E extends Bufferable> extends ArrayCycle<E> {
|
|||||||
|
|
||||||
// eerste before weg
|
// eerste before weg
|
||||||
|
|
||||||
// eerste after wordt huidig
|
// eerste after wordt huidig
|
||||||
|
|
||||||
// voeg laatste after toe
|
// voeg laatste after toe
|
||||||
|
|
||||||
return size() == 0 ? null : get(index);
|
return size() == 0 ? null : get(index);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected int previous(int index) {
|
protected int previous(int index) {
|
||||||
if (--index < 0) {
|
if (--index < 0) {
|
||||||
index = Math.max(0, size() - 1);
|
index = Math.max(0, size() - 1);
|
||||||
}
|
}
|
||||||
return index;
|
return index;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected int next(int index) {
|
protected int next(int index) {
|
||||||
System.out.println(index);
|
System.out.println(index);
|
||||||
if (++index >= size()) {
|
if (++index >= size()) {
|
||||||
index = 0;
|
index = 0;
|
||||||
|
|
||||||
}
|
}
|
||||||
return index;
|
return index;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
BufferedArrayCycle<Dummy> bac = new BufferedArrayCycle<Dummy>(2, 3);
|
BufferedArrayCycle<Dummy> bac = new BufferedArrayCycle<Dummy>(2, 3);
|
||||||
for (int i = 1; i <= 10; ++i) {
|
for (int i = 1; i <= 10; ++i) {
|
||||||
bac.add(new Dummy(i));
|
bac.add(new Dummy(i));
|
||||||
}
|
}
|
||||||
bac.remove(0);
|
bac.remove(0);
|
||||||
System.out.println(bac.get(2).id);
|
System.out.println(bac.get(2).id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,18 +1,18 @@
|
|||||||
package base.util;
|
package base.util;
|
||||||
|
|
||||||
public class Dummy implements Bufferable {
|
public class Dummy implements Bufferable {
|
||||||
public int id;
|
public int id;
|
||||||
|
|
||||||
public Dummy(int id) {
|
public Dummy(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void load() {
|
public void load() {
|
||||||
System.out.println("Dummy #" + id + ": load()");
|
System.out.println("Dummy #" + id + ": load()");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void unload() {
|
public void unload() {
|
||||||
System.out.println("Dummy #" + id + ": load()");
|
System.out.println("Dummy #" + id + ": load()");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,95 +15,94 @@ import base.worker.pool.ListenerPool;
|
|||||||
import base.worker.pool.PooledListener;
|
import base.worker.pool.PooledListener;
|
||||||
|
|
||||||
public abstract class Listen<E> extends Work implements Listener<E> {
|
public abstract class Listen<E> extends Work implements Listener<E> {
|
||||||
protected static final Worker.Type WORKER_TYPE = Worker.Type.DIRECT;
|
protected static final Worker.Type WORKER_TYPE = Worker.Type.DIRECT;
|
||||||
|
|
||||||
protected Listener<E> listener;
|
protected Listener<E> listener;
|
||||||
protected Worker.Type workerType;
|
protected Worker.Type workerType;
|
||||||
public Queue<E> queue;
|
public Queue<E> queue;
|
||||||
|
|
||||||
public Listen() {
|
public Listen() {
|
||||||
this(WORKER_TYPE);
|
this(WORKER_TYPE);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Listen(Worker.Type workerType) {
|
protected Listen(Worker.Type workerType) {
|
||||||
this.workerType = workerType;
|
this.workerType = workerType;
|
||||||
switch (workerType) {
|
switch (workerType) {
|
||||||
case DIRECT:
|
case DIRECT:
|
||||||
return;
|
return;
|
||||||
case FOREGROUND:
|
case FOREGROUND:
|
||||||
listener = new ForegroundListener<E>(this);
|
listener = new ForegroundListener<E>(this);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
listener = new BackgroundListener<E>(this);
|
listener = new BackgroundListener<E>(this);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
queue = new ConcurrentLinkedQueue<E>();
|
queue = new ConcurrentLinkedQueue<E>();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Listen(Worker worker) {
|
protected Listen(Worker worker) {
|
||||||
this.worker = worker;
|
this.worker = worker;
|
||||||
queue = new ConcurrentLinkedQueue<E>();
|
queue = new ConcurrentLinkedQueue<E>();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Listen(ListenerPool<E> listenerPool) {
|
protected Listen(ListenerPool<E> listenerPool) {
|
||||||
listener = new PooledListener<E>(this);
|
listener = new PooledListener<E>(this);
|
||||||
listenerPool.add((PooledListener<E>) listener);
|
listenerPool.add((PooledListener<E>) listener);
|
||||||
queue = new ConcurrentLinkedQueue<E>();
|
queue = new ConcurrentLinkedQueue<E>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void add(E element) {
|
public synchronized void add(E element) {
|
||||||
if (workerType.equals(Worker.Type.DIRECT)) {
|
if (workerType.equals(Worker.Type.DIRECT)) {
|
||||||
input(element);
|
input(element);
|
||||||
} else {
|
} else {
|
||||||
listener.add(element);
|
listener.add(element);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() {
|
public void start() {
|
||||||
if (workerType.equals(Worker.Type.DIRECT)) {
|
if (workerType.equals(Worker.Type.DIRECT)) {
|
||||||
try {
|
try {
|
||||||
activate();
|
activate();
|
||||||
} catch (ActivateException e) {
|
} catch (ActivateException e) {
|
||||||
logger.error("Failed to start directly", e);
|
logger.error("Failed to start directly", e);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
super.start();
|
super.start();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
super.stop();
|
super.stop();
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void work() {
|
public void work() {
|
||||||
while (!queue.isEmpty()) {
|
while (!queue.isEmpty()) {
|
||||||
logger.debug("Listen: work() > input");
|
logger.debug("Listen: work() > input");
|
||||||
input(queue.poll());
|
input(queue.poll());
|
||||||
}
|
}
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
logger.debug("Listen: work() > wait");
|
logger.debug("Listen: work() > wait");
|
||||||
try {
|
try {
|
||||||
wait();
|
wait();
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
logger.debug("Listen: work() > notified");
|
logger.debug("Listen: work() > notified");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(Object object) {
|
public void input(Object object) {
|
||||||
// This lookup should be cached
|
MethodType methodType = MethodType.methodType(void.class, object.getClass());
|
||||||
MethodType methodType = MethodType.methodType(void.class, object.getClass());
|
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
MethodHandle methodHandle;
|
||||||
MethodHandle methodHandle;
|
try {
|
||||||
try {
|
methodHandle = lookup.findVirtual(getClass(), "input", methodType);
|
||||||
methodHandle = lookup.findVirtual(getClass(), "input", methodType);
|
methodHandle.invoke(this, object);
|
||||||
methodHandle.invoke(this, object);
|
} catch (Exception e) {
|
||||||
} catch (Exception e) {
|
logger.error("", e);
|
||||||
logger.error("", e);
|
} catch (Throwable e) {
|
||||||
} catch (Throwable e) {
|
logger.error("", e);
|
||||||
logger.error("", e);
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,61 +13,61 @@ import base.worker.pool.PooledWorker;
|
|||||||
import base.worker.pool.WorkerPool;
|
import base.worker.pool.WorkerPool;
|
||||||
|
|
||||||
public abstract class Work implements Control {
|
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 Logger logger = LoggerFactory.getLogger(getClass());
|
||||||
|
|
||||||
protected Worker worker;
|
protected Worker worker;
|
||||||
|
|
||||||
protected Work() {
|
protected Work() {
|
||||||
this(WORKER_TYPE);
|
this(WORKER_TYPE);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Work(Worker.Type workerType) {
|
protected Work(Worker.Type workerType) {
|
||||||
switch (workerType) {
|
switch (workerType) {
|
||||||
case FOREGROUND:
|
case FOREGROUND:
|
||||||
worker = new DirectWorker(this);
|
worker = new DirectWorker(this);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
worker = new ThreadWorker(this);
|
worker = new ThreadWorker(this);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Work(Worker worker) {
|
protected Work(Worker worker) {
|
||||||
this.worker = worker;
|
this.worker = worker;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Work(WorkerPool workerPool) {
|
protected Work(WorkerPool workerPool) {
|
||||||
worker = new PooledWorker(this);
|
worker = new PooledWorker(this);
|
||||||
workerPool.add((PooledWorker) worker);
|
workerPool.add((PooledWorker) worker);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void sleep(int time) {
|
protected void sleep(int time) {
|
||||||
worker.sleep(time);
|
worker.sleep(time);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() {
|
public void start() {
|
||||||
logger.debug("Work: start()");
|
logger.debug("Work: start()");
|
||||||
worker.start();
|
worker.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
logger.debug("Work: stop()");
|
logger.debug("Work: stop()");
|
||||||
worker.stop();
|
worker.stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean active() {
|
public boolean active() {
|
||||||
logger.debug("Work: active()");
|
logger.debug("Work: active()");
|
||||||
return worker.active();
|
return worker.active();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
logger.debug("Work: exit()");
|
logger.debug("Work: exit()");
|
||||||
worker.exit();
|
worker.exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {}
|
public void activate() throws ActivateException {}
|
||||||
public void deactivate() throws DeactivateException {}
|
public void deactivate() throws DeactivateException {}
|
||||||
public abstract void work();
|
public abstract void work();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,19 +4,19 @@ import base.work.Listen;
|
|||||||
import base.worker.pool.Listener;
|
import base.worker.pool.Listener;
|
||||||
|
|
||||||
public class BackgroundListener<E> extends ThreadWorker implements Listener<E> {
|
public class BackgroundListener<E> extends ThreadWorker implements Listener<E> {
|
||||||
protected Listen<E> listen;
|
protected Listen<E> listen;
|
||||||
|
|
||||||
public BackgroundListener(Listen<E> listen) {
|
public BackgroundListener(Listen<E> listen) {
|
||||||
super(listen);
|
super(listen);
|
||||||
this.listen = listen;
|
this.listen = listen;
|
||||||
}
|
}
|
||||||
|
|
||||||
public BackgroundListener(Listen<E> listen, boolean start) {
|
public BackgroundListener(Listen<E> listen, boolean start) {
|
||||||
super(listen);
|
super(listen);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void add(E element) {
|
public void add(E element) {
|
||||||
listen.queue.add(element);
|
listen.queue.add(element);
|
||||||
listen.notify();
|
listen.notify();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ package base.worker;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public class DirectIntervalWorker extends ThreadIntervalWorker {
|
public class DirectIntervalWorker extends ThreadIntervalWorker {
|
||||||
public DirectIntervalWorker(Work work, int interval) {
|
public DirectIntervalWorker(Work work, int interval) {
|
||||||
super(work, false);
|
super(work, false);
|
||||||
this.interval = interval;
|
this.interval = interval;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DirectIntervalWorker(IntervalWork intervalWork) {
|
public DirectIntervalWorker(IntervalWork intervalWork) {
|
||||||
super(intervalWork);
|
super(intervalWork);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package base.worker;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public class DirectWorker extends ThreadWorker {
|
public class DirectWorker extends ThreadWorker {
|
||||||
public DirectWorker(Work work) {
|
public DirectWorker(Work work) {
|
||||||
super(work, false);
|
super(work, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,7 @@ import base.work.Listen;
|
|||||||
import base.worker.pool.Listener;
|
import base.worker.pool.Listener;
|
||||||
|
|
||||||
public class ForegroundListener<E> extends BackgroundListener<E> implements Listener<E> {
|
public class ForegroundListener<E> extends BackgroundListener<E> implements Listener<E> {
|
||||||
public ForegroundListener(Listen<E> listen) {
|
public ForegroundListener(Listen<E> listen) {
|
||||||
super(listen, false);
|
super(listen, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,35 +3,35 @@ package base.worker;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public abstract class IntervalWork extends Work {
|
public abstract class IntervalWork extends Work {
|
||||||
protected IntervalWork() {
|
protected IntervalWork() {
|
||||||
this(WORKER_TYPE);
|
this(WORKER_TYPE);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected IntervalWork(int interval) {
|
protected IntervalWork(int interval) {
|
||||||
this(WORKER_TYPE, interval);
|
this(WORKER_TYPE, interval);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected IntervalWork(Worker.Type workerType) {
|
protected IntervalWork(Worker.Type workerType) {
|
||||||
switch (workerType) {
|
switch (workerType) {
|
||||||
case FOREGROUND:
|
case FOREGROUND:
|
||||||
worker = new DirectIntervalWorker(this);
|
worker = new DirectIntervalWorker(this);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
case BACKGROUND:
|
case BACKGROUND:
|
||||||
worker = new ThreadIntervalWorker(this);
|
worker = new ThreadIntervalWorker(this);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected IntervalWork(Worker.Type workerType, int interval) {
|
protected IntervalWork(Worker.Type workerType, int interval) {
|
||||||
switch (workerType) {
|
switch (workerType) {
|
||||||
case FOREGROUND:
|
case FOREGROUND:
|
||||||
worker = new DirectIntervalWorker(this, interval);
|
worker = new DirectIntervalWorker(this, interval);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
case BACKGROUND:
|
case BACKGROUND:
|
||||||
worker = new ThreadIntervalWorker(this, interval);
|
worker = new ThreadIntervalWorker(this, interval);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,41 +6,41 @@ import java.util.TimerTask;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public class ThreadIntervalWorker extends ThreadWorker {
|
public class ThreadIntervalWorker extends ThreadWorker {
|
||||||
protected static final int INTERVAL = 500;
|
protected static final int INTERVAL = 500;
|
||||||
protected int interval;
|
protected int interval;
|
||||||
|
|
||||||
public ThreadIntervalWorker(Work work) {
|
public ThreadIntervalWorker(Work work) {
|
||||||
super(work);
|
super(work);
|
||||||
interval = INTERVAL;
|
interval = INTERVAL;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ThreadIntervalWorker(Work work, boolean thread) {
|
public ThreadIntervalWorker(Work work, boolean thread) {
|
||||||
super(work, thread);
|
super(work, thread);
|
||||||
interval = INTERVAL;
|
interval = INTERVAL;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ThreadIntervalWorker(Work work, int interval) {
|
public ThreadIntervalWorker(Work work, int interval) {
|
||||||
super(work);
|
super(work);
|
||||||
this.interval = interval;
|
this.interval = interval;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Timer timer;
|
protected Timer timer;
|
||||||
|
|
||||||
public synchronized void start(boolean thread) {
|
public synchronized void start(boolean thread) {
|
||||||
if (!active) {
|
if (!active) {
|
||||||
activate = true;
|
activate = true;
|
||||||
timer = new Timer();
|
timer = new Timer();
|
||||||
timer.schedule(new TimerTask() {
|
timer.schedule(new TimerTask() {
|
||||||
public void run() {
|
public void run() {
|
||||||
Worker worker = ThreadIntervalWorker.this;
|
Worker worker = ThreadIntervalWorker.this;
|
||||||
worker.runActivate();
|
worker.runActivate();
|
||||||
worker.runDeactivate();
|
worker.runDeactivate();
|
||||||
worker.runWork();
|
worker.runWork();
|
||||||
}}, 0, interval);
|
}}, 0, interval);
|
||||||
active = true;
|
active = true;
|
||||||
}
|
}
|
||||||
if (!thread) {
|
if (!thread) {
|
||||||
try {
|
try {
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
wait();
|
wait();
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,7 @@ public class ThreadIntervalWorker extends ThreadWorker {
|
|||||||
|
|
||||||
public synchronized void stop() {
|
public synchronized void stop() {
|
||||||
if (active) {
|
if (active) {
|
||||||
timer.cancel();
|
timer.cancel();
|
||||||
deactivate = true;
|
deactivate = true;
|
||||||
run();
|
run();
|
||||||
notifyAll();
|
notifyAll();
|
||||||
|
|||||||
@@ -8,15 +8,15 @@ public class ThreadWorker extends Worker implements Runnable {
|
|||||||
protected boolean thread = true;
|
protected boolean thread = true;
|
||||||
|
|
||||||
public ThreadWorker(Work work, boolean thread) {
|
public ThreadWorker(Work work, boolean thread) {
|
||||||
this(work);
|
this(work);
|
||||||
this.thread = thread;
|
this.thread = thread;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ThreadWorker(Work work) {
|
public ThreadWorker(Work work) {
|
||||||
super(work);
|
super(work);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void start(boolean thread) {
|
public synchronized void start(boolean thread) {
|
||||||
if (!active) {
|
if (!active) {
|
||||||
activate = true;
|
activate = true;
|
||||||
}
|
}
|
||||||
@@ -30,11 +30,11 @@ public class ThreadWorker extends Worker implements Runnable {
|
|||||||
run();
|
run();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void start() {
|
public synchronized void start() {
|
||||||
start(thread);
|
start(thread);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ import base.exception.worker.DeactivateException;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public abstract class Worker {
|
public abstract class Worker {
|
||||||
public enum Type {
|
public enum Type {
|
||||||
DIRECT, FOREGROUND, BACKGROUND, POOLED
|
DIRECT, FOREGROUND, BACKGROUND, POOLED
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final int SLEEP = 100;
|
public static final int SLEEP = 100;
|
||||||
|
|
||||||
@@ -23,30 +23,30 @@ public abstract class Worker {
|
|||||||
|
|
||||||
protected Work work;
|
protected Work work;
|
||||||
|
|
||||||
public Worker(Work work) {
|
public Worker(Work work) {
|
||||||
this.work = work;
|
this.work = work;
|
||||||
logger = LoggerFactory.getLogger(work.getClass());
|
logger = LoggerFactory.getLogger(work.getClass());
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean active() {
|
public boolean active() {
|
||||||
logger.debug("Worker: active()");
|
logger.debug("Worker: active()");
|
||||||
return deactivate || active;
|
return deactivate || active;
|
||||||
}
|
}
|
||||||
|
|
||||||
public final void run() {
|
public final void run() {
|
||||||
logger.debug("Worker: run()");
|
logger.debug("Worker: run()");
|
||||||
while (run || deactivate) {
|
while (run || deactivate) {
|
||||||
runActivate();
|
runActivate();
|
||||||
runDeactivate();
|
runDeactivate();
|
||||||
runWork();
|
runWork();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void runActivate() {
|
public void runActivate() {
|
||||||
if (activate && !active) {
|
if (activate && !active) {
|
||||||
logger.debug("Worker: runActivate()");
|
logger.debug("Worker: runActivate()");
|
||||||
try {
|
try {
|
||||||
work.activate();
|
work.activate();
|
||||||
active = true;
|
active = true;
|
||||||
} catch (ActivateException e) {
|
} catch (ActivateException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
@@ -57,8 +57,8 @@ public abstract class Worker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void runDeactivate() {
|
public void runDeactivate() {
|
||||||
if (deactivate && active) {
|
if (deactivate && active) {
|
||||||
logger.debug("Worker: runDeactivate()");
|
logger.debug("Worker: runDeactivate()");
|
||||||
try {
|
try {
|
||||||
work.deactivate();
|
work.deactivate();
|
||||||
} catch (DeactivateException e) {
|
} catch (DeactivateException e) {
|
||||||
@@ -72,11 +72,11 @@ public abstract class Worker {
|
|||||||
|
|
||||||
public void runWork() {
|
public void runWork() {
|
||||||
if (active) {
|
if (active) {
|
||||||
logger.debug("Worker: runWork() > work");
|
logger.debug("Worker: runWork() > work");
|
||||||
work.work();
|
work.work();
|
||||||
} else if (run) {
|
} else if (run) {
|
||||||
try {
|
try {
|
||||||
logger.debug("Worker: runWork() > wait");
|
logger.debug("Worker: runWork() > wait");
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
wait();
|
wait();
|
||||||
}
|
}
|
||||||
@@ -100,15 +100,15 @@ public abstract class Worker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public abstract void start();
|
public abstract void start();
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
logger.debug("Worker: stop()");
|
logger.debug("Worker: stop()");
|
||||||
if (active && !activate) {
|
if (active && !activate) {
|
||||||
deactivate = true;
|
deactivate = true;
|
||||||
}
|
}
|
||||||
activate = false;
|
activate = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
abstract public void exit();
|
abstract public void exit();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
package base.worker.pool;
|
package base.worker.pool;
|
||||||
|
|
||||||
public interface Listener<E> {
|
public interface Listener<E> {
|
||||||
public void add(E element);
|
public void add(E element);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,32 +7,32 @@ import java.util.concurrent.LinkedBlockingQueue;
|
|||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class ListenerPool<E> {
|
public class ListenerPool<E> {
|
||||||
protected int poolSize;
|
protected int poolSize;
|
||||||
protected BlockingQueue<Wrapper<E>> queue;
|
protected BlockingQueue<Wrapper<E>> queue;
|
||||||
protected ExecutorService executorService;
|
protected ExecutorService executorService;
|
||||||
|
|
||||||
public ListenerPool(int poolSize) {
|
public ListenerPool(int poolSize) {
|
||||||
this.poolSize = poolSize;
|
this.poolSize = poolSize;
|
||||||
queue = new LinkedBlockingQueue<Wrapper<E>>();
|
queue = new LinkedBlockingQueue<Wrapper<E>>();
|
||||||
executorService = Executors.newFixedThreadPool(poolSize);
|
executorService = Executors.newFixedThreadPool(poolSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
public PooledListener<E> add(PooledListener<E> listener) {
|
public PooledListener<E> add(PooledListener<E> listener) {
|
||||||
listener.setPoolQueue(queue);
|
listener.setPoolQueue(queue);
|
||||||
return listener;
|
return listener;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() {
|
public void start() {
|
||||||
for (int i = 0; i < poolSize; ++i) {
|
for (int i = 0; i < poolSize; ++i) {
|
||||||
Runnable runnable = new ListenerPoolRunnable<E>(queue, i);
|
Runnable runnable = new ListenerPoolRunnable<E>(queue, i);
|
||||||
executorService.execute(runnable);
|
executorService.execute(runnable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void await() {
|
public void await() {
|
||||||
try {
|
try {
|
||||||
executorService.awaitTermination(0, TimeUnit.SECONDS);
|
executorService.awaitTermination(0, TimeUnit.SECONDS);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,22 +3,22 @@ package base.worker.pool;
|
|||||||
import java.util.concurrent.BlockingQueue;
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
|
||||||
class ListenerPoolRunnable<E> implements Runnable {
|
class ListenerPoolRunnable<E> implements Runnable {
|
||||||
protected BlockingQueue<Wrapper<E>> queue;
|
protected BlockingQueue<Wrapper<E>> queue;
|
||||||
protected int id;
|
protected int id;
|
||||||
|
|
||||||
public ListenerPoolRunnable(BlockingQueue<Wrapper<E>> queue, int id) {
|
public ListenerPoolRunnable(BlockingQueue<Wrapper<E>> queue, int id) {
|
||||||
this.queue = queue;
|
this.queue = queue;
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
try {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
System.out.println("Thread #" + id + " waiting...");
|
System.out.println("Thread #" + id + " waiting...");
|
||||||
Wrapper<E> wrapper = queue.take();
|
Wrapper<E> wrapper = queue.take();
|
||||||
wrapper.deliver();
|
wrapper.deliver();
|
||||||
Thread.sleep((int) (Math.random() * 1000));
|
Thread.sleep((int) (Math.random() * 1000));
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,24 +5,24 @@ import java.util.concurrent.BlockingQueue;
|
|||||||
import base.work.Listen;
|
import base.work.Listen;
|
||||||
|
|
||||||
public class PooledListener<E> extends PooledWorker implements Listener<E> {
|
public class PooledListener<E> extends PooledWorker implements Listener<E> {
|
||||||
protected BlockingQueue<Wrapper<E>> poolQueue;
|
protected BlockingQueue<Wrapper<E>> poolQueue;
|
||||||
protected Listen<E> listen;
|
protected Listen<E> listen;
|
||||||
|
|
||||||
public PooledListener(Listen<E> listen) {
|
public PooledListener(Listen<E> listen) {
|
||||||
super(listen);
|
super(listen);
|
||||||
this.listen = listen;
|
this.listen = listen;
|
||||||
}
|
|
||||||
|
|
||||||
public void setPoolQueue(BlockingQueue<Wrapper<E>> poolQueue) {
|
|
||||||
this.poolQueue = poolQueue;
|
|
||||||
}
|
|
||||||
|
|
||||||
public synchronized void add(E element) {
|
|
||||||
Wrapper<E> wrapper = new Wrapper<E>(this, element);
|
|
||||||
poolQueue.add(wrapper);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void input(E element) {
|
public void setPoolQueue(BlockingQueue<Wrapper<E>> poolQueue) {
|
||||||
listen.input(element);
|
this.poolQueue = poolQueue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public synchronized void add(E element) {
|
||||||
|
Wrapper<E> wrapper = new Wrapper<E>(this, element);
|
||||||
|
poolQueue.add(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
void input(E element) {
|
||||||
|
listen.input(element);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -6,44 +6,44 @@ import base.work.Work;
|
|||||||
import base.worker.Worker;
|
import base.worker.Worker;
|
||||||
|
|
||||||
public class PooledWorker extends Worker {
|
public class PooledWorker extends Worker {
|
||||||
protected BlockingQueue<Worker> activateQueue;
|
protected BlockingQueue<Worker> activateQueue;
|
||||||
protected BlockingQueue<Worker> deactivateQueue;
|
protected BlockingQueue<Worker> deactivateQueue;
|
||||||
|
|
||||||
public PooledWorker(Work work) {
|
public PooledWorker(Work work) {
|
||||||
super(work);
|
super(work);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setActivateQueue(BlockingQueue<Worker> activateQueue) {
|
public void setActivateQueue(BlockingQueue<Worker> activateQueue) {
|
||||||
this.activateQueue = activateQueue;
|
this.activateQueue = activateQueue;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDeactivateQueue(BlockingQueue<Worker> deactivateQueue) {
|
public void setDeactivateQueue(BlockingQueue<Worker> deactivateQueue) {
|
||||||
this.deactivateQueue = deactivateQueue;
|
this.deactivateQueue = deactivateQueue;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() {
|
public void start() {
|
||||||
if (!active) {
|
if (!active) {
|
||||||
activate = true;
|
activate = true;
|
||||||
}
|
}
|
||||||
if (!run) {
|
if (!run) {
|
||||||
run = true;
|
run = true;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
deactivateQueue.remove(this);
|
deactivateQueue.remove(this);
|
||||||
activateQueue.put(this);
|
activateQueue.put(this);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
System.out.println("stop!! " + active);
|
System.out.println("stop!! " + active);
|
||||||
if (active) {
|
if (active) {
|
||||||
deactivate = true;
|
deactivate = true;
|
||||||
}
|
}
|
||||||
activateQueue.remove(this);
|
activateQueue.remove(this);
|
||||||
deactivateQueue.add(this);
|
deactivateQueue.add(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,34 +9,34 @@ import base.util.ArrayCycle;
|
|||||||
import base.worker.Worker;
|
import base.worker.Worker;
|
||||||
|
|
||||||
public class WorkerPool {
|
public class WorkerPool {
|
||||||
protected int poolSize;
|
protected int poolSize;
|
||||||
protected BlockingQueue<Worker> activateQueue;
|
protected BlockingQueue<Worker> activateQueue;
|
||||||
protected BlockingQueue<Worker> deactivateQueue;
|
protected BlockingQueue<Worker> deactivateQueue;
|
||||||
protected ArrayCycle<Worker> workerCycle;
|
protected ArrayCycle<Worker> workerCycle;
|
||||||
protected ExecutorService executorService;
|
protected ExecutorService executorService;
|
||||||
|
|
||||||
public WorkerPool(int poolSize) {
|
public WorkerPool(int poolSize) {
|
||||||
this.poolSize = poolSize;
|
this.poolSize = poolSize;
|
||||||
activateQueue = new LinkedBlockingQueue<Worker>();
|
activateQueue = new LinkedBlockingQueue<Worker>();
|
||||||
deactivateQueue = new LinkedBlockingQueue<Worker>();
|
deactivateQueue = new LinkedBlockingQueue<Worker>();
|
||||||
workerCycle = new ArrayCycle<Worker>();
|
workerCycle = new ArrayCycle<Worker>();
|
||||||
executorService = Executors.newFixedThreadPool(poolSize);
|
executorService = Executors.newFixedThreadPool(poolSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void start() {
|
public void start() {
|
||||||
for (int i = 0; i < poolSize; ++i) {
|
for (int i = 0; i < poolSize; ++i) {
|
||||||
Runnable runnable = new WorkerPoolRunnable(activateQueue, deactivateQueue, workerCycle, i + 1);
|
Runnable runnable = new WorkerPoolRunnable(activateQueue, deactivateQueue, workerCycle, i + 1);
|
||||||
executorService.execute(runnable);
|
executorService.execute(runnable);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void stop() {
|
public void stop() {
|
||||||
// Must be graceful
|
// Must be graceful
|
||||||
executorService.shutdownNow();
|
executorService.shutdownNow();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void add(PooledWorker worker) {
|
public void add(PooledWorker worker) {
|
||||||
worker.setActivateQueue(activateQueue);
|
worker.setActivateQueue(activateQueue);
|
||||||
worker.setDeactivateQueue(deactivateQueue);
|
worker.setDeactivateQueue(deactivateQueue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,36 +6,36 @@ import base.util.ArrayCycle;
|
|||||||
import base.worker.Worker;
|
import base.worker.Worker;
|
||||||
|
|
||||||
public class WorkerPoolRunnable implements Runnable {
|
public class WorkerPoolRunnable implements Runnable {
|
||||||
protected BlockingQueue<Worker> activateQueue;
|
protected BlockingQueue<Worker> activateQueue;
|
||||||
protected BlockingQueue<Worker> deactivateQueue;
|
protected BlockingQueue<Worker> deactivateQueue;
|
||||||
protected ArrayCycle<Worker> workerCycle;
|
protected ArrayCycle<Worker> workerCycle;
|
||||||
protected int id;
|
protected int id;
|
||||||
|
|
||||||
public WorkerPoolRunnable(BlockingQueue<Worker> activateQueue, BlockingQueue<Worker> deactivateQueue, ArrayCycle<Worker> workerCycle, int id) {
|
public WorkerPoolRunnable(BlockingQueue<Worker> activateQueue, BlockingQueue<Worker> deactivateQueue, ArrayCycle<Worker> workerCycle, int id) {
|
||||||
this.activateQueue = activateQueue;
|
this.activateQueue = activateQueue;
|
||||||
this.deactivateQueue = deactivateQueue;
|
this.deactivateQueue = deactivateQueue;
|
||||||
this.workerCycle = workerCycle;
|
this.workerCycle = workerCycle;
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void run() {
|
public void run() {
|
||||||
while (true) {
|
while (true) {
|
||||||
if (!deactivateQueue.isEmpty()) {
|
if (!deactivateQueue.isEmpty()) {
|
||||||
try {
|
try {
|
||||||
Worker worker = deactivateQueue.take();
|
Worker worker = deactivateQueue.take();
|
||||||
worker.runDeactivate();
|
worker.runDeactivate();
|
||||||
workerCycle.remove(worker);
|
workerCycle.remove(worker);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
} else if (!activateQueue.isEmpty() || workerCycle.isEmpty()) {
|
} else if (!activateQueue.isEmpty() || workerCycle.isEmpty()) {
|
||||||
try {
|
try {
|
||||||
Worker worker = activateQueue.take();
|
Worker worker = activateQueue.take();
|
||||||
worker.runActivate();
|
worker.runActivate();
|
||||||
workerCycle.add(worker);
|
workerCycle.add(worker);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
} else {
|
} else {
|
||||||
Worker worker = workerCycle.next();
|
Worker worker = workerCycle.next();
|
||||||
worker.runWork();
|
worker.runWork();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,15 +2,15 @@ package base.worker.pool;
|
|||||||
|
|
||||||
|
|
||||||
class Wrapper<E> {
|
class Wrapper<E> {
|
||||||
protected PooledListener<E> listener;
|
protected PooledListener<E> listener;
|
||||||
protected E element;
|
protected E element;
|
||||||
|
|
||||||
public Wrapper(PooledListener<E> listener, E element) {
|
public Wrapper(PooledListener<E> listener, E element) {
|
||||||
this.listener = listener;
|
this.listener = listener;
|
||||||
this.element = element;
|
this.element = element;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deliver() {
|
public void deliver() {
|
||||||
listener.input(element);
|
listener.input(element);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,10 +6,10 @@ import org.junit.runners.Suite.SuiteClasses;
|
|||||||
|
|
||||||
@RunWith(Suite.class)
|
@RunWith(Suite.class)
|
||||||
@SuiteClasses({
|
@SuiteClasses({
|
||||||
TestTcpSocketCommunication.class,
|
TestTcpSocketCommunication.class,
|
||||||
TestTcpChannelCommunication.class,
|
TestTcpChannelCommunication.class,
|
||||||
TestUdpUnicastCommunication.class,
|
TestUdpUnicastCommunication.class,
|
||||||
TestUdpMulticastCommunication.class
|
TestUdpMulticastCommunication.class
|
||||||
})
|
})
|
||||||
|
|
||||||
public class AllTests {}
|
public class AllTests {}
|
||||||
|
|||||||
@@ -12,83 +12,83 @@ import base.server.channel.TcpServer;
|
|||||||
import base.server.channel.TcpServerClient;
|
import base.server.channel.TcpServerClient;
|
||||||
|
|
||||||
public class TestTcpChannelCommunication {
|
public class TestTcpChannelCommunication {
|
||||||
protected TestTcpServer server;
|
protected TestTcpServer server;
|
||||||
protected TestTcpClient client;
|
protected TestTcpClient client;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
server = new TestTcpServer(1234);
|
server = new TestTcpServer(1234);
|
||||||
server.start();
|
server.start();
|
||||||
client = new TestTcpClient(1234);
|
client = new TestTcpClient(1234);
|
||||||
client.start();
|
client.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public void tearDown() throws Exception {
|
public void tearDown() throws Exception {
|
||||||
client.exit();
|
client.exit();
|
||||||
server.exit();
|
server.exit();
|
||||||
|
|
||||||
// Should add blocking stop and exit to worker
|
// Should add blocking stop and exit to worker
|
||||||
while (client.active() || server.active()) {
|
while (client.active() || server.active()) {
|
||||||
Thread.sleep(100);
|
Thread.sleep(100);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testSendClientToServer() throws Exception {
|
public void testSendClientToServer() throws Exception {
|
||||||
String message = "test";
|
String message = "test";
|
||||||
client.send(message.getBytes());
|
client.send(message.getBytes());
|
||||||
synchronized (server) {
|
synchronized (server) {
|
||||||
server.wait(2000);
|
server.wait(2000);
|
||||||
}
|
}
|
||||||
byte[] buffer = server.buffer;
|
byte[] buffer = server.buffer;
|
||||||
assertNotNull("Received input", buffer);
|
assertNotNull("Received input", buffer);
|
||||||
assertEquals("Message intact", message, new String(buffer).trim());
|
assertEquals("Message intact", message, new String(buffer).trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testSendServerToClient() throws Exception {
|
public void testSendServerToClient() throws Exception {
|
||||||
// If client can send, connection has been established
|
// If client can send, connection has been established
|
||||||
client.send("init".getBytes());
|
client.send("init".getBytes());
|
||||||
|
|
||||||
String message = "test";
|
String message = "test";
|
||||||
server.send(message.getBytes());
|
server.send(message.getBytes());
|
||||||
synchronized (client) {
|
synchronized (client) {
|
||||||
client.wait(2000);
|
client.wait(2000);
|
||||||
}
|
}
|
||||||
byte[] buffer = client.buffer;
|
byte[] buffer = client.buffer;
|
||||||
assertNotNull("Received input", buffer);
|
assertNotNull("Received input", buffer);
|
||||||
assertEquals("Message intact", message, new String(buffer).trim());
|
assertEquals("Message intact", message, new String(buffer).trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestTcpServer extends TcpServer {
|
class TestTcpServer extends TcpServer {
|
||||||
public byte[] buffer;
|
public byte[] buffer;
|
||||||
|
|
||||||
public TestTcpServer(int port) {
|
public TestTcpServer(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(TcpServerClient client, byte[] buffer) {
|
public void input(TcpServerClient client, byte[] buffer) {
|
||||||
this.buffer = buffer;
|
this.buffer = buffer;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestTcpClient extends TcpClient {
|
class TestTcpClient extends TcpClient {
|
||||||
public byte[] buffer;
|
public byte[] buffer;
|
||||||
|
|
||||||
public TestTcpClient(int port) {
|
public TestTcpClient(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void input(byte[] buffer) {
|
protected void input(byte[] buffer) {
|
||||||
this.buffer = buffer;
|
this.buffer = buffer;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,82 +12,82 @@ import base.server.socket.TcpServer;
|
|||||||
import base.server.socket.TcpServerClient;
|
import base.server.socket.TcpServerClient;
|
||||||
|
|
||||||
public class TestTcpSocketCommunication {
|
public class TestTcpSocketCommunication {
|
||||||
protected TestTcpServer server;
|
protected TestTcpServer server;
|
||||||
protected TestTcpClient client;
|
protected TestTcpClient client;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
server = new TestTcpServer(1234);
|
server = new TestTcpServer(1234);
|
||||||
server.start();
|
server.start();
|
||||||
client = new TestTcpClient(1234);
|
client = new TestTcpClient(1234);
|
||||||
client.start();
|
client.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public void tearDown() throws Exception {
|
public void tearDown() throws Exception {
|
||||||
client.exit();
|
client.exit();
|
||||||
server.exit();
|
server.exit();
|
||||||
|
|
||||||
// Should add blocking stop and exit to worker
|
// Should add blocking stop and exit to worker
|
||||||
while (client.active() || server.active()) {
|
while (client.active() || server.active()) {
|
||||||
Thread.sleep(100);
|
Thread.sleep(100);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testSendClientToServer() throws Exception {
|
public void testSendClientToServer() throws Exception {
|
||||||
String message = "test";
|
String message = "test";
|
||||||
client.send(message.getBytes());
|
client.send(message.getBytes());
|
||||||
synchronized (server) {
|
synchronized (server) {
|
||||||
server.wait(2000);
|
server.wait(2000);
|
||||||
}
|
}
|
||||||
byte[] buffer = server.buffer;
|
byte[] buffer = server.buffer;
|
||||||
assertNotNull("Received input", buffer);
|
assertNotNull("Received input", buffer);
|
||||||
assertEquals("Message intact", message, new String(buffer).trim());
|
assertEquals("Message intact", message, new String(buffer).trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testSendServerToClient() throws Exception {
|
public void testSendServerToClient() throws Exception {
|
||||||
// If client can send, connection has been established
|
// If client can send, connection has been established
|
||||||
client.send("init".getBytes());
|
client.send("init".getBytes());
|
||||||
|
|
||||||
String message = "test";
|
String message = "test";
|
||||||
server.send(message.getBytes());
|
server.send(message.getBytes());
|
||||||
synchronized (client) {
|
synchronized (client) {
|
||||||
client.wait(2000);
|
client.wait(2000);
|
||||||
}
|
}
|
||||||
byte[] buffer = client.buffer;
|
byte[] buffer = client.buffer;
|
||||||
assertNotNull("Received input", buffer);
|
assertNotNull("Received input", buffer);
|
||||||
assertEquals("Message intact", message, new String(buffer).trim());
|
assertEquals("Message intact", message, new String(buffer).trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestTcpServer extends TcpServer {
|
class TestTcpServer extends TcpServer {
|
||||||
public byte[] buffer;
|
public byte[] buffer;
|
||||||
|
|
||||||
public TestTcpServer(int port) {
|
public TestTcpServer(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(TcpServerClient client, byte[] buffer) {
|
public void input(TcpServerClient client, byte[] buffer) {
|
||||||
this.buffer = buffer;
|
this.buffer = buffer;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestTcpClient extends TcpClient {
|
class TestTcpClient extends TcpClient {
|
||||||
public byte[] buffer;
|
public byte[] buffer;
|
||||||
|
|
||||||
public TestTcpClient(int port) {
|
public TestTcpClient(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void input(byte[] buffer) {
|
protected void input(byte[] buffer) {
|
||||||
this.buffer = buffer;
|
this.buffer = buffer;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,53 +11,53 @@ import base.server.datagram.UdpMulticastClient;
|
|||||||
import base.server.datagram.UdpMulticastServer;
|
import base.server.datagram.UdpMulticastServer;
|
||||||
|
|
||||||
public class TestUdpMulticastCommunication {
|
public class TestUdpMulticastCommunication {
|
||||||
protected UdpMulticastServer server;
|
protected UdpMulticastServer server;
|
||||||
protected TestUdpMulticastClient client;
|
protected TestUdpMulticastClient client;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
server = new UdpMulticastServer(1234);
|
server = new UdpMulticastServer(1234);
|
||||||
server.start();
|
server.start();
|
||||||
client = new TestUdpMulticastClient(1234);
|
client = new TestUdpMulticastClient(1234);
|
||||||
client.start();
|
client.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public void tearDown() throws Exception {
|
public void tearDown() throws Exception {
|
||||||
client.exit();
|
client.exit();
|
||||||
server.exit();
|
server.exit();
|
||||||
|
|
||||||
// Should add blocking stop and exit to worker
|
// Should add blocking stop and exit to worker
|
||||||
while (client.active() || server.active()) {
|
while (client.active() || server.active()) {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testServerToClientCommunication() throws Exception {
|
public void testServerToClientCommunication() throws Exception {
|
||||||
String message = "test";
|
String message = "test";
|
||||||
server.send(message.getBytes());
|
server.send(message.getBytes());
|
||||||
System.err.println("send");
|
System.err.println("send");
|
||||||
synchronized (client) {
|
synchronized (client) {
|
||||||
client.wait(2000);
|
client.wait(2000);
|
||||||
}
|
}
|
||||||
byte[] buffer = client.buffer;
|
byte[] buffer = client.buffer;
|
||||||
assertNotNull("Received input", buffer);
|
assertNotNull("Received input", buffer);
|
||||||
assertEquals("Message intact", message, new String(buffer).trim());
|
assertEquals("Message intact", message, new String(buffer).trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestUdpMulticastClient extends UdpMulticastClient {
|
class TestUdpMulticastClient extends UdpMulticastClient {
|
||||||
public byte[] buffer;
|
public byte[] buffer;
|
||||||
|
|
||||||
public TestUdpMulticastClient(int port) {
|
public TestUdpMulticastClient(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void input(byte[] buffer) {
|
public void input(byte[] buffer) {
|
||||||
this.buffer = buffer;
|
this.buffer = buffer;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,51 +11,51 @@ import base.server.datagram.UdpSender;
|
|||||||
import base.server.datagram.UdpServer;
|
import base.server.datagram.UdpServer;
|
||||||
|
|
||||||
public class TestUdpUnicastCommunication {
|
public class TestUdpUnicastCommunication {
|
||||||
protected TestUdpServer server;
|
protected TestUdpServer server;
|
||||||
protected UdpSender sender;
|
protected UdpSender sender;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() throws Exception {
|
public void setUp() throws Exception {
|
||||||
server = new TestUdpServer(1234);
|
server = new TestUdpServer(1234);
|
||||||
server.start();
|
server.start();
|
||||||
sender = new UdpSender(1234);
|
sender = new UdpSender(1234);
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
public void tearDown() throws Exception {
|
public void tearDown() throws Exception {
|
||||||
server.exit();
|
server.exit();
|
||||||
|
|
||||||
// Should add blocking stop and exit to worker
|
// Should add blocking stop and exit to worker
|
||||||
while (server.active()) {
|
while (server.active()) {
|
||||||
Thread.sleep(100);
|
Thread.sleep(100);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testSendClientToServer() throws Exception {
|
public void testSendClientToServer() throws Exception {
|
||||||
String message = "test";
|
String message = "test";
|
||||||
sender.send(message.getBytes());
|
sender.send(message.getBytes());
|
||||||
synchronized (server) {
|
synchronized (server) {
|
||||||
server.wait(2000);
|
server.wait(2000);
|
||||||
}
|
}
|
||||||
byte[] buffer = server.buffer;
|
byte[] buffer = server.buffer;
|
||||||
assertNotNull("Received input", buffer);
|
assertNotNull("Received input", buffer);
|
||||||
assertEquals("Message intact", message, new String(buffer).trim());
|
assertEquals("Message intact", message, new String(buffer).trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestUdpServer extends UdpServer {
|
class TestUdpServer extends UdpServer {
|
||||||
public byte[] buffer;
|
public byte[] buffer;
|
||||||
|
|
||||||
public TestUdpServer(int port) {
|
public TestUdpServer(int port) {
|
||||||
super(port);
|
super(port);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void input(byte[] buffer) {
|
protected void input(byte[] buffer) {
|
||||||
this.buffer = buffer;
|
this.buffer = buffer;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,50 +5,50 @@ import java.lang.invoke.MethodHandles;
|
|||||||
import java.lang.invoke.MethodType;
|
import java.lang.invoke.MethodType;
|
||||||
|
|
||||||
public class Test {
|
public class Test {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
try {
|
try {
|
||||||
new Test().start();
|
new Test().start();
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void start() throws Throwable {
|
private void start() throws Throwable {
|
||||||
input((Object) new A());
|
input((Object) new A());
|
||||||
input((Object) new B());
|
input((Object) new B());
|
||||||
input((Object) new String[] {"a", "b"});
|
input((Object) new String[] {"a", "b"});
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(Object object) throws Throwable {
|
public void input(Object object) throws Throwable {
|
||||||
System.out.println("Object");
|
System.out.println("Object");
|
||||||
MethodType methodType = MethodType.methodType(void.class, object.getClass());
|
MethodType methodType = MethodType.methodType(void.class, object.getClass());
|
||||||
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
MethodHandles.Lookup lookup = MethodHandles.lookup();
|
||||||
MethodHandle methodHandle = lookup.findVirtual(getClass(), "input", methodType);
|
MethodHandle methodHandle = lookup.findVirtual(getClass(), "input", methodType);
|
||||||
try {
|
try {
|
||||||
methodHandle.invoke(this, object);
|
methodHandle.invoke(this, object);
|
||||||
} catch (NoSuchMethodException e) {
|
} catch (NoSuchMethodException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(A object) {
|
public void input(A object) {
|
||||||
System.out.println("A");
|
System.out.println("A");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(B object) {
|
public void input(B object) {
|
||||||
System.out.println("B");
|
System.out.println("B");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(String[] object) {
|
public void input(String[] object) {
|
||||||
System.out.println("String[]");
|
System.out.println("String[]");
|
||||||
}
|
}
|
||||||
|
|
||||||
public class A {
|
public class A {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public class B {
|
public class B {
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,12 +4,12 @@ import worker.dummy.DummyWork;
|
|||||||
|
|
||||||
|
|
||||||
public class TestDirectWork {
|
public class TestDirectWork {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
DummyWork work = new DummyWork(1);
|
DummyWork work = new DummyWork(1);
|
||||||
work.setWork(100);
|
work.setWork(100);
|
||||||
work.start();
|
work.start();
|
||||||
try {
|
try {
|
||||||
Thread.sleep(10000);
|
Thread.sleep(10000);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,15 +4,15 @@ import worker.dummy.DummyIntervalWork;
|
|||||||
import base.work.Work;
|
import base.work.Work;
|
||||||
|
|
||||||
public class TestIntervalWork {
|
public class TestIntervalWork {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Work work = new DummyIntervalWork(500);
|
Work work = new DummyIntervalWork(500);
|
||||||
for (int i = 0; i < 10; ++i) {
|
for (int i = 0; i < 10; ++i) {
|
||||||
work.start();
|
work.start();
|
||||||
System.out.println("--");
|
System.out.println("--");
|
||||||
try {
|
try {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
work.stop();
|
work.stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,17 +3,17 @@ package worker;
|
|||||||
import worker.dummy.DummyListen;
|
import worker.dummy.DummyListen;
|
||||||
|
|
||||||
public class TestListen {
|
public class TestListen {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
DummyListen<Integer> listen = new DummyListen<Integer>(0);
|
DummyListen<Integer> listen = new DummyListen<Integer>(0);
|
||||||
listen.start();
|
listen.start();
|
||||||
for (int i = 0; i < 10; ++i) {
|
for (int i = 0; i < 10; ++i) {
|
||||||
listen.add(i);
|
listen.add(i);
|
||||||
try {
|
try {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Thread.sleep(10000);
|
Thread.sleep(10000);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,31 +8,31 @@ import worker.dummy.DummyListen;
|
|||||||
import base.worker.pool.ListenerPool;
|
import base.worker.pool.ListenerPool;
|
||||||
|
|
||||||
public class TestPooledListen {
|
public class TestPooledListen {
|
||||||
protected int id;
|
protected int id;
|
||||||
|
|
||||||
public TestPooledListen(int id) {
|
public TestPooledListen(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(Integer element) {
|
public void input(Integer element) {
|
||||||
System.out.println("#" + id + ": " + element);
|
System.out.println("#" + id + ": " + element);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
ListenerPool<Integer> listenerPool = new ListenerPool<Integer>(5);
|
ListenerPool<Integer> listenerPool = new ListenerPool<Integer>(5);
|
||||||
List<DummyListen<Integer>> listenList = new ArrayList<DummyListen<Integer>>();
|
List<DummyListen<Integer>> listenList = new ArrayList<DummyListen<Integer>>();
|
||||||
for (int i = 0; i < 20; ++i) {
|
for (int i = 0; i < 20; ++i) {
|
||||||
DummyListen<Integer> listen = new DummyListen<Integer>(listenerPool, i + 1);
|
DummyListen<Integer> listen = new DummyListen<Integer>(listenerPool, i + 1);
|
||||||
listenList.add(listen);
|
listenList.add(listen);
|
||||||
}
|
}
|
||||||
listenerPool.start();
|
listenerPool.start();
|
||||||
|
|
||||||
System.out.println("Starting to give out elements!");
|
System.out.println("Starting to give out elements!");
|
||||||
for (int i = 0; i < 100; ++i) {
|
for (int i = 0; i < 100; ++i) {
|
||||||
DummyListen<Integer> randomListen = listenList.get((new Random()).nextInt(listenList.size()));
|
DummyListen<Integer> randomListen = listenList.get((new Random()).nextInt(listenList.size()));
|
||||||
randomListen.add(i);
|
randomListen.add(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
//listenerPool.await();
|
//listenerPool.await();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,37 +9,37 @@ import base.work.Work;
|
|||||||
import base.worker.pool.WorkerPool;
|
import base.worker.pool.WorkerPool;
|
||||||
|
|
||||||
public class TestPooledWork {
|
public class TestPooledWork {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
WorkerPool workerPool = new WorkerPool(3);
|
WorkerPool workerPool = new WorkerPool(3);
|
||||||
|
|
||||||
List<DummyWork> workList = new ArrayList<DummyWork>();
|
List<DummyWork> workList = new ArrayList<DummyWork>();
|
||||||
for (int i = 0; i < 10; ++i) {
|
for (int i = 0; i < 10; ++i) {
|
||||||
DummyWork work = new DummyWork(workerPool, i + 1);
|
DummyWork work = new DummyWork(workerPool, i + 1);
|
||||||
workList.add(work);
|
workList.add(work);
|
||||||
}
|
}
|
||||||
workerPool.start();
|
workerPool.start();
|
||||||
|
|
||||||
System.out.println("Starting work!");
|
System.out.println("Starting work!");
|
||||||
ArrayList<Work> activeWorkList = new ArrayList<Work>();
|
ArrayList<Work> activeWorkList = new ArrayList<Work>();
|
||||||
for (int i = 0; i < 8; ++i) {
|
for (int i = 0; i < 8; ++i) {
|
||||||
DummyWork work = workList.get((new Random()).nextInt(workList.size()));
|
DummyWork work = workList.get((new Random()).nextInt(workList.size()));
|
||||||
work.setWork(1000);
|
work.setWork(1000);
|
||||||
work.start();
|
work.start();
|
||||||
activeWorkList.add(work);
|
activeWorkList.add(work);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Thread.sleep(2000);
|
Thread.sleep(2000);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
int i = 0;
|
int i = 0;
|
||||||
for (Work work : activeWorkList) {
|
for (Work work : activeWorkList) {
|
||||||
if (++i > 5) {
|
if (++i > 5) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
work.stop();
|
work.stop();
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
Thread.sleep(100000);
|
Thread.sleep(100000);
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
System.exit(0);
|
System.exit(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ package worker.dummy;
|
|||||||
import base.worker.IntervalWork;
|
import base.worker.IntervalWork;
|
||||||
|
|
||||||
public class DummyIntervalWork extends IntervalWork {
|
public class DummyIntervalWork extends IntervalWork {
|
||||||
public DummyIntervalWork(int interval) {
|
public DummyIntervalWork(int interval) {
|
||||||
super(interval);
|
super(interval);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void work() {
|
public void work() {
|
||||||
System.out.println(":-)");
|
System.out.println(":-)");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,23 +4,23 @@ import base.work.Listen;
|
|||||||
import base.worker.pool.ListenerPool;
|
import base.worker.pool.ListenerPool;
|
||||||
|
|
||||||
public class DummyListen<T> extends Listen<T> {
|
public class DummyListen<T> extends Listen<T> {
|
||||||
protected int id;
|
protected int id;
|
||||||
|
|
||||||
public DummyListen(ListenerPool<T> listenerPool, int id) {
|
public DummyListen(ListenerPool<T> listenerPool, int id) {
|
||||||
super(listenerPool);
|
super(listenerPool);
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DummyListen(int id) {
|
public DummyListen(int id) {
|
||||||
super();
|
super();
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(Integer input) {
|
public void input(Integer input) {
|
||||||
System.out.println("#" + id + ", input = " + input);
|
System.out.println("#" + id + ", input = " + input);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void input(byte[] input) {
|
public void input(byte[] input) {
|
||||||
System.out.println("#" + id + ", input = " + new String(input).trim());
|
System.out.println("#" + id + ", input = " + new String(input).trim());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,37 +6,37 @@ import base.work.Work;
|
|||||||
import base.worker.pool.WorkerPool;
|
import base.worker.pool.WorkerPool;
|
||||||
|
|
||||||
public class DummyWork extends Work {
|
public class DummyWork extends Work {
|
||||||
protected int id;
|
protected int id;
|
||||||
protected volatile int work;
|
protected volatile int work;
|
||||||
|
|
||||||
public DummyWork(int id) {
|
public DummyWork(int id) {
|
||||||
super();
|
super();
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DummyWork(WorkerPool workerPool, int id) {
|
public DummyWork(WorkerPool workerPool, int id) {
|
||||||
super(workerPool);
|
super(workerPool);
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setWork(int work) {
|
public void setWork(int work) {
|
||||||
System.out.println("#" + id + ", set work @ " + work);
|
System.out.println("#" + id + ", set work @ " + work);
|
||||||
this.work = work;
|
this.work = work;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void work() {
|
public void work() {
|
||||||
System.out.println("#" + id + ", work = " + work);
|
System.out.println("#" + id + ", work = " + work);
|
||||||
if (--work < 1) {
|
if (--work < 1) {
|
||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
sleep(300);
|
sleep(300);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
System.out.println("#" + id + ", activating...");
|
System.out.println("#" + id + ", activating...");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deactivate() throws DeactivateException {
|
public void deactivate() throws DeactivateException {
|
||||||
System.out.println("#" + id + ", deactivating...");
|
System.out.println("#" + id + ", deactivating...");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,14 +41,14 @@ public abstract class Component extends Listen<Input> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Component(Type type) {
|
public Component(Type type) {
|
||||||
super(type);
|
super(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Component(String title) {
|
public Component(String title) {
|
||||||
this.title = title;
|
this.title = title;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setRouter(Router router) {
|
public void setRouter(Router router) {
|
||||||
this.router = router;
|
this.router = router;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,21 +41,21 @@ public class Main extends Mimis {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static Component[] getApplications() {
|
public static Component[] getApplications() {
|
||||||
return getComponents(mimis.application.Application.class);
|
return getComponents(mimis.application.Application.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Component[] getDevices() {
|
public static Component[] getDevices() {
|
||||||
return getComponents(mimis.device.Device.class);
|
return getComponents(mimis.device.Device.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Component[] getComponents(Class<?> clazz) {
|
public static Component[] getComponents(Class<?> clazz) {
|
||||||
ArrayList<Component> componentList = new ArrayList<Component>();
|
ArrayList<Component> componentList = new ArrayList<Component>();
|
||||||
for (Object object : ServiceLoader.load(clazz)) {
|
for (Object object : ServiceLoader.load(clazz)) {
|
||||||
if (object instanceof Component) {
|
if (object instanceof Component) {
|
||||||
componentList.add((Component) object);
|
componentList.add((Component) object);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return componentList.toArray(new Component[]{});
|
return componentList.toArray(new Component[]{});
|
||||||
}
|
}
|
||||||
|
|
||||||
public Main() {
|
public Main() {
|
||||||
@@ -106,8 +106,8 @@ public class Main extends Mimis {
|
|||||||
case PREVIOUS:
|
case PREVIOUS:
|
||||||
applicationManager.currentChanged();
|
applicationManager.currentChanged();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ public abstract class Mimis extends Component {
|
|||||||
protected ArrayCycle<Component> componentCycle;
|
protected ArrayCycle<Component> componentCycle;
|
||||||
|
|
||||||
public Mimis(Component... currentArray) {
|
public Mimis(Component... currentArray) {
|
||||||
super(Worker.Type.FOREGROUND);
|
super(Worker.Type.FOREGROUND);
|
||||||
this.currentArray = initialize(false, currentArray);
|
this.currentArray = initialize(false, currentArray);
|
||||||
componentCycle = new ArrayCycle<Component>(currentArray);
|
componentCycle = new ArrayCycle<Component>(currentArray);
|
||||||
router = new Router();
|
router = new Router();
|
||||||
@@ -91,8 +91,8 @@ public abstract class Mimis extends Component {
|
|||||||
case EXIT:
|
case EXIT:
|
||||||
exit();
|
exit();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,8 +73,8 @@ public class GomPlayerApplication extends WindowsApplication {
|
|||||||
case PREVIOUS:
|
case PREVIOUS:
|
||||||
seekWork.start(Amount.MEDIUM, -1);
|
seekWork.start(Amount.MEDIUM, -1);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,8 +100,8 @@ public class GomPlayerApplication extends WindowsApplication {
|
|||||||
case FULLSCREEN:
|
case FULLSCREEN:
|
||||||
command(0x8154);
|
command(0x8154);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -57,8 +57,8 @@ public class PhotoViewerApplication extends WindowsApplication {
|
|||||||
case VOLUME_DOWN:
|
case VOLUME_DOWN:
|
||||||
zoomWork.start(-1);
|
zoomWork.start(-1);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,8 +108,8 @@ public class PhotoViewerApplication extends WindowsApplication {
|
|||||||
end(Action.FULLSCREEN);
|
end(Action.FULLSCREEN);
|
||||||
}*/
|
}*/
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -92,8 +92,8 @@ public class WinampApplication extends WindowsApplication {
|
|||||||
case REWIND:
|
case REWIND:
|
||||||
seekWork.start(-1);
|
seekWork.start(-1);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,8 +150,8 @@ public class WinampApplication extends WindowsApplication {
|
|||||||
system(Command.System.MAXIMIZE);
|
system(Command.System.MAXIMIZE);
|
||||||
command(WINAMP_VISPLUGIN);
|
command(WINAMP_VISPLUGIN);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -66,9 +66,9 @@ public class WMPApplication extends WindowsApplication {
|
|||||||
break;
|
break;
|
||||||
case REPEAT:
|
case REPEAT:
|
||||||
command(18843);
|
command(18843);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,8 +85,8 @@ public class WMPApplication extends WindowsApplication {
|
|||||||
case VOLUME_DOWN:
|
case VOLUME_DOWN:
|
||||||
volumeWork.stop();
|
volumeWork.stop();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -108,8 +108,8 @@ public class iTunesApplication extends Component implements Application, iTunesE
|
|||||||
case VOLUME_DOWN:
|
case VOLUME_DOWN:
|
||||||
volumeWork.start(-VOLUME_CHANGE_RATE);
|
volumeWork.start(-VOLUME_CHANGE_RATE);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,8 +151,8 @@ public class iTunesApplication extends Component implements Application, iTunesE
|
|||||||
case DISLIKE:
|
case DISLIKE:
|
||||||
iTunes.playlistAddCurrentTrack(PLAYLIST_DISLIKE);
|
iTunes.playlistAddCurrentTrack(PLAYLIST_DISLIKE);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -62,8 +62,8 @@ public class iPodApplication extends LircApplication {
|
|||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,8 +84,8 @@ public class iPodApplication extends LircApplication {
|
|||||||
case VOLUME_DOWN:
|
case VOLUME_DOWN:
|
||||||
volumeWork.stop();
|
volumeWork.stop();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -52,8 +52,8 @@ public class MPCApplication extends WindowsApplication {
|
|||||||
case VOLUME_DOWN:
|
case VOLUME_DOWN:
|
||||||
volumeWork.start(-1);
|
volumeWork.start(-1);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,8 +83,8 @@ public class MPCApplication extends WindowsApplication {
|
|||||||
case FULLSCREEN:
|
case FULLSCREEN:
|
||||||
command(830);
|
command(830);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -108,8 +108,8 @@ public class VLCApplication extends CMDApplication {
|
|||||||
case REWIND:
|
case REWIND:
|
||||||
seekWorker.start(Amount.SMALL, "-");
|
seekWorker.start(Amount.SMALL, "-");
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} catch (ActivateException e) {
|
} catch (ActivateException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
@@ -148,8 +148,8 @@ public class VLCApplication extends CMDApplication {
|
|||||||
case REPEAT:
|
case REPEAT:
|
||||||
command("command=pl_repeat");
|
command("command=pl_repeat");
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -105,8 +105,8 @@ public class LircDevice extends CMDApplication implements Device, LircButtonList
|
|||||||
case END:
|
case END:
|
||||||
route(new Release(button));
|
route(new Release(button));
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (general) {
|
if (general) {
|
||||||
|
|||||||
@@ -47,8 +47,8 @@ public class LircService extends TcpClient {
|
|||||||
protected String send;
|
protected String send;
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
LircService lircService = new LircService();
|
LircService lircService = new LircService();
|
||||||
lircService.start();
|
lircService.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
public LircService() {
|
public LircService() {
|
||||||
@@ -72,7 +72,7 @@ public class LircService extends TcpClient {
|
|||||||
|
|
||||||
|
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
super.activate();
|
super.activate();
|
||||||
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
|
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
|
||||||
printWriter = new PrintWriter(outputStream);
|
printWriter = new PrintWriter(outputStream);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ public class WiimoteDevice extends Component implements Device, GestureListener
|
|||||||
|
|
||||||
/* Worker */
|
/* Worker */
|
||||||
public void activate() throws ActivateException {
|
public void activate() throws ActivateException {
|
||||||
if (wiimote == null) {
|
if (wiimote == null) {
|
||||||
motionDevice.setRouter(router);
|
motionDevice.setRouter(router);
|
||||||
motionDevice.start();
|
motionDevice.start();
|
||||||
parser(Action.ADD, taskMapCycle.player);
|
parser(Action.ADD, taskMapCycle.player);
|
||||||
@@ -170,8 +170,8 @@ public class WiimoteDevice extends Component implements Device, GestureListener
|
|||||||
gestureDevice.loadGesture("tmp/gesture #" + gestureId);
|
gestureDevice.loadGesture("tmp/gesture #" + gestureId);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,8 +189,8 @@ public class WiimoteDevice extends Component implements Device, GestureListener
|
|||||||
logger.debug("Gesture close release");
|
logger.debug("Gesture close release");
|
||||||
gestureDevice.close(Signal.END);
|
gestureDevice.close(Signal.END);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,9 +211,9 @@ public class WiimoteDevice extends Component implements Device, GestureListener
|
|||||||
|
|
||||||
/* Listeners */
|
/* Listeners */
|
||||||
public void onButtonsEvent(WiimoteButtonsEvent event) {
|
public void onButtonsEvent(WiimoteButtonsEvent event) {
|
||||||
if (!active()) {
|
if (!active()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int pressed = event.getButtonsJustPressed() - event.getButtonsHeld();
|
int pressed = event.getButtonsJustPressed() - event.getButtonsHeld();
|
||||||
int released = event.getButtonsJustReleased();
|
int released = event.getButtonsJustReleased();
|
||||||
try {
|
try {
|
||||||
@@ -230,9 +230,9 @@ public class WiimoteDevice extends Component implements Device, GestureListener
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void onMotionSensingEvent(MotionSensingEvent event) {
|
public void onMotionSensingEvent(MotionSensingEvent event) {
|
||||||
if (!active()) {
|
if (!active()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
gestureDevice.add(event.getGforce());
|
gestureDevice.add(event.getGforce());
|
||||||
motionDevice.add(event);
|
motionDevice.add(event);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ public class WiimoteService extends WiiUseApiManager implements WiimoteListener
|
|||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Logger logger = LoggerFactory.getLogger(WiimoteService.class);
|
Logger logger = LoggerFactory.getLogger(WiimoteService.class);
|
||||||
for (Wiimote wm : WiiUseApiManager.getWiimotes(1, false)) {
|
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) {
|
public void onButtonsEvent(WiimoteButtonsEvent event) {
|
||||||
getWiimoteDevice(event).onButtonsEvent(event);
|
getWiimoteDevice(event).onButtonsEvent(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void onMotionSensingEvent(MotionSensingEvent event) {
|
public void onMotionSensingEvent(MotionSensingEvent event) {
|
||||||
|
|||||||
@@ -93,8 +93,8 @@ public class MotionDevice extends Component {
|
|||||||
case SCREEN_DOWN:
|
case SCREEN_DOWN:
|
||||||
wiimoteDevice.begin(Action.LOAD);
|
wiimoteDevice.begin(Action.LOAD);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} else if (button instanceof NumberButton) {
|
} else if (button instanceof NumberButton) {
|
||||||
NumberButton numberButton = (NumberButton) button;
|
NumberButton numberButton = (NumberButton) button;
|
||||||
@@ -140,8 +140,8 @@ public class MotionDevice extends Component {
|
|||||||
replay = true;
|
replay = true;
|
||||||
replayWork.start();
|
replayWork.start();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,22 +28,22 @@ public class HoldButton extends JButton implements MouseListener {
|
|||||||
|
|
||||||
public HoldButton(HoldButtonListener holdButtonListener) {
|
public HoldButton(HoldButtonListener holdButtonListener) {
|
||||||
this.holdButtonListener = holdButtonListener;
|
this.holdButtonListener = holdButtonListener;
|
||||||
addMouseListener(this);
|
addMouseListener(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void mousePressed(MouseEvent event) {
|
public void mousePressed(MouseEvent event) {
|
||||||
if (event.getButton() == MouseEvent.BUTTON1) {
|
if (event.getButton() == MouseEvent.BUTTON1) {
|
||||||
holdButtonListener.buttonPressed(this);
|
holdButtonListener.buttonPressed(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void mouseReleased(MouseEvent event) {
|
public void mouseReleased(MouseEvent event) {
|
||||||
if (event.getButton() == MouseEvent.BUTTON1) {
|
if (event.getButton() == MouseEvent.BUTTON1) {
|
||||||
holdButtonListener.buttonReleased(this);
|
holdButtonListener.buttonReleased(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void mouseClicked(MouseEvent event) {}
|
public void mouseClicked(MouseEvent event) {}
|
||||||
public void mouseEntered(MouseEvent event) {}
|
public void mouseEntered(MouseEvent event) {}
|
||||||
public void mouseExited(MouseEvent event) {}
|
public void mouseExited(MouseEvent event) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,172 +16,172 @@ import base.work.Work;
|
|||||||
import com.Ostermiller.util.CircularByteBuffer;
|
import com.Ostermiller.util.CircularByteBuffer;
|
||||||
|
|
||||||
public class Converter extends Work {
|
public class Converter extends Work {
|
||||||
public static final String COMMAND = "lame --mp3input --cbr %s - - --quiet";
|
public static final String COMMAND = "lame --mp3input --cbr %s - - --quiet";
|
||||||
public static final int BYTES = 4096; // bytes
|
public static final int BYTES = 4096; // bytes
|
||||||
public static final int BUFFER = 30000; // milliseconds
|
public static final int BUFFER = 30000; // milliseconds
|
||||||
public static final int BUFFERING = 1000; // milliseconds
|
public static final int BUFFERING = 1000; // milliseconds
|
||||||
|
|
||||||
protected int targetRate;
|
protected int targetRate;
|
||||||
protected int rate;
|
protected int rate;
|
||||||
protected int buffer;
|
protected int buffer;
|
||||||
protected boolean convert;
|
protected boolean convert;
|
||||||
|
|
||||||
protected Process process;
|
protected Process process;
|
||||||
protected InputStream sourceInputStream, processInputStream, inputStream;
|
protected InputStream sourceInputStream, processInputStream, inputStream;
|
||||||
protected OutputStream processOutputStream;
|
protected OutputStream processOutputStream;
|
||||||
protected CircularByteBuffer circularByteBuffer;
|
protected CircularByteBuffer circularByteBuffer;
|
||||||
protected BufferWorker bufferWorker;
|
protected BufferWorker bufferWorker;
|
||||||
|
|
||||||
public Converter(InputStream inputStream) {
|
public Converter(InputStream inputStream) {
|
||||||
this(inputStream, -1);
|
this(inputStream, -1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Converter(InputStream inputStream, int targetRate) {
|
public Converter(InputStream inputStream, int targetRate) {
|
||||||
super();
|
super();
|
||||||
this.sourceInputStream = inputStream;
|
this.sourceInputStream = inputStream;
|
||||||
this.targetRate = targetRate;
|
this.targetRate = targetRate;
|
||||||
bufferWorker = new BufferWorker();
|
bufferWorker = new BufferWorker();
|
||||||
convert = false;
|
convert = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
super.exit();
|
super.exit();
|
||||||
bufferWorker.exit();
|
bufferWorker.exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void activate() throws ActivateException {
|
public synchronized void activate() throws ActivateException {
|
||||||
/* Read bitrate */
|
/* Read bitrate */
|
||||||
BufferedInputStream bufferedInputStream = new BufferedInputStream(sourceInputStream);
|
BufferedInputStream bufferedInputStream = new BufferedInputStream(sourceInputStream);
|
||||||
Bitstream bitStream = new Bitstream(bufferedInputStream);
|
Bitstream bitStream = new Bitstream(bufferedInputStream);
|
||||||
try {
|
try {
|
||||||
rate = bitStream.readFrame().bitrate() / 1000;
|
rate = bitStream.readFrame().bitrate() / 1000;
|
||||||
buffer = BUFFER * rate / 8;
|
buffer = BUFFER * rate / 8;
|
||||||
} catch (BitstreamException e) {
|
} catch (BitstreamException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Check for need to convert */
|
/* Check for need to convert */
|
||||||
if (targetRate < 0 || rate == targetRate) {
|
if (targetRate < 0 || rate == targetRate) {
|
||||||
logger.debug("No conversion required");
|
logger.debug("No conversion required");
|
||||||
inputStream = sourceInputStream;
|
inputStream = sourceInputStream;
|
||||||
} else {
|
} else {
|
||||||
logger.debug("Converting from " + rate + "kbps to " + targetRate + "kbps");
|
logger.debug("Converting from " + rate + "kbps to " + targetRate + "kbps");
|
||||||
try {
|
try {
|
||||||
String command = String.format(COMMAND, rate > targetRate ? "-B " + targetRate : "-F -b " + targetRate);
|
String command = String.format(COMMAND, rate > targetRate ? "-B " + targetRate : "-F -b " + targetRate);
|
||||||
logger.debug("Starting process: " + command);
|
logger.debug("Starting process: " + command);
|
||||||
process = Runtime.getRuntime().exec(command);
|
process = Runtime.getRuntime().exec(command);
|
||||||
processInputStream = process.getInputStream();
|
processInputStream = process.getInputStream();
|
||||||
processOutputStream = process.getOutputStream();
|
processOutputStream = process.getOutputStream();
|
||||||
|
|
||||||
/* Buffer output */
|
/* Buffer output */
|
||||||
circularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
|
circularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
|
||||||
inputStream = circularByteBuffer.getInputStream();
|
inputStream = circularByteBuffer.getInputStream();
|
||||||
bufferWorker.start();
|
bufferWorker.start();
|
||||||
convert = true;
|
convert = true;
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
super.activate();
|
super.activate();
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deactivate() throws DeactivateException {
|
public void deactivate() throws DeactivateException {
|
||||||
super.deactivate();
|
super.deactivate();
|
||||||
try {
|
try {
|
||||||
sourceInputStream.close();
|
sourceInputStream.close();
|
||||||
bufferWorker.stop();
|
bufferWorker.stop();
|
||||||
if (convert) {
|
if (convert) {
|
||||||
circularByteBuffer.clear();
|
circularByteBuffer.clear();
|
||||||
convert = false;
|
convert = false;
|
||||||
}
|
}
|
||||||
inputStream.close();
|
inputStream.close();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
throw new DeactivateException();
|
throw new DeactivateException();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void work() {
|
public void work() {
|
||||||
if (!convert) {
|
if (!convert) {
|
||||||
try {
|
try {
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
wait();
|
wait();
|
||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
byte[] bytes = new byte[BYTES];
|
byte[] bytes = new byte[BYTES];
|
||||||
int read = 0;
|
int read = 0;
|
||||||
try {
|
try {
|
||||||
logger.debug("Writing input to process");
|
logger.debug("Writing input to process");
|
||||||
// Should be interrupted by stop()/exit()
|
// Should be interrupted by stop()/exit()
|
||||||
while ((read = sourceInputStream.read(bytes)) > 0) {
|
while ((read = sourceInputStream.read(bytes)) > 0) {
|
||||||
/* Limit buffer size */
|
/* Limit buffer size */
|
||||||
while (inputStream.available() > buffer) {
|
while (inputStream.available() > buffer) {
|
||||||
int progress = (int) ((1 - (inputStream.available() - buffer) / (float) buffer) * 100);
|
int progress = (int) ((1 - (inputStream.available() - buffer) / (float) buffer) * 100);
|
||||||
logger.trace("Waiting for buffer to empty: " + progress + "%");
|
logger.trace("Waiting for buffer to empty: " + progress + "%");
|
||||||
sleep(BUFFERING);
|
sleep(BUFFERING);
|
||||||
}
|
}
|
||||||
processOutputStream.write(bytes, 0, read);
|
processOutputStream.write(bytes, 0, read);
|
||||||
}
|
}
|
||||||
processOutputStream.close();
|
processOutputStream.close();
|
||||||
logger.debug("Stopped writing input to process");
|
logger.debug("Stopped writing input to process");
|
||||||
process.waitFor();
|
process.waitFor();
|
||||||
logger.debug("Process finished");
|
logger.debug("Process finished");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized InputStream getInputStream() {
|
public synchronized InputStream getInputStream() {
|
||||||
if (!active()) {
|
if (!active()) {
|
||||||
start();
|
start();
|
||||||
try {
|
try {
|
||||||
wait();
|
wait();
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return inputStream;
|
return inputStream;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void setInputStream(InputStream inputStream) {
|
public synchronized void setInputStream(InputStream inputStream) {
|
||||||
this.inputStream = inputStream;
|
this.inputStream = inputStream;
|
||||||
}
|
}
|
||||||
|
|
||||||
class BufferWorker extends Work {
|
class BufferWorker extends Work {
|
||||||
public void work() {
|
public void work() {
|
||||||
byte[] bytes = new byte[BYTES];
|
byte[] bytes = new byte[BYTES];
|
||||||
int read = 0;
|
int read = 0;
|
||||||
try {
|
try {
|
||||||
OutputStream bufferOutputStream = circularByteBuffer.getOutputStream();
|
OutputStream bufferOutputStream = circularByteBuffer.getOutputStream();
|
||||||
logger.debug("Start buffering process output");
|
logger.debug("Start buffering process output");
|
||||||
while ((read = processInputStream.read(bytes, 0, BYTES)) > 0) {
|
while ((read = processInputStream.read(bytes, 0, BYTES)) > 0) {
|
||||||
bufferOutputStream.write(bytes, 0, read);
|
bufferOutputStream.write(bytes, 0, read);
|
||||||
}
|
}
|
||||||
logger.debug("Finished buffering process output");
|
logger.debug("Finished buffering process output");
|
||||||
bufferOutputStream.close();
|
bufferOutputStream.close();
|
||||||
} catch (IOException e) {}
|
} catch (IOException e) {}
|
||||||
stop();
|
stop();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Mp3 mp3 = new Mp3(new File("stream.mp3"), 128);
|
Mp3 mp3 = new Mp3(new File("stream.mp3"), 128);
|
||||||
InputStream inputStream = mp3.getInputStream();
|
InputStream inputStream = mp3.getInputStream();
|
||||||
|
|
||||||
/* Play */
|
/* Play */
|
||||||
//Utils.play(inputStream);
|
//Utils.play(inputStream);
|
||||||
|
|
||||||
/* Write to file */
|
/* Write to file */
|
||||||
Utils.write(inputStream, new File("output.mp3"));
|
Utils.write(inputStream, new File("output.mp3"));
|
||||||
mp3.exit();
|
mp3.exit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,185 +17,185 @@ import com.Ostermiller.util.CircularByteBuffer;
|
|||||||
import com.Ostermiller.util.CircularObjectBuffer;
|
import com.Ostermiller.util.CircularObjectBuffer;
|
||||||
|
|
||||||
public class List extends Work {
|
public class List extends Work {
|
||||||
public static final int STEP = 80; // milliseconds
|
public static final int STEP = 80; // milliseconds
|
||||||
public static final int RATE = 192; // kbps
|
public static final int RATE = 192; // kbps
|
||||||
public static final int OVERLAP = 20000; // milliseconds
|
public static final int OVERLAP = 20000; // milliseconds
|
||||||
|
|
||||||
protected File file;
|
protected File file;
|
||||||
protected String[] fileArray;
|
protected String[] fileArray;
|
||||||
|
|
||||||
protected int rate;
|
protected int rate;
|
||||||
protected int chunk;
|
protected int chunk;
|
||||||
protected int overlap;
|
protected int overlap;
|
||||||
protected byte[] bytes;
|
protected byte[] bytes;
|
||||||
protected boolean next;
|
protected boolean next;
|
||||||
protected Mp3 mp3, nextMp3;
|
protected Mp3 mp3, nextMp3;
|
||||||
|
|
||||||
protected InputStream mp3InputStream;
|
protected InputStream mp3InputStream;
|
||||||
protected OutputStream audioOutputStream;
|
protected OutputStream audioOutputStream;
|
||||||
protected CircularByteBuffer circularByteBuffer;
|
protected CircularByteBuffer circularByteBuffer;
|
||||||
protected CircularObjectBuffer<String> circularStringBuffer;
|
protected CircularObjectBuffer<String> circularStringBuffer;
|
||||||
|
|
||||||
public List(File file) {
|
public List(File file) {
|
||||||
this(file, RATE);
|
this(file, RATE);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List(File file, int rate) {
|
public List(File file, int rate) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
this.rate = rate;
|
this.rate = rate;
|
||||||
chunk = STEP * rate / 8;
|
chunk = STEP * rate / 8;
|
||||||
overlap = OVERLAP * RATE / 8;
|
overlap = OVERLAP * RATE / 8;
|
||||||
bytes = new byte[chunk];
|
bytes = new byte[chunk];
|
||||||
next = true;
|
next = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void exit() {
|
public void exit() {
|
||||||
super.exit();
|
super.exit();
|
||||||
if (mp3 != null) {
|
if (mp3 != null) {
|
||||||
mp3.exit();
|
mp3.exit();
|
||||||
}
|
}
|
||||||
if (nextMp3 != null) {
|
if (nextMp3 != null) {
|
||||||
nextMp3.exit();
|
nextMp3.exit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void activate() throws ActivateException {
|
public synchronized void activate() throws ActivateException {
|
||||||
try {
|
try {
|
||||||
Scanner scanner = new Scanner(file);
|
Scanner scanner = new Scanner(file);
|
||||||
ArrayList<String> fileList = new ArrayList<String>();
|
ArrayList<String> fileList = new ArrayList<String>();
|
||||||
while (scanner.hasNextLine()) {
|
while (scanner.hasNextLine()) {
|
||||||
fileList.add(scanner.nextLine());
|
fileList.add(scanner.nextLine());
|
||||||
}
|
}
|
||||||
scanner.close();
|
scanner.close();
|
||||||
if (fileList.size() > 0) {
|
if (fileList.size() > 0) {
|
||||||
fileArray = fileList.toArray(new String[0]);
|
fileArray = fileList.toArray(new String[0]);
|
||||||
|
|
||||||
circularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
|
circularByteBuffer = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
|
||||||
audioOutputStream = circularByteBuffer.getOutputStream();
|
audioOutputStream = circularByteBuffer.getOutputStream();
|
||||||
|
|
||||||
circularStringBuffer = new CircularObjectBuffer<String>(CircularByteBuffer.INFINITE_SIZE);
|
circularStringBuffer = new CircularObjectBuffer<String>(CircularByteBuffer.INFINITE_SIZE);
|
||||||
setNext();
|
setNext();
|
||||||
super.activate();
|
super.activate();
|
||||||
notifyAll();
|
notifyAll();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} catch (FileNotFoundException e) {
|
} catch (FileNotFoundException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void work() {
|
public synchronized void work() {
|
||||||
try {
|
try {
|
||||||
int left = chunk;
|
int left = chunk;
|
||||||
while (left > 0) {
|
while (left > 0) {
|
||||||
/* Check for need to load next mp3 */
|
/* Check for need to load next mp3 */
|
||||||
int available = mp3InputStream == null ? -1 : mp3InputStream.available();
|
int available = mp3InputStream == null ? -1 : mp3InputStream.available();
|
||||||
boolean expect = mp3 == null ? false : mp3.active();
|
boolean expect = mp3 == null ? false : mp3.active();
|
||||||
|
|
||||||
/* Act when no more data is expected */
|
/* Act when no more data is expected */
|
||||||
if (!expect) {
|
if (!expect) {
|
||||||
if (available < overlap) {
|
if (available < overlap) {
|
||||||
setNext();
|
setNext();
|
||||||
next = false;
|
next = false;
|
||||||
nextMp3.start();
|
nextMp3.start();
|
||||||
}
|
}
|
||||||
if (available < 1) {
|
if (available < 1) {
|
||||||
swap();
|
swap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Transfer data */
|
/* Transfer data */
|
||||||
int read = mp3InputStream.read(bytes, 0, left);
|
int read = mp3InputStream.read(bytes, 0, left);
|
||||||
left -= read;
|
left -= read;
|
||||||
audioOutputStream.write(bytes, 0, read);
|
audioOutputStream.write(bytes, 0, read);
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
/* Swap to next if stream has stopped */
|
/* Swap to next if stream has stopped */
|
||||||
setNext();
|
setNext();
|
||||||
swap();
|
swap();
|
||||||
} catch (IllegalStateException e) {
|
} catch (IllegalStateException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
sleep(STEP);
|
sleep(STEP);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected File getRandomFile() {
|
protected File getRandomFile() {
|
||||||
return new File(fileArray[(int) (Math.random() * fileArray.length)]);
|
return new File(fileArray[(int) (Math.random() * fileArray.length)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void setNext() {
|
public synchronized void setNext() {
|
||||||
if (nextMp3 == null) {
|
if (nextMp3 == null) {
|
||||||
logger.debug("Initialize next mp3");
|
logger.debug("Initialize next mp3");
|
||||||
nextMp3 = new Mp3(getRandomFile(), rate);
|
nextMp3 = new Mp3(getRandomFile(), rate);
|
||||||
} else if (next) {
|
} else if (next) {
|
||||||
logger.debug("Load next mp3");
|
logger.debug("Load next mp3");
|
||||||
nextMp3.setFile(getRandomFile());
|
nextMp3.setFile(getRandomFile());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void next() {
|
public synchronized void next() {
|
||||||
logger.debug("Stop current mp3");
|
logger.debug("Stop current mp3");
|
||||||
mp3.stop();
|
mp3.stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void swap() {
|
public void swap() {
|
||||||
logger.debug("Swap to next mp3");
|
logger.debug("Swap to next mp3");
|
||||||
Mp3 swapMp3 = mp3;
|
Mp3 swapMp3 = mp3;
|
||||||
mp3 = nextMp3;
|
mp3 = nextMp3;
|
||||||
nextMp3 = swapMp3;
|
nextMp3 = swapMp3;
|
||||||
next = true;
|
next = true;
|
||||||
|
|
||||||
/* Swap stream and announce title */
|
/* Swap stream and announce title */
|
||||||
mp3InputStream = mp3.getInputStream();
|
mp3InputStream = mp3.getInputStream();
|
||||||
try {
|
try {
|
||||||
circularStringBuffer.write(mp3.getTitle());
|
circularStringBuffer.write(mp3.getTitle());
|
||||||
} catch (BufferOverflowException e) {
|
} catch (BufferOverflowException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
} catch (IllegalStateException e) {
|
} catch (IllegalStateException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized InputStream getInputStream() {
|
public synchronized InputStream getInputStream() {
|
||||||
if (circularByteBuffer == null) {
|
if (circularByteBuffer == null) {
|
||||||
start();
|
start();
|
||||||
try {
|
try {
|
||||||
wait();
|
wait();
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return circularByteBuffer.getInputStream();
|
return circularByteBuffer.getInputStream();
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized CircularObjectBuffer<String> getMetaBuffer() {
|
public synchronized CircularObjectBuffer<String> getMetaBuffer() {
|
||||||
if (circularStringBuffer == null) {
|
if (circularStringBuffer == null) {
|
||||||
start();
|
start();
|
||||||
try {
|
try {
|
||||||
wait();
|
wait();
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return circularStringBuffer;
|
return circularStringBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
int rate = 192;
|
int rate = 192;
|
||||||
List list = new List(new File(List.class.getClassLoader().getResource("txt/mp3").toURI()), rate);
|
List list = new List(new File(List.class.getClassLoader().getResource("txt/mp3").toURI()), rate);
|
||||||
Shoutcast shoutcast = new Shoutcast(rate, 9876);
|
Shoutcast shoutcast = new Shoutcast(rate, 9876);
|
||||||
|
|
||||||
shoutcast.setInputStream(list.getInputStream());
|
shoutcast.setInputStream(list.getInputStream());
|
||||||
shoutcast.setMetaBuffer(list.getMetaBuffer());
|
shoutcast.setMetaBuffer(list.getMetaBuffer());
|
||||||
shoutcast.start();
|
shoutcast.start();
|
||||||
while (true) {
|
while (true) {
|
||||||
try {
|
try {
|
||||||
Thread.sleep(15000);
|
Thread.sleep(15000);
|
||||||
list.next();
|
list.next();
|
||||||
} catch (InterruptedException e) {}
|
} catch (InterruptedException e) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,69 +12,69 @@ import sound.util.Utils;
|
|||||||
import base.exception.worker.ActivateException;
|
import base.exception.worker.ActivateException;
|
||||||
|
|
||||||
public class Mp3 extends Converter {
|
public class Mp3 extends Converter {
|
||||||
protected File file;
|
protected File file;
|
||||||
protected String title;
|
protected String title;
|
||||||
|
|
||||||
public Mp3(File file) {
|
public Mp3(File file) {
|
||||||
this(file, -1);
|
this(file, -1);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Mp3(File file, int targetRate) {
|
public Mp3(File file, int targetRate) {
|
||||||
super(null, targetRate);
|
super(null, targetRate);
|
||||||
setFile(file);
|
setFile(file);
|
||||||
title = "";
|
title = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void activate() throws ActivateException {
|
public synchronized void activate() throws ActivateException {
|
||||||
/* Open file */
|
/* Open file */
|
||||||
try {
|
try {
|
||||||
sourceInputStream = new FileInputStream(file);
|
sourceInputStream = new FileInputStream(file);
|
||||||
} catch (FileNotFoundException e) {
|
} catch (FileNotFoundException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
throw new ActivateException();
|
throw new ActivateException();
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Read ID3V2 tags */
|
/* Read ID3V2 tags */
|
||||||
try {
|
try {
|
||||||
MP3File mp3File = new MP3File(file);
|
MP3File mp3File = new MP3File(file);
|
||||||
String album = clean(mp3File.getID3v2Tag().getAlbumTitle());
|
String album = clean(mp3File.getID3v2Tag().getAlbumTitle());
|
||||||
String artist = clean(mp3File.getID3v2Tag().getLeadArtist());
|
String artist = clean(mp3File.getID3v2Tag().getLeadArtist());
|
||||||
String track = clean(mp3File.getID3v2Tag().getSongTitle());
|
String track = clean(mp3File.getID3v2Tag().getSongTitle());
|
||||||
if (album.isEmpty()) {
|
if (album.isEmpty()) {
|
||||||
title = String.format("%s - %s", artist, track, album);
|
title = String.format("%s - %s", artist, track, album);
|
||||||
} else {
|
} else {
|
||||||
title = String.format("%s - %s {%s}", artist, track, album);
|
title = String.format("%s - %s {%s}", artist, track, album);
|
||||||
}
|
}
|
||||||
logger.debug("Title: " + title);
|
logger.debug("Title: " + title);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
} catch (TagException e) {
|
} catch (TagException e) {
|
||||||
logger.error("", e);
|
logger.error("", e);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
sourceInputStream.skip(100000);
|
sourceInputStream.skip(100000);
|
||||||
} catch (IOException e) {}
|
} catch (IOException e) {}
|
||||||
super.activate();
|
super.activate();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected String clean(String input) {
|
protected String clean(String input) {
|
||||||
String output = input.replace("\0", "");
|
String output = input.replace("\0", "");
|
||||||
return output.replace("<EFBFBD><EFBFBD>", "");
|
return output.replace("<EFBFBD><EFBFBD>", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getTitle() {
|
public String getTitle() {
|
||||||
return title;
|
return title;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFile(File file) {
|
public void setFile(File file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
final Mp3 mp3 = new Mp3(new File("input.mp3"), 128);
|
final Mp3 mp3 = new Mp3(new File("input.mp3"), 128);
|
||||||
Utils.write(mp3.getInputStream(), new File("one.mp3"));
|
Utils.write(mp3.getInputStream(), new File("one.mp3"));
|
||||||
mp3.setFile(new File("stream.mp3"));
|
mp3.setFile(new File("stream.mp3"));
|
||||||
Utils.write(mp3.getInputStream(), new File("two.mp3"));
|
Utils.write(mp3.getInputStream(), new File("two.mp3"));
|
||||||
mp3.exit();
|
mp3.exit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ import sound.Consumer;
|
|||||||
import sound.Producer;
|
import sound.Producer;
|
||||||
|
|
||||||
public abstract class Transducer implements Consumer, Producer {
|
public abstract class Transducer implements Consumer, Producer {
|
||||||
public int rate;
|
public int rate;
|
||||||
|
|
||||||
public Transducer(Producer producer) {
|
public Transducer(Producer producer) {
|
||||||
//setProducer(producer);
|
//setProducer(producer);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getRate() {
|
public int getRate() {
|
||||||
return rate;
|
return rate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,22 +3,22 @@ package pipe;
|
|||||||
import java.io.RandomAccessFile;
|
import java.io.RandomAccessFile;
|
||||||
|
|
||||||
public class Client {
|
public class Client {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
try {
|
try {
|
||||||
// Connect to the pipe
|
// Connect to the pipe
|
||||||
RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\detest", "rw");
|
RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\detest", "rw");
|
||||||
String echoText = "Hello word\n";
|
String echoText = "Hello word\n";
|
||||||
|
|
||||||
// write to pipe
|
// write to pipe
|
||||||
pipe.write(echoText.getBytes());
|
pipe.write(echoText.getBytes());
|
||||||
|
|
||||||
// read response
|
// read response
|
||||||
String echoResponse = pipe.readLine();
|
String echoResponse = pipe.readLine();
|
||||||
System.out.println(echoResponse);
|
System.out.println(echoResponse);
|
||||||
pipe.close();
|
pipe.close();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,51 +4,51 @@ package pipe;
|
|||||||
* @author Vikram S Khatri vikram.khatri@us.ibm.com
|
* @author Vikram S Khatri vikram.khatri@us.ibm.com
|
||||||
*/
|
*/
|
||||||
public class Pipe {
|
public class Pipe {
|
||||||
static final int ERROR_PIPE_CONNECTED = 535;
|
static final int ERROR_PIPE_CONNECTED = 535;
|
||||||
static final int ERROR_BROKEN_PIPE = 109;
|
static final int ERROR_BROKEN_PIPE = 109;
|
||||||
static final int PIPE_ACCESS_DUPLEX = 0x00000003;
|
static final int PIPE_ACCESS_DUPLEX = 0x00000003;
|
||||||
static final int PIPE_WAIT = 0x00000000;
|
static final int PIPE_WAIT = 0x00000000;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
System.loadLibrary("pipe");
|
System.loadLibrary("pipe");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static final native int CreateNamedPipe(
|
public static final native int CreateNamedPipe(
|
||||||
String pipeName,
|
String pipeName,
|
||||||
int ppenMode,
|
int ppenMode,
|
||||||
int pipeMode,
|
int pipeMode,
|
||||||
int maxInstances,
|
int maxInstances,
|
||||||
int outBufferSize,
|
int outBufferSize,
|
||||||
int inBufferSize,
|
int inBufferSize,
|
||||||
int defaultTimeOut,
|
int defaultTimeOut,
|
||||||
int securityAttributes);
|
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(
|
public static final native int CreateFile(
|
||||||
String fileName,
|
String fileName,
|
||||||
int desiredAccess,
|
int desiredAccess,
|
||||||
int shareMode,
|
int shareMode,
|
||||||
int securityAttributes,
|
int securityAttributes,
|
||||||
int creationDisposition,
|
int creationDisposition,
|
||||||
int flagsAndAttributes,
|
int flagsAndAttributes,
|
||||||
int templateFile);
|
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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,82 +6,82 @@ import java.io.InputStream;
|
|||||||
|
|
||||||
public class TestPipe {
|
public class TestPipe {
|
||||||
|
|
||||||
private int namedPipeHandle;
|
private int namedPipeHandle;
|
||||||
private String pipeName, srcFile;
|
private String pipeName, srcFile;
|
||||||
private int pipeBuffer = 131072, fileBuffer = 8192;
|
private int pipeBuffer = 131072, fileBuffer = 8192;
|
||||||
|
|
||||||
public TestPipe(String pipeName, String srcFile) {
|
public TestPipe(String pipeName, String srcFile) {
|
||||||
this.pipeName = pipeName;
|
this.pipeName = pipeName;
|
||||||
this.srcFile = srcFile;
|
this.srcFile = srcFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void log(String message) {
|
private void log(String message) {
|
||||||
System.out.println(message);
|
System.out.println(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean createPipe() {
|
private boolean createPipe() {
|
||||||
namedPipeHandle = Pipe.CreateNamedPipe(
|
namedPipeHandle = Pipe.CreateNamedPipe(
|
||||||
pipeName,
|
pipeName,
|
||||||
Pipe.PIPE_ACCESS_DUPLEX,
|
Pipe.PIPE_ACCESS_DUPLEX,
|
||||||
Pipe.PIPE_WAIT,
|
Pipe.PIPE_WAIT,
|
||||||
5,
|
5,
|
||||||
pipeBuffer,
|
pipeBuffer,
|
||||||
pipeBuffer,
|
pipeBuffer,
|
||||||
0xffffffff,
|
0xffffffff,
|
||||||
0);
|
0);
|
||||||
if (namedPipeHandle == -1) {
|
if (namedPipeHandle == -1) {
|
||||||
log("CreateNamedPipe failed for " + pipeName + " for error Message " + Pipe.FormatMessage(Pipe.GetLastError()));
|
log("CreateNamedPipe failed for " + pipeName + " for error Message " + Pipe.FormatMessage(Pipe.GetLastError()));
|
||||||
} else {
|
} else {
|
||||||
log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle);
|
log("Named Pipe " + pipeName + " created successfully Handle=" + namedPipeHandle);
|
||||||
}
|
}
|
||||||
return namedPipeHandle != -1;
|
return namedPipeHandle != -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean connectToPipe() {
|
private boolean connectToPipe() {
|
||||||
log("Waiting for a client to connect to pipe " + pipeName);
|
log("Waiting for a client to connect to pipe " + pipeName);
|
||||||
boolean connected = Pipe.ConnectNamedPipe(namedPipeHandle, 0);
|
boolean connected = Pipe.ConnectNamedPipe(namedPipeHandle, 0);
|
||||||
if (!connected) {
|
if (!connected) {
|
||||||
int lastError = Pipe.GetLastError();
|
int lastError = Pipe.GetLastError();
|
||||||
if (lastError == Pipe.ERROR_PIPE_CONNECTED)
|
if (lastError == Pipe.ERROR_PIPE_CONNECTED)
|
||||||
connected = true;
|
connected = true;
|
||||||
}
|
}
|
||||||
log((connected ? "Connected to the pipe " : "Falied to connect to the pipe ") + pipeName);
|
log((connected ? "Connected to the pipe " : "Falied to connect to the pipe ") + pipeName);
|
||||||
return connected;
|
return connected;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void runPipe() {
|
public void runPipe() {
|
||||||
if (createPipe() && connectToPipe()) {
|
if (createPipe() && connectToPipe()) {
|
||||||
log("Client connected.");
|
log("Client connected.");
|
||||||
try {
|
try {
|
||||||
File f1 = new File(this.srcFile);
|
File f1 = new File(this.srcFile);
|
||||||
InputStream in = new FileInputStream(f1);
|
InputStream in = new FileInputStream(f1);
|
||||||
log("Sending data to the pipe");
|
log("Sending data to the pipe");
|
||||||
byte[] buf = new byte[fileBuffer];
|
byte[] buf = new byte[fileBuffer];
|
||||||
int len, bytesWritten;
|
int len, bytesWritten;
|
||||||
while ((len = in.read(buf)) > 0) {
|
while ((len = in.read(buf)) > 0) {
|
||||||
bytesWritten = Pipe.WriteFile(namedPipeHandle, buf, len);
|
bytesWritten = Pipe.WriteFile(namedPipeHandle, buf, len);
|
||||||
log("Sent " + len + "/" + bytesWritten + " bytes to the pipe");
|
log("Sent " + len + "/" + bytesWritten + " bytes to the pipe");
|
||||||
if (bytesWritten == -1) {
|
if (bytesWritten == -1) {
|
||||||
int errorNumber = Pipe.GetLastError();
|
int errorNumber = Pipe.GetLastError();
|
||||||
log("Error Writing to pipe " + Pipe.FormatMessage(errorNumber));
|
log("Error Writing to pipe " + Pipe.FormatMessage(errorNumber));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
in.close();
|
in.close();
|
||||||
Pipe.FlushFileBuffers(namedPipeHandle);
|
Pipe.FlushFileBuffers(namedPipeHandle);
|
||||||
Pipe.CloseHandle(namedPipeHandle);
|
Pipe.CloseHandle(namedPipeHandle);
|
||||||
Pipe.DisconnectNamedPipe(namedPipeHandle);
|
Pipe.DisconnectNamedPipe(namedPipeHandle);
|
||||||
log("Writing to the pipe completed.");
|
log("Writing to the pipe completed.");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
String pipeName = "\\\\.\\pipe\\detest";
|
String pipeName = "\\\\.\\pipe\\detest";
|
||||||
String fileName = "txt/bla.txt";
|
String fileName = "txt/bla.txt";
|
||||||
//fileName = "C:\\Users\\Rik\\Music\\Artists\\+44\\When Your Heart Stops Beating\\+44 - 155.mp3";
|
//fileName = "C:\\Users\\Rik\\Music\\Artists\\+44\\When Your Heart Stops Beating\\+44 - 155.mp3";
|
||||||
TestPipe testPipe = new TestPipe(pipeName, fileName);
|
TestPipe testPipe = new TestPipe(pipeName, fileName);
|
||||||
testPipe.runPipe();
|
testPipe.runPipe();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package sound;
|
package sound;
|
||||||
|
|
||||||
public interface Consumer {
|
public interface Consumer {
|
||||||
public void start(Producer producer);
|
public void start(Producer producer);
|
||||||
public void stop();
|
public void stop();
|
||||||
public void exit();
|
public void exit();
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user