I try to establish a websocketconnection. But my websocketcontent keeps being rejected as not being readable. Right now I establish a connection by using the following handler stack:
p.addLast(ClientSslHandler),
p.addLast(new HttpClientCodec()),
p.addLast(new HttpObjectAggregator(8192)),
p.addLast(new WebSocketClientProtocolHandler(...)),
p.addlast(new myHandler);
The problem is (I think) that HttpClientCodec keeps encoding my Websocketframes as Httpframes.
Thats why i think I can use HttpClientUpgradeHandler so deal with the handshake and then change to a pure Websocketconnection. Is this a viable solution? Or are there other workarounds?
Edit: changed WebSocketClientProtocolHandler to HttpClientUpgradeHandler
Edit2:
public class ShipSocketClient {
static final String URL = System.getProperty("url", "wss://10.2.3.44:4712");
public static void main(String[] args) throws Exception{
URI uri = new URI(URL);
String scheme = uri.getScheme() == null? "ws" : uri.getScheme();
final String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
final int port;
if (uri.getPort() == -1) {
if ("ws".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("wss".equalsIgnoreCase(scheme)) {
port = 443;
} else {
port = -1;
}
} else {
port = uri.getPort();
}
if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
System.err.println("Only WS(S) is supported.");
return;
}
final boolean ssl = "wss".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
List<String> CipherList = new ArrayList<String>();
CipherList.add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256");
//CipherList.add("TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8");
CipherList.add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256");
File vidksFile = new File("C:\\Users\\LETTAU\\Videos\\key.pem");
File vidcertFile = new File("C:\\Users\\LETTAU\\Videos\\cert.pem");
//CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
sslCtx = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.ciphers(CipherList)
.protocols("TLSv1.2")
.clientAuth(ClientAuth.REQUIRE)
.keyManager(vidcertFile, vidksFile)
.build();
}
else{
sslCtx = null;
}
EventLoopGroup group = new NioEventLoopGroup();
try{
WebSocketClientHandshaker wsHandShaker = WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, "ship", false, new DefaultHttpHeaders());
WebSocketClientProtocolHandler wsPrClHandler = new WebSocketClientProtocolHandler(wsHandShaker,true);
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
SslHandler ClientSslHandler = sslCtx.newHandler(ch.alloc(), host, port);
HttpClientCodec sourceCodec = new HttpClientCodec();
//New approach with HttpClientUpgradeHandler
//ShipClientProtocolHandler is a class which extends WebSocketClientProtocolHandler implements HttpClientUpgradeHandler.UpgradeCodec
HttpClientUpgradeHandler httpToWsUpgrader = new HttpClientUpgradeHandler(sourceCodec, new ShipClientProtocolHandler(wsHandShaker,true), 8096);
if (sslCtx != null) {
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(ClientSslHandler);
}
p.addLast(
new LoggingHandler(LogLevel.INFO),
sourceCodec,
new HttpObjectAggregator(8192),
//httpToWsUpgrader,
new LoggingHandler(LogLevel.INFO),
wsPrClHandler);
}
}
);
Channel ch = b.connect(uri.getHost(), port).sync().channel();
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String msg = console.readLine();
if (msg == null) {
break;
} else if ("ping".equals(msg.toLowerCase())) {
WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
ch.writeAndFlush(frame);
} else if ("cmi".equals(msg.toLowerCase())) {
ByteBuf bBuf = Unpooled.buffer(16);
bBuf.writeByte(0);
bBuf.writeByte(0);
BinaryWebSocketFrame bytebuffer = new BinaryWebSocketFrame(bBuf);
ch.writeAndFlush(bytebuffer);
} else if ("cdp".equals(msg.toLowerCase())) {
ByteBuf bBuf = Unpooled.buffer(1000);
//bBuf.writeByte(0);
//bBuf.writeByte(1);
ByteBufUtil.writeUtf8(bBuf,"{\"connectionHello\":[{\"phase\":\"ready\"},{\"waiting\":60000}]}");
BinaryWebSocketFrame bytebuffer = new BinaryWebSocketFrame(bBuf);
ch.writeAndFlush(bytebuffer);
} else {
WebSocketFrame frame = new TextWebSocketFrame(msg);
ch.writeAndFlush(frame);
}
}
} finally {
group.shutdownGracefully();
}
}
Edit3: Some addtitional Information on why i think HttpClientCodec is the problem:
This is what a received package looks like:
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 88 1d 11 30 53 54 41 54 45 5f 57 41 49 54 5f 43 |...0STATE_WAIT_C|
|00000010| 4c 4f 53 45 5f 43 4f 4e 4e 45 43 54 49 4f 4e |LOSE_CONNECTION |
+--------+-------------------------------------------------+----------------+
This is what an outgoing package looks like:
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 82 9d 12 1e 8c 5a 12 1f f7 78 71 71 e2 34 77 7d |.....Z...xqq.4w}|
|00000010| f8 33 7d 70 c4 3f 7e 72 e3 78 28 3c fe 3f 73 7a |.3}p.?~r.x(<.?sz|
|00000020| f5 78 6f |.xo |
+--------+-------------------------------------------------+----------------+
If you want to upgrade to WebSockets you should use the WebSocketClientHandshaker.
Netty itself contains an example for it:
https://github.com/netty/netty/tree/netty-4.1.28.Final/example/src/main/java/io/netty/example/http/websocketx/client
Related
Starting from the WiFiClient HTTPS Request example, I'm trying to get some code from a Github Gist using their API, but some parts of the file are missing
[...]
const char* host = "api.github.com";
const int httpsPort = 443;
String url = "/gists/0b3d5d67342c055cc9ba34b59d075da7";
// Use web browser to view and copy
// SHA1 fingerprint of the certificate
const char fingerprint[] PROGMEM = "59 74 61 88 13 CA 12 34 15 4D 11 0A C1 7F E6 67 07 69 42 F5";
void setup() {
Serial.begin(115200);
wifiSetup();
// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;
Serial.print("Connecting to ");
Serial.println(host);
Serial.printf("Using fingerprint '%s'\n", fingerprint);
client.setFingerprint(fingerprint);
if (!client.connect(host, httpsPort)) {
Serial.println("Connection failed");
return;
}
Serial.print("Requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: ESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Request sent");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("Headers received");
break;
}
}
String line = client.readStringUntil('\n');
line = line.substring(line.indexOf("content\":") + 10, line.indexOf("},") - 2);
Serial.println("Reply was:");
Serial.println("==========");
Serial.println(toHTML(line));
Serial.println("==========");
Serial.println("Setup end");
}
void loop() {
}
String toHTML(String source) {
Serial.print("toHTML length before/after: ");
Serial.print(source.length());
Serial.print("/");
source.replace("\\\\n", "==NEWLINE==");//Preserve document newlines
source.replace("\\n", "\n");//Replace newline
source.replace("==NEWLINE==", "\\n");
source.replace("\\\"", "\"");//Replace quotes
source.replace("\\t", "\t");//Replace tabs
Serial.println(source.length());
return source;
}
File I'm trying to get:
[...]
function printDebugMap() {
map.forEach((value, key) => {
printDebug(`${key} = [${value}]`);
});
}
</script>
</head>
<body>
<h1 id="AppName">Spreadsheet Automatico</h1>
<form onsubmit="return doNameInput()">
<p>Nome giocatori:</p>
<input type="text" id="nameBox">
<input type="submit" value="Submit">
</form>
<hr/>
What I actually get: some text is skipped
[...]
function printDebugMap() {
map.forEach((value, key) => {
printDebug(`${ype="text" id="nameBox">
<input type="submit" value="Submit">
</form>
<hr/>
when I add some random unrelated code which part is missing part changes, so I don't know what I'm doing wrong
I want filter the messages with type X from table below whose TO value is not equal to FROM value of any Type Y records in same table. (eg. ee) using Linq.
Message TO FROM Type
------- ---- ----- ------
aa 11 22 X
bb 33 44 X
cc 55 11 Y
dd 66 33 Y
ee 77 88 X
I have used this but not working
var messages1 = messages.Where(x => x.Type == 'X');
var messages2 = messages.Where(x => x.Type == 'Y');
var filteredMessages = messages1
.Where(x => !messages2.Any(y => y.From == x.To));
I am not able to reproduce your issue, although I am getting the correct output.
private static void Main(string[] args)
{
List<MessageItem> messages = new List<MessageItem>
{
new MessageItem
{
Message = "aa",
From = 22,
To = 11,
Type = "X"
},
new MessageItem
{
Message = "bb",
From = 44,
To = 33,
Type = "X"
},
new MessageItem
{
Message = "cc",
From = 11,
To = 55,
Type = "Y"
},
new MessageItem
{
Message = "dd",
From = 33,
To = 66,
Type = "Y"
},
new MessageItem
{
Message = "ee",
From = 88,
To = 77,
Type = "X"
}
};
var messages1 = messages.Where(x => x.Type == "X").ToList();
var messages2 = messages.Where(x => x.Type == "Y").ToList();
var filteredMessages = messages1.FindAll(x => !messages2.Any(y => x.To == y.From));
}
The model class:
public class MessageItem
{
public string Message { get; set; }
public int From { get; set; }
public int To { get; set; }
public string Type { get; set; }
}
Outputting:
I have a feature through which i am trying to post a message onto JMS topic.This feature is exposed as rest endpoint and is deployed in weblogic server.However , i face an issue which is onetime alone on weblogic startup. When i try to do an integration testing against the rest endpoint, it throws the following exception when the in the code snippet where session is trying to get created.
I have used IBM MQ Jars for JMS integration along with classes from Javax extension. (IBM MQ version - 7.0.1.9)
The following is my code snippet and exception thrown while trying to create a connection
private Connection createConnection() {
ombConnectionProperties = loadOmbConnectionProperties();
if (ombConnectionProperties.size() == 0 || ombConnectionProperties == null) {
buildBusinessException("Could not load OMB properties from environment resource", ExceptionStatus.INTERNAL_SERVER_ERROR);
}
try {
initSSL(ombConnectionProperties);
Hashtable<String, String> initialContextPropertiesMatrix = buildInitialContextPropertiesMatrix(ombConnectionProperties);
ic = new InitialContext(initialContextPropertiesMatrix);
if(ombConnectionProperties.getProperty("workflow.omb.queueManager")!=null) {
if(ic!=null) {
connectionFactory = (ConnectionFactory) ic.lookup(ombConnectionProperties.getProperty("workflow.omb.queueManager"));
}
}
if(connectionFactory!=null) {
connection = connectionFactory.createConnection();
}
} catch (Exception e) {
propagateException(e);
}
return connection;
}
private Session createSession() {
try {
if(connection!=null) {
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
}catch (Exception e) {
propagateException(e);
}
return session;
}
private Hashtable<String, String> buildInitialContextPropertiesMatrix(Properties ombConnectionProperties) {
Hashtable<String, String> initialContextPropertiesMatrix = new Hashtable<String, String>();
if (ombConnectionProperties.getProperty("workflow.omb.ldapProviderUrl") != null) {
initialContextPropertiesMatrix.put(PROVIDER_URL, ombConnectionProperties.getProperty("workflow.omb.ldapProviderUrl"));
}
initialContextPropertiesMatrix.put(INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
initialContextPropertiesMatrix.put(SECURITY_AUTHENTICATION, "simple");
if (ombConnectionProperties.getProperty("workflow.omb.ldapPrincipal") != null) {
initialContextPropertiesMatrix.put(SECURITY_PRINCIPAL, ombConnectionProperties.getProperty("workflow.omb.ldapPrincipal"));
}
if (ombConnectionProperties.getProperty("workflow.omb.ldapCredential") != null) {
initialContextPropertiesMatrix.put(SECURITY_CREDENTIALS, ombConnectionProperties.getProperty("workflow.omb.ldapCredential"));
}
return initialContextPropertiesMatrix;
}
public void publishWorkflowControlMessage(String workflowName, String action) {
try {
init();
String inboundControlMessageXML = buildWorkflowControlMessageXML(workflowName, action);
Destination destination = null;
if (ombConnectionProperties.getProperty("workflow.omb.topicName") != null) {
destination = (Destination) ic.lookup("cn=" + ombConnectionProperties.getProperty("workflow.omb.topicName"));
}
MessageProducer producer;
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage(inboundControlMessageXML);
producer.send(message);
} catch (Exception e) {
propagateException(e);
} finally {
try {
if(session!=null){
session.close();
}
if(connection!=null){
connection.close();
}
} catch (JMSException e) {
LOG.error("Exception Occured while closing the OMB connection", e);
throw new RuntimeException("Exception occured while trying to close the OMB connection", e);
}
}
}
workflow.omb.ldapProviderUrl = ldap://esdqa.csfb.net/ou=MQ,ou=Services,dc=csfb,dc=CS-Group,dc=com
workflow.omb.ldapPrincipal = uid=MQRDP,ou=People,o=Administrators,dc=CS- Group,dc=com
workflow.omb.ldapCredentials = aGMk643R
workflow.omb.queueManager = cn=USTCMN01_CF
workflow.omb.topicName = EDM.BIRS.RDP.ONEPPM.TO_RDA
workflow.omb.certificate.url = properties//jks//test//keystore.jks
workflow.omb.certificate.password = rFzv0UOS
P.S: The issue is seen only when i try to connect to JMS at the server startup.When i try for second time it works fine and from then on there are no issues and i am able to post message to the topic.I have no idea whats going wrong.However , when I execute this program as a standalone client it works fine.
Caused by: java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:417)
at java.lang.Short.parseShort(Short.java:120)
at java.lang.Short.valueOf(Short.java:153)
at java.lang.Short.valueOf(Short.java:178)
at com.ibm.msg.client.jms.internal.JmsReadablePropertyContextImpl.parseShort(JmsReadablePropertyContextImpl.java:752)
at com.ibm.msg.client.jms.internal.JmsReadablePropertyContextImpl.getShortProperty(JmsReadablePropertyContextImpl.java:326)
at com.ibm.msg.client.wmq.common.internal.WMQPropertyContext.getShortProperty(WMQPropertyContext.java:360)
at com.ibm.msg.client.wmq.internal.WMQSession.<init>(WMQSession.java:311)
at com.ibm.msg.client.wmq.internal.WMQConnection.createSession(WMQConnection.java:980)
at com.ibm.msg.client.jms.internal.JmsConnectionImpl.createSession(JmsConnectionImpl.java:572)
at com.ibm.mq.jms.MQConnection.createSession(MQConnection.java:339)
Am adding the properties in the connection object which I evaluated in debug bug. When I invoke the call the very first time the size of the object is 77 and when I invoke the call again then the size is increased to 78 which resolves it and it was the property "XMSC_ADMIN_OBJECT_TYPE" which is missing in the initial connection object. I am pasting the entire list below
0 = {HashMap$Entry#18264} "XMSC_WMQ_HEADER_COMP" -> " size = 1"
1 = {HashMap$Entry#18265} "wildcardFormat" -> "0"
2 = {HashMap$Entry#18266} "XMSC_WMQ_BROKER_PUBQ" -> "SYSTEM.BROKER.DEFAULT.STREAM"
3 = {HashMap$Entry#18267} "XMSC_WMQ_CONNECTION_TAG" ->
4 = {HashMap$Entry#18268} "XMSC_WMQ_BROKER_SUBQ" -> "SYSTEM.JMS.ND.SUBSCRIBER.QUEUE"
5 = {HashMap$Entry#18269} "XMSC_WMQ_SHARE_CONV_ALLOWED" -> "1"
6 = {HashMap$Entry#18270} "XMSC_WMQ_SSL_SOCKET_FACTORY" -> "null"
7 = {HashMap$Entry#18271} "multicast" -> "0"
8 = {HashMap$Entry#18272} "brokerVersion" -> "-1"
9 = {HashMap$Entry#18273} "XMSC_WMQ_MESSAGE_SELECTION" -> "0"
10 = {HashMap$Entry#18274} "XMSC_WMQ_CLEANUP_LEVEL" -> "1"
11 = {HashMap$Entry#18275} "XMSC_CLIENT_ID" -> "null"
12 = {HashMap$Entry#18276} "XMSC_WMQ_SUBSCRIPTION_STORE" -> "1"
13 = {HashMap$Entry#18277} "XMSC_WMQ_RECEIVE_EXIT" -> "null"
14 = {HashMap$Entry#18278} "XMSC_WMQ_SSL_CERT_STORES_COL" -> "null"
15 = {HashMap$Entry#18279} "XMSC_WMQ_CLIENT_RECONNECT_TIMEOUT" -> "1800"
16 = {HashMap$Entry#18280} "XMSC_WMQ_RECEIVE_EXIT_INIT" -> "null"
17 = {HashMap$Entry#18281} "XMSC_WMQ_TEMP_TOPIC_PREFIX" ->
18 = {HashMap$Entry#18282} "XMSC_WMQ_CONNECT_OPTIONS" -> "0"
19 = {HashMap$Entry#18283} "XMSC_WMQ_MAP_NAME_STYLE" -> "true"
20 = {HashMap$Entry#18284} "XMSC_WMQ_MSG_BATCH_SIZE" -> "10"
21 = {HashMap$Entry#18285} "XMSC_WMQ_USE_CONNECTION_POOLING" -> "true"
22 = {HashMap$Entry#18286} "XMSC_WMQ_TARGET_CLIENT_MATCHING" -> "true"
23 = {HashMap$Entry#18287} "XMSC_USERID" ->
24 = {HashMap$Entry#18288} "XMSC_WMQ_SPARSE_SUBSCRIPTIONS" -> "false"
25 = {HashMap$Entry#18289} "XMSC_WMQ_MSG_COMP" -> " size = 1"
26 = {HashMap$Entry#18290} "XMSC_WMQ_MAX_BUFFER_SIZE" -> "1000"
27 = {HashMap$Entry#18291} "XMSC_WMQ_CONNECTION_MODE" -> "1"
28 = {HashMap$Entry#18292} "XMSC_WMQ_CLIENT_RECONNECT_OPTIONS" -> "0"
29 = {HashMap$Entry#18293} "XMSC_WMQ_CHANNEL" -> "USTCMN01_CLS_01"
30 = {HashMap$Entry#18294} "XMSC_WMQ_TEMP_Q_PREFIX" ->
31 = {HashMap$Entry#18295} "XMSC_WMQ_RECEIVE_ISOLATION" -> "0"
32 = {HashMap$Entry#18296} "XMSC_WMQ_POLLING_INTERVAL" -> "5000"
33 = {HashMap$Entry#18297} "XMSC_CONNECTION_TYPE" -> "1"
34 = {HashMap$Entry#18298} "XMSC_WMQ_QUEUE_MANAGER" -> "USTCMN01"
35 = {HashMap$Entry#18299} "XMSC_WMQ_PROCESS_DURATION" -> "0"
36 = {HashMap$Entry#18300} "XMSC_WMQ_CLONE_SUPPORT" -> "0"
37 = {HashMap$Entry#18301} "XMSC_WMQ_SSL_CIPHER_SUITE"
..............
........
48 = {HashMap$Entry#18312} "XMSC_ADMIN_OBJECT_TYPE" -> "20"
..........
............
I am trying to open a fileChooser using javafx FileChooser I'm assigning a listner to the FXML button via the controller the application loads fine, however when I click the button the file chooser opens followed promptly by a crash.
This is driving me nuts, I think it is todo with the implementation of the xcode interface from java, however I am totally lost on this one.
Has anymore come across this before when using JavaFx ??
my stack trace is:
012-12-06 23:24:02.732 java[16800:707] Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType
2012-12-06 23:24:02.733 java[16800:707] (
0 CoreFoundation 0x00007fff8b8c20a6 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff858393f0 objc_exception_throw + 43
2 CoreFoundation 0x00007fff8b8c1ee8 +[NSException raise:format:arguments:] + 104
3 Foundation 0x00007fff89f926a2 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 189
4 AppKit 0x00007fff85d5356c -[NSEvent _initWithCGSEvent:eventRef:] + 2782
5 AppKit 0x00007fff85fd43ea +[NSEvent eventWithCGEvent:] + 243
6 libglass.dylib 0x00000001630e300f listenTouchEvents + 31
7 CoreGraphics 0x00007fff8be07115 processEventTapData + 150
8 CoreGraphics 0x00007fff8be06f68 _CGYPostEventTapData + 189
9 CoreGraphics 0x00007fff8be0c26a _XPostEventTapData + 107
10 CoreGraphics 0x00007fff8be0c362 CGYEventTap_server + 106
11 CoreGraphics 0x00007fff8be07056 eventTapMessageHandler + 30
12 CoreFoundation 0x00007fff8b831410 __CFMachPortPerform + 288
13 CoreFoundation 0x00007fff8b8312d9 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
14 CoreFoundation 0x00007fff8b831019 __CFRunLoopDoSource1 + 153
15 CoreFoundation 0x00007fff8b86419f __CFRunLoopRun + 1775
16 CoreFoundation 0x00007fff8b8636b2 CFRunLoopRunSpecific + 290
17 HIToolbox 0x00007fff882d40a4 RunCurrentEventLoopInMode + 209
18 HIToolbox 0x00007fff882d3d84 ReceiveNextEventCommon + 166
19 HIToolbox 0x00007fff882d3cd3 BlockUntilNextEventMatchingListInMode + 62
20 AppKit 0x00007fff85c74613 _DPSNextEvent + 685
21 AppKit 0x00007fff85c73ed2 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
22 libglass.dylib 0x00000001630ce8c3 +[GlassApplication enterNestedEventLoopWithEnv:] + 163
23 libglass.dylib 0x00000001630d24d3 -[DialogDispatcher runModal] + 163
24 Foundation 0x00007fff8a012220 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] + 212
25 Foundation 0x00007fff8a0120c8 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] + 131
26 libglass.dylib 0x00000001630d29c5 Java_com_sun_glass_ui_mac_MacCommonDialogs__1showFileOpenChooser + 981
27 ??? 0x0000000101dc3f90 0x0 + 4326178704
)
2012-12-06 23:24:02.734 java[16800:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType'
First throw call stack:
(
0 CoreFoundation 0x00007fff8b8c20a6 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff858393f0 objc_exception_throw + 43
2 CoreFoundation 0x00007fff8b8c1ee8 +[NSException raise:format:arguments:] + 104
3 Foundation 0x00007fff89f926a2 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 189
4 AppKit 0x00007fff85d5356c -[NSEvent _initWithCGSEvent:eventRef:] + 2782
5 AppKit 0x00007fff85fd43ea +[NSEvent eventWithCGEvent:] + 243
6 libglass.dylib 0x00000001630e300f listenTouchEvents + 31
7 CoreGraphics 0x00007fff8be07115 processEventTapData + 150
8 CoreGraphics 0x00007fff8be06f68 _CGYPostEventTapData + 189
9 CoreGraphics 0x00007fff8be0c26a _XPostEventTapData + 107
10 CoreGraphics 0x00007fff8be0c362 CGYEventTap_server + 106
11 CoreGraphics 0x00007fff8be07056 eventTapMessageHandler + 30
12 CoreFoundation 0x00007fff8b831410 __CFMachPortPerform + 288
13 CoreFoundation 0x00007fff8b8312d9 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
14 CoreFoundation 0x00007fff8b831019 __CFRunLoopDoSource1 + 153
15 CoreFoundation 0x00007fff8b86419f __CFRunLoopRun + 1775
16 CoreFoundation 0x00007fff8b8636b2 CFRunLoopRunSpecific + 290
17 HIToolbox 0x00007fff882d40a4 RunCurrentEventLoopInMode + 209
18 HIToolbox 0x00007fff882d3d84 ReceiveNextEventCommon + 166
19 HIToolbox 0x00007fff882d3cd3 BlockUntilNextEventMatchingListInMode + 62
20 AppKit 0x00007fff85c74613 _DPSNextEvent + 685
21 AppKit 0x00007fff85c73ed2 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
22 libglass.dylib 0x00000001630ce8c3 +[GlassApplication enterNestedEventLoopWithEnv:] + 163
23 libglass.dylib 0x00000001630d24d3 -[DialogDispatcher runModal] + 163
24 Foundation 0x00007fff8a012220 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] + 212
25 Foundation 0x00007fff8a0120c8 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] + 131
26 libglass.dylib 0x00000001630d29c5 Java_com_sun_glass_ui_mac_MacCommonDialogs__1showFileOpenChooser + 981
27 ??? 0x0000000101dc3f90 0x0 + 4326178704
)
libc++abi.dylib: terminate called throwing an exception
The Controller code is:
public class AppController implements Initializable {
#FXML
private TableView<Transactions> tableTranactions;
#FXML
private TableColumn<Transactions, Integer> accountID;
#FXML
private TableColumn<Transactions, String> colTranDate;
#FXML
private TableColumn<Transactions, String> colDescription;
#FXML
private TableColumn<Transactions, Double> colAmount;
#FXML
private TableColumn<Transactions, Integer> colCompany;
#FXML
private TableColumn<Transactions, String> colTransType;
#FXML
private Button btnClear;
#FXML
private Button btnFileChoose;
#FXML
private LineChart<String, Double> chartLineSpendingByMonth;
#FXML
private Pane paneGraph;
#FXML
private Pane paneGraphWeek;
#FXML
private Pane paneAddRecord;
#FXML
private PieChart pieSpendingCatalogue;
#FXML
private Label lblTransactions;
#FXML
private TextField txtFilePath;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
System.out.println("starting application");
showTransactions();
btnFileChoose.setOnAction(new EventHandler<ActionEvent>() {
/**
WHAT IS CAUSING THIS CODE SEGMENT TO FAIL??? **/
#Override
public void handle(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select File");
//Set extension filter
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("CSV", ".csv");
fileChooser.getExtensionFilters().add(extFilter);
//Show open file dialog
File file = fileChooser.showOpenDialog(null);
if(file!=null)
txtFilePath.setText(file.getPath());
}
});
}
#FXML
private void showTransactions()
{
hideAll();
tableTranactions.setVisible(true);
btnClear.setVisible(true);
accountID.setCellValueFactory(new PropertyValueFactory<Transactions, Integer>("accountid"));
colTranDate.setCellValueFactory(new PropertyValueFactory<Transactions, String>("tranDate"));
colDescription.setCellValueFactory(new PropertyValueFactory<Transactions, String>("descrip"));
colAmount.setCellValueFactory(new PropertyValueFactory<Transactions, Double>("amount"));
colCompany.setCellValueFactory(new PropertyValueFactory<Transactions, Integer>("comid"));
colTransType.setCellValueFactory(new PropertyValueFactory<Transactions, String>("transType"));
updateTransactionData();
}
public void hideAll()
{
tableTranactions.setVisible(false);
btnClear.setVisible(false);
paneGraph.setVisible(false);
paneGraphWeek.setVisible(false);
paneAddRecord.setVisible(false);
}
public void clearTable()
{
ObservableList<Transactions> data = tableTranactions.getItems();
data.removeAll(data);
}
public void updateTransactionData()
{
TransactionDAO trans = new TransactionDAO();
ObservableList<Transactions> data = tableTranactions.getItems();
data.addAll(trans.getAll());
}
public void showAddRecord()
{
hideAll();
paneAddRecord.setVisible(true);
}
public void showHistoric()
{
hideAll();
CatalogueSpendingDAO catalogue = new CatalogueSpendingDAO();
ObservableList<PieChart.Data> data = pieSpendingCatalogue.getData();
ObservableList<CatalogueSpending_total> values = catalogue.getTotal();
data.removeAll(data);
for(CatalogueSpending_total i : values)
{
data.add(new PieChart.Data(i.getDescription(), i.getTotal()));
}
// start adding line chart
ObservableList<XYChart.Series<String, Double>> spendingByMonthData = chartLineSpendingByMonth.getData();
Boolean add = false;
if(spendingByMonthData.size() > 0)
spendingByMonthData.removeAll(spendingByMonthData);
XYChart.Series<String, Double> series = (spendingByMonthData.size() > 0 ? spendingByMonthData.get(0): null);
if(series == null)
{
series = new XYChart.Series<String, Double>();
add = true;
}
SpendingByMonthDAO spendingByMonthDAO = new SpendingByMonthDAO();
ObservableList<SpendingByMonth> spendingByMonthDatabase = spendingByMonthDAO.getTotal();
for(SpendingByMonth i : spendingByMonthDatabase)
{
series.getData().add(new XYChart.Data<String, Double>(i.getDate(), i.getTotal()));
}
spendingByMonthData.size();
spendingByMonthData.add(0,series);
pieSpendingCatalogue.animatedProperty();
paneGraph.setVisible(true);
}
public void showWeeklyCharts()
{
hideAll();
//TODO populate the graphs here
paneGraphWeek.setVisible(true);
}
}
System Information
java version: Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
OS: OS X 10.8.2
SOLVED:
Runtime compiler was a much older version of hava Java 1.7.0
Also found this link:
https://forums.oracle.com/forums/thread.jspa?threadID=2444130
It seems once I updated the jdk via http://jdk7.java.net/download.html to java version 7u10 Build b18 the problem goes away :-)
I want to convert an image and an audio file into a binary stream, process it and then reconstruct the image from the same binary stream in Java. How can I do that? Has anybody worked on this? Please help me out as soon as possible. Any hints or pseudocode will be highly appreciated.
This is how I tried to do it but it just creates an empty file while reconstructing the image.
For image to binary:-
File file = new File("E:\\image.jpg");
BufferedImage img = ImageIO.read(file);
// write image to byte array in-memory (jpg format)
ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", b);
byte[] jpgByteArray = b.toByteArray();
// convert it to a String with 0s and 1s
StringBuilder sb = new StringBuilder();
for (byte by : jpgByteArray) {
sb.append(Integer.toBinaryString(by & 0xFF));
For binary to image:-
byte[] original = obj.orig_seq.getBytes();
InputStream in = new ByteArrayInputStream(original);
BufferedImage img = ImageIO.read(in);
ImageIO.write(img, "jpg",
new File("E:\\mypic_new.jpg"));
To use Binary String you can use this
StringBuilder sb = new StringBuilder();
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream("YourImage.jpg"))) {
for (int i; (i = is.read()) != -1;) {
String temp = "0000000" + Integer.toBinaryString(i).toUpperCase();
if (temp.length() == 1) {
sb.append('0');
}
temp = temp.substring(temp.length() - 8);
sb.append(temp).append(' ');
}
}
System.out.print(sb);
and here is your desired output
0000000 11111111 00000111 00011111 00101111 01111111
you can also use Hexadecimal and convert your file into a simple string like this (suggestion)
StringBuilder sb = new StringBuilder();
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream("YourFile.txt"))) {
for (int i; (i = is.read()) != -1;) {
String temp = Integer.toHexString(i).toUpperCase();
if (temp.length() == 1) {
sb.append('0');
}
sb.append(temp).append(' ');
}
}
System.out.print(sb);
and the output would be something like this
00 FF 07 1F 2F 7F