-
Notifications
You must be signed in to change notification settings - Fork 0
/
SO500Q_backup.txt
500 lines (500 loc) · 525 KB
/
SO500Q_backup.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
How can I Java webstart multiple, dependent, native libraries? : Example: I have two shared objects (same should apply to .dlls). The first shared object is from a third-party library, we'll call it libA.so. I have wrapped some of this with JNI and created my own library, libB.so. Now libB depends on libA.When webstarting, both libraries are places in some webstart working area. My java code attempts to load libB. At this point the system loader will attempt to load libA which is not in the system library path (java.library.path won't help this). The end result is that libB has an unsatisfied link and cannot be used. I have tried loading libA before libB, but that still does not work. Seems the OS wants to do that loading for me. Is there any way I can make this work other than statically compiling?
Java Logging vs Log4J : Is it still worth to add the log4j library to a Java 5 project just to loglet's say some exceptions to a file with some nice rollover settings.Or will the standard util.logging facility do the job as well?What do you think?
mtom serving word doc : has anyone been able to serve a word doc using metro (webservices) as a mtom stream? Does anyone have example, or know where there is example code please for client and server?
How do I create a thread dump of a Java Web Start application : Is it possible to get a thread dump of a Java Web Start application? And if so, how?It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically?In the Java Web Start Console I can get a list of threads by pressing 't' but stacktraces are not included.If answers require certain java versions, please say so.
How can I access the classes loaded by Java Web Start when dynamically compiling code? : I am dynamically compiling code in my client application. When I start the application with Java Web Start I get an exception. The exception only occurs when it is run through Java Web Start.//The exceptionevolver.core.model.change.execution.ExecutionException: Compilation failed!DynamicComparator.java:2: package evolver.core.model.i does not existimport evolver.core.model.i.IDefaultObject; ^DynamicComparator.java:9: cannot find symbolsymbol : class PropertyBaglocation: class DynamicComparatorPropertyBag b2 = new PropertyBag(dob2); ^The PropertyBag above should have been provided by the JNLPClassloader asit is part of one of the files that are downloaded by JWSThe code that causes the problem looks like this.public static int compile(String javaFileName) { ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintWriter w = new PrintWriter(os); int res = com.sun.tools.javac.Main.compile(new String[]{-d, ./, javaFileName}, w); if (res != 0) throw new ExecutionException(Compilation failed! + \n\n + os.toString()); return res;}Any help will be very appreciated!
Turn an array of pixels into an Image object with Java's ImageIO? : I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:public Image getImageFromArray(int[] pixels, int width, int height) { MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width); Toolkit tk = Toolkit.getDefaultToolkit(); return tk.createImage(mis);}Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.
Objections against Java Webstart? : Since the release of Adobe AIR I am wondering why Java Web Start has not gained more attention in the past as to me it seems to be very similar, but web start is available for a much longer time.Is it mainly because of bad marketing from Sun, or are there more technical concerns other than the need of having the right JVM installed? Do you have bad experiences using Web Start? If yes, which? What are you recommendations when using Web Start for distributing applications?
What are the advantages/disadvantages for distributing multi stage tasks via JMS or JavaSpaces? : When trying to distribute work that requires a multiple stage processing pipeline what are the communication, synchronization and throughput costs limitations in JMS vs JavaSpaces?
Using Blitz implementation of JavaSpaces : I have great doubts about this forum, but I am willing to be pleasantly surprised ;) Kudos and great karma to those who get me back on track.I am attempting to use the blitz implementation of JavaSpaces (a href=http://www.dancres.org/blitz/blitz_js.html rel=nofollow noreferrerhttp://www.dancres.org/blitz/blitz_js.html) to implement the ComputeFarm example provided at a href=http://today.java.net/pub/a/today/2005/04/21/farm.html rel=nofollow noreferrerhttp://today.java.net/pub/a/today/2005/04/21/farm.htmlThe in memory example works fine, but whenever I attempt to use the blitz out-of-box implementation i get the following error:(yes com.sun.jini.mahalo.TxnMgrProxy is in the class path)2008-09-24 09:57:37.316 ERROR [Thread-4] JavaSpaceComputeSpace 155 - Exception while taking task.java.rmi.ServerException: RemoteException in server thread; nested exception is: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:644) at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597) at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212) at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568) at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540) at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778) at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148) at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244) at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241) at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136) at java.lang.Thread.run(Thread.java:595) at com.sun.jini.jeri.internal.runtime.Util.__________EXCEPTION_RECEIVED_FROM_SERVER__________(Util.java:108) at com.sun.jini.jeri.internal.runtime.Util.exceptionReceivedFromServer(Util.java:101) at net.jini.jeri.BasicInvocationHandler.unmarshalThrow(BasicInvocationHandler.java:1303) at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvocationHandler.java:832) at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocationHandler.java:659) at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.java:528) at $Proxy0.take(Unknown Source) at org.dancres.blitz.remote.BlitzProxy.take(BlitzProxy.java:157) at compute.impl.javaspaces.JavaSpaceComputeSpace.take(JavaSpaceComputeSpace.java:138) at example.squares.SquaresJob.collectResults(SquaresJob.java:47) at compute.impl.AbstractJobRunner$CollectThread.run(AbstractJobRunner.java:28)Caused by: java.rmi.UnmarshalException: unmarshalling method/arguments; nested exception is: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:619) at com.sun.jini.jeri.internal.runtime.ObjectTable$6.run(ObjectTable.java:597) at net.jini.export.ServerContext.doWithServerContext(ServerContext.java:103) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch0(ObjectTable.java:595) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.access$700(ObjectTable.java:212) at com.sun.jini.jeri.internal.runtime.ObjectTable$5.run(ObjectTable.java:568) at com.sun.jini.start.AggregatePolicyProvider$6.run(AggregatePolicyProvider.java:527) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:565) at com.sun.jini.jeri.internal.runtime.ObjectTable$Target.dispatch(ObjectTable.java:540) at com.sun.jini.jeri.internal.runtime.ObjectTable$RD.dispatch(ObjectTable.java:778) at net.jini.jeri.connection.ServerConnectionManager$Dispatcher.dispatch(ServerConnectionManager.java:148) at com.sun.jini.jeri.internal.mux.MuxServer$2.run(MuxServer.java:244) at com.sun.jini.start.AggregatePolicyProvider$5.run(AggregatePolicyProvider.java:513) at java.security.AccessController.doPrivileged(Native Method) at com.sun.jini.jeri.internal.mux.MuxServer$1.run(MuxServer.java:241) at com.sun.jini.thread.ThreadPool$Worker.run(ThreadPool.java:136) at java.lang.Thread.run(Thread.java:595)Caused by: java.lang.ClassNotFoundException: com.sun.jini.mahalo.TxnMgrProxy at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at net.jini.loader.pref.PreferredClassLoader.loadClass(PreferredClassLoader.java:922) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:242) at net.jini.loader.pref.PreferredClassProvider.loadClass(PreferredClassProvider.java:613) at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247) at net.jini.loader.ClassLoading.loadClass(ClassLoading.java:138) at net.jini.io.MarshalInputStream.resolveClass(MarshalInputStream.java:296) at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1544) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1466) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348) at com.sun.jini.jeri.internal.runtime.Util.unmarshalValue(Util.java:221) at net.jini.jeri.BasicInvocationDispatcher.unmarshalArguments(BasicInvocationDispatcher.java:1049) at net.jini.jeri.BasicInvocationDispatcher.dispatch(BasicInvocationDispatcher.java:599) ... 17 more
Can i update a signed jar using an ANT Task? : Hi I am trying to deploy an application using webstart. I have a requirement to update a jar which is signed before i actually deploy( basically to update the IP/Port info). I am trying to use ANT to update the jar. Is there are way to achive this?
Loading animated gif from JAR file into ImageIcon : I'm trying to create a ImageIcon from a animated gif stored in a jar file.ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream(animated.gif)));The image loads, but only the first frame of the animated gif. The animation does not play. If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:ImageIcon imageIcon = new ImageIcon(/path/on/filesystem/animated.gif);How can I load an animated gif into an ImageIcon from a jar file?EDIT: Here is a complete test case, why doesn't this display the animation?import javax.imageio.ImageIO;import javax.swing.*;public class AnimationTest extends JFrame { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { AnimationTest test = new AnimationTest(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }); } public AnimationTest() { super(); try { JLabel label = new JLabel(); ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream(animated.gif))); label.setIcon(imageIcon); imageIcon.setImageObserver(label); add(label); pack(); } catch (Exception e) { e.printStackTrace(); } }}
Emulating user input for java.util.Scanner : I'm writing a game in Java, and I want the user to be able to provide input from both the command line and my GUI. Currently, I use this method to get input: static String getInput(){ System.out.println(Your move:); Scanner sc = new Scanner(System.in); return sc.nextLine(); }I want to keep using this, but let a mousePressed event emulate the user actually typing in their input as well. It's not that efficient of a solution, but it makes sense in my application. So the question is: how do I simulate a user typing to System.in from the code side?
Do I have to explicitly call System.exit() in a Webstart application? : Recently I converted a Swing application to Webstart. The process was pretty straightforward, but I found that after I close all windows, my application's JVM did not terminate. The thread dump showed that there are a couple of non-daemon threads, notably Swing's EDT, AWT and a couple of websart related threads. The actual strategy used is that each window increments a counter when it is created and decrements one when it is closed. The default close operation is DISPOSE_ON_CLOSE. Wen the counter reaches zero, I stop all threadpools and release all JNI resources.When I launched the application from a bat file (same JARs), it terminated fine when all windows were closed, so I figured that the problem has something to do with Webstart.Now the questions:Can anybody tell me what exactly is happening? Why does Webstart leave zombie JVMs? Is there a way to release the Webstart resources explicitly without halting the JVM? I've always had the opinion that calling System.exit() encourages the sloppy practice of not releasing your resources and relying on the OS to clean up after you (which can lead to nasty surprises if you reuse the code later)... am I missing something?See also the a href=http://stackoverflow.com/questions/216315/what-is-the-best-way-to-detect-whether-an-application-is-launched-by-webstartfollowup question for detecting whether the app has been launched by Webstart.
Which annotation should I use: @IdClass or @EmbeddedId : The JPA (Java Persistence API) specification has 2 different ways to specify entity composite keys: @IdClass and @EmbeddedId. I'm using both annotations on my mapped entities, but it turns out to be a big mess to people who aren't very familiar with JPA. I want to adopt only one way to specify composite keys. Which one is really the best? Why?
What is the best way to detect whether an application is launched by Webstart : As it was made clear in my a href=http://stackoverflow.com/questions/212009/do-i-have-to-explicitly-call-systemexit-in-a-webstart-applicationrecent question, Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6).I want to restrict this hack as much as possible and I am looking for a reliable way to detect whether the application is running under Webstart. Right now I am checking that the value of the system property webstart.version is not null, but I couldn't find any guarantees in the documentation that this property should be set by future versions/alternative implementations.Are there any better ways (preferably ones that do not ceate a dependency on the the webstart API?)
Write dpi metadata to a jpeg image in Java : I am trying to programatically set the dpi metadata of an jpeg image in Java. The source of the image is a scanner, so I get the horizontal/vertical resolution from TWAIN, along with the image raw data. I'd like to save this info for better print results.Here's the code I have so far. It saves the raw image (byteArray) to a JPEG file, but it ignores the X/Ydensity information I specify via IIOMetadata. Any advice what I'm doing wrong? Any other solution (third-party library, etc) would be welcome too. import java.awt.image.BufferedImage;import java.awt.image.WritableRaster;import java.io.File;import javax.imageio.IIOImage;import javax.imageio.ImageIO;import javax.imageio.ImageTypeSpecifier;import javax.imageio.metadata.IIOMetadata;import javax.imageio.plugins.jpeg.JPEGImageWriteParam;import javax.imageio.stream.ImageOutputStream import org.w3c.dom.Element; import com.sun.imageio.plugins.jpeg.JPEGImageWriter;public boolean saveJpeg(int[] byteArray, int width, int height, int dpi, String file){ BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); WritableRaster wr = bufferedImage.getRaster(); wr.setPixels(0, 0, width, height, byteArray); try { // Image writer JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix(jpeg).next(); ImageOutputStream ios = ImageIO.createImageOutputStream(new File(file)); imageWriter.setOutput(ios); // Compression JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam(); jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); jpegParams.setCompressionQuality(0.85f); // Metadata (dpi) IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), jpegParams); Element tree = (Element)data.getAsTree(javax_imageio_jpeg_image_1.0); Element jfif = (Element)tree.getElementsByTagName(app0JFIF).item(0); jfif.setAttribute(Xdensity, Integer.toString(dpi)); jfif.setAttribute(Ydensity, Integer.toString(dpi)); jfif.setAttribute(resUnits, 1); // density is dots per inch // Write and clean up imageWriter.write(data, new IIOImage(bufferedImage, null, null), jpegParams); ios.close(); imageWriter.dispose(); } catch (Exception e) { return false; } return true;}Thanks!
How many Web service objects are created in JAX-WS RI? : When I annotate a Java class with @WebService and use it with JAX-WS RI (Metro), how many objects of my class does the JAX-WS RI create? Is there at most one object at all times or (perhaps depending on usage) can there be more instances be created?
Is there a .NET equivalent of Java Web Start? : Is there a .NET equivalent of Java Web Start?I want a one-click, from the web, lightweight install for a group of .NET assemblies and resources. Hopefully, the link would continue to keep the user updated with the latest version, similar to what Java Web Start does. The application is written in F#, for what it's worth.
Enabling https for Java Webstart : I have a swing application deployed in HTTP Server. Users use the browser to point an URL and install the client using java webstart. Now I need to enable https access to my application deployed on HTTP server. I am using JDK 1.5 as default jdk supported in the jnlp file. For time being I use a self signed certificate to the sign the jars (by default created using Sun's jarsigner, keytool, etc, utils).Solution/steps would be much appreciated.Thanks in advanceRamesh
How do I use JDK6 ToolProvider and JavaCompiler with the context classloader? : My usage case is compiling generated source files from a java program using the ToolProvider and JavaCompiler classes provided in JDK 6. The source files contain references to classes in the context classloader (it runs in a J2EE container), but not in the system classloader. My understanding is that by default the ToolProvider will create the JavaCompiler instance with the system classloader.Is there a way to specify a classloader for JavaCompiler to use?I tried this approach, modified from something on IBM DeveloperWorks:FileManagerImpl fm = new FileManagerImpl(compiler.getStandardFileManager(null, null, null););with FileManagerImpl defined as:static final class FileManagerImpl extends ForwardingJavaFileManagerJavaFileManager { public FileManagerImpl(JavaFileManager fileManager) { super(fileManager); } @Override public ClassLoader getClassLoader(JavaFileManager.Location location) { new Exception().printStackTrace(); return Thread.currentThread().getContextClassLoader(); }}The stacktrace indicates it's only called once during annotation processing. I verified the class referenced in the source file to be compiled is not on the system classpath but is available from the context classloader.
Can Scanner in Java read text from a dialog box : Scanner can only get input from system console? not be able to get from any dialog window?Thanks.
Tiff compression using Java ImageIO : I am having issues converting a png to tiff. The conversion goes fine, but the image is huge. I think the issue is that I am not doing the compression correctly? Anyone have any suggestions??Here is the code samplepublic static void test() throws IOException { // String fileName = 4958813_1; String fileName = 4848970_1; String inFileType = .PNG; String outFileType = .TIFF; ImageIO.scanForPlugins(); File fInputFile = new File(I:/HPF/UU/ + fileName + inFileType); InputStream fis = new BufferedInputStream(new FileInputStream( fInputFile)); PNGImageReaderSpi spi = new PNGImageReaderSpi(); ImageReader reader = spi.createReaderInstance(); ImageInputStream iis = ImageIO.createImageInputStream(fis); reader.setInput(iis, true); BufferedImage bi = reader.read(0); TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi(); ImageWriter writer = tiffspi.createWriterInstance(); //IteratorImageWriter iter = ImageIO.getImageWritersByFormatName(TIFF); //ImageWriter writer = iter.next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType(LZW); param.setCompressionQuality(0.5f); File fOutputFile = new File(I:\\HPF\\UU\\ + fileName + outFileType); ImageOutputStream ios = ImageIO.createImageOutputStream(fOutputFile); writer.setOutput(ios); writer.write(bi);}
How to add a driver to javax.comm? Serial port programming in Java : I am trying to use a RS-232 serial port on my PC with javax.comm class. I am newby on that API, so first of all I go through the documentation and I find out that the first thing you should do is list all the ports from the class CommPortListener and pick up one of them.That worked just fine! Problem is, now, that my port is missing. It lists the /dev/ttyS0 and /dev/ttyS1 ports, non existents on my computer. My ports (I have been working with them several times) are /dev/ttySNX0 and /dev/ttySNX1.Again surfing the web I find out that I should do something like register or load the driver of my card onto the API system, stuff that could be done in previous versions, but not now. Moreover, I tried to do it under windows and they offer me a generic version of the API, with needs some RXTX application which is starting to beat me.I would thank any sugestions, links to documentation... something... that allow me to use my serial ports through Java, wich, in the end, is my objective...Thanks folks!!!!
Convert PNG to bitonal TIFF : -Edit-FYI.. I am converting bamp;w documents scanned in as greyscale or color. 1)The first solution worked, it just reversed black amp; white (black background, white text). It also took nearly 10 minutes.2)The JAI solution in the 2nd answer didn't work for me. I tried it before posting here.Has anyone worked with other libraries free or pay that handle image manipulation well?-Original-I am trying to convert an PNG to a bitonal TIFF using Java ImageIO. Has anyone had any luck doing this? I have got it to convert from PNG to TIFF. I am not sure if I need to convert the BufferedImage (PNG) that I read in or convert on the TIFF as I write it. I have searched and searched but nothing seems to work? Does anyone have an suggestions where to look?Here is the code that converts... public static void test() throws IOException { String fileName = 4848970_1; // String fileName = color; String inFileType = .PNG; String outFileType = .TIFF; File fInputFile = new File(I:/HPF/UU/ + fileName + inFileType); InputStream fis = new BufferedInputStream(new FileInputStream(fInputFile)); ImageReaderSpi spi = new PNGImageReaderSpi(); ImageReader reader = spi.createReaderInstance(); ImageInputStream iis = ImageIO.createImageInputStream(fis); reader.setInput(iis, true); BufferedImage bi = reader.read(0); int[] xi = bi.getSampleModel().getSampleSize(); for (int i : xi) { System.out.println(bitsize + i); } ImageWriterSpi tiffspi = new TIFFImageWriterSpi(); TIFFImageWriter writer = (TIFFImageWriter) tiffspi.createWriterInstance(); // TIFFImageWriteParam param = (TIFFImageWriteParam) writer.getDefaultWriteParam(); TIFFImageWriteParam param = new TIFFImageWriteParam(Locale.US); String[] strings = param.getCompressionTypes(); for (String string : strings) { System.out.println(string); } param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType(LZW); File fOutputFile = new File(I:\\HPF\\UU\\ + fileName + outFileType); OutputStream fos = new BufferedOutputStream(new FileOutputStream(fOutputFile)); ImageOutputStream ios = ImageIO.createImageOutputStream(fos); writer.setOutput(ios); writer.write(null, new IIOImage(bi, null, null), param); ios.flush(); writer.dispose(); ios.close();}I have tried changing the compression to type CCITT T.6 as that appears to be what I want, but I get an error Bits per sample must be 1 for T6 compression! Any suggestion would be appreciated.
JRuby and Java objects : Please tell me if it is possible to do the following:create an instance of a specific class in Javapass it to JRuby to do something with itcontinue using the modified version in JavaMay you provide a small working example?EDIT: It turns out that embedding was the simplest way to achieve this. More information is available on a href=http://github.com/jruby/jruby/wiki/RedBridge rel=nofollow noreferrerEmbedding JRuby.
How to refer to the Java Wireless Toolkit storage root in Ant? : I'm looking for a way to automatically get the Java Wireless Toolkit storage root (the directory where the JWT stores the file system of a mobile device simulator) in an Ant build file.Is there a property file or an environment variable that the JWT stores that path?
How can I customise the namespace prefixes in Metro/JavaEE auto-generated WSDL? : I'm using Java 6 + JavaEE + Tomcat 6 + Metro for SOAP web services. In the response, the namespace prefixes are ns2, ns3, ns4, and so on. I'd like to be able to instruct the web services stack to use custom names instead.How do I do this?
java web start JAVA_HOME : I have an application that starts a Swing gui using java web start. The user has 4 versions of java 1.6 installed (1.6.0.3, 1.6.0.5, 1.6.0.7. 1.6.0.11) Webstart is selecting java version 1.6.0.11 but JAVA_HOME is set to java version 1.6.0.3. Could this cause any potential problems for webstart? rich
What has made Adobe Flex more “acceptable” than its predecessors? : I have been building enterprise software for the last 10 years. In this time we have seen enterprise applications move from client server to thin clients. We have also seen the move to hosted solutions, albeit under a few names (asp, SaaS, cloud computing). With all these changes the impetuous has been mainly from driven from the IT department not the end user. In the first rounds of these revolutions the user experience was reduced in the name of single point of management and reduced desktop footprint. During this time there have been many attempts to give the user a rich experience while still satisfying the crotchety IT department. The first was by the industry leader Microsoft in the form of the ActiveX control. The guys from Sun then followed suit with the applet and then more recently java webstart. All of these solutions seemed to scratch the itch but never gained wide expectance by the more stringent IT departments.Then flex came on the scene from Macromedia. What did they do differently? Is it sustainable? Does Microsoft’s emulation with Silverlight prove they have changed the rules of the game? Will Web programming be changed forever?
How to use ImageIO to save multiple BufferedImages to a file : I tried both of the following options:1.BufferedImage Buffered_Image;MemoryCacheImageOutputStream MemoryCache_OutputStream = new MemoryCacheImageOutputStream(new FileOutputStream(C:/Test.mov,false));while (notFinished) // Main recording loop.{ Buffered_Image=robot.createScreenCapture(); // Capture Screen image. try { ImageIO.write(Buffered_Image,png,MemoryCache_OutputStream); } catch (Exception e) { e.printStackTrace(); }}2.BufferedImage Buffered_Image;ImageWriter writer;try{ ImageOutputStream ios=ImageIO.createImageOutputStream(new File(C:/Test.mov)); Iterator writers=ImageIO.getImageWritersByFormatName(png); while (writers.hasNext()) { writer=(ImageWriter)writers.next(); writer.setOutput(ios); Out(writer.toString()+ canInsertImage : +writer.canInsertImage(0)); // Got this: com.sun.imageio.plugins.png.PNGImageWriter@19fcc69 // canInsertImage : false }}catch (Exception e) { }cntPics=0;while (notFinished) // Main recording loop.{ Buffered_Image=robot.createScreenCapture(); // Capture Screen image. writer.write(null,new IIOImage(Buffered_Image,null,null),null); if (writer.canInsertImage(-1)) { // Append image at highest index writer.writeInsert(-1,new IIOImage(Buffered_Image,null,null),null); } else Out(Writer can’t append image Id : +cntPics); cntPics++;}Neither of them worked, what's the correct way to save multiple PNG images to a file?Edit:You are right, I found a java program called a href=http://sourceforge.net/project/showfiles.php?group_id=129468 rel=nofollow noreferrerKrut that can record screen sessions, but it uses JPEGImageEncoder, the image quality isn't as good as I want, so I wonder if I can use ImageIO to encode the sequence.If ImageIO can't do it, my next question would be is there a stand alone open source PNGImageEncoder that I can use to encode it? I know there are open source PNGImageEncoders, but they tend to be tangled in projects and hard to get all the supporting files out of it, any ideas? Thanks!
Can I import Java class files into JRuby? : The documentation seems to suggest that in order for me to import Java classes into JRuby, that they must be in a JAR file:In order to use resources within a jar file from JRuby the jar file must either be on the classpath or you can make it available with the require method(a href=http://wiki.jruby.org/wiki/Calling_Java_from_JRuby#Require_a_jar_file_to_make_resources_in_the_jar_discoverable_within_JRuby rel=nofollow noreferrerhttp://wiki.jruby.org/wiki/Calling_Java_from_JRuby#Require_a_jar_file_to_make_resources_in_the_jar_discoverable_within_JRuby)Is it at all possible to import .class files directly?Thanks!
jar resources in jnlp are not signed by the same certificate : I've been working with web start for a couple years now and have experience with signing the jars and what not. I am taking my first attempt at deploying a RCP app with web start and though I have in fact signed all of the jars with the same certificate I keep getting this error: 'jar resources in jnlp are not signed by the same certificate'Has anyone else came across this? If so, any ideas on how to fix?
Separating presentation/web-services : Is it a good practice to develop web-service and web-site in two different languages, on two different servers? E.g. right now I create a Java web-service running on Glassfish and Ruby on Rails presentation layer running in the same server.I'd like to leave web-service on the same server but use Ruby 1.9, running in Passenger.Is it a good idea? I don't have experience in architecture of web-apps.
How to mix java webstart with RMI? : I want to distribute a webstart application which uses RMI.I want to avoid to ask the user the address of the RMI server, because the website that distributes the application is also the RMI server.Furthermore, I don't know the address of the server at build time, therefore the address must be added with ad hoc configuration to the JNLP, or the address must be provided at execution time. This is the preferred way: is it possible to do so?
Easier way to guarantee integer input through Scanner? : For a program I am writing, I need to ask a user for an integer between 1 and 8. I've tried multiple (cleaner) ways of doing this but none of them worked, so I'm left with this: int x = 0; while (x 1 || x 8) { System.out.print(Please enter integer (1-8): ); try { x = Integer.parseInt(inputScanner.next()); } catch(NumberFormatException e) { x = 0; } }Where inputScanner is a Scanner. Surely there is a better way?
Is there a way in scala to convert from any Map to java.util.Map? : I use a lot of scala maps, occasionally I want to pass them in as a map to a legacy java api which wants a java.util.Map (and I don't care if it throws away any changes).
Why does Java Web Start not work with 64-bit Java environments? : a href=http://java.com/en/download/help/webstart_64bits.xml rel=nofollow noreferrerJava Web Start does not come with 64-bit builds of the JDK. Why is this? What is lacking that keeps it from building and working?
Iterating over Java collections in Scala : I'm writing some Scala code which uses the a href=http://en.wikipedia.org/wiki/Apache_POI rel=nofollow noreferrerApache POI API. I would like to iterate over the rows contained in the java.util.Iterator that I get from the Sheet class. I would like to use the iterator in a for each style loop, so I have been trying to convert it to a native Scala collection but will no luck.I have looked at the Scala wrapper classes/traits, but I can not see how to use them correctly. How do I iterate over a Java collection in Scala without using the verbose while(hasNext()) getNext() style of loop?Here's the code I wrote based on the correct answer:class IteratorWrapper[A](iter:java.util.Iterator[A]){ def foreach(f: A = Unit): Unit = { while(iter.hasNext){ f(iter.next) } }}object SpreadsheetParser extends Application{ implicit def iteratorToWrapper[T](iter:java.util.Iterator[T]):IteratorWrapper[T] = new IteratorWrapper[T](iter) override def main(args:Array[String]):Unit = { val ios = new FileInputStream(assets/data.xls) val workbook = new HSSFWorkbook(ios) var sheet = workbook.getSheetAt(0) var rows = sheet.rowIterator() for (val row - rows){ println(row) } }}
Real-time Java interoperability : I am wondering how it's the interoperability between JRE6 and the JVM from a href=http://www.rtsj.org rel=nofollow noreferrerrtsj. It seems that I have to use only their implementation (since the code will be interpreted using their JVM), so I cannot use many of the features that Java 6 has to offer.Can it support a GUI? (say for example to modify the parameters of an industrial process).I might be wrong, hoping to get some feedback from you.Also, it seems that are more real time implementations for Java. Which one did you use and which one did you like most?
Where to pass runtime argument in wrapper.conf file in java service wrapper? : Iam trying to create window service for my jar application. Application needs an argument and System property value while runtime. I dont know where to give argument value and system variable value in wrapper.conf file. please help me. I am getting the below errorwrapper | Launching a JVM...jvm 1 | WrapperManager: Initializing...jvm 1 |jvm 1 | WrapperSimpleApp Usage:jvm 1 | java org.tanukisoftware.wrapper.WrapperSimpleApp {app_class} [app_arguments]jvm 1 |jvm 1 | Where:jvm 1 | app_class: The fully qualified class name of the application to run.jvm 1 | app_arguments: The arguments that would normally be passed to thejvm 1 | application.wrapper | JVM exited while loading the application.
java.util.Scanner and Wikipedia : I'm trying to use java.util.Scanner to take Wikipedia contents and use it for word based searches. The fact is that it's all fine but when reading some words it give me errors.Looking at code and making some check it turned out that with some words it seems not to recognize the encoding, or so, and the content is no more readable.This is the code used to take the page:// -Start-try { connection = new URL(http://it.wikipedia.orgwiki/+word).openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter(\\Z); content = scanner.next();// if(word.equals(pubblico))// System.out.println(content); System.out.println(Doing: + word);//EndThe problem arises with words as pubblico for the italian wikipedia.the result of the println on word pubblico is like this (cutted):ï¿ï¿½]Ksr�~E�1A���E�ER3tHZ�4v��amp;PZjtc�¿½ï¿½D�7_|����=8��Ø}Do you have any idea why? Yet looked at page source and headers are the same, with same encoding...Turned Out that content is gzipped, so can i tell wikipedia not to send me teir pages zipped or it's the only way? thank you
implements Runnable vs. extends Thread : From what time I've spent with threads in Java, I've found these two ways to write threads:With implements Runnable:public class MyRunnable implements Runnable { public void run() { //Code }}//Started with a new Thread(new MyRunnable()).start() callOr, with extends Thread:public class MyThread extends Thread { public MyThread() { super(MyThread); } public void run() { //Code }}//Started with a new MyThread().start() callIs there any significant difference in these two blocks of code ?
Real time thread synchronization with normal threads : How would one synchronize one real-time thread with a normal thread in Java? Take for example a real-time thread that calculates some temperatures and the GUI thread that has to collect those numbers and show them on some controls.The implementation of the real-time library shouldn't matter as it should follow the specifications.
Diagnosing and improving performance of a java jnlp compared to jar file : Customer X has asked for ways to improve the startup time of a Java process he uses. The problem is, it is not run through a jar file, but rather 'jnlp' (which I am assuming indicates it is a java webstart application)StartUserWorx.jnlpIs there a way to convert this to a JAR file and then have the user invoke the application locally, and include a startup flag to the JRE to allocate more ram to the process?The user is getting a bit frustrated, because other workers in the same office use the same application on almost identical machines, and yet his process seems to always take a much longer time to load (a few minutes rather than a few seconds).
How to prevent piracy for java webstart application : I have this java swing application that I intend to sell over the internet. At the moment I'm leaning towards deploying the application using java webstart. The product will be licensed for the user to use the program on one computer at a time only. I am concerned about piracy with this model. I would like to install some security features to enforce the license model. The goal is to at least make it difficult for a licensed user to copy the installed product including license key to unlicensed users. Here are the options I am looking at now:Force the user to authenticate to the mother ship with a username/password each time the program is launched.Simply install a license key somewhere (hidden?) on the users PC after they have registered and paid. At runtime, verify that there is a valid license key installed.Use/build a security package that is based on a hardware fingerprint of the users computer. This fingerprint would be computed each time the app is started and compared with the locally installed license key using some sort of hash. This license key would be would only be valid with this hardware fingerprint. One of the issues here is that once this application is installed, there isn't any runtime need for the application to contact the mother ship, other than checking for application updates using java webstart. Everything the app does it does locally and displays the results to the user using swing. So any solution involving a mother ship would basically mean building a server infrastructure for the sole purpose of license verification.I guess what I'm looking for is something java based that is at least somewhat secure, easy to deploy and is not a pain for the user. What security/licensing approach have you used?EDIT: I should add that I am not necessarily looking for a silver bullet to prevent absolutely everyone from defeating security. There will always be someone with enough time on their hands to find ways to get it done. I'm not so concerned with these guys. I'm basically looking to make it difficult for a casual user to simply copy the license key and send to his buddies. Implemented correctly, the solution should convince the casual user that it is simpler to just buy it.
Java Web Start - Popularity : I recently used a Java Web Start application. I launched it from my web browser using an embedded jnlp link in the page I was viewing. The application was downloaded, launched and worked just fine. It had access to my local file-system and remembered my preferences between restarting it.What I want to know is why are Java Web Start applications not a more popular delivery format for complex applications on the web? Why do developers often spend considerable time amp; energy replicating desktop functionality in html/javascript when the power of a desktop application could be delivered more easily using Java amp; Java Web Start?I know that in some corporate environments, e.g banking, they are relatively popular ways of delivering complex trading applications to clients, but why are they not pervasive across the web as a whole?(For the sake of discussion let's assume a world where: download sources are trusted amp; applications are signed (i.e. no security concerns), download speeds are fast (load time is quick) and developers know Java (in the numbers they know html/js/php)).
Anyone using JavaSpaces technology? : Are there real practical uses of JavaSpaces technology out there and how exactly is it implemented?
Netbeans and .NET web services : I'm not an experienced java developer so any comment will be welcomed ...I've written a web service using c# and I wanted to consume this service from java - used Netbeans for this task.All methods works well beside one: the method expecting a type called BusinessDataField2 - this type contains 2 fields: name(string) and value(object)Those fields are filled using get,set methods - this works easily at the .NET environment.However ...I can see that Java requires different parameters for the get and set methods - the parameter is :JAXBElementJAXBElement The question is: how do I instantiate this object? I tried many different ways but nothing worked...Thanks,ofer
ImageIO.write not saving out as gif, but works for jpgs and pngs? : I suspect the solution here is probably really simple, but I'm stumped...// Create the buffered image.BufferedImage bufferedImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);// fill image data (works fine)ImageIO.write(bufferedImage, JPG, f1); // works fineImageIO.write(bufferedImage, PNG, f2); // works fineImageIO.write(bufferedImage, GIF, f3); // this returns false, creates a broken gif file, but fires no exceptionsDoes ImageIO.write() not work for gifs? is this some sort of throwback to gif being a proprietary Compuserve thing? Or am I just being stupid (I'm guessing it's the last one :) )
Confusion over class resolution in Oracle java stored procedures : I'm trying to use a third-party java library within oracle. The library seems compatible with the same 1.4 version of the jvm that our Oracle 10g server hosts, since it runs fine outside of Oracle, so I feel like I should be able to get this to work. This library ends up making SOAP-based http requests, and I get class resolution errors when I run in Oracle.Here's a line that shows the difference:Class msgfact = Class.forName(com.sun.xml.messaging.saaj.soap.MessageFactoryImpl);I tried to register these libraries into Oracle with the loadjava utility, and I got what I thought was a successful result:C:\loadjava -verbose -schema MYUSER -user MYUSER/MYPWD@dbinstance -force saaj-impl.jarIt looks like everything gets loaded, and I can see this MessageFactoryImpl class in that list. But then I try to run this line of code from Oracle SQL (inside another class I wrote and loaded with loadjava), this line throws a ClassNotFoundException (java.lang.ClassNotFoundException: com/sun/xml/messaging/saaj/soap/MessageFactoryImpl).Then I went back and tried to add the -resolve switch at the loadjava command line. It acts like these saaj classes are getting registered, but they aren't resolving properly. How can I successfully get these saaj classes into Oracle, or if for some reason Oracle already has these loaded, how can I convince my own code to successfully use the existing class?FWIW, I already took the steps to make sure that the appropriate socket permissions were granted and my code can successfully make a generic http request to the target url. It just has trouble using the library's SOAP stack to make it happen.EDIT:Here is a sample of my loadjava result. This seems to be showing exactly what's failing, but I'm confused as to why these particular classes aren't being resolved when they seem to be handled properly in the pre-resolution steps. I've eliminated about 80% of the file here, but there are other classes that show the same class resolution issues.arguments: '-verbose' '-schema' 'MYSCHEMA' '-user' 'MYSCHEMA/MYSCHEMA@actest' '-resolve' '-force' 'saaj-impl.jar' [snip]creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactoryloading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactorycreating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandlerloading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandlercreating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandlerloading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandlercreating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImplloading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImplcreating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImplloading : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl[snip]resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/AttachmentPartImplresolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/Enveloperesolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactoryerrors : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/SOAPPartImpl could not be resolvedresolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandlerresolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandlerresolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImplerrors : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolvederrors : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/impl/EnvelopeImpl could not be resolvederrors : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1 ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolvedskipping : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$2[snip]The following operations failed class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory: resolution class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl: resolution class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl: resolution class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1: resolution[snip]exiting : Failures occurred during processing
Java appears hung : I've been using the Java Service wrapper in a custom application for quite a while and it's been working fine. Since updating our application to a new version in the last few days the JVM started hanging and then wrapper prints this in the log: JVM appears hung: Timed out waiting for signal from JVM.It then automatically terminates the JVM and starts the app again. This happens after about 10 hours of running, which just makes it harder to debug.Of course I am going to look through the changes that we've made, but no major changes were made that I would suspect is causing this type of problem.Where can I look to try and figure out what is happening? Debug messages from the application don't indicate anything interesting. If the JVM just crashes it will usually create a dump, which can help in debugging it, but it's hanging, so it's not creating a dump. If I make it not restart the service automatically is there anything I can do to get some useful information out of the JVM before restarting it?It seems to me that the JVM shouldn't hang from typical programming errors. What have you run into before that can cause the JVM to hang?
Can a signed Jar be run as an executable? : I ask because I have an unsigned jar that runs and a signed version that doesn't. Looking at the manifests, I see no main class thing for the signed one. Do I have to run a signed jar from web start?
How do you clear the Java Console? : I have output messages displayed on the a href=http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/console.html rel=nofollow noreferrerJava console for an application that started using webstart. Instead of the user manually clearing message, is there a way of clearing console messages in code?These messages are printed at the rate of about 1000 per second and seem to end up using too much memory, i could have stopped the printing to console, but the requirement is to always have it.
Consuming .NET webservice in Java (metro) - XMLNode/XMLDocument consumption? : I am a bit rusty in my Java, and this is my first time using metro/JAX-WS, so if this is a dumb question I apologize.I have to write a client that consumes a .NET webservice. I've got the basics down; I have generated the wrappers from the WSDL, and I can create my object and port and make a call and get a response. Widgets d = new Widgets(); WidgetsSoap dp = d.getWidgetsSoap(); ((BindingProvider)dp).getRequestContext(). put(javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY, http://actualsite/foo.asmx); UserGetWidgetsResponse.UserGetWidgetsResult j = dp.userGetWidgets();The webservice's return values are almost all XmlDocument or XmlNode. How do I get from the wsimport-generated UserGetWidgetsResponse.UserGetWidgetsResult to the actual XML returned by the call? I have a number of these services with a bunch of methods, so I'm hoping to find a solution that does not require modifying the generated wrappers in any way. I also do not have control over the information returned by the web services.
How do I pipe the Java console output to a file? : I found a bug in an application that completely freezes the JVM. The produced stacktrace would provide valuable information for the developers and I would like to retrieve it from the Java console. When the JVM crashes, the console is frozen and I cannot copy the contained text anymore.Is there way to pipe the Java console directly to a file or some other means of accessing the console output of a Java application?Update: I forgot to mention, without changing the code. I am a manual tester.Update 2: This is under Windows XP and it's actually a web start application. Piping the output of javaws jnlp-url does not work (empty file).
Which do you prefer: Java Web Start, or Java Applets? : Which do you think is better as a programmer, and as a end user, and why?
How to get an InputStream from a BufferedImage? : How can I get an InputStream from a BufferedImage object? I tried this but ImageIO.createImageInputStream() always returns NULLBufferedImage bigImage = GraphicsUtilities.createThumbnail(ImageIO.read(file), 300);ImageInputStream bigInputStream = ImageIO.createImageInputStream(bigImage);The image thumbnail is being correctly generated since I can paint bigImage to a JPanel with success.Thank you.
Dynamically load additional jar files using Web Start / JNLP : The a href=http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/development.html#retrieving rel=nofollow noreferrerWeb Start Developers Guide statesblockquote All application resources must be retrieved from the JAR files specified in the resources section of the JNLP file, or retrieved explicitly using an HTTP request to the Web server. Storing resources in JAR files is recommended, since they will be cached on the local machine by Java Web Start./blockquoteNow, I have some resources I want to dynamically load after my application has been started (for example OSGi bundles). I can do this using plain HTTP, but I would like to make use of Web Start's support for local caching and versioned/architecture-specific resources.Is there a way to download additional jar files from the original code base (as specified in the application's jnlp file) using the Web Start infrastructure?Or alternatively: is there already an established way to integrate OSGi and Web Start that would relieve me of the task to install bundles from the Web Start server?
How to get image height and width using java? : Is there any other way besides using a href=https://docs.oracle.com/javase/8/docs/api/javax/imageio/ImageIO.html#read-java.io.File- rel=nofollow noreferrerImageIO.read to get image height and width?Because I encounter an issue that locks up the thread.at com.sun.medialib.codec.jpeg.Decoder.njpeg_decode(Native Method) at com.sun.medialib.codec.jpeg.Decoder.decode(Decoder.java:87) at com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReader.decode(CLibJPEGImageReader.java:73) - locked 0xd96fb668 (a com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReader) at com.sun.media.imageioimpl.plugins.clib.CLibImageReader.getImage(CLibImageReader.java:320) - locked 0xd96fb668 (a com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReader) at com.sun.media.imageioimpl.plugins.clib.CLibImageReader.read(CLibImageReader.java:384) - locked 0xd96fb668 (a com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageReader) at javax.imageio.ImageIO.read(ImageIO.java:1400) at javax.imageio.ImageIO.read(ImageIO.java:1322)This error only occurs on a Sun app server and therefore I suspect that it is a Sun bug.
Can't find ports with javax.comm api : I am trying to install the javax.comm api on a machine (I already installed on another machine and it is working fine) but when I run the sample BlackBox application I get a message that says No serial ports found!. I have followed the instructions and put win32com.dll in the bin directory of the jdk, comm.jar in the lib directory of the jdk, and javax.comm.properties in the lib directory of the jdk. I have also added the comm.jar file to the classpath since i am using a jdk and not jre. All this and I still can't get BlackBox to find any serial ports. Can anybody help me with this?
How can I debug applications under Java Web Start (JNLP)? : I know how I can debug a remote Java VM with Eclipse, but how can I do it with a Java Web Start program. I have a problem that only occurs in Java Web Start. It must be security related.I need a solution that will work with a current Java VM like 1.6.0_12.
Scanner vs. StringTokenizer vs. String.Split : I just learned about Java's Scanner class and now I'm wondering how it compares/competes with the StringTokenizer and String.Split. I know that the StringTokenizer and String.Split only work on Strings, so why would I want to use the Scanner for a String? Is Scanner just intended to be one-stop-shopping for spliting?
Lock a file while writing it on the disk : I have two independant threads F1 and F2 (to be precise, two instances of java.util.concurrent.FutureTask) that are running in parallel.F1 do some processing, and then copy the result in a XML file. Then, it repeats these steps until it has nothing to do (many XML files are created).F2 looks in the F1 output directory, and take one file, parse it, and execute some processing on it.This works quite pretty well, except that sometimes, F2 gets truncated XML data from the file. I mean by that an incomplete XML, where some XML node are not present. The problem is that it is not always reproductible, and the files that are truncated are not always the same.Because of that, I am thinking that while F1 is writing one file on the disk, F2 is trying to read the same file. That's why sometimes I get this kind of error.My question: I am wondering if there is some mechanism that locks (even for reading) the file F1 is currently writing until it has completely finished to write it on the disk, so F2 will not be able to read it until the file is unlocked. Or any other way to solve my issue will be welcome !F1 is writing the file this way:try { file = new File(some-file.xml); FileUtils.writeStringToFile(file, xmlDataAsString);} catch (IOException ioe) { LOGGER.error(Error occurred while storing the XML in a file., ioe);}F2 is reading the file this way:private File getNextFileToMap() { File path = getPath(); // Returns the directory where F1 stores the results... File[] files = path.listFiles(new FilenameFilter() { public boolean accept(File file, String name) { return name.toLowerCase().endsWith(.xml); } }); if (files.length 0) { return files[0]; } return null;}// Somewhere in my main method of F2...f = getNextFileToMap();Node xmlNode = null;try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(f); if (doc != null) { xmlNode = doc.getDocumentElement(); }} catch (Exception e) { LOGGER.error(Error while getting the XML from the file + f.getAbsolutePath(), e);}
JAX-WS Consuming web service with WS-Security and WS-Addressing : I'm trying to develop a standalone Java web service client with JAX-WS (Metro) that uses WS-Security with Username Token Authentication (Password digest, nonces and timestamp) and timestamp verification along with WS-Addressing over SSL. The WSDL I have to work with does not define any security policy information. I have been unable to figure out exactly how to add this header information (the correct way to do so) when the WSDL does not contain this information. Most examples I have found using Metro revolve around using Netbeans to automatically generate this from the WSDL which does not help me at all. I have looked into WSIT, XWSS, etc. without much clarity or direction. JBoss WS Metro looked promising not much luck yet there either.Anyone have experience doing this or have suggestions on how to accomplish this task? Even pointing me in the right direction would be helpful. I am not restricted to a specific technology other than it must be Java based.
Writing a cleaner and more modular command-parser : I'm writing a debugger for a Z80-emulator we are writing in a school project, using Java. The debugger reads a command from the user, executes it, reads another command, etc. Commands can either be argument less, have optional arguments, or take an unlimited amount of arguments. Arguments are mostly integers, but occasionally they're strings.Currently, we're using the Scanner-class for reading and parsing input. a href=http://pastebin.com/m2a062299 rel=nofollow noreferrerThe read-method looks kinda like like this (I'm writing this off the top of my head, not paying attention to syntax nor correctness).This was a kludge written in the beginning of the project, which quickly got out of hand as we added more and more commands to the debugger.The major issues I have with this code is the large amount of repetition, the highlevel of if/else-nestedness, and the all around uglyness.I would like suggestions on how to make this code more beautiful and modular, and what kind of patterns that are suitable for this kind of program. I would also like more general suggestions on code style.
How can I save a PNG with a tEXt or iTXt chunk from Java? : I am currently using javax.imageio.ImageIO to write a PNG file. I would like to include a tEXt chunk (and indeed any of the chunks a href=http://en.wikipedia.org/wiki/Portable_Network_Graphics#Ancillary_chunks rel=nofollow noreferrerlisted here), but can see no means of doing so.By the looks of com.sun.imageio.plugins.png.PNGMetadata it should be possible.I should be most grateful for any clues or answers.M.
Is there an equivalent to the Scanner class in C# for strings? : In Java I can pass a Scanner a string and then I can do handy things like, scanner.hasNext() or scanner.nextInt(), scanner.nextDouble() etc.This allows some pretty clean code for parsing a string that contains rows of numbers.How is this done in C# land?If you had a string that say had:0 0 1 22 39 0 0 1 2 33 33In Java I would pass that to a scanner and do a while(scanner.hasNext()) myArray[i++] = scanner.nextInt();Or something very similar. What is the C#' ish way to do this?
How to obtain a Java stack trace from a client running under web start? : I wanted to get ideas from the SO community about this issue.Here is the problem:We have a user on the other side of the world launching our app through WebStart. The user, however, is complaining that her whole application freezes up and becomes unresponsive. Usually, the client is doing a lot of database queries to a distributed database.Questions:If we ask her to do a CTRL-Break on her application, where would the JVM write the stack trace to?Would it be enough just to use JConsole?Would implementing JMX beans on the client be overkill? Would it actually help in troubleshooting issues in production?Right now the users are running on JRE 1.5.0-b08, but we do plan on migrating to JRE 6 in a couple of months.What do you think?
What are some interesting uses for Java Agents? : Starting with Java 5 there's an option to add Java Agents to the class loader.Have you written any Agents?have you used any Agents?What are interesting uses of Agents?
Mini-OSGi that can run in a sandbox (like AppEngine or WebStart)? : I really like the concept of modular bundles as implemented by OSGi.I also like managed deployment services like Google AppEngine (for web application) or Java WebStart (for client software).These two ideas seem to complement each-other rather well conceptually.However, the OSGi standard includes a couple of features that make it impossible for implementations like Felix or Equinox to run on top of sandboxed virtual machines, such as AppEngine or Webstart. In these environments, it is not possible to get direct access to a file system, for example, which precludes the OSGi bundle cache that is used to store persistent bundle state and native libraries.Now, I have no great interest in using native libraries or have persistent bundle state. Is there some framework that implements the core bundle and services concept of OSGi (ideally in a compatible way so that OSGi bundles can be deployed into it as is), but can work without a bundle cache (and other facilities not available in a sandbox)?I am looking for something like a limited version of Felix that works on AppEngine or WebStart.Of course, if the WebStart engine and the Google AppEngine just provided OSGi framework services out-of-the-box that would be great, too...Update: Another very limiting aspect of AppEngine is that you cannot start new Threads. This prevents (among other things) asynchronous bundle life-cycle management. Obviously not an issue with WebStart.
Java's Scanner vs String.split() vs StringTokenizer; which should I use? : I am currently using split() to scan through a file where each line has number of strings delimited by '~'. I read somewhere that Scanner could do a better job with a long file, performance-wise, so I thought about checking it out. My question is: Would I have to create two instances of Scanner? That is, one to read a line and another one based on the line to get tokens for a delimiter? If I have to do so, I doubt if I would get any advantage from using it. Maybe I am missing something here?
Can I add classes to sun's rt.jar file? : I downloaded the Javax.mail package. I have jdk1.6.0_11.Problem is...I cannot get javac or java to find those classes!I can get apps to compile using JCreator LE ( by adding the mail jarto its search list ) but, when I try to run the app in a command window,it fails.Can I add these new classes to the rt.jar without hurting my jdk installation? I know java has it wired up to look there for classes.(And, the mail classes are inside a javax package - seems like they could reasonably be added to the javax folder in rt.jar..Thanks!Phil D'
use of delimiter function from scanner for abc-def : I'm currently trying to filter a text-file which contains words that are separated with a -. I want to count the words.scanner.useDelimiter(([.,:;()?!\ \t\n\r]+));The problem which occurs simply is: words that contain a - will get separated and counted for being two words. So just escaping with \- isn't the solution of choice.How can I change the delimiter-expression, so that words like foo-bar will stay, but the - alone will be filtered out and ignored?Thanks ;)
How to get java Logger output to file by default : Netbeans thoughtfully sprinkles Logger.getLogger(this.getClass().getName()).log(Level. [...]statements into catch blocks. Now I would like to point them all to a file (and to console).Every logging tutorial and such only me tells how to get a specific logger to output into a file, but I assume there is a better way than fixing every automatically generated logging statement? Setting a handler for some sort of root logger or something?
How safe would it be to use functional-java to add closures to a Java production project? : I would love to use closures in Java. I have read that they may or may not make it into Java 7. But an open-source project called a href=http://code.google.com/p/functionaljava/ rel=nofollow noreferrerfunctional-java has implemented functional features including closures. How safe would it be to use such a library in an enterprise production app? Is there a better way to add closures to Java currently?
What are your experiences using the functional java project? : I was reading the following question - a href=http://stackoverflow.com/questions/766745/how-safe-would-it-be-to-use-functional-java-to-add-closures-to-a-java-productionHow safe would it be to use functional-java to add closures to a Java production project? and I had been thinking of using the a href=http://functionaljava.org/ rel=nofollow noreferrerFunctional Java project as well in my current project. I was wondering what are Stack Overflow's users experiences with using the Functional Java project? In particular, I'm curious about some of these specifics:Did it increase code quality or clarity?Improve productivity?Reduce potential points of failure?Impact performance?
read a file using Scanner: Why am I getting an error when using Scanner for read files in java? : This example demonstrates using Scanner to read a file line by line (it does not perform a write operation) I don't know why I get an error when I try to compile. Could somebody explain the reason to me?. I'm using jcreatorLE and JDK 1.6 to run my program:import java.io.*;import java.util.Scanner;public final class File_read { public static void main(String... aArgs) throws FileNotFoundException { ReadWithScanner parser = new ReadWithScanner(C:\\Temp\\test.txt); parser.processLineByLine(); log(Done.); } /** * @param aFileName full name of an existing, readable file. */ public ReadWithScanner(String aFileName){ fFile = new File(aFileName); } /** Template method that calls {@link #processLine(String)}. */ public final void processLineByLine() throws FileNotFoundException { Scanner scanner = new Scanner(fFile); try { //first use a Scanner to get each line while ( scanner.hasNextLine() ){ processLine( scanner.nextLine() ); } } finally { //ensure the underlying stream is always closed scanner.close(); } } /** * Overridable method for processing lines in different ways. * * PThis simple default implementation expects simple name-value pairs, separated by an * '=' sign. Examples of valid input : * ttheight = 167cm/tt * ttmass = 65kg/tt * ttdisposition = grumpy/tt * ttthis is the name = this is the value/tt */ protected void processLine(String aLine){ //use a second Scanner to parse the content of each line Scanner scanner = new Scanner(aLine); scanner.useDelimiter(=); if ( scanner.hasNext() ){ String name = scanner.next(); String value = scanner.next(); log(Name is : + quote(name.trim()) + , and Value is : + quote(value.trim()) ); } else { log(Empty or invalid line. Unable to process.); } //(no need for finally here, since String is source) scanner.close(); } // PRIVATE // private final File fFile; private static void log(Object aObject){ System.out.println(String.valueOf(aObject)); } private String quote(String aText){ String QUOTE = '; return QUOTE + aText + QUOTE; }} This is the result from running it:--------------------Configuration: Default--------------------C:\Users\administrador\Documents\File_read.java:15: invalid method declaration; return type required public ReadWithScanner(String aFileName){ ^1 errorProcess completed.
speech recognition in java : I want to use speech recognition in my project and I found this code but when I run it I get an error which is:blockquoterun: java.lang.NullPointerException at newpackage.HelloWorld.main(HelloWorld.java:55)/blockquotePlease could one of you help me in this problem?This is the server code that I use:package newpackage;import java.util.logging.Level;import java.util.logging.Logger;import javax.speech.*;import javax.speech.recognition.*;import java.io.FileReader;import java.util.Locale;public class HelloWorld extends ResultAdapter { static Recognizer rec; // Receives RESULT_ACCEPTED event: print it, clean up, exit public void resultAccepted(ResultEvent e) { Result r = (Result)(e.getSource()); ResultToken tokens[] = r.getBestTokens(); for (int i = 0; i tokens.length; i++) System.out.print(tokens[i].getSpokenText() + ); System.out.println(); try { // Deallocate the recognizer and exit rec.deallocate(); } catch (EngineException ex) { Logger.getLogger(HelloWorld.class.getName()).log(Level.SEVERE, null, ex); } catch (EngineStateError ex) { Logger.getLogger(HelloWorld.class.getName()).log(Level.SEVERE, null, ex); } System.exit(0); } public static void main(String args[]) { try { // Create a recognizer that supports English. rec = Central.createRecognizer( new EngineModeDesc(Locale.ENGLISH)); // Start up the recognizer rec.allocate(); // Load the grammar from a file, and enable it FileReader reader = new FileReader(args[0]); RuleGrammar gram = rec.loadJSGF(reader); gram.setEnabled(true); // Add the listener to get results rec.addResultListener(new HelloWorld()); // Commit the grammar rec.commitChanges(); // Request focus and start listening rec.requestFocus(); rec.resume(); } catch (Exception e) { e.printStackTrace(); // System.out.println(the problem); } }}
Is there a good alternative to javax.imageio out there? : I'm looking for a good alternative to the javax.imageio package, that lets me do simple rotating, cutting and scaling operations on images. For example, I would like to doint angle, height, width;image.rotateRight(angle).scale(height, width);in order to obtain an image that is rotated angle degrees to the right and scaled down to height x width pixels.Using Graphics2D and BufferedImages, I will have to do this, which is neither readable, nor easy to write:BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D graphics = result.createGraphics();graphics.translate(height/2, width/2);graphics.rotate(angle);graphics.translate(-width/2, -height/2);graphics.drawImage(image, 0, 0, width, height, null);(Actually, that code doesn't even account for non-square images, which will require me to do even more magic with the translating).
How to make canvas with Swing? : I'm trying to make a paint editor with Java in which I have a toolbar with the objects that I would like to paste in the canvas. I'm using Swing components to make the GUI, but when I looked for the way of making the canvas, I only found the class canvas from AWT. Is there any way to make something similar to canvas with Swing? (for example, JPanel?) I have read that using the class canvas from AWT with a GUI made with swing won't work correctly, is that true?
Java WebStart: property ... ignored when using ? : I have a problem modernizing a Java WebStart application under Java 6 u 13 (the latest at this moment)We desire to use the new mechanism to have several master configuration files each with their own configuration , which then include another jnlp file which is autogenerated to ensure that the jar list is accurate. After quite a bit of poking I have made it work, except for the fact that the properties defined in the master file is not available to the program when Main is invoked.The master JNLP looks like (anonymized):jnlp information title.../title vendor.../vendor description.../description description kind=short.../description homepage href=http://....jnlp/ icon href=http://....gif/ !-- offline-allowed/ -- /information security all-permissions/ /security resources j2se version=1.6+/ extension href=http://...extension.jnlp / property name=server.name value=SERVER/ /resources application-desc main-class=Main//jnlpand the extension.jnlp looks like:!-- Generated automatically. Do not edit! --jnlp information titleextension built 2009-04-22 12:39:58 CEST/title vendor.../vendor /information securityall-permissions//security resources jar href=A.jar / jar href=B.jar / jar href=logback-classic-0.9.14.jar / jar href=logback-core-0.9.14.jar / jar href=slf4j-api-1.5.6.jar / /resources component-desc //jnlpI have tried putting the proprty in the extension.jnlp too. Did not help. The JVM is reused and not relaunched according to the log in the Java Plugin Console.Any suggestions?
Creating animated GIF with ImageIO? : Has anybody managed to convince ImageIO to write an animated GIF, and in particular setting the correct metadata? My first attempt is roughly as follows (where b1 and b2 are BufferedImages):ImageTypeSpecifier spec = new ImageTypeSpecifier(b1);ImageWriter wr = ImageIO.getImageWriters(spec, GIF).next();wr.setOutput(ImageIO.createImageOutputStream(new File(C:\\Flashing.gif)));ImageWriteParam param = wr.getDefaultWriteParam();IIOMetadata meta = wr.getDefaultImageMetadata(spec, param);wr.prepareWriteSequence(meta);wr.writeToSequence(new IIOImage(b1, null, null), param);wr.writeToSequence(new IIOImage(b2, null, null), param);This appears to almost work, but:I clearly need to somehow set proper metadata to set the time between the images and ideally make them loop (I was naively hoping the default would do something sensible, but hey...)whatever metadata it is writing by default is obviously not quite right: the GIMP gives a couple of error messages when loading the file, although embedding the image in a test web page in Firefox does display the two images in very quick succession, which is tantilisingly close to what I want...If anyone has got writing animated GIFs from ImageIO to work and can share a snippet of working code or how to fix the above problems, it would be greatly appreciated!
javax.comm: Error when device is disconnected : I have an application that reads data from a com port using javax.comm.The problem I am having is that if the device that I'm reading from is unexpectedly disconnected I get an error in the console that says WaitCommEvent: Error 5I have looked around and can't find any helpful information about this. I have set all of the notifyOn* methods to true so I think I should be receiving all of the events but I'm not catching this one.The error message that is printed out does not come from anywhere in my code so it must be in the javax.comm package somewhere. Can anyone tell me how to handle this error so that I can close the com port properly when it occurs?Thanks!
Load java.util.logging.config.file for default initialization : I'm trying to load a custom log.properties file when my application is started.My properties file is in the same package as my main class, so I assumed that the -Djava.util.logging.config.file=log.properties command line parameter should get the properties file loaded.But the properties are only loaded when i specify a full absolute path to the properties file. Any suggestions how to use a relative path?
Access non-public classes in sun.awt package [specifically: FetcherInfo] : Question:I have some performance problem in my app - and the bottleneck is sun.awt.image.ImageFetcher.run, and I canno't get any (more) meaningfull info from profiler. So I figured that it would be nice to look at jobs that ImageFetcher is doing. I couldn't get access to FetcherInfo class, that holds all ImageFetcher jobs. To obtain FetcherInfo instance I have to call FetcherInfo.getFetcherInfo(). I created class in package sun.awt.image (just in my project, i didnt tinker with rt.jar). To get FetcherInfo i use: try{ for(Method method : FetcherInfo.class.getDeclaredMethods()){ method.setAccessible(true); if(method.getName().equals(getFetcherInfo)){ m = method; } }}catch (Exception e){ e.printStackTrace();}FetcherInfo info = null;try { info = (FetcherInfo) m.invoke(null);} catch (IllegalAccessException e) { e.printStackTrace();} catch (InvocationTargetException e) { e.printStackTrace();}And I get exception: Exception in thread IMAGE-FETCHER-WATCHER java.lang.IllegalAccessError: tried to access class sun.awt.image.FetcherInfo from class sun.awt.image.FetcherDebugAnd the stack trace points to:for(Method method : FetcherInfo.class.getDeclaredMethods()){The same exception was raised by: FetcherInfo.class.getMethod(getFetcherInfo);So anyone has any ideas how to either:Obtain ImageFetcher instanceFind out what images are getting loadedSOLUTIONThe problem was that i've put my class into sun.java.awt package to get access to package protected members, without putting it into rt.jar, and exception was thrown hen calling ImageFetcher.class.
Is it possible to use Java webstart execute .exe or dll? : I know java webstart is running under a secure sandbox. Is it possible to include a .dll/.exe in the jar (or have the webstart download it to the local machine) and then execute it (using Runtime.exec or process,etc)Please Advise. Any suggestion/comment is welcome!
How to embed Java Web Start (with jnlp) application on google? : I have created some simple app in Java, and 'deployed' it using Java Web Start (and jnlp) on my local machine. Now I would like to put it on the web, to have some feedback from various people.I was thinking about embedding my app in Google infrastructure (pages.google.com/sites.google.com/blogger.com - whatever). Question: How do I do that?What do I change in my .jnlp file (now i have there local path hardcoded - 'jnlp codebase=file:/D:/Projects/SomeApp/dist...')?How to embed file structure (/../dist/somefiles and /../dist/lib/somefiles) into (mentioned) Google infrastructure?
Reading text with Java Scanner next(Pattern pattern) : I am trying to use the Scanner class to read a line using the next(Pattern pattern) method to capture the text before the colon and then after the colon so that s1 = textbeforecolon and s2 = textaftercolon.The line looks like this:something:somethingelse
Java WebStart and endorsed directories : How do I specify in java webstart .jnlp file, that some of my jars are overriding the JRE builtin implementations? Just like the endorsed lib property on a regular application.
Convert static windows library to dll : I have a library contains a bunch of static *lib files, I wish to access them from JNA (a Java library that allows one to dynamically call `dll's from JAVA Code), so is there a way to magically change static lib to dll? Code was compiled using Visual studio (hope that is relevant), and I also have appropriate header files.I do not have access to source code, also I would like to do it using only free (as in beer) tools.
Debugger won't work with JMockit : Hopefully an easy question here for someone.....I'm using RAD 7.5.2, and am writing Junit tests. I was writing them just fine with JUnit 3, and then I wanted to mock up some function calls. So I loaded up jmockit 0.9.7 and Junit 4.6. I also include -javaagent:jmockit.jar as a VM argument.When I Run As Junit Test, it goes along with no problems at all (at least, none that I can see on the output). The output of Junit is good, and no errors are dumped to the console.When I Debug as Junit Test, it won't work. It dumps me out into:InstrumentationImpl.class -- Source not found...and when I hit continue....NativeMethodAccessorImpl.class -- Source not found...and when I hit continue...The JUnit ends after this. It dumps the following to the console:Exception in thread main java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:618) at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:160)Caused by: java.lang.UnsatisfiedLinkError: sun/instrument/InstrumentationImpl.redefineClasses0([Ljava/lang/instrument/ClassDefinition;)V at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:98) at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:197) at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:184) at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:116) at mockit.internal.RedefinitionEngine.setUpInternalStartupMock(RedefinitionEngine.java:53) at mockit.internal.Startup.loadInternalStartupMocks(Startup.java:123) at mockit.internal.Startup.initialize(Startup.java:110) at mockit.internal.Startup.premain(Startup.java:97) ... 5 moreFatal error: processing of -javaagent failedI can run both JUnit 3 and JUnit 4 on my tests with no problem, it's when I use the -javaagent:jmockit.jar (with the debugger; by themselves they're fine) that things get ugly, and I have to do that to use the jmockit stuff.Thoughts?
How do I start my Java program with more than one java agent? : I'm aware of how to start a java progam with a java agent:java -javaagent:myAgent.jar MyJavaProgramBut what if I want to add 2 or more java agents to instrument my program? I do not want to reinvoke the java -javaagent:... for every agent I have to load in JVM.I've tried something like this :java -javaagent:agentA.jar, agentB.jar MyJavaProgramor something like this:java -javaagent:agentA.jar agentB.jar MyJavaProgramBut have no success.Is there an answer to solve my problem ?Thank you.
NullPointerException using ImageIO.read : I'm getting an NPE while trying to read in an image file, and I can't for the life of me figure out why. Here is my line:BufferedImage source = ImageIO.read(new File(imgPath));imgPath is basically guaranteed to be valid and right before it gets here it copies the file from the server. When it hits that line, I get this stack trace:Exception in thread Thread-26 java.lang.NullPointerException at com.ctreber.aclib.image.ico.ICOReader.getICOEntry(ICOReader.java:120) at com.ctreber.aclib.image.ico.ICOReader.read(ICOReader.java:89) at javax.imageio.ImageIO.read(ImageIO.java:1400) at javax.imageio.ImageIO.read(ImageIO.java:1286) at PrintServer.resizeImage(PrintServer.java:981) ---My function Stack of rest of my application hereAlso, this is thrown into my output window:Can't create ICOFile: Can't read bytes: 2I have no idea what is going on, especially since the File constructor is succeeding. I can't seem to find anybody who has had a similar problem. Anybody have any ideas? (Java 5 if that makes any difference)
How to learn game development? : I've been a web programmer for a while and I can also program in Java. I have an idea for a small, multiplayer RPG game that I want to work on. It will be played through a java applet in the user's web browser.I have written the design document and specifications of the gameplay. What I'd like to know now is how I can develop the game? I've worked only with windows-like business apps in the past, with built-in widgets for textboxes, dropdowns, etc. With game programming it seems that I would have to build my own widget/controls for the UI of the game.These are the specific questions I have in mind:1) How to display a 'loading...' message with a progress bar while the game's images, sound, etc are being downloaded. (Using the java applet)2) How to create the UI of the game with its own menu, controls, etc. Such as by clicking the map icon it would show up a map to them. Clicking the friends icon would let them chat to their friends, etc.3) And other, general game development issues that i should know about, like whether I should use 2D or 3D graphics, physics in games, etc.If there's a good recommendation for a book that will help me, do share.
Deleting Java's temporary internet files : In the Java Control Panel on Windows there are settings for temporary internet files wherein all the applets and webstart stuff is cached. For certain users of our application this caching doesn't work properly and they need to delete all the files through the control panel before our webstart application will update itself properly.Overlooking the other implications of doing so, is there anyway we can programmatically delete the temporary file cache when we do an update, preferably through Java and without resorting to any batch file or Windows hackery quackery?
java 6 broke webstart application installation with error 'java.lang.Exception: cache failed for' : After upgrading to the latest java version (Java 6 update 13) a webstart application that was being used in production environments for many years, stopped installing with the following error:java.lang.Exception: cache failed forhttp://localhost:8080/ReactorStudio/studio/installer.jnlp at com.sun.javaws.Launcher.updateFinalLaunchDesc(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.launch(Unknown Source) at com.sun.javaws.Main.launchApp(Unknown Source) at com.sun.javaws.Main.continueInSecureThread(Unknown Source) at com.sun.javaws.Main$1.run(Unknown Source) at java.lang.Thread.run(Unknown Source)The application jnlp is downloaded correctly and all the associated jar files. The application also contains a reference to an installer jnlp file that extracts a few files to the local disk the first the application is being run.Any ideas on what is the problem, or how I could bypass this?
How to allow running only one instance of a Java program at a time? : I need to prevent users from starting my Java application (WebStart Swing app) multiple times. So if the application is already running it shouldn't be possible to start it again or show a warning / be closed again.Is there some convenient way to achieve this? I thought about blocking a port or write sth to a file. But hopefully you can access some system properties or the JVM?btw. target platform is Windows XP with Java 1.5
Applet (or WebStart application) calling a server : best practices? : I'd like to write an applet (or a java Web start application) calling its server (servlet?) to invoke some methods and to send/retrieve data. What would be the best way/technology to send and to retrieve those message ?
Eclipse warning about synthetic accessor for private static nested classes in Java? : My coworker suggested making several of the Eclipse code-formatting and warning settings to be more rigorous. The majority of these changes make sense, but I get this one weird warning in Java. Here's some test code to reproduce the problem:package com.example.bugs;public class WeirdInnerClassJavaWarning { private static class InnerClass { public void doSomething() {} } final private InnerClass anInstance; { this.anInstance = new InnerClass(); // !!! this.anInstance.doSomething(); }}// using this.anInstance instead of anInstance prevents another warning,// Unqualified access to the field WeirdInnerClassJavaWarning.anInstance The line with the !!! gives me this warning in Eclipse with my new warning settings:blockquote Access to enclosing constructor WeirdInnerClassJavaWarning.InnerClass() is emulated by a synthetic accessor method. Increasing its visibility will improve your performance./blockquoteWhat does this mean? The warning goes away when I change private static class to protected static class, which makes no sense to me.edit: I finally figured out the correct fix. The real problem here seems to be that this nested private static class is missing a public constructor. That one tweak removed the warning:package com.example.bugs;public class WeirdInnerClassJavaWarning { private static class InnerClass { public void doSomething() {} public InnerClass() {} } final private InnerClass anInstance; { this.anInstance = new InnerClass(); this.anInstance.doSomething(); }}I want the class to be a private nested class (so no other class can have access to it, including subclasses of the enclosing class) and I want it to be a static class.I still don't understand why making the nested class protected rather than private is another method of fixing the problem, but maybe that is a quirk/bug of Eclipse.(apologies, I should have called it NestedClass instead of InnerClass to be more clear.)
why do I get UnsupportedClassVersionError in jnlp? : I get an UnsupportedClassVersionError thrown when launching jnlp, however when I try to run the relevant jar files from command line everything works fine. I tried setting j2se versions to 1.5+, 1.6+, using signed/unsigned jar files, but all that doesn't help.I'm trying to launch my own jar file with two supporting jar files (mysql-connector.jar and swingx.jar). My jar file has been compiled with 1.6 compliance settings in Eclipse and built into a jar with ant. Since I can launch the 3 jars from command line using java 1.6 I'm a bit baffled that jnlp fails. Any help is appreciated.Here is the jnlp file:?xml version=1.0 encoding=utf-8?!-- JNLP File --jnlp spec=1.5+ codebase=http://www.etc.com/p href=demo-daily.jnlp information titledemo: daily stock charting utility/title offline-allowed/ /information security /security resources j2se href=http://java.sun.com/products/autodl/j2se version=1.6+ / jar href=demo-daily.jar main=true / jar href=swingx.jar main=false / jar href=mysql-connector.jar main=false / /resources application-desc main-class=quipu.viewers.charts.stockcharts.daily//jnlpThe error I get is:java.lang.UnsupportedClassVersionError: Bad version number in .class fileat java.lang.ClassLoader.defineClass1(Native Method)at java.lang.ClassLoader.defineClass(ClassLoader.java:675)at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)at java.net.URLClassLoader.access$100(URLClassLoader.java:56)at java.net.URLClassLoader$1.run(URLClassLoader.java:195)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:188)at com.sun.jnlp.JNLPClassLoader.findClass(JNLPClassLoader.java:256)at java.lang.ClassLoader.loadClass(ClassLoader.java:316)at java.lang.ClassLoader.loadClass(ClassLoader.java:251)at com.sun.javaws.Launcher.doLaunchApp(Launcher.java:1052)at com.sun.javaws.Launcher.run(Launcher.java:105)at java.lang.Thread.run(Thread.java:613)
Why some times Java does not request for new versions of jar files? : Every time we update our Java application (Java client and Java server) we have the problems that some clients approx. 1% - 2% does not load the new jar files. This occur with applets and also with Java Web Start. If you clear the Java Cache then all is working correct.Any idea why Java does not check for new jar files on every start?
Why the jpg file I converted from a gif file isn't crisp and clear? : I use the following code to convert a gif file to a jpg file, it works but the result jpg file isn't the same quality as the original gif file, why ? Any way to improve the quality ?try{ ImageIO.write(ImageIO.read(new File(C:/abc.gif)),jpg,new File(C:/abc.jpg));}catch (Exception e) { e.printStackTrace(); }So, to ask this question from another angle, with the above approach, how to increase the output quality ?
How to regulate the amount of printouts generated by a logging instruction produces over time? : How can I limit a program log printouts to a maximum of X printouts within Y seconds?Programming server side with java.util.logging, my code has a lot of info, warning, and error statements like:s_logger.logp(Level.WARNING, myClassName, myMethodName, msg.code.in.properties.file);On the one hand, I do want to see the warning message above printed to the STDOUT, since it serves an indication that something went wrong, especially when investigating problems in production, but on the other hand, printing numerous lines that tells the same story over a short period of time, has no added value but instead hit performance and introduces scrolling blindness. What I'm looking for is a mechanism/API that could regulate the printouts to no more than x messages, per message code, during y seconds. For example, over the course of a minute, I don't want to generate and write to the log more than 10 messages of the type: transaction timed out. I'd be happy for a API or a library reference, Anyone?
Dynamicly generate a JNLP file for a Java Web Start application? : I'm writing a servlet to return a JNLP file with several dynamically generated parameters to be passed to a web start program. Right now my code uses a stock template and token replacement, but I have to think there is a way to generate this file programmaticly within a servlet.Are there any tools available for this?
Using Netbeans to design GUIs and the ability to start with Web Start : I designed a GUI program using Netbeans 6.5 on a computer running Vista. I uploaded it to my server and tested out the web start. It worked fine.Later when using a Mac, it was not able to work. I tested it out in Ubuntu and was unsuccessful as well. I even tried to compile the source code on Ubuntu and I got this:Task required to generate JNLP file is missing, probably the library 'JWS Ant Tasks' is missing either from shared folder or from IDE installation.Basically the Java Desktop Application ran fine on the Windows computer but will not run on other computers. I just created a test Application on the Ubuntu computer, uploaded it and it ran fine.How come the program I compiled and ran yesterday on a computer running Vista will not run on Ubuntu? Thanks.
Retrieve an image from the web in java : I am trying to read an image that resides somewhere on the web from my Java program. So far I have successfully loaded an image by using the following code.URL url = new URL(http://www.google.com/images/nav_logo4.png);Image img = Toolkit.getDefaultToolkit().getImage(url);What I want to know is why this code (which is the first i tried) does not work:BufferedImage img = ImageIO.read(new File(http://www.google.com/images/nav_logo4.png));This would have the benefit of giving me a BufferedImage. Also, how can I make the above code block until the image is loaded? I know I can use an ImageObserver, but is there a simpler way?When I try the second option, I get this exception:javax.imageio.IIOException: Can't read input file!
Java Code for calculating Leap Year : I am following The Art and Science of Java book and it shows how to calculate a leap year.The book uses ACM Java Task Force's library.Here is the code the books uses:import acm.program.*;public class LeapYear extends ConsoleProgram { public void run() { println(This program calculates leap year.); int year = readInt(Enter the year: ); boolean isLeapYear = ((year % 4 == 0) amp;amp; (year % 100 != 0) || (year % 400 == 0)); if (isLeapYear) { println(year + is a leap year.); } else println(year + is not a leap year.); }}Now, this is how I calculated the leap year. import acm.program.*;public class LeapYear extends ConsoleProgram { public void run() { println(This program calculates leap year.); int year = readInt(Enter the year: ); if ((year % 4 == 0) amp;amp; year % 100 != 0) { println(year + is a leap year.); } else if ((year % 4 == 0) amp;amp; (year % 100 == 0) amp;amp; (year % 400 == 0)) { println(year + is a leap year.); } else { println(year + is not a leap year.); } }}Is there anything wrong with my code or should i use the one provided by the book ?EDIT :: Both of the above code works fine, What i want to ask is which code is the best way to calculate the leap year.
Java webstart Security : What is the option in Java Webstart command line to skip the security check? This is for testing purposes only.javaws myfile.jar
Java Webstart Options : I am using javaws to run an application in OS X 10.5.7, Java(TM) SE Runtime Environment (build 1.6.0_13-b03-211), and it seems that the command line arugments are broken in os X. I run the following command in linux and it works fine.javaws -wait -J-Djavaws.package.runtype=debug http://company.com/launch.jnlpand the runtime gives me the property javaws.package.runtype=debug. But when I run the same arugment in os X, I get jnlpx.vmargs = -Djavaws.package.runtype=debugIs this an error, or just an unknown feature?
JWS JNLP no Desktop Icon on Mac : I seem to be having a problem getting the icon for a Java Web Start program to appear on the Mac desktop, or under Applications. The icon's and menu's are created and work properly under windows XP and Vista, is there something different that must be done for Macs?On the Mac there aren't output any errors, it prompts me with the question if I would like to create the shortcuts, I click yes, and then it continues launching the program but never seems to produce them.
Threadsafe publishing of java object structure? : Assuming that I have the following code:final Catalog catalog = createCatalog();for (int i = 0; i 100; i++{ new Thread(new CatalogWorker(catalog)).start();}Catalog is an object structure, and the method createCatalog() and the Catalog object structure has not been written with concurrency in mind. There are several non-final, non-volatile references within the product catalog, there may even be mutable state (but that's going to have to be handled)The way I understand the memory model, this code is not thread-safe. Is there any simple way to make it safe ? (The generalized version of this problem is really about single-threaded construction of shared structures that are created before the threads explode into action)
Can I use Scanner class in text file for getting information? : this code is correct??String note = text.txt;FileWriter file = new FileWriter(note);Scanner sc = new Scanner(System.in);System.out.println(Enter your name:);String name = sc.next();file.close();How can I pass this file to the program as a command line argument???
JPA EntityManager: Why use persist() over merge()? : EntityManager.merge() can insert new objects and update existing ones.Why would one want to use persist() (which can only create new objects)?
Using Scanner.next() to get text input : I am trying to get text input from the keyboard in Java 6. I am new to the language and whenever i run the following code, I get this error:package test1;import java.util.Scanner;public class Test {public static void main(String[] args) { boolean quit = false; while (!quit){ Scanner keyIn; String c = x; while (c != y amp;amp; c != n) { keyIn = new Scanner(System.in); c = keyIn.next(); keyIn.close(); } if (c == n) quit = true; } }}Exception in thread main java.util.NoSuchElementExceptionat java.util.Scanner.throwFor(Scanner.java:838)at java.util.Scanner.next(Scanner.java:1347)at test1.Test.main(Test.java:11)Am I mis-using the next() method? I thought it would wait for user input but it looks like it isn't and throwing the exception saying that there is nothing left in the scanner.
How can I convert a Java Iterable to a Scala Iterable? : Is there an easy way to convert a java.lang.Iterable[_]to aScala.Iterable[_]?
how to install php and javabridge on Tomcat : how to set the environment variables of javabridge.what are the setting can be change for installing JavaBridge and php on Tomcat
Recommended way to send email from a web app? : I have a web app on JBoss 4.2.3 and I'd like it to send email. I could do something like:try {Properties props = System.getProperties();props.put(mail.transport.protocol, smtp );props.put(mail.smtp.starttls.enable,false );props.put(mail.smtp.host,smtp.somehost.com);props.put(mail.smtp.auth, true );Authenticator auth = new SMTPAuthenticator();Session session = Session.getInstance(props, auth);// -- Create a new message --Message msg = new MimeMessage(session);// -- Set the FROM and TO fields --msg.setFrom(new InternetAddress(me@somehost.com));msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient@somewhere.com, false));msg.setSubject(yadayada);msg.setText(Yada yada);// -- Set some other header information --msg.setHeader(MyMail, Mr. XYZ );msg.setSentDate(new Date());// -- Send the message --Transport.send(msg);}catch (Exception ex) { ex.printStackTrace(); System.out.println(Exception +ex);}but it doesn't feel right. Will this scale?
input/output with Java Web Start : I'm working on converting a very simple java desktop application to run in java web start and I'm having all kinds of trouble with the input/output files. Most specifically I can't seem to find any information on how to handle i/o in a web start application. I tried placing the input files in the same folder on my web server as the jar and jnlp file, but it doesn't read it.I've got one input file that I want to keep on the web server and read into the application from there. I've got a second file that I want the application to generate on the client machine the first time it's run, and read in from there every time thereafter.If anyone knows what considerations I need to take for i/o in java web start or can point me towards a resource that explains it I would appreciate it.
Trouble understanding :state in Clojure : I understand what :state /does/. It creates a field, like in Java, in your class. What I don't understand is what is the point of this? It seems like I only see it done with Clojure-generated classes that extend other classes. a href=http://www.fatvat.co.uk/2009/05/clojure-and-robocode.html rel=nofollow noreferrerhttp://www.fatvat.co.uk/2009/05/clojure-and-robocode.html being one example. I don't know Java, and I'm not very well versed in Object Oriented Programming. Can someone explain the point of :state to me, and where it all fits in with Java interop?Thanks a lot!NOTE: When I say :state, I am referring to (:gen-class :state)
When you extend a Java class in Clojure and define a method of the same name as one in that class, what is happening? : I've been reading through Programming Clojure, and I've been having some trouble understanding Stuarts primary Java Interop example. He extends DefaultHandler, and creates a startElement method, and then passes that handler to an XML parser. What I don't understand, is what exactly is happening. Does his implementation of startElement override the one defined in DefaultHandler? I'm confused. I have no experience with Java, and little with object orientation.Thanks!
Can I supress the loading dialogs in Java Web Start? : I'm trying to put together a Java Webstart app, but don't want it to display the Webstart splash screen, or downloading app boxes. Is there any way I can turn them off? (I'm fine with it displaying the Permissions Request box, but nothing else).
Launching a browser window from Java WebStart (JNLP) in Java 6u13+ : There is a bug in Java 6u13 and 6u14. a href=http://bugs.sun.com/view_bug.do?bug_id=6835450 rel=nofollow noreferrerhttp://bugs.sun.com/view_bug.do?bug_id=6835450Simply put, the following code is supposed to open a browser window, but because of a bug in the framework, it stopped working in Java 1.6 update 13. Nothing opens anymore. There was a similar bug for Java applets (that was fixed in update 14), but this one still exists in update 14 for Java WebStart/JNLP. getAppletContext().showDocument(new URL(http://www.sun.com),_blank);Do you know of any workarounds?
Oracle Java Stored Procedure Command-line Interaction : I have a funny requirement.We need to have a command-line interaction in a Java Stored Procedure. In spite of granting appropriate permissions using the dbms_java.grant_permission commands, I am encountering java.io.IOException, where I read from System.in using java.io.InputStreamReader.Where is the problem?The Java Source is here:import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.sql.ResultSet;import java.sql.Statement;import java.sql.Connection;import java.sql.SQLException;import oracle.jdbc.driver.OracleDriver;public class ExecuteInteractiveBatch { public static void aFunction() { Connection connection = null; try { int rowFetched = 0; connection = new OracleDriver().defaultConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(SELECT count(1) cnt from sometable where c = 2); int count = 0; if (rs.next()) { count = rs.getInt(1); } rs.close(); stmt.close(); rs = null; stmt = null; if (count == 1) { System.out.println(Do you want to continue?); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String response = reader.readLine(); if (Y.equalsIgnoreCase(response)) { stmt = connection.createStatement(); int rowsAffected = stmt.executeUpdate(DELETE from sometable where c=2); System.out.println( + rowsAffected + row(s) deleted); stmt.close(); } } } catch (IOException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } finally { try { if (connection != null || !connection.isClosed()) { connection.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } }}
Having trouble calling getCodeBase in Clojure : I'm trying to write a function to play a sound file once, using some resources I found. The code is as follows:(defn play [file] (let [songp (URL. (.getCodeBase) file) song (.newAudioClip songp)] (. song play)))The problem is, (.getCodeBase) is a malformed member expression. I'm not sure what to do. How do you call a method like this? In the Java code I looked at, it was simply called like so:getCodeBase()Am I missing something?
Java Webstart with parameters : Can I launch a Java WebStart application with a set of parameters just like an applet is configured with the param tags ?Thanks
How do I attach to Skype using Skype4Java? : I am getting the following exception when trying to run the MakeCall example code:com.skype.NotAttachedException at com.skype.Utils.convertToSkypeException(Utils.java:36) at com.skype.Skype.setDebug(Skype.java:116) at com.skype.sample.MakeCall.main(MakeCall.java:26)Caused by: com.skype.connector.NotAttachedException at com.skype.connector.Connector.assureAttached(Connector.java:580) at com.skype.connector.Connector.addConnectorListener(Connector.java:604) at com.skype.connector.Connector.addConnectorListener(Connector.java:591) at com.skype.connector.Connector.setDebug(Connector.java:209) at com.skype.Skype.setDebug(Skype.java:114) ... 1 moreNow, I have not provided any sort of API credentials, so I kind of expect it to fail. My question then, is how do I provide whatever credentials necessary to attach my connector? The documentation on Skype4Java seems pretty slim.After not getting any tips here, I have cross-posted this question on the a href=http://forum.skype.com/index.php?showtopic=397881 rel=nofollow noreferrerSkype community forum as well.
Is there a faster way to deploy WSIT Services than autodeploy? : We've recently upgraded our services technology stack. We opted for the WSIT implementation of JAX-WS.Currently, we're relying on our Glassfish Application Server to deploy the web service automatically based on the JAX-WS annotations. We have about two dozen different services and hundreds of operations, so this autodeployment takes quite a while. Is there a faster way to deploy than autodeployment?What I'm looking for is something that can do the work at compile time or build time instead.
Convert Byte Array to image in Java - without knowing the type : Sounds simple right? Use ImageIO.read(new ByteArrayInputStream(bytes));Here's the wrinkle. For some reason it is detecting a jpeg as a bmp, and that is the first ImageReader returned when I call ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));IteratorImageReader readers=ImageIO.getImageReaders(iis);This causes the image to come out corrupted. Is there a way to tell through java short of looking directly at the bytes for the header, and failing that does anyone know of a good reference for the byte headers for the different images? Just letting you guys know I am still working on this. I'll let you know if/when I have an answer. I thank all of you for your responses so far.
Exchange server will not accept username/password provided with javax.mail API : I have a lovely little Java client that sends signed email messages. We have an Exchange server that requires username/password authentication to send a message.When I connect to the exchange server, I get this error:avax.mail.AuthenticationFailedException: failed to connect at javax.mail.Service.connect(Service.java:322) at javax.mail.Service.connect(Service.java:172)When I connect to other servers (Unix servers), I have no problem.Below is the full debug trace. I can't figure it out. DEBUG: JavaMail version 1.4.2DEBUG: successfully loaded resource: /META-INF/javamail.default.providersDEBUG: Tables of loaded providersDEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SM}DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], }DEBUG: successfully loaded resource: /META-INF/javamail.default.address.mapDEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]DEBUG SMTP: useEhlo true, useAuth trueDEBUG SMTP: trying to connect to host SERVER, port 25, isSSL false220 SERVER ESMTP (deca81216f2ecf4fd6fedb030e3dcfd0)DEBUG SMTP: connected to host SERVER, port: 25EHLO CLIENT250-SERVER Hello CLIENT [192.1.1.1], pleased to meet you250-STARTTLS250-PIPELINING250-SIZE 100000000250-AUTH LOGIN PLAIN250-AUTH=LOGIN PLAIN250-8BITMIME250 HELPDEBUG SMTP: Found extension STARTTLS, arg DEBUG SMTP: Found extension PIPELINING, arg DEBUG SMTP: Found extension SIZE, arg 100000000DEBUG SMTP: Found extension AUTH, arg LOGIN PLAINDEBUG SMTP: Found extension AUTH=LOGIN, arg PLAINDEBUG SMTP: Found extension 8BITMIME, arg DEBUG SMTP: Found extension HELP, arg STARTTLS220 Ready to start TLSEHLO CLIENT250-SERVER Hello CLIENT [192.1.1.1], pleased to meet you250-PIPELINING250-SIZE 100000000250-AUTH LOGIN PLAIN250-AUTH=LOGIN PLAIN250-8BITMIME250 HELPDEBUG SMTP: Found extension PIPELINING, arg DEBUG SMTP: Found extension SIZE, arg 100000000DEBUG SMTP: Found extension AUTH, arg LOGIN PLAINDEBUG SMTP: Found extension AUTH=LOGIN, arg PLAINDEBUG SMTP: Found extension 8BITMIME, arg DEBUG SMTP: Found extension HELP, arg DEBUG SMTP: Attempt to authenticateDEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 AUTH LOGIN334 VXNlcn5hbWU6RVJOXHNsK2FyZmlu334 UGFzc3dvcmQ6UVdFUnF3ZXIxMjM0IUAjJA==535 Error: authentication failedDEBUG SMTP: useEhlo true, useAuth trueDEBUG SMTP: trying to connect to host SERVER, port 25, isSSL false220 SERVER ESMTP (deca81216f2ecf4fd6fedb030e3dcfd0)DEBUG SMTP: connected to host SERVER, port: 25EHLO CLIENT250-SERVER Hello CLIENT [192.1.1.1], pleased to meet you250-STARTTLS250-PIPELINING250-SIZE 100000000250-AUTH LOGIN PLAIN250-AUTH=LOGIN PLAIN250-8BITMIME250 HELPDEBUG SMTP: Found extension STARTTLS, arg DEBUG SMTP: Found extension PIPELINING, arg DEBUG SMTP: Found extension SIZE, arg 100000000DEBUG SMTP: Found extension AUTH, arg LOGIN PLAINDEBUG SMTP: Found extension AUTH=LOGIN, arg PLAINDEBUG SMTP: Found extension 8BITMIME, arg DEBUG SMTP: Found extension HELP, arg STARTTLS220 Ready to start TLSEHLO CLIENT250-SERVER Hello CLIENT [192.1.1.1], pleased to meet you250-PIPELINING250-SIZE 100000000250-AUTH LOGIN PLAIN250-AUTH=LOGIN PLAIN250-8BITMIME250 HELPDEBUG SMTP: Found extension PIPELINING, arg DEBUG SMTP: Found extension SIZE, arg 100000000DEBUG SMTP: Found extension AUTH, arg LOGIN PLAINDEBUG SMTP: Found extension AUTH=LOGIN, arg PLAINDEBUG SMTP: Found extension 8BITMIME, arg DEBUG SMTP: Found extension HELP, arg DEBUG SMTP: Attempt to authenticateDEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 AUTH LOGIN334 VXNlcm5hbWU6RVJOXHNsZ2FyZmlu334 UGFzc3dvcmQ6UVdFUnF3ZXIxMjM0IUAjJA==535 Error: authentication failedError sending mail: failed to connectjavax.mail.AuthenticationFailedException: failed to connect at javax.mail.Service.connect(Service.java:322) at javax.mail.Service.connect(Service.java:172) at SignMessage.sendSigned(SignMessage.java:248) at SignMessage.main(SignMessage.java:340
Problem with matching token in a line, using Scanner in Java : I need to match certain things from lines of an input text. The lines look like this: to be/ Σ _ Σ [1pos, 1neg] {0=1, 2=1}I am using the Scanner class to read each line of the text, and I have written the following code. However, something is not working properly, because the patter to is not matched against the line, and it should be, because to is contained in the line (I have tried to match not only to from the line, but nothing matches): Scanner scanner = new Scanner(file); while(scanner.hasNext()) { String line = scanner.nextLine(); System.out.println(line: + line); Pattern p_pos = Pattern.compile(to); Matcher m_pos = p_pos.matcher(line); String match = m_pos.group(0); System.out.println(match: + match); boolean b_pos = m_pos.matches(); if(b_pos) { System.out.println(match); } }Output:line: to be/ Σ _ Σ [1pos, 1neg] {0=1, 2=1}Exception in thread main java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group(Matcher.java:485) at lady.PhrasesFromFile.readFile(PhrasesFromFile.java:31) at lady.PhrasesFromFile.main(PhrasesFromFile.java:17)I have one more question: how can I process the line so that I store everything from the beginning of the line till the first / symbol? I couldn't find any method for that in the API. Is it possible to do so? I basically want consecutively to go through the line, store pieces of the line in different variables, and then use the values of these variables. Since I do not know how many token I have before the first / symbol, I cannot use next() a certain number of times.Thank you in advance.
Setting java.util.logging destination programmatically : I'm using java.util.logging for logging and tracing purposes. How can I within a Java application dynamically set the file to which the log should be written.
java console menu : I'm writing a java console menu. however, my jre doesn't support Scanner. What is the walk around to this problem? java.util.Scanner scanner = new Scanner (System.in);
Javaagent class unloading : I have a java agent which instruments bytecode.I am using the attach apis in java 6 to allow users to dynamically load the agent and instrument and deinstrument code using my java agent.I am using the Boot-Class-Path manifest attribute to make sure my javagent classes are in the boot classpath so that my users can instrument classes like ArrayList, etc.However the problem comes with versioning.Lets say a user dynamically attaches version 1 of my agent.Then I given him version 2. Now since his app server never shut down since he attached version 1 of my agent, the version 1 classes are still loaded. I need some way such that when my client version 2 of the javaagent, the version 1 is unloaded.I know one way would be to write a customer classloader for my javaagent's classes, and set the classloader reference to null.However in that case I wont be able to instrument classes in the boot classpath since my classloader will be below in the hierarchy from the boot classloader and thus my users cant instrument classes like ArrayList because if I add a call inside ArrayList's methods to one of my agent's classes' methods the boot class loader wont be able to see them.So is there any way to solve the boot classpath issue and still unload the previous agent's classes?
Launch Runnable Jar from Web Start : This is my first time trying to use Web Start, and I am trying to launch my runnable jar. I get the following error from my webpage as I click the link to launch the jar. Can anyone help me out? The Notepad example from the tutorial works fine from another link on the test page (JNLP and jar in same folder as I have too). The jar and jnlp are definitely in the same folder, yet the jar cannot be found. Thanks in advance.Folder Structure:/MyApp/MyApp/MyApp.jnlp/MyApp/MyApp.jarJNLP File:?xml version=1.0 encoding=utf-8?jnlp spec=1.0+ codebase=http://localhost/MyApp href=MyApp.jnlp information titleMyApp Demo/title vendorCompany Name/vendor /information resources jar href=MyApp.jar/ j2se version=1.5+ href=http://java.sun.com/products/autodl/j2se/ /resources application-desc main-class=MyAppMain argumentarg1/argument argumentarg2/argument /application-desc/jnlpException:com.sun.deploy.net.FailedDownloadException: Unable to load resource: http://localhost/MyApp/MyApp.jar at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source) at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source) at com.sun.javaws.LaunchDownload.downloadJarFiles(Unknown Source) at com.sun.javaws.LaunchDownload.downloadEagerorAll(Unknown Source) at com.sun.javaws.Launcher.downloadResources(Unknown Source) at com.sun.javaws.Launcher.prepareLaunchFile(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.launch(Unknown Source) at com.sun.javaws.Main.launchApp(Unknown Source) at com.sun.javaws.Main.continueInSecureThread(Unknown Source) at com.sun.javaws.Main$1.run(Unknown Source) at java.lang.Thread.run(Unknown Source)Wrapped Exception:java.io.FileNotFoundException: http://localhost/MyApp/MyApp.jar at sun.reflect.GeneratedConstructorAccessor2.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source) at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source) at com.sun.deploy.net.BasicHttpRequest.doGetRequest(Unknown Source) at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source) at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source) at com.sun.javaws.LaunchDownload.downloadJarFiles(Unknown Source) at com.sun.javaws.LaunchDownload.downloadEagerorAll(Unknown Source) at com.sun.javaws.Launcher.downloadResources(Unknown Source) at com.sun.javaws.Launcher.prepareLaunchFile(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source) at com.sun.javaws.Launcher.launch(Unknown Source) at com.sun.javaws.Main.launchApp(Unknown Source) at com.sun.javaws.Main.continueInSecureThread(Unknown Source) at com.sun.javaws.Main$1.run(Unknown Source) at java.lang.Thread.run(Unknown Source)Caused by: java.io.FileNotFoundException: http://localhost/MyApp/MyApp.jar at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) ... 20 moreConsole:Java Web Start 1.6.0_15Using JRE version 1.6.0_15-b03 Java HotSpot(TM) Client VMUser home directory = C:\Documents and Settings\username----------------------------------------------------c: clear console windowf: finalize objects on finalization queueg: garbage collecth: display this help messagem: print memory usageo: trigger loggingp: reload proxy configurationq: hide consoler: reload policy configurations: dump system and deployment propertiest: dump thread listv: dump thread stack0-5: set trace level to n----------------------------------------------------#### Java Web Start Error:#### Unable to load resource: http://localhost/MyApp/MyApp.jar
ASM bytecode instrumentation for method entry / exit : I've created a JVMTI agent that does the following at a high level:onClassLoadHook send the bytecodes for the loaded class to a separate Java process that will instrument the class using ASMget the bytecodes back and load themIn my seperate java process that instruments the loaded Java class I do the following :.... cr = new ClassReader(inBytes, offset, inLen); cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); ClassAdapter ca = new ClassAdapter(cw) { .. .. @Override public MethodVisitor visitMethod(final int access, final String name, final String desc, String signature, String[] exceptions) { return new MethodAdapter(mv) { @Override public void visitCode() { mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESTATIC, com/amir/Tester, callTestStatic3, (Ljava/lang/Object;)V); mv.visitCode(); } } }When I try to decompile the class that is written after this instrumentation using Java Decompiler - I see the following decompiled function which I know is wrong : public void func1(int arg1, int arg2) { int b; Tester.callTestStatic3(???); System.out.println(arg = + a + b = + b); }because my function actually looks like this :public void func1(int a, int b) { System.out.println(arg = +a + b = +b);}Can anyone tell me if I did something wrong here? My only clue is that if instead of passing in as an argument to my function the THIS pointer, if I pass in primitive types, everything works out finie. Is there something special about the THIS pointer that I need to manage? I've compared the bytecodes, and I've used ASMIFIER to get a clue as to what statements I need to use to generate the right bytecodes.
Why Java ImageIO flattens JPEG colors : When I read certain JPG files, colors are flattened. Here is a simple example that reads a jpg and just writes the same image to another file.import java.awt.image.BufferedImage;import java.io.File;import javax.imageio.ImageIO;public class JPegReadTest { public static void main(String[] args) { if (args.length == 2) { try { BufferedImage src = ImageIO.read(new File(args[0])); ImageIO.write(src, jpg, new File(args[1])); } catch (Exception e) { e.printStackTrace(); } } else { System.err.println(Usage: java JPegReadTest src dest); } }}If you try this with for example a href=http://www.flickr.com/photos/visualpanic/233508614/sizes/l/ rel=nofollow noreferrerhttp://www.flickr.com/photos/visualpanic/233508614/sizes/l/ , the colors of the destination image differ from the source file. Why is that? How to fix it?Also tried saving the image as png, but the colors are bland in it too (so assuming color info is not read properly).
Starting a Java agent after program start : Is it possible to insert a javaagent after virtual machine start from within the same VM?Lets say for example we have an agent in a jar myagent.jar with the appropriate meta data set-up and an agentmain method already implemented. Now the users program calls an API call which should result in the insertion of the agent so that it can redefine the classes.Can it be done and how?
JNLP doesn't show splash screen when launching from a desktop icon : I have been able to create a JNLP file, which successfully sets up a splash screen amp; a desktop icon for a Java program launched through Web Start. Here's the relevant chunk of the JNLP: Now, to launch the program, I find I can either click on the JNLP, in which case the splash screen shows, or on the desktop icon, in which case the default Java Web Start splash screen shows instead. This is on Windows XP amp; Windows Vista, and it's Java 1.5 and Java 1.6.Is there a way to get my splash screen to show when launching from the JNLP file, instead of the Java one?Thanks.
Can we deny a java object from serialization other than giving transient keyword : We can avoid serialising fields by using the transient keyword.Is there any other way of doing that?
Invalid byte 1 of 1 utf-8 sequence in vb.net : From my Windows Service I am passing a well-formed XML string to a Java Web Service. The Java Web Service will process the data and return me a status code. Though I am passing a well formatted XML file. I am getting an error from the Java Web Service of:blockquote Invalid byte 1 of 1 utf-8 sequence in vb.net/blockquoteWhat is the reason for this?Transferred from answer by author:Sorry for not providing more details. Here is the sample XML I am generating from VB.net Windows service and there are CDATA tags for a few elements.?xml version=1.0 encoding=utf-8?bookstore book category=COOKING title lang=enEveryday Italian/title authorGiada De Laurentiis/author year2005/year price30.00/price /book book category=CHILDREN title lang=enHarry Potter/title authorJ K. Rowling/author year2005/year price29.99/price /book book category=WEB title lang=enLearning XML/title authorErik T. Ray/author year2003/year price39.95/price /book/bookstoreI am passing the above XML to the Java Web Service.The XML received by the Java Application though is not cleanly formatted. For some reason few closing tags are broken and appearing in next line.For example:book category=WEB title lang=enLearning XML/title authorErik T. Ray/author year2003/year price39.95/price /bookCould this be part of the trouble?
How to get line number using scanner : I'm using scanner to read a text file line by line but then how to get line number since scanner iterates through each input?My program is something like this:s = new Scanner(new BufferedReader(new FileReader(input.txt)));while (s.hasNext()) {System.out.print(s.next());This works fine but for example:1,2,3 3,4,5I want to know line number of it which mean 1,2,3 is in line 1 and 3,4,5 is in line 2.How do I get that?
How to recreate shortcut to webstart application? : I use the shortcut tag in my appliation's jnlp descriptor to create a desktop link and a menu entry for my application.If these shortcuts get deleted on the client - how can they be reinstalled automatically without user action? Is there a configuration option for the jnlp file?(btw I'm using java6)
How to get updated jnlp file when using shortcuts? : If my jnlp descriptor on the server changes and I start my application from the browser, a new jnlp file will be created in the cache and my desktop shortcuts will be updated to use the new jnlp file. (that's good so far).But if I start my app using the desktop shortcut (or the menu entry), then my app won't know about the changed jnlp file on the server and will still use the cached outdated one.Is it possible to force webstart not only to get the newest jarfiles but also update the jnlp file itsself when starting the app?Background: I pass some parameters to my application (defined in the descriptor with the argument tag) to configure my app. If these arguments are changed - this must work of course too when using the shortcut.I'm using java6 (u15).EDIT: actually i've found this a href=http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=b5fd9a3ad1e340ddfe9b1bbce00?bug_id=6838214 rel=nofollow noreferrerjava bug 6838214 which seems to refer to my problem I think. If I interpret it correctly this should have been fixed in java6u14, but under u15 I still have this issue!
Deploying an SWT application on Java Webstart : Is it possible to deploy SWT applications using JNLP. Especially loading the swt native library (dll in Windows, so in Linux)? Any links? I found one at a href=http://www.ibm.com/developerworks/opensource/library/os-jws/ rel=nofollow noreferrerIBM Developer Works, however it just describes using swt.jar. In addition to that, is it possible to load the native dll files over JNLP?
Does a Java Scanner implicitly create a buffer even if you do not pass it one? : If I have the following example file where each number is represents a byte (123 has bytes 1, 2, and 3):123456789Let's say I create a FileInputStream. This reads in the binary byte by byte. So .read() returns 1, then 2, etc. Now let's say I create a buffer. The initial chunk it reads in (if I understand buffers correctly) is 1-5. This allows it to not only read in byte by byte, but in the case of characters whole lines, etc. But if I hit .read() again, I start at 6, and NOT where the BufferedReader stopped (so if 3 is a line break, and I told the BufferedReader to print the first line, it prints 1-2, and then using .read() from the FileInputStream gives me 6, and not 3.)In order to be able to parse data by the delimiter, does a Scanner implicitly create a buffer like how a BufferedReader creates a buffer so that it can find line breaks, etc? And if I pass a separate FileInputStream into the Scanner, using .read() will NOT print the first byte following the first delimiter the scanner found, but rather at the end of the chunk the scanner took?
JavaWebStart app randomly fails : I have a JAR signed with a self-signed certificate and deployed by JWS.It usually runs ok (most of the times) but sometimes fails which is quite annoying, It shows the splashscreen but nothing else.These are the last log lines:recorddate2009-09-08T16:55:33/datemillis1252421733468/millissequence173/sequenceloggercom.sun.deploy/loggerlevelFINE/levelclasscom.sun.deploy.util.LoggerTraceListener/classmethodprint/methodthread10/threadmessagenetwork: Conectando socket://127.0.0.1:4590 con proxy=DIRECT/message/recordrecorddate2009-09-08T16:55:37/datemillis1252421737171/millissequence174/sequenceloggercom.sun.deploy/loggerlevelFINE/levelclasscom.sun.deploy.util.LoggerTraceListener/classmethodprint/methodthread10/threadmessagesecurity: JAVAWS AppPolicy Permission requested for: http://127.0.0.1/ikuspro/ikuspro.jar/message/recordrecorddate2009-09-08T16:55:37/datemillis1252421737171/millissequence175/sequenceloggercom.sun.deploy/loggerlevelFINE/levelclasscom.sun.deploy.util.LoggerTraceListener/classmethodprint/methodthread10/threadmessagesecurity: We were not granted permission, exiting/message/record/logAnd this is my jnlp file?xml version=1.0 encoding=utf-8?!-- Fichero JNLP de Ikuspro --jnlp spec=6.0 codebase=http://127.0.0.1/ikuspro href=ikuspro.jnlpinformationtitleIkuspro/titlevendorMyName/vendorhomepage href=/descriptionIkuspro/descriptiondescription kind=shortDesc+/descriptionicon href=ikusproLogo.png/icon kind=splash href=splash.png/offline-allowed/shortcut online=truedesktop/menu submenu=Ikuspro//shortcut/informationsecurityall-permissions//securityupdate check=timeout policy=prompt-update/updateresourcesj2se version=1.6 java-vm-args=-esa -Xnoclassgc/jar href=ikuspro.jar//resourcesapplication-desc main-class=ikuspro.main.Ikuspro//jnlpAs I've said It doesn't always happen and the certificate has been accepted permanently.Besides I see that the debugging is in FINE level, How can I make it more verbose?Thanks in advance
Passing command line arguments to javaws (Java WebStart) executable : Summary for those who might not want to read that much:How do I do this: ? If we could pass ad-hoc command-line args to javaws, then javaws apps could be more like 1st class citizen ordinary application. E.g. we could pass filenames of files to be opened.I would like to know if there is a way to pass ad-hoc command line arguments to the javaws executable. I already know how to specify them in JNLP file:application-desc main-class=org.example.ClassNameargument...While this can be used for what i want to accomplish, i treat this as a workaround.I tried javaws http://example.org/launch.jnlp some CLI args hereBut some CLI args here were just ignored, i think.If we could pass ad-hoc command-line args to javaws, then javaws apps could be more like 1st class citizen ordinary application. E.g. we could pass filenames of files to be opened.Like e.g.javaws [options] http://example.org/launch.jnlp my_file.jpgHaving arguments hardcoded in JNLP does not satisfy this use case.
Java Webstart with Tibco Native Libs : I am trying to deploy an application that uses the native implementation of Tibrv through the TibrvJ library using Java Webstart.I have packaged up all of the Windows dlls from inside c:\tibco\tibrv\bin into a Jar file and have added these to the nativelib element in the JNLP file. I was hoping that webstart would take the dll files from thetibco-7.5.1-nativelibs.jar file and allow them to be loaded via System.loadLibrary which is called from Tibrv.open(). However it doesn't seem to want to work properly.My JNLP file looks like this:?xml version=1.0 encoding=utf-8?!DOCTYPE jnlp PUBLIC -//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0//EN http://java.sun.com/dtd/JNLP-6.0.dtdjnlp spec=6.0+ codebase=http://somewhere:8080/my-gui/application href=launch.jnlp information titleMy GUI/title vendorTechnology/vendor descriptionDashboard/description description kind=shortDashboard/description icon href=icon/Stocks-128x128.png / offline-allowed / shortcut online=true desktop / menu submenu=Dashboard / /shortcut /information security all-permissions / /security update check=always policy=prompt-update / resources j2se version=1.6+ href=http://java.sun.com/products/autodl/j2se java-vm-args=-Xmx120M -ea / property name=log4j.configuration value=live/log4j.xml / property name=swing.aatext value=true / jar href=tibrvj-7.5.1.jar / jar href=dashboard-gui.jar main=true / /resources resources nativelib href=nativelib/tibco-7.5.1-nativelibs.jar / /resources application-desc main-class=com.somewhere.Main argumentclasspath:/live/client.xml/argument argument/live/live.properties/argument /application-desc/jnlp The application launches but as soon as a call is made to open tib then it falls apart with an error along the lines of:[Root exception is TibrvException[error=22,message=Version mismatch: libtibrv version 7.4 does not match version of tibrvj shared library 7.5]]TibrvException[error=901,message=Library not found: tibrvj]]The users have a variety of Tib installations already on their PCs from Tib 7.2 through to 7.5. The Webstart Application only works correctly on a machine with 7.5 installed which matches the Jar file inside the package. So it doesn't appear to do anything with the nativelib jar.I would like to avoid having to deploy 3 versions of the web start application for the different versions of Tib that the users have installed.Has anyone else managed to get this combination of TibrvJ and Webstart working?
Bytecode instrumentation generating java verifier error : I am using ASM in order to do bytecode instrumentation for Java programs. What I'm doing is simple - When instrumenting a method, if the instruction is a PUTFIELD, simply do a DUP_X1 right before the instruction, then visit the PUTFIELD and inject a function call with an argument that includes the DUP'ed stack entry. public void visitFieldInsn( int opcode, String owner, // owner of this field... String name, String desc) { boolean did_dup = false; if(opcode == Opcodes.PUTFIELD) { if(!owner.equals(java/lang/System)) { if (desc.startsWith(L)) { mv.visitInsn(Opcodes.DUP_X1); did_dup = true; } } } mv.visitFieldInsn(opcode, owner, name, desc); if (did_dup) { mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESTATIC, com/amir/ASide, updateG, (Ljava/lang/Object;Ljava/lang/Object;)V); } }The code looks like this BEFORE and AFTER instrumentation, respectively :public void setA(ClassA classa){ refA = classa; eyeColor = classa.eyeColor;}public void setA(ClassA classa){ ASide.updateG(refA = classa, this); ASide.updateG(eyeColor = classa.eyeColor, this);}But when I run the instrumented code, I get :java.lang.VerifyError: Expecting to find object/array on stackCan you offer has any help on this?
Where is the source code for /jre/lib/deploy.jar? : Where is the source code for /jre/lib/deploy.jar?I have the source code for other jars like rt.jar (in /src.zip) but not deploy.jar.I need it to debug webstart.I'm using 1.6 on Windows if that makes a difference.
java 6 web services share domain specific classes between server and client : Context: Considering below defined Engine class being parameter of some webservice method. As we have both server and client in java we may have some benefits (???) in sharing Engine class between server and client ( i.e we may put in a common jar file to be added to both client and server classpath ) Some benefits would be : we keep specific operations like 'brushEngine' in same place build is faster as we do not need in our case to generate java code for client classes but to use them from the server build) if we later change server implementation for 'brushEngine' this is reflected automatically in client . Questions: How to share below detailed Engine class using java 6 tools ( i.e wsimport , wsgen etc )?Is there other tools for java that can achieve this sharing ?Is sharing a case that java 6 web services support is missing ?Can this case be reduced to other web service usage patterns?Thanks.Code:public class Engine { private String engineData; public String getData(){ return data; } public setData(String value){ this.data = value; } public void brushEngine(){ engineData = BrushedEngine+engineData; } }
How do you create a javax.swing.Timer that fires immediately, then every t milliseconds? : Right now, I have code that looks something like this:Timer timer = new javax.swing.Timer(5000, myActionEvent);According to what I'm seeing (and the a href=http://java.sun.com/javase/6/docs/api/javax/swing/Timer.html rel=nofollow noreferrerJavadocs for the Timer class), the timer will wait 5000 milliseconds (5 seconds), fire the action event, wait 5000 milliseconds, fire again, and so on. However, the behavior that I'm trying to obtain is that the timer is started, the event is fired, the timer waits 5000 milliseconds, fires again, then waits before firing again.Unless I missed something, I don't see a way to create a timer that doesn't wait before firing. Is there a good, clean way to emulate this?
Java 6: Examples for implementing own scripting language using javax.script? : I really can't find good examples for implementing own scripting language usinga href=http://java.sun.com/javase/6/docs/api/javax/script/package-summary.html rel=nofollow noreferrerjavax.script ...I need just something to start.DocumentationsExamplesTutorialsVideosPresentations slides (PDF)Note 1: I'm really not talking about javascript ;)Note 2: I don't need examples, how to use existing implementations, Iwant to implement an own language.Thank you.
Java: JAXB and using char : I'm working on a project with JAXB but I run into a small problem with JAXB and the char datatype. char gender = 'M';Translates after marshalling into:gender77/genderSo I think that char is mapped to integer, but I simply want to map it to a String. How can I do this? Is it even possible?
Java Scanner class reading strings : I got the following code: int nnames; String names[]; System.out.print(How many names are you going to save: ); Scanner in = new Scanner(System.in); nnames = in.nextInt(); names = new String[nnames]; for (int i = 0; i names.length; i++){ System.out.print(Type a name: ); names[i] = in.next(); } System.out.println(names[0]);When I run this code, the scanner will only pick up the first name and not the last name. And it will sometimes skip a line when trying to enter a name, it will show up as if I had left the name blank and skip to the next name. I don't know what's causing this.I hope someone can help me!EDIT: I have tried in.nextLine(); it fixes the complete names but it still keeps a line, here is an example of the output:How many names are you going to save: 3Type a name: Type a name: John DoeType a name: John Lennon
Java Scanner class reading strings : I got the following code:int nnames;String names[];System.out.print(How many names are you going to save: );Scanner in = new Scanner(System.in);nnames = in.nextInt();names = new String[nnames];for (int i = 0; i names.length; i++){ System.out.print(Type a name: ); names[i] = in.nextLine();}And the output for that code is the following:How many names are you going to save:3 Type a name: Type a name: John DoeType a name: John LennonNotice how it skipped the first name entry?? It skipped it and went straight for the second name entry. I have tried looking what causes this but I don't seem to be able to nail it. I hope someone can help me. Thanks
Image that doesn't show up in IE or Chrome only : I have a jpeg that shows up properly in FF, but won't appear in IE or Chrome. I tried downloading the image and loading it in IE and Chrome directly without success: both browsers shows a broken icon. So this is not a network issue.This file is a result of an image resize by javax.imageio.ImageIO. I have processed over 1000 images successfully.Windows explorer shows the thumbnail properly, and I can edit it successfully in Microsoft Office Picture Manager.Is there any tool that could help me understand what is wrong with this file?
redirecting a java web start app logs to a file : We have an application that we access over Java web start internally at our office.all the logs produced by the app are displayed in Firefox's console.what I want to do is to redirect that to a file.is that possible ?and how to do that ?P.S : the application is designed as follow : a client app that accesses an EJB on a server.the client part is the one made available through java webstart.
How to include external configuration for webstart application : I have webstart application that needs external configuration. Configuration must be external, because it will be changed manually by our customer. I considered adding another jar with this configuration. Application is signed and giving our keys to customer is not a option. I'm leaning towards placing this file to be accessible from web server.How retrive codebase url from webstart application inside or is there a way to configure webstart jnlp file to add other file than jar to classpath?I use maven for complete build, if it is a clue.Any others ideas are acceptable.
Force VM to launch in 32-bit mode WebStart JNLP : I am running a Java 32-bit app on Mac OS X Leopard via Web Start. I need to make sure the VM loads in 32-bit mode. How can I do this in the JNLP?
Using scanner to get input not printing as expected : This is for a friend of mine who is having trouble with Java for school.I do know some programming, but not Java.Scanner kbReader = new Scanner(System.in);System.out.print(Name of item: );String name = kbReader.next();System.out.println(Original price of item: $);double price = kbReader.nextDouble();Outputs:Name of item: CoatOriginal price of item: $10Why is the input for Original price of item: $ on the next line?I was guessing it was because I went from String to double, but can't think of a different way to do it?
Does Java Web Start give a default program folder? : For Java Web Start is there a default place to store and access data related to my program? Or do I need to create a folder? For Java Web Start (assuming I don't get a program folder) is it standard to just create on in Program Files for window, Applications for mac, etc?
SWT and Java WebStart on Mac OS X 10.5 : I am using the most stable SWT Cocoa downloads for Mac OS X and and launching my app via Java WebStart. All jnilib files are within my app jar on its root. The app downloads, verifies, but I cannot get any buttons to respond. I can enter data into all my UI components. My VM arguements are -d32 and -XstartOnFirstThread.The app works fine as a stand alone app bundle (running in 32-bit mode), and works fine running out of Eclipse on the same machine. Is there a known issue with Cocoa SWT (swt-3.5-cocoa-macosx.zip) and WebStart on Mac? The JNLP is pretty standard, so maybe there is a setting that needs to be declared?
Authenticating a Java Web Start Client App : I have a Java Web Start Application which communicates against my server via a web service (over https).I want to restrict the usage of the webservice to my app only, so that 3rd party apps don't work.What strategies to I have? This question is somewhat broad, but running in JWS disables some options, like doing a checksum over all jars (at least I don't know a way of doing this in a JWS environment).I can always implement my own auth scheme, but since the client code is on the client-side, one can always disassemble the class files and crack the auth mechanism.
Possible to launch JWS applet within browser instead of standalone? : Is it possible to embed an applet in HTML so that it will be displayed within the browser window yet launched through Java Web Start via a JNLP file instead of using the browser's Java plugin? If so, how is this done?I've only been able to launch my applet in a standalone window, but disliking the user experience pop-ups create, I'd prefer that it be embedded in the browser window.I'd like to use JWS instead of the plugin because I need to control my applet's maximum heap size, which I don't believe is possible with the browser plugin, at least not on Mac OS 10.5.
Using Scanner in Java how can I hasNext(aString) where the string is not regex pattern? : I am trying to do as my question states, sooo I have the following code which would find the match. String test = scan.next();if (test.equals($let)) return 1;However, I would prefer to use hasNext as to not consume a token; however, when i do the following it fails.if (scan.hasNext($let)) return 1;I realize the when giving has next a variable it expects a pattern, but I thought if i don't have any regex symbols it should work. I also thought $ was possibly some regex symbol so I tried /$ however, that did not work!Thanks for the help!
disable java log rotation : I use java.util.logging.Logger to log in my app : FileHandler fh=new FileHandler(this.todayFileName, 0, 1, true); fh.setFormatter(new SimpleFormatter()); Logger.getLogger(rootLogger.getName()).setLevel(Level.ALL); Logger.getLogger(rootLogger.getName()).addHandler(fh); but this does work well except that log rotation is enabled.and i get files :run.log run.log.1 run.log.2 what I want is to get only one log file, with no rotation enabled.how do I do that ?
Java - Creating a string by selecting certain numbers from within a text file : I have a .txt file that has numbers 1-31 in it called numbers. I've set up a scanner like this: cardCreator = new Scanner (new File (numbers));After this, I'm kind of confused on which methods I could use. I want to set up a conditional statement that will go through numbers, evaluate each line (or numbers 1-31), and include each number a string called numbersonCard, if they meet certain criteria.I can kind of picture how this would work (maybe using hasNext(), or nextLine() or something), but I'm still a little overwhelmed by the API... Any suggestions as to which methods I might use?
Where is the jar files cached for Java Web Start/JNLP applications? : Where is the jar files cached for Java Web Start/JNLP applications?
Why would you use logging.properties if App Engine automatically logs stdout stderr to INFO WARNING? : According to the documentation for Google App Engine for Java:blockquote The App Engine Java SDK includes a template logging.properties file, in the appengine-java-sdk/config/user/ directory. To use it, copy the file to your WEB-INF/classes directory (or elsewhere in the WAR), then the system property java.util.logging.config.file to WEB-INF/classes/logging.properties (or whichever path you choose, relative to the application root). You can set system properties in the appengine-web.xml file, as follows:/blockquoteappengine-web-app xmlns=http://appengine.google.com/ns/1.0 ... system-properties property name=java.util.logging.config.file value=WEB-INF/classes/logging.properties / /system-properties/appengine-web-appblockquote The Google Plugin for Eclipse new project wizard creates these logging configuration files for you, and copies them to WEB-INF/classes/ automatically. For java.util.logging, you must set the system property to use this file./blockquoteIf your write to standard out or standard error, that will automatically get logged as INFO or WARNING. So, why do you need to use a logging.properties file? Does this give you some additional control over your logging?
Java Web Start: unsigned cglib : I am using hibernate on the server side with a client application started via Java Web Start.I can't sign the jars (I'd like to but I can't). I get a permission exception when I get a POJO with lazy fields.Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission cglib.debugLocation read) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPropertyAccess(Unknown Source) at java.lang.System.getProperty(Unknown Source) at net.sf.cglib.core.DebuggingClassWriter.(DebuggingClassWriter.java:35) ... 44 moreHow can I avoid that? I thought about setting the collection to null before returning the pojo to the client but I'd like to find a better solution.
Java Scala interop: transparent List and Map conversion : I am learning Scala and I have a Java project to migrate to Scala. I want to migrate it by rewriting classes one-by-one and checking that new class didn't break the project.This Java project uses lots of java.util.List and java.util.Map. In new Scala classes I would like to use Scala’s List and Map to have good-looking Scala code.The problem is that new classes (those are wtitten in Scala) do not integrate seamelessly with existing Java code: Java needs java.util.List, Scala needs its own scala.List.Here is a simplified example of the problem. There are classes Main, Logic, Dao. They call each other in a line: Main - Logic - Dao.public class Main { public void a() { ListInteger res = new Logic().calculate(Arrays.asList(1, 2, 3, 4, 5)); }}public class Logic { public ListInteger calculate(ListInteger ints) { ListInteger together = new Dao().getSomeInts(); together.addAll(ints); return together; }}public class Dao { public ListInteger getSomeInts() { return Arrays.asList(1, 2, 3); }}In my situation, classes Main and Dao are framework classes (I don’t need to migrate them). Class Logic is business-logic and will benefit a lot from Scala cool features.I need to rewrite class Logic in Scala while preserving integrity with classes Main and Dao. The best rewrite would look like (doesn’t work):class Logic2 { def calculate(ints: List[Integer]) : List[Integer] = { val together: List[Integer] = new Dao().getSomeInts() together ++ ints }}Ideal behaviour: Lists inside Logic2 are native Scala Lists. All in/out java.util.Lists get boxed/unboxed automagically. But this doesn't work.Instead, this does work (thanks to a href=http://github.com/jorgeortiz85/scala-javautils rel=nofollow noreferrerscala-javautils (a href=http://en.wikipedia.org/wiki/GitHub rel=nofollow noreferrerGitHub)):import org.scala_tools.javautils.Implicits._class Logic3 { def calculate(ints: java.util.List[Integer]) : java.util.List[Integer] = { val together: List[Integer] = new Dao().getSomeInts().toScala (together ++ ints.toScala).toJava }}But it looks ugly.How do I achieve transparent magic conversion of Lists and Maps between Java - Scala (without need to do toScala/toJava)?If it is not possible, what are the best practices for migrating Java - Scala code that uses java.util.List and friends?
why not use java web start instead of other RIA frameworks? : There are many RIA frameworks popping up (flex, extjs, gwt to name very few). If my server is written in Java, why not use java web start? The benefits I see: I get to program in a language that is easy to debug (compared to javascript), I can use the same code in server and client side (validations, model objects). With SWT I get nice looking GUI.Even if it means requiring a plugin in the browser (or using a cli tool), if my application is an enterprise application, does it matter?
Java Scanner Headache : I have a text file which looks like:name11 0 1 0 10 1 1 1 00 0 0 0 0name21 0 1 0 10 0 1 1 00 0 0 0 1i.e., a plaintext label followed by a few rows with 1/0 separated by spaces. The number of rows of 1/0 is variable, but each row between any two particular labels should have the same number of 1/0s (though might potentially not).How do I grab each name+rows chunk with a scanner? Is there any elegant way to enforce the consistency on the number of rows (and provide some sort of feedback if they aren't consistent)?I'm thinking there might be a convenient way with clever delimiter specification, but I can't seem to get that working.
Java Scanner Delimiter Usage : I'd like to specify a delimiter for a scanner that splits on some pattern, but doesn't remove that pattern from the tokens. I can't seem to make this work, as anything that is identified by the regex also gets eaten as part of the delimiter. Any suggestions?My specific problem, I have file that looks like:text/numbers mixnumbersnumberstext/numbers mixnumbersnumbersnumbers..I'd like to split out from the text/numbers mix+rows until the next text/numbers mix. I have the regex to identify them, but as stated, using that as the delimiter eats part of what I want.EDIT: code addition:static final String labelRegex=\\s*[^01\\s*]\\w+\\s*;static final Pattern labelPattern = Pattern.compile(labelRegex, Pattern.MULTILINE);is the pattern I used to identify the text/numbers bit (I know my numbers rows contain all 1/0s separated by spaces).When I initialize the scanner:stateScan = new Scanner(new BufferedReader(new FileReader(source)));stateScan.useDelimiter(labelPattern);that eats the labels, and just leaves the rows. I currently have a working implementation that starts two scanners on two buffered file readers from the same source, one splitting by states and the other by labels. I'd really like it to be just one grabbing label+state.
Calculating the difference between two Java date instances : I'm using Java's java.util.date class in Scala and want to compare a date object and the current time. I know I can calculate the delta by using getTime():(new java.util.Date()).getTime() - oldDate.getTime()However, this just leaves me with a Long representing milliseconds. Is there any simpler, nicer way to get a time delta?
Is it valid to sign a Java war file and include the MANIFEST.MF in /META-INF : I am looking to sign a war file for distribution via Java Web Start. As I understand it, the jar signer tool ignores the contents of the META-INF directory so that the signing process does not change the digest value of the jar file.Will this same process work for a war file? I've never used a META-INF directory in the root of a war file, and I'm not sure it is legal to do so. Even if it is, will this be accepted by the Webstart security manager as a properly signed file?Thanks in advance,Rob.
Java/ImageIO getting image dimensions without reading the entire file? : Is there a way to get the dimensions of an image without reading the entire file?URL url=new URL(BIG_IMAGE_URL);BufferedImage img=ImageIO.read(url);System.out.println(img.getWidth()+ +img.getHeight());img=null;
Java Web Start window title problem : I've written a JavaFX application that uses Java Web Start. For some reason, the window title is always Java (on Linux) or blank (on Windows). However, the desktop icon has the correct application title and image. From what I've found so far, the important bit here is the information title element in the JNLP file. What am I missing? NOTE: I'm happy to post my JNLP content if someone says it would be of use.
How to set classpath when I use javax.tools.JavaCompiler compile the source? : I use the class javax.tools.JavaCompiler (jdk6) to compile a source file, but the source file depends on some jar file. How to set the classpath of the javax.tools.JavaCompiler?
unboxing using the ASM Java library : I'm using the ASM Java library to replace some reflection. I generate the body of this method:void set(Object object, int fieldIndex, Object value);With this generated method, I can set fields on an object at runtime without using reflection. It works great. However, I found it fails for primitive fields. Here is the relevant part of my set method:for (int i = 0, n = cachedFields.length; i n; i++) { mv.visitLabel(labels[i]); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, targetClassName); mv.visitVarInsn(ALOAD, 3); Field field = cachedFields[i].field; Type fieldType = Type.getType(field.getType()); mv.visitFieldInsn(PUTFIELD, targetClassName, field.getName(), fieldType.getDescriptor()); mv.visitInsn(RETURN);}This code is generating case labels for a select. It works great for objects but for primitives I get this error:blockquote Expecting to find float on stack/blockquoteOk, that makes sense, I need to do the unboxing myself. I implemented the following:for (int i = 0, n = cachedFields.length; i n; i++) { mv.visitLabel(labels[i]); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, targetClassName); mv.visitVarInsn(ALOAD, 3); Field field = cachedFields[i].field; Type fieldType = Type.getType(field.getType()); switch (fieldType.getSort()) { case Type.BOOLEAN: mv.visitTypeInsn(CHECKCAST, java/lang/Boolean); mv.visitMethodInsn(INVOKEVIRTUAL, java/lang/Boolean, booleanValue, ()Z); break; case Type.BYTE: mv.visitTypeInsn(CHECKCAST, java/lang/Byte); mv.visitMethodInsn(INVOKEVIRTUAL, java/lang/Byte, byteValue, ()B); break; case Type.CHAR: mv.visitTypeInsn(CHECKCAST, java/lang/Character); mv.visitMethodInsn(INVOKEVIRTUAL, java/lang/Character, charValue, ()C); break; case Type.SHORT: mv.visitTypeInsn(CHECKCAST, java/lang/Short); mv.visitMethodInsn(INVOKEVIRTUAL, java/lang/Short, shortValue, ()S); break; case Type.INT: mv.visitTypeInsn(CHECKCAST, java/lang/Integer); mv.visitMethodInsn(INVOKEVIRTUAL, java/lang/Integer, intValue, ()I); break; case Type.FLOAT: mv.visitTypeInsn(CHECKCAST, java/lang/Float); mv.visitMethodInsn(INVOKEVIRTUAL, java/lang/Float, floatValue, ()F); break; case Type.LONG: mv.visitTypeInsn(CHECKCAST, java/lang/Long); mv.visitMethodInsn(INVOKEVIRTUAL, java/lang/Long, longValue, ()J); break; case Type.DOUBLE: mv.visitTypeInsn(CHECKCAST, java/lang/Double); mv.visitMethodInsn(INVOKEVIRTUAL, java/lang/Double, doubleValue, ()D); break; case Type.ARRAY: mv.visitTypeInsn(CHECKCAST, fieldType.getDescriptor()); break; case Type.OBJECT: mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName()); break; } mv.visitFieldInsn(PUTFIELD, targetClassName, field.getName(), fieldType.getDescriptor()); mv.visitInsn(RETURN);}I have traced through and it definitely goes into case Type.FLOAT for the appropriate field, however, I get this error:blockquote Expecting to find object/array on stack/blockquoteThis is where I'm stuck. For the life of me I can't figure out why the unboxing doesn't work. The ALOAD, 3 is putting the third parameter of the set method on the stack, which should be a Float. Any ideas?I found the asm-commons library has a GeneratorAdapter class that has an unbox method. However, I don't really want to include yet another JAR for something that should be so simple. I looked at the GeneratorAdapter source and it is doing something very similar. I tried to modify my code to use GeneratorAdapter, just to see if it worked, but didn't find it at all easy to convert.
Setting the from name in a javax.mail.MimeMessage? : Currently, our application uses a javax.mail to send email, using javax.mail.MailMessage. We set the From headers of the email this way:Message msg = new MimeMessage(mailSession);msg.setFrom(new InternetAddress(mail@companyxyz.com));This works just fine, but we'd like to make the From section a little more user-friendly. Currently, someone receiving an email will see mail@companyxyz.com in the From section of their inbox. Instead, we'd like them to see Company XYZ there. I figure this is probably done with the addHeader() method, but I'm not sure what the header name would be.
Java Web Start: How to write files to windows UNC Path? : I have an Java application for copying large amounts of data from users' workstations to a server. The java.io.File class is supposed to work with UNC paths very well and in fact it does but only when I run the app in standard execution model.When the application is launched via Web Start I get a FileNotFoundException when trying to open a FileOutputStream with The network path was not found in message. Again everything works fine when I download the jar to the PC and lauch it from command line.My app is signed and i define all-permissions in JNLP.Edit: I have also discovered that when I map the UNC path to a drive letter it works too.
Compiling a set of Java files inside a directory tree with the JSR 199 Compiler API : I'm trying to compile many files using the Compiler API.Say I have a directory structureblockquote.../program +/org +/foo |+ Main.java +/bar + Tools.java/blockquoteIs there any way to discover all the Java files and make it compiler everything without resorting to recursing into all the directories and finding all the *.java files?EDIT: What I'm trying to do is compile all the classes that I get in some directory tree. These classes are independent of each other. Then I load the classes and instantiate some objects of these classes and call methods. None of the classes need to have main.
Automation server can't create object - Microsoft JScript runtime error : I am trying to run a Java webstart application which is launched from a html page. While loading I get an alert with the message Automation server can't create object a couple of times after which the applications starts and works fine. The alerts come up only on one of the workstations. Any pointers on where I should look?Regards,Dutch
WSContext.getUserPrincipal() returns null for password digest authentication : In my WebService I need to log the caller's id, but wsContext.getUserPrincipal() returns null even though the user was authenticated using WS-Security with password authentication. According to the JavaDocs for JAX-WS 2.1 WSContext.getUserPrincipal() should only return null if the user has not been authenticated.Do I have to do something in the security handler to set the user principal into the WSContext? The docs seem to indicate that it is done automatically.I'm using the metro 1.1 stack (1.1.5 I think) with jax-ws 2.1.3 stack on Tomcat.
How to read pixel color in a java BufferedImage with transparency : I am reading pixel color in a BufferedImage as follows:.....InputStream is = new BufferedInputStream(conn.getInputStream());BufferedImage image = ImageIO.read(is);int color = image.getRGB(x, y);int red = (colour amp; 0x00ff0000) 16;int green = (colour amp; 0x0000ff00) 8;int blue = colour amp; 0x000000ff;Now this works fine except for png's with transparency. I find that if x,y refer to a transparent pixel with no color, i still read a color, generally the same color as used elsewhere in the image.How do I detect that the pixel is actually transparent and not colored?Thanks
cannot find symbol in net beans : i am having code which is using javax.comm lib file,i am getting error saying cannot find symbol.i want to know where exactly my jar file should be?i using windows xp and net beans ide
SWT and Webstart on Mac : I'm trying to develop a UI using SWT and Java Webstart. As a starting point I've created a simple app that works fine with Windows and Linux, but fails to work on Mac. My test app is available a href=http://www.bcfantasy.com/webstart rel=nofollow noreferrerhere. There are also links to the jar files and class code. Can anyone explain how to make this work on Mac?
Comparison between Sun Metro and Apache CXF for webservices development? : What are the relative strengths and weaknesses between Sun Metro and Apache CXF for webservice development in Java. Is there another framework that I should be looking at as well?
New Java applet plugin not being used? : I am deploying a signed amp; trusted applet. We need to run the applet in a separate JVM amp; increase the heap size. Setting separate_jvm amp; java_arguments works on our local boxes. Curiously we have clients that though they are using 1.6.0_15 don't seem to be running the new plugin architecture. When I check their Java config, use next-generation plugin is checked amp; IE7's option use Java 1.6.0_15 for applet plugin is also checked. Nothing seems obviously wrong. The Java console also reports the correct version, but neither separate_jvm nor java_arguments are respected.Just as a sanity check we wrapped the applet in a JNLP amp; set up our web page to serve the applet with a jnlp_href. The applet tag had a bogus code parameter to ensure the JVM was actually running the JNLP. The Java console complains that it cannot find the bogus class when it should be properly loading the JNLP.Are there security settings or something else that might cause what I'm seeing?
Java file read problem : I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
How two diffrent projects running on java and .net can interact with each other using WCF? : I have a wcf services projects and a second project for consuming these services is in java.My question is how can i create proxy classes for java to consume my wcf services ?Is there any other way to consume wcf services through Java clients ?
Java Web Start (JNLP) Loading Message : Is it possible to display a custom loading message when a user loads a java web start application from a webpage? Maybe a progressbar or something similar. Users with slow connections see Java Loading... for far too long while the jars are downloaded for the first time.
InputMissMatchException : I want to read data about MMORPG characters from a .txt file and then filter on experience (minimum experience). But I'm getting this exception, which I know the meaning of but I really don't understand what I'm doing wrong. this my code:I'm not good at java, I'm a beginner actually. Can someone please explain this to me. Probably I'm soing something very stupid :PKarakter (Character):import java.util.Scanner;public class Karakter { private String name; private int experience; private int maxHealthPoints; private int healthPoints; private int maxGreed; private int greed; public Karakter(String nm, int exp, int mHP, int hp, int mG, int g) { name = nm; experience = exp; maxHealthPoints = mHP; healthPoints = hp; maxGreed = mG; greed = g; } public String toString() { String s = ; s += getName(); s += getExperience(); s += getMaxHealthPoints(); s += getHealthPoints(); s += getMaxGreed(); s += getGreed(); return s; } public static Karakter read(Scanner sc) { String name = sc.next(); int experience = sc.nextInt(); int maxHealthPoints = sc.nextInt(); int healthPoints = sc.nextInt(); int maxGreed = sc.nextInt(); int greed = sc.nextInt(); return new Karakter(name, experience, maxHealthPoints, healthPoints, maxGreed, greed); } public boolean hasExperience(int min) { return experience = min; } // returns true if Krakters have the same name public boolean equals(Object other) { if(!(other instanceof Karakter)) { return false; } else { Karakter that = (Karakter) other; return that.name == this.name; } } public String getName() { return name; } public int getExperience() { return experience; } public int getMaxHealthPoints() { return maxHealthPoints; } public int getHealthPoints() { return healthPoints; } public int getMaxGreed() { return maxGreed; } public int getGreed() { return greed; }}Karakters (Characters): import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.Scanner;public class Karakters {private ArrayListKarakter kars = new ArrayListKarakter(); public void voegToe(Karakter kar) { if(!kars.contains(kar)) { kars.add(kar); } } // returns an arraylist of characters with exp = minexp public ArrayListKarakter karaktersVanaf(int minExperience) { Karakter kar = null; for(int i = 0; i kars.size(); i++) { if(kar.hasExperience(minExperience)) kars.add(kar); } return kars; } public static Karakters read(String infile) { Karakters k = new Karakters(); try { FileReader fr = new FileReader(infile); Scanner sc = new Scanner(fr); int aantal = sc.nextInt(); for(int i = 0; i aantal ; i++) { Karakter kar = Karakter.read(sc); k.kars.add(kar); } fr.close(); } catch(IOException iox) { System.out.println(iox); return null; } return k; }}KarakterZoeker (Main method):import java.util.ArrayList;import java.util.Scanner;public class KarakterZoeker { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Karakters kars = Karakters.read(infile.txt); System.out.println(Welke experience wilt u minimaal?); int minExp = sc.nextInt(); ArrayListKarakter s = kars.karaktersVanaf(minExp); System.out.println(s.toString()); } }And this is the error: Exception in thread main java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at Karakter.read(Karakter.java:38) at Karakters.read(Karakters.java:41) at KarakterZoeker.main(KarakterZoeker.java:14)these lines:Karakter kar = Karakter.read(sc); (in Karakters)int experience = sc.nextInt(); (in Karakter)Karakters kars = Karakters.read(infile.txt); (in KarakterZoeker)this is the txt file:2name = Dursleyexperience = 15maxHealthPoints = 20healthPoints = 10maxGreed = 3greed = 1name = Aragornexperience = 45maxHealthPoints = 40healthPoints = 30maxGreed = 20greed = 10
Clojure: working with a java.util.HashMap in an idomatic Clojure fashion : I have a java.util.HashMap object m (a return value from a call to Java code) and I'd like to get a new map with an additional key-value pair.If m were a Clojure map, I could use:(assoc m key value)But trying that on a HashMap gives:java.lang.ClassCastException: java.util.HashMap cannot be cast to clojure.lang.AssociativeNo luck with seq either:(assoc (seq m) key value)java.lang.ClassCastException: clojure.lang.IteratorSeq cannot be cast to clojure.lang.AssociativeThe only way I managed to do it was to use HashMap's own put, but that returns void so I have to explicitly return m:(do (. m put key value) m)This is not idiomatic Clojure code, plus I'm modifying m instead of creating a new map.Any ideas on how to work with a HashMap in a more Clojure-ish way?
Importing from Text File Java question : I decided to create a currency converter in Java, and have it so that it would pull the conversion values out of a text file (to allow for easy editability since these values are constantly changing). I did manage to do it by using the Scanner class and putting all the values into an ArrayList.Now I'm wondering if there is a way to add comments to the text file for the user to read, which Scanner will ignore. // doesn't seem to work.Thanks
Either WSDL or wsimport and wsdl (mono) are horribly broken : EDIT I started off with the example given below, but I have now:Tried the example from the W3C spec. After fixing another error (binding was called StockQuoteSoapBinding in one place, StockQuoteBinding in another), it gives the same issue.Tried the mono generator wsdl to see if wsimport was to blame. It gives an equivalent error.So it seems to me that despite all the hype about SOAP, it doesn't actually work - at least not as advertised. I can't believe nobody has run the most findable examples of wsdl through these generators.Original Questionwsimport is failing on the following wsdl:?xml version=1.0 encoding=UTF-8?wsdl:definitions name=OrdersService xmlns:xsd=http://www.w3.org/1999/XMLSchema xmlns:wsdl=http://schemas.xmlsoap.org/wsdl/ xmlns:soap=http://schemas.xmlsoap.org/wsdl/soap/ xmlns:os=http://example/schema/OrdersService xmlns:tns=http://example/ns/OrdersService targetNamespace=http://example/ns/OrdersService wsdl:types xsd:schema targetNamespace=http://example/schema/OrdersService xsd:element name=o:GetOrders xsd:complexType xsd:sequence xsd:element name=criteria type=string/ /xsd:sequence /xsd:complexType /xsd:element xsd:element name=os:GetOrdersResponse xsd:complexType xsd:all xsd:element name=orders type=string/ /xsd:all /xsd:complexType /xsd:element /xsd:schema /wsdl:types wsdl:message name=GetOrdersRequest wsdl:part name=parameters element=os:GetOrders/ /wsdl:message wsdl:message name=GetOrdersResponse wsdl:part name=parameters element=os:GetOrdersResponse/ /wsdl:message wsdl:portType name=GetOrdersPortType wsdl:operation name=GetOrders wsdl:input message=tns:GetOrdersRequest/ wsdl:output message=tns:GetOrdersResponse/ /wsdl:operation /wsdl:portType wsdl:binding name=GetOrdersBinding type=tns:GetOrdersPortType soap:binding style=document transport=http://schemas.xmlsoap.org/soap/http/ wsdl:operation name=GetOrders soap:operation soapAction=/ wsdl:inputsoap:body use=literal//wsdl:input wsdl:outputsoap:body use=literal//wsdl:output /wsdl:operation /wsdl:binding wsdl:service name=OrdersService wsdl:port name=GetOrdersPort binding=tns:GetOrdersBinding soap:address location=http://localhost:8080/svc/OrdersService/GetOrders/ /wsdl:port /wsdl:service/wsdl:definitionsWith:parsing WSDL...[ERROR] Schema descriptor {http://example/schema/OrdersService}GetOrders in message part parameters is not defined and could not be bound to Java. Perhaps the schema descriptor {http://example/schema/OrdersService}GetOrders is not defined in the schema imported/included in the WSDL. You can either add such imports/includes or run wsimport and provide the schema location using -b switch. line 35 of file:test.wsdl
What are the impacts of setting establishSecurityContext=False if i use https? : My WFC service uses wsHttpBinding configured with:security mode=TransportWithMessageCredential message establishSecurityContext=True clientCredentialType=UserName/ transport clientCredentialType=None proxyCredentialType=None//securityOne of our partner is trying to invoke our services using the java the Metro library. They have a href=http://social.msdn.microsoft.com/forums/en-US/wcf/thread/f11d0045-e00d-4c76-8a72-562077826565/ rel=nofollow noreferrerthis problem. I have to set establishSecurityContext=False for this to work. We did a quick test and it works indeed when I set it to false. What would be the impacts of not using secure sessions (by setting establishSecurityContext=False). I'm already running on https. So will I be OK in terms of security? And are there other impacts to consider (performance maybe)?Thanks
Need help with scanner class for creating tokens : blockquote Errors im getting: cannot find symbol constructor method Token. but i do have a constructor in Token class cannot find symbol variable tokenCode. i clearly use it alll over and i think i initialized it properly so whats wrong? cannot find symbol variable scantest. i have that in same folder where all classes are in why wont it read it?/blockquoteimport java.io.BufferedReader; import java.io.FileReader; import java.io.*;public class scanner implements CompilerConstants { private char c; private BufferedReader source; public int token; private String attr = ; //private int val = '0'; private public scanner(BufferedReader buffer) { source = buffer; getChar(); } //constructor of scanner public void getChar() { c = (char)(source.read()); //do a read in } //lookup for finding identifiers public boolean lookup(String word) { boolean check = false; for(int i=0; i RESERVEDWORD.length;i++) if(word==(RESERVEDWORD[i])) { check = true; } return check; } //public boolean T(int tcc, String attt) //to return token //{ // tokenCode = tcc; // attribute = attt; // return T; // } public Token nextToken() throws IOException { attr = ; //need to save to do lookup see if its identifier or not while(c!=EOFCHAR); //if not end of file then do { while (Character.isWhitespace(c))//remove white space, check whether is letter or digit { getChar(); } if (Character.isLetter(c)) { while(Character.isLetterOrDigit(c)) { attr = attr + c; getChar(); } return new Token(lookup(attr), attr); // } else if (Character.isDigit(c)) { while(Character.isDigit(c)) { attr = attr + c; getChar(); } return new Token(NUMBER, attr); } else { switch (c) { case '' : getChar(); if(c=='') { getChar(); return new Token(NE, null); } else if (c=='=') { getChar(); return new Token(LE, null); } return new Token(LT, null); case '' : getChar(); if(c=='') { getChar(); return new Token(NE, null); } else if (c=='=') { getChar(); return new Token(GE, null); } return new Token(GT, null); case '=' : getChar(); return new Token(EQ, null); case '|' : getChar(); return new Token(OR, null); case '+' : getChar(); return new Token(PLUS, null); case '-' : getChar(); return new Token(MINUS, null); case '*' : getChar(); return new Token(TIMES, null); case '/' : getChar(); return new Token(DIVIDE, null); case '[' : getChar(); return new Token(LEFTSQ, null); case ']' : getChar(); return new Token(RIGHTSQ, null); case '(' : getChar(); return new Token(LEFTPAREN, null); case ')' : getChar(); return new Token(RIGHTPAREN, null); case ',' : getChar(); return new Token(COMMA, null); case EOFCHAR : getChar(); return new Token(EOF, null); } } // switch //return EOF.Token; return Token(tokenCode, attr); //tokenAttribute } // if // return Token;} // getTokenpublic static void main(String[] args){ BufferedReader source = new BufferedReader(new FileReader(scantest.echo));}}blockquoteToken class/blockquotepublic class Token implements CompilerConstants { private int tokenCode; private String attribute; public Token(int tc, String att) //constructor { tokenCode = tc; attribute = att; } public int getToken()//return tokencode { return tokenCode; } //return token attribute public String tokenAttribute() { return attribute; } public String toString(){ String tokenString = tokenCode + ; switch (tokenCode) { //// relational expressions for metasymbols case AND: return (tokenString + /n AND); case IDENTIFIER: return (tokenString + /n IDENTIFIER + attribute); case OR: return (tokenString + /n OR); case NOT: return (tokenString + /n NOT); case ARRAY: return (tokenString + /n ARRAY); case BEGIN: return (tokenString + /n BEGIN ); case BOOLEAN: return (tokenString + /n BOOLEAN ); case DO: return (tokenString + /n DO ); case ELSE: return (tokenString + /n ELSE); case END: return (tokenString + /n END); case FOR: return (tokenString + /n FOR); case FROM: return (tokenString + /n FROM); case IF: return (tokenString + /n IF); case INTEGER: return (tokenString + /n INTEGER); case PROCEDURE: return (tokenString + /n PROCEDURE); case PROGRAM: return (tokenString + /n PROGAM); case READ: return (tokenString + /n READ); case START: return (tokenString + /n START); case THEN: return (tokenString + /n THEN); case TO: return (tokenString + /n TO); case TRUE: return (tokenString + /n TRUE); case WHILE: return (tokenString + /n WHILE); case WRITE: return (tokenString + /n WRITE); case WRITELN: return (tokenString + /n WRITELN); case NUMBER: return (tokenString + /n NUMBER + attribute); case STRING: return (tokenString + /n STRING + attribute); case LT: return (tokenString + /n LT); case LE: return (tokenString + /n LE); case GT: return (tokenString + /n GT); case GE: return (tokenString + /n GE); case EQ: return (tokenString + /n EQ); case NE: return (tokenString + /n NE); case PLUS: return (tokenString + /n PLUS); case MINUS: return (tokenString + /n MINUS); case TIMES: return (tokenString + /n TIMES); case DIVIDE: return (tokenString + /n DIVIDE); case LEFTSQ: return (tokenString + /n LEFTSQ); case RIGHTSQ: return (tokenString + /n RIGHTSQ); case LEFTPAREN: return (tokenString + /n LEFTPAREN); case COLONEQUAL: return (tokenString + /n COLONEQUAL); case COMMA: return (tokenString + /n COMMA); case EOF: return (tokenString + /n EOF); } return tokenString; } } blockquoteCompilerConstants/blockquotepublic interface CompilerConstants { public static final int AND = 1; public static final int ARRAY = 2; public static final int BEGIN = 3; public static final int BOOLEAN = 4; public static final int DO = 5; public static final int ELSE = 6; public static final int END = 7; public static final int FALSE = 8; public static final int FOR = 9; public static final int FROM = 10; public static final int IF = 11; public static final int INTEGER = 12; public static final int NOT = 13; public static final int OR = 14; public static final int PROCEDURE = 15; public static final int PROGRAM = 16; public static final int READ = 17; public static final int START = 18; public static final int THEN = 19; public static final int TO = 20; public static final int TRUE = 21; public static final int WHILE = 22; public static final int WRITE = 23; public static final int WRITELN = 24; public static final int IDENTIFIER = 30; public static final int NUMBER = 31; public static final int STRING = 32; public static final int LT = 33; public static final int LE = 34; public static final int GT = 35; public static final int GE = 36; public static final int EQ = 37; public static final int NE = 38; public static final int PLUS = 39; public static final int MINUS = 40; public static final int TIMES = 41; public static final int DIVIDE = 42; public static final int LEFTSQ = 43; public static final int RIGHTSQ = 44; public static final int LEFTPAREN = 45; public static final int RIGHTPAREN = 46; public static final int COLONEQUAL = 47; public static final int COMMA = 48; public static final int EOF = 99; public static final char EOFCHAR = (char)(-1); public static final String[] RESERVEDWORD = {,and,array,begin,boolean, do,else,end,false,for,from,if,integer,not,or, procedure,program,read,start,then,to,true,while, write,writeln}; public static final boolean DEBUG = true;} // interface CompilerConstants
jnlp webstart nativelib: how to specify different architecture for os : in a java webstart file (jnlp) you can specify the nativelib tag to load binaries. you can also specify toload different ones for different operating systems by also specifying the os attribute.for example:resources os=Linux nativelib href=....jar//resourcesresources os=Windows nativelib href=....jar//resourcesresources os=Mac OS X nativelib href=....jar/ /resourcesbut how can i specify even different binaries for different architectures? for example win32 and win64 or linux 32 and linux 64bit. operating systems. where can i find a list of options for the os-attribute?
Does javax.tools depend on the JDK? : I want to use JavaCompiler to dynamically create some classes. I found the source code of the javax.tools package, but there is no implementation; some posts on the internet say it depends on tools.jar, I am not sure tools.jar associates with JRE.So, can I run the program in a JRE environment without JDK installed?Another question, what is the implementation detail of JavaCompiler, is it creating a new process to invoke the javac command?thanks
Maven webstart plugin not finding dependencies : Hoping someone can help me with this strange one. I’m trying to run the webstart plugin but it doesn’t seem to be able to find the main class within the jar being produce. The pom is as simple as it can get, and the class Test exists, and is being compiled and placed in the jar. Can someone please point me in the right direction?project modelVersion4.0.0/modelVersion nameDesktop Components/name groupIdcom.test/groupId artifactIdtest/artifactId version1.0/version packagingjar/packaging build plugins plugin groupIdorg.codehaus.mojo.webstart/groupId artifactIdwebstart-maven-plugin/artifactId executions execution phaseprocess-resources/phase goals goaljnlp-download-servlet/goal /goals /execution /executions configuration jnlpFiles jnlpFile jarResources jarResource groupIdcom.test/groupId artifactIdtest/artifactId version1.0/version mainClassTest/mainClass /jarResource /jarResources /jnlpFile /jnlpFiles /configuration /plugin /plugins /build/projectHere is the Maven trace:C:\TEMP\webstart-testmvn webstart:jnlp –e+ Error stacktraces are turned on.[INFO] Scanning for projects...[INFO] ------------------------------------------------------------------------[INFO] Building Desktop Components[INFO] task-segment: [webstart:jnlp] (aggregator-style)[INFO] ------------------------------------------------------------------------[INFO] Preparing webstart:jnlp[INFO] ------------------------------------------------------------------------[INFO] Building Desktop Components[INFO] ------------------------------------------------------------------------[INFO] [resources:resources {execution: default-resources}][WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent![INFO] skip non existing resourceDirectory C:\TEMP\webstart-test\src\main\resources[INFO] [webstart:jnlp-download-servlet {execution: default}][INFO] No templateFilename found for launch2.jnlp. Will use the default template.[INFO] No resources found in C:\TEMP\webstart-test\src\main\jnlp\resourcesDownloading: http://repo1.maven.org/maven2/com/test/test/1.0/test-1.0.pom[INFO] Unable to find resource 'com.test:test:pom:1.0' in repository central (http://repo1.maven.org/maven2)No template specified Using default one.***** Webstart JAR URL: jar:file:/C:/apache-maven-2.2.1/repo/org/codehaus/mojo/webstart/webstart-maven-plugin/1.0-alpha-2/webstart-maven-plugin-1.0-alpha-2.jar!/[INFO] [compiler:compile {execution: default-compile}][INFO] Nothing to compile - all classes are up to date[INFO] [resources:testResources {execution: default-testResources}][WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent![INFO] skip non existing resourceDirectory C:\TEMP\webstart-test\src\test\resources[INFO] [compiler:testCompile {execution: default-testCompile}][INFO] No sources to compile[INFO] [surefire:test {execution: default-test}][INFO] No tests to run.[INFO] [jar:jar {execution: default-jar}][INFO] Building jar: C:\TEMP\webstart-test\target\test-1.0.jar[INFO] [webstart:jnlp {execution: default-cli}][INFO] No resources found in C:\TEMP\webstart-test\src\main\jnlp\resources[INFO] ------------------------------------------------------------------------[ERROR] BUILD ERROR[INFO] ------------------------------------------------------------------------[INFO] Failure to run the plugin:[INFO] ------------------------------------------------------------------------[INFO] TraceThe trace followsorg.apache.maven.lifecycle.LifecycleExecutionException: Failure to run the plugin: at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:719) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:569) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:539) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:284) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138) at org.apache.maven.cli.MavenCli.main(MavenCli.java:362) at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:592) at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315) at org.codehaus.classworlds.Launcher.launch(Launcher.java:255) at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430) at org.codehaus.classworlds.Launcher.main(Launcher.java:375)Now the Caused by traceCaused by: org.apache.maven.plugin.MojoExecutionException: Failure to run the plugin: at org.codehaus.mojo.webstart.AbstractJnlpMojo.execute(AbstractJnlpMojo.java:289) at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490) at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694) ... 17 moreCaused by: java.lang.NullPointerException at org.codehaus.mojo.webstart.AbstractJnlpMojo.execute(AbstractJnlpMojo.java:214) ... 19 moreAnd the final Maven trace[INFO] ------------------------------------------------------------------------[INFO] Total time: 9 seconds[INFO] Finished at: Fri Nov 13 11:16:54 GMT 2009[INFO] Final Memory: 12M/22M[INFO] ------------------------------------------------------------------------
How to validate Java logging properties files? : I have a basic facility for allowing users to remotely apply changes to the logging files in my application. Some logs are configured using java.util.logging properties files, and some are configured using log4j/log4cplus-style properties files. I'd like to do some basic validation of the properties that users try to apply. Namely, I want to assure the following:Every logging.properties file must always contain at least a root logger/logging levelThe logger/level must be set to a valid value. That is, they should not be able to set .level = GIBBERISH or anything like that.I'll probably allow them to set MaxFileSize and MaxBackupIndex (log4j), and .limit and .count properties (java.util.logging), too.What's the best way to accomplish this? I can obviously just loop over the keys and values in a Properties object and look for their values in a hard-coded Map or some other data structure that tells what valid properties are, but I'm trying to come up with a solution that's a little more elegant than that.
how to catch blank input with scanner class in java : I am using the scanner class to capture user input from the command line (strings only), as an alternative to my previous a href=http://stackoverflow.com/questions/1737611/proper-way-to-read-user-input-from-command-line-in-javaquestion.The following seems to work fine, except the blank lines are not caught as they should by the second conditional. For example when I press enter, this should be captured as a blank line and the second conditional should be true. However a new blank line is displayed on the console everytime, with the entire console scrolling upward if I keep hitting enter, rather than the logic in the conditional.Is there a proper way to catch a blank input from the command line using scanner? (someone hitting just enter, or hit space a few times and then enter) Thank you for any adviceMachine aMachine = new Machine();String select;Scanner br = new Scanner(System.in); while(aMachine.stillInUse()){ select = br.next(); if (Pattern.matches([rqRQ1-6], select.trim())) { aMachine.getCommand(select.trim().toUpperCase()).execute(aMachine); } /* * Ignore blank input lines and simply * redisplay current status -- Scanner doesn't catch this */ else if(select.trim().isEmpty()){ aMachine.getStatus(); /* * Everything else is treated * as an invalid command */ else { System.out.println(aMachine.badCommand()+select); aMachine.getStatus(); } }
Webservice security : I have exposed one web service (Service Interface to access my application), What are the different ways to create/implement web service security? Could anyone please suggest some idea?
How to hide interface methods in the web service when using @WebService's `endpointInterface` attribute? : Is there a way to prevent a method from an interface used in @WebService's endpointInterface attribute to be exposed in the web service? I'm using the endpointInterface as that seems to be the only way to make the service work on JBoss with Metro, not doing so results in a:javax.xml.ws.WebServiceException: Undefined port type
java.util.concurrent vs. Boost Threads library : How do the Boost Thread libraries compare against the java.util.concurrent libraries?Performance is critical and so I would prefer to stay with C++ (although Java is a lot faster these days). Given that I have to code in C++, what libraries exist to make threading easy and less error prone. I have heard recently that as of JDK 1.5, the Java memory model was changed to fix some concurrency issues. How about C++? The last time I did multithreaded programming in C++ was 3-4 years ago when I used pthreads. Although, I don't wish to use that anymore for a large project. The only other alternative that I know of is Boost Threads. However, I am not sure if it is good. I've heard good things about java.util.concurrent, but nothing yet about Boost threads.
Looping Forever : I'm trying to loop an exception, but for some reason its not giving me the option to re write my scanner file:I don't know how to use BufferedReader so that's why I'm using this. Any clues?Here's my standard class with my methodpackage arrayExceptionsWithInput;import java.util.*;public class GetThoseNumbersBaby { int firstInt; int secondInt; boolean error; Scanner yourNumbers = new Scanner(System.in); public void findNumbers() { System.out.println( please enter your first number); firstInt = yourNumbers.nextInt(); System.out.println( pleas enter your second number); secondInt = yourNumbers.nextInt(); int finalInt = (firstInt+secondInt); System.out.println(total is: + finalInt); }}And here's my main class with the exception being implemeted with a loop:package arrayExceptionsWithInput;import java.util.*;public class InputException{ public static void main(String[] args) { boolean error = false; GetThoseNumbersBaby zack = new GetThoseNumbersBaby(); { do { try { zack.findNumbers(); } catch(InputMismatchException Q) { System.out.println( one of your integers was incorrect, please try again); Q.printStackTrace(); error = true; } } while (error == true); } error = false; }}If anyone has any ideas on how to loop this differently I'm all ears.
java wrapper around log4j logger and java.util.logging : I am writing a library. The library can be used by applications that use log4j loggers and java.util.logging loggers.So, I wrote a quick wrapper class, that encapsulates both loggers. I allow the application to set one or both loggers. And in my library I use the encapsulated class to print to either logger.My question is, since many threads can simultaneously be using the same instance of the wrapper class to log messages using the class' methods (for example: fatal() below), what steps should be taken to make these methods thread safe?public class MultiLogger { private static org.apache.log4j.Logger _log4jLogger = null; private static java.util.logging.Logger _javaUtilLogger = null; private MultiLogger () { } // log4j FATAL, log util SEVERE public void fatal (Object message) { if (_log4jLogger != null) { _log4jLogger.log(, Level.FATAL, message, null); } if (_javaUtilLogger != null) { _javaUtilLogger.severe((String) message); } } ...}Any other comments appreciated too.
Java: .class file and java.lang.Class : Is java.lang.Class the same as the actual .class file? i.e. is the content equivalent?I want to send the .class over socket, and was wondering if instead of trying to find and load the actual .class file, if I could just transmit the java.lang.Class instead?Elaboration (read if you want more info)Suppose I have a Java class called SomeObj. When this file is compiled, a file called SomeObj.class will be generated.We also know that if I have SomeObj as a type, we could get its java.lang.Class type by doing:Class someObjClss = SomeObj.class;We know java.lang.Class implements Serializable, thus it can be transmitted.So is java.lang.Class basically the object representation of the actual .class file?UPDATE:Assuming I have transmitted the .class file over to another host, do I just use the defineClass() method to construct the class back?Link a href=http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ClassLoader.html rel=nofollow noreferrerhereUPDATE2:This code does returns null InputStream. How is that possible?Class clazz = String.class;String className = clazz.getName(); System.out.println(className);URL url = clazz.getResource(className);if( url != null ){ String pathName = url.getPath(); System.out.println(className);}InputStream inputStream = clazz.getResourceAsStream(className);if(inputStream != null ){ System.out.println(inputStream.available());}
How to deploy Java Communications API : I've been developing a java application with the eclipse RCP which requires the Java Communications API. Now as the javax.comm has to be setup first (install javax.comm.properties, win32comm.dll and comm.jar) my question ist: How should I deploy my application to make sure javax.comm will be setup on the user's machine? Should I provide an installer which does the setup or should I let the application itself export the files in their respective directories?I have never before done such a thing, so I'd appreciate any help.Thanks
Javax.mail in JNLP : I have a problem with my program. I develop in Netbeans, and when i run the program it is working fine. i built it, created a *.jar file, and updatet it in my JNLP file.here comes the trouble. as i'm using javax.mail.* in my program, the jnlp package just ignores all parts of it. Just to be clear, i'm working on a mail client. now i can check the numbers of the mails in the inbox. that is what the program ignores in JNLP.Thanks for any help.
What can I do to make jar / classes smaller? : I'm developing a Java Applet, and reducing the size of the binary code will make the applet open faster and will improve the user experience.Is there anything I can do to reduce the size of classes and / or jar files? I want to be sure I'm not missing obvious tricks.I know that in the C++ world compiler options for e.g. stripping debug symbols can make a huge difference, but I've never seen something like that for Java.
Casting objects in JRuby : Is there a way I can explicitly cast one Java object to another Java class from JRuby? Sometimes I want to be able to invoke SomeJavaClass#aMethod(MySuperClass) rather than SomeJavaClass#aMethod(MyClass) from JRuby. From Java, I'd do this:someJavaObject.aMethod( (MySuperClass) myObj );but I didn't see a #cast ruby method or anything like that to do the equivalent from JRuby.Note that the question a href=http://stackoverflow.com/questions/548565/casting-java-objects-from-jrubyCasting Java Objects From JRuby lacks an answer for the general case, which is why I'm re-asking the question.
Using a Java library with Scala reserved words : I'm using an external library written in Java (a href=http://en.wikipedia.org/wiki/Selenium_%28software%29 rel=nofollow noreferrerSelenium). One of the function calls has the signature type(String, String), and I keep getting compiler errors when trying to call it from Scala, that is:selenium.type(ab,abc)Is there a workaround for this issue?
Java: Infinite loop using Scanner in.hasNextInt() : I am using the following code:while (invalidInput){ // ask the user to specify a number to update the times by System.out.print(Specify an integer between 0 and 5: ); if (in.hasNextInt()) { // get the update value updateValue = in.nextInt(); // check to see if it was within range if (updateValue = 0 amp;amp; updateValue = 5) { invalidInput = false; } else { System.out.println(You have not entered a number between 0 and 5. Try again.); } } else { System.out.println(You have entered an invalid input. Try again.); }}However, if I enter a 'w' it will tell me You have entered invalid input. Try Again. and then it will go into an infinite loop showing the text Specify an integer between 0 and 5: You have entered an invalid input. Try again.Why is this happening? Isn't the program supposed to wait for the user to input and press enter each time it reaches the statement:if (in.hasNextInt())
ASM jar - Why my java project has a dependency on this? : I have a Java project and internally it is dependent on asm jar. Strangely, I don't even know why my project somehow is dependent on this library (might be brought in by maven as a transitive dependency)?Can anyone help me know why some one needs asm jar?Thanks in advance !EDIT:Can you also mention for what purposes/use-cases one might need asm jar?
How to suppress the keystore password prompt when using Java Webstart with client auth? : Is there a way to suppress the password prompt when using Java Webstart with a https server that uses client authentication? I would like to do this, because the webstarted app runs on a touch screen device that got no keyboard and runs in a kiosk mode. Therefore it would be sufficient to either remove the password from the keystore or to store it somewhere, maybe in the desktop shortcut that starts the app.I already tried to attach a JVM Parameter to the shortcut like this, but it doesn't work:javaws -J-Djavax.net.ssl.keyStorePassword=mypass https://...I also found out, when I activate the use browser keystore-option in the Java Control Panel and add the certificate to it, I can cancel the password prompt and still connect successfully. It seems like only the Java-Keystore asks for a password and Internet-Explorer's doesn't.
Why doesn't this for-loop let me input text the first cycle? : What I want to do is ask the user for a number of strings to read into an array, and then ask the user to input that number of strings and read them into the array. When I run this code it never asks me for an input the first cycle of the first for-loop, just prints out String #0: String #1: and then I can input text. Why is that and what did I do wrong?import java.util.Scanner;public class ovn9 {public static void main(String[] args){ Scanner sc=new Scanner(System.in); System.out.print(Number of inputs: ); int lines= sc.nextInt(); String[] text=new String[lines]; for(int x=0; xtext.length; x++) { System.out.print(String #+x+: ); text[x] = sc.nextLine(); } for(int y=0; ytext.length; y++) System.out.println(text[y]);}}
java.util.ConcurrentModificationException in Non Multithreaded Program : Hey SO Guru's im having one heck of a job with this code public void kill(double GrowthRate, int Death){ int before = population.size(); for (PopulationMember p : population) { int[] probs = ProbablityArrayDeath(GrowthRate,Death,(int)p.fitness()); if (probs[RandomNumberGen.nextRandomInt(0, 99)]==0) { population.remove(p); } } System.out.println(Intial Population: +before+, Deaths:+(before- population.size())+, New Population: +population.size());}When I run my program the first time it tries to run the code it hits this errorException in thread main java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793) at java.util.HashMap$KeyIterator.next(HashMap.java:828) at Genetics.Population.kill(Population.java:181) at Genetics.Population.run(Population.java:47) at Control.Main.main(Main.java:35)Having goggled around a bit this seems to be an error that normally happens with threads why they try and access the same resource concurrently, but this is what getting me im not multithreading at all in this system.Can someone explain why this is happening, or think of a hack to get around itMany thanks ^_^
Copying only non-existent files in ant : I'm deploying my project to a web-server to be deployed with java Web Start. However, Web Start uses modification date to figure out whether to download the resources again (by default).What I want is a way to only deploy those (jar) files that do not already exist. This is made possible by having build-version numbers on all my jars, so 2 jars with the same name have the same contents.Notes:The jar modification dates will always be newer in the build (which is why I'm getting this problem), due to downloading from svn or ivyThere's a way to do this using sun's download servlet, more files etc, but I'm lazy, don't need it, and this (simpler) solution will be more robust in the long term
Java server-client | server wont receive second request : I'm trying to write a client and time server for an assignment and I'm having trouble getting the server to receive the second request from the client. The first request goes through fine without a hitch. then it just stalls. I'm actually pretty lost in this whole thing and rather uncomfortable with java still, so I have no idea what I'm missing. Any pointers are greatly appreciated. Thanks!Here's the sever code: import java.io.*; import java.util.*; import java.net.*; import java.text.*; public class myServer { protected static final int PORT_NUMBER = 55555; public static void main( String args[]) { try { ServerSocket servsock = new ServerSocket(PORT_NUMBER); System.out.println(Server running...); while(true) { Socket sock = servsock.accept(); System.out.println(Connection from: + sock.getInetAddress()); Scanner in = new Scanner(sock.getInputStream()); PrintWriter out = new PrintWriter(sock.getOutputStream()); String request = ; request = in.next(); System.out.println(Request: + request); if(request.toUpperCase().equals(TIME)) { out.println(getTime()); out.flush(); } else { out.println(Invalid Request...); out.flush(); } } } catch(Exception e) { System.out.println(e.toString()); } } protected static String getTime() { DateFormat dateFormat = new SimpleDateFormat(HH:mm:ss); Date date = new Date(); return (dateFormat.format(date)); }}Here's the Client: import java.io.*; import java.util.*; import java.net.*; public class myClient { protected static final String HOST = 127.0.0.1; protected static final int PORT = 55555; protected static Socket sock; public static void main(String args[]) { try { sock = new Socket(HOST,PORT); System.out.println(Connected to + HOST + on port + PORT); Scanner response = new Scanner(sock.getInputStream()); PrintWriter request = new PrintWriter(sock.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String txt = ; while(!txt.toUpperCase().equals(EXIT)) { System.out.print(prompt:); txt = in.readLine(); request.println(txt); request.flush(); System.out.println(response.next()); } request.close(); response.close(); in.close(); sock.close(); } catch(IOException e) { System.out.println(e.toString()); } } }
Java, ASM org.objectweb.asm.util.CheckClassAdapter causes Unsupported major.minor version 0.0 : I am getting following exception:java.lang.UnsupportedClassVersionError: net/sourceforge/barbecue/BarcodeException : **Unsupported major.minor version 0.0** at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:621) at java.lang.ClassLoader.defineClass(ClassLoader.java:466) at pl.wroc.pwr.judy2.master.TestClassLoader.loadClass(TestClassLoader.java:51) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getConstructor(Class.java:1657) at junit.framework.TestSuite.getTestConstructor(TestSuite.java:83) at junit.framework.TestSuite.init(TestSuite.java:131) at org.junit.internal.runners.JUnit38ClassRunner.init(JUnit38ClassRunner.java:67) at org.junit.internal.builders.JUnit3Builder.runnerForClass(JUnit3Builder.java:14) at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57) at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29) at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57) at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24) at junit.framework.JUnit4TestAdapter.init(JUnit4TestAdapter.java:31) at junit.framework.JUnit4TestAdapter.init(JUnit4TestAdapter.java:24) at pl.wroc.pwr.judy2.util.JUnitTestRunner.runTest(JUnitTestRunner.java:26)When trying to instrument some bytecode with below source code. (to be precise, I get this exception when I am trying to execute modified bytecode) public byte[] instrument(byte[] bytecode) { ClassReader cr = new ClassReader(bytecode); ClassWriter cw = new ClassWriter(cr, 0); // create new class adapter AbstractInstrumentClassAdapter ca = new InstrumentClassAdapterTracer(cw, tracer); // System.out.println(----------------------------------- Daikon start); cr.accept(ca, 0); ClassReader cr2 = new ClassReader(cw.toByteArray()); ClassWriter cw2 = new ClassWriter(cr2, 0); ClassAdapter checker = new CheckClassAdapter(cw); AbstractInstrumentClassAdapter ca2 = new InstrumentClassAdapterInstrumenter(checker); cr2.accept(checker, 0); return cw2.toByteArray(); }I thought it could be my InstrumentClassAdapterInstrumenter implementation, so I left it out and I am using only CheckClassAdapter at the moment. Can anybody see what am I doing wrong?Cheers,
Problem converting PNG to JPG using Java (ImageIO.write()) : I am using ImageIO.write() to convert PNG files to JPG. For some reason, my result image has a pink layer over it. I have searched far and wide for a solution but haven't found any. The code works for all other types of images except PNG.
PNG to JPG Java ImageIO problem : I have tried both lines of code below to no avail. The code works fine with jpg, or gif but turns the image pink if a png.ImageIO.write(input, jpg, profileFile);RenderedOp op = JAI.create(filestore, input, pFileName, jpeg);Anyone else run into this problem? I haven't been able to find a solution.
How do i input a string from a buffered reader? : Im used too using Scanner mainly and want too try using a buffered reader:heres what i have so farimport java.util.*;import java.io.*;public class IceCreamCone {// variablesString flavour;int numScoops;Scanner flavourIceCream = new Scanner(System.in);// constructorpublic IceCreamCone(){}// methodspublic String getFlavour() throws IOexception { try{ BufferedReader keyboardInput; keyboardInput = new BufferedReader(new InputStreamReader(System.in)); System.out.println( please enter your flavour ice cream); flavour = keyboardInput.readLine(); return keyboardInput.readLine(); } catch (IOexception e) { e.printStackTrace(); }}im fairly sure to get an int you can say Integer.parseInt(keyboardInput.readLine());but what do i do if i want a String
Java compiled with gcj using javax.comm api. Possible? : I have a java program that I'm required to compile into a Linux native program using gcj-4.3. This program requires serial port access. The javax.comm api provides serial port access but I'm not sure how to get my compiled java program to use it.The target box has Java installed, but of course my compiled program isn't running in the JRE...so I'm not exactly sure how I can link in the comm.jar file or how that file can find the .properties file it requires.I wonder if I can just compile the comm.jar allong with my .jar file and link the two object files together. Can my code then reference the classes in comm.jar? Thanks in advance for your help!
Is there an easy way to reduce the number of colors in an IndexedColorModel? : I have a large 8-bit PNG image. I am using Java to slice the image into smaller 32x32 images. I use Java's ImageIO to load the PNG into a BufferedImage and then call it's getSubimage(x, y, 32, 32). I then use ImageIO to write each tile out as a PNG.The problem is that the resulting image has the same IndexColorModel as the original image. For example, one 32x32 tile has only 8 total colors but it includes a color model with all 100-odd colors from the original image.I would like to remove unused colors from the 32x32 tile's IndexColorModel before I write out the PNG. There is no sense including color data for colors not used in the image and I'd like the images to be as small as possible.Is there a built-in mechanism to do this or can someone point me to an (easy) way to modify/reduce the ColorModel?Thanks!
Who Uses Real Time Java? : I noticed that a href=https://en.wikipedia.org/wiki/Real_time_Java rel=nofollow noreferrerReal Time Java 2.2 was released back in September, seems to have come a long way from when I last looked at it. However, does anybody know of any real world uses, commercial or academic to date?a href=http://java.sun.com/javase/technologies/realtime/index.jsp rel=nofollow noreferrerhttp://java.sun.com/javase/technologies/realtime/index.jsp
signing jars to be used over web start : I have a java web start app that uses Swing and needs to allow a user to open a file local on their machine. My application is failing to run because it says that the the single jar I am trying to use is unsigned. I did however, sign it.In my .jnlp file I am specifying security as:security j2ee-application-client-permissions//securityand I used the following commands to create the keystoare sign my jar file, validator.jar:keytool -genkey -keystore mykeys -alias https://www.mydomain.comjarsigner -keystore mykeys -storetype JKS validator.jar https://www.mydomain.comAny ideas?Thanks!
jnlp unaivalable service exception : I am trying to use the FileOpenSerivce, but I always get an UnaivableServiceException regardless of whether I run it from Eclipse, or from my local webserver using the jnlp file. I am using an unsigned jar, which from what I understand is ok.I got a debugger connected, and when running under Webstart, everything seems to succeed just fine. I am attempting to get FileContents like so:FileContents fileContents = fileOpenService.openFileDialog(null, null);I never see a dialog, and fileContents is always null.Thanks!
Memory effects of synchronization in Java : a href=http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#synchronization rel=nofollow noreferrerJSR-133 FAQ says:blockquote But there is more to synchronization than mutual exclusion. Synchronization ensures that memory writes by a thread before or during a synchronized block are made visible in a predictable manner to other threads which synchronize on the same monitor. After we exit a synchronized block, we release the monitor, which has the effect of flushing the cache to main memory, so that writes made by this thread can be visible to other threads. Before we can enter a synchronized block, we acquire the monitor, which has the effect of invalidating the local processor cache so that variables will be reloaded from main memory. We will then be able to see all of the writes made visible by the previous release./blockquoteI also remember reading that on modern Sun VMs uncontended synchronizations are cheap. I am a little confused by this claim. Consider code like:class Foo { int x = 1; int y = 1; .. synchronized (aLock) { x = x + 1; }}Updates to x need the synchronization, but does the acquisition of the lock clear the value of y also from the cache? I can't imagine that to be the case, because if it were true, techniques like lock striping might not help. Alternatively can the JVM reliably analyze the code to ensure that y is not modified in another synchronized block using the same lock and hence not dump the value of y in cache when entering the synchronized block?
How to inspect the stack using an ASM visitor? : I am attempting to use the Java byte code engineering library a href=http://asm.ow2.org/index.html rel=nofollow noreferrerASM to perform static analysis. I have the situation where I would like to inspect the variables being assigned to a field.I have MethodVisitor which implements the visitFieldInsn() method. I am specifically looking for the putfield command. That is no problem. The problem is that when I encounter putfield, I want to be able to access the variable that's going to be assigned to the field. Specifically I want to access information about the type of the variable.At the moment I really only need to look at what's at the top of the stack, but if there's a more general way to inspect it that's even better.Is there a way using ASM to inspect the variables on the stack?
Event Dispatch Thread meets the Java Memory Model : This is related to an earlier a href=http://stackoverflow.com/questions/1621495/if-more-than-one-thread-can-access-a-field-should-it-be-marked-as-volatilequestion I asked, where the answer was:blockquote If a field is accessed by multiple threads, it should be volatile or final, or accessed only with synchronized blocks. Otherwise, assigned values may not be visible to other threads./blockquoteIn addition anything that manipulates pixels on screen should be run from the a href=http://java.sun.com/docs/books/tutorial/uiswing/concurrency/dispatch.html rel=nofollow noreferrerevent dispatch thread although this is handled transparently when you use repaint / paint.Therefore, by my understanding, we need worry about the memory model for something as simple as an animation of a sprite moving across the screen.My question is, is this understanding correct, and Sun tutorial examples eg a href=http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html rel=nofollow noreferrerTumbleItem (a href=http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TumbleItemProject/src/components/TumbleItem.java rel=nofollow noreferrersource) incorrect?
threading issues with java swing and web start : EDIT: After fixing a few issues, the bigger issue that I am having is being caused by Apache POI which I am using. I am working on figuring that out now. Apparently it is being restricted by the Sandbox.I'm very new to Swing, and created a small Swing app that I now need to have run via web start. I'm trying to use the FileOpenService and update a Text display. I think I am running into threading issues, because the FileOpenService dialog never appears, and my text display is not getting updated. I can't really find any examples where they are doing anything different than I am right now.Ideas?Thanks!Edit: I now have the FileOpenService dialog appearing. I changed my main to this:public static void main(String[] args) throws Exception { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new MainFrame(); } });}However, I still can't get my display to update. This is where I am doing the update: Runnable r = new Runnable() { public void run() { for (final String s : Logger.getMessages()) append(s + \n); } }; try { if (SwingUtilities.isEventDispatchThread()) r.run(); else SwingUtilities.invokeAndWait(r); } and my append method:private void append(Color c, String s) {// throws Exception { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); int len = _textPaneLog.getDocument().getLength(); try { _textPaneLog.getDocument().insertString(len, s, aset); } catch (BadLocationException e) { e.printStackTrace(); }}
where can I see exceptions thrown from within a java web start app? : I'm trying to debug a locally running java web start application. There is a call failing that I am trying to get a stack trace for, but it appears that nothing is ever getting printed out anywhere. The app just appears to be doing nothing.Thanks!
Is there a mono (.Net) equivalent to the Scanner-class in Java : In Java there is a nice class called Scanner for reading strings and streams of a certain format to data-structures like integers, floats,... Is there any equivalent in Mono? In .Net there is a binary-reader, but it reads the data as binaries. I want a class that read the data by parsing it from a string.EDIT: reaction on the current answers, I know most of the data-types have a parse-method, but the problem with these are, they don't read the string sequentially. In Java you simply initialize the object, and by activating methods, you sequentially read the data-types.
Profiling a Java Web Start application : There are a lot of java profilers out there, any recommendations as to what would be best for profiling a java web start application that is being deployed to glassfish inside a war?
Metro + Jetty + OSGi = pain : I am trying to swap out Sun's HTTPServer for the much better Jetty server, within an OSGi bundle, running on Equinox.I have tried this:System.setProperty(com.sun.net.httpserver.HttpServerProvider,org.mortbay.jetty.j2se6.JettyHttpServerProvider);but when endpoint.publish(url) is called, and the server is spawned, it complains of a ClassNotFoundException for org.mortbay.jetty.j2se6.JettyHttpServerProvider.However, the correct jars are in the bundle, and indeed in the Activator I can instantiate a org.mortbay.jetty.j2se6.JettyHttpServerProvider. I think that this is a some kind of classpath issue - the spawned server is in a different classpath maybe? I have tried adding the JARs in at the JDK level, but this doesn't make any difference.Can oanyone shed any light how on earth to get this working?P.S. Maybe hideous System.setProperty calls will vanish from the world one day. Hopefully :)
Extract Integer Part in String : What is the best way to extract the integer part of a string likeHello123How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?
I am not able launch JNLP applications using Java Web Start? : Up until recently, I was able to launch/open JNLP files in Firefox using Java web start.Don't know what happened all of a sudden JNLP files stopped launching, a splash screen appears saying Java Starting... and then nothing happens. Even the Java Console in the browser and javacpl.cpl applet doesn't open.Tried all possibilities: removed all older version and installed the latest JRE (java version 1.6.0_17), still it doesn't work.Done some googling for this problem, people suggested to start javaws.exe with -viewer option but same behavior (a splash screen appears saying Java Starting... and then disappears)The problem is that I don't know any place (logs etc.) to look for to see what is causing the problem.I am using WinXP SP3, and some of the screenshots below shows further info about my system. I can provide any other detail if required but please help me solve this problem.
Problem consuming Exchange Web Service 2010 with jax-ws metro : I am trying to consume the Exchange 2010 Web Service interface using JAX-WS. I'm using JAX-WS 2.2 RI (Metro 2.0). 2.1 exhibited the same problem.I am running into trouble with Exchange, which returns HTTP/1.1 415 Cannot process the message because the content type 'text/xml;charset=utf-8' was not the expected type 'text/xml; charset=utf-8'. as a reponse (2.1 quoted the charset value, otherwise same response).Apparently I need to dictate the exact Content-type header for Exchange to be happy.Is there a way for me to do this without forcing me to manually rebuild the dependency? I currently rely on published maven artifacts, and would like to continue doing this if at all possible.The consuming process is a regular J2SE app, with no containers in sight. I have control of the application and can add pretty much anything required to the applications scope, but can not add out-of-process items like proxy servers. The client classes were generated from local WSDL, but the charset specification is derived from constants declared in the jaxws RI implementation, not the generated code. The resulting HTTP transport is thus handled by the standard http/https client from Sun JRE5 or JRE6.
IMAP - javax.mail. - Fetching Only Body Without Attachment : I am trying to develop an IMAP email client using the javax.mail API. I have been able to contact the servers, fetch emails, attachments and other operations without any problem.However, we would not want to fetch the attachment until the user wants to view it explit in order to improve the performance. This would mean that we would need information which would indicate if the email has an attachment, if yes, then the filename(s) and the size(s)but would not send me the actual content of the email. However, I was not able to find a method in the API description which would return just the multi-part content. Is there a way I could fetch just the body and the details of the attachment but not the actual attachment?Thanks,Aravind
Does ImageIO read imply anti-aliased scaling? : I've replaced the Java internal ImageFetcher with an own implementation using ImageIO. Some image renderers of our software, which use these images, now draw anti-aliased scaled images instead of non anti-aliased. The only change is the source of the image, which are now BufferedImages instead of Toolkit-Images.The question now is, where is the difference? Which property causes the images to scale anti-aliased? I've always thought that the anti-alias key ONLY depends on the graphics I paint on - but this is obviously wrong.By the way: unfortunately I cannot change the renderers.
See a JWS apps stack trace? : How can I view a JWS apps stack trace?
Can't read and write a TIFF image file using Java ImageIO standard library : I don't know what to do with TIFF images, but I can't read or write any of them using straight Java standard ImageIO library. Any thoughts?Thanks.
Using CXF web service from java web start : UPDATE: I have submitted my question to the CXF User's mailing list, here.UPDATE: I have currently signed all of my jars. I still can't seem to get CXF setup in a way that it can find the WSDL. My last attempt was to place the WSDL inside of my WAr file so I can access it through a web browser. I set the wsdllocation inside of the client to the URL (a href=http://www.example.com/app/example.wsdl rel=nofollow noreferrerhttp://www.example.com/app/example.wsdl). I am now getting the following exception:Exception in thread AWT-EventQueue-0 java.lang.ExceptionInInitializerErrorat com.sun.xml.internal.ws.util.xml.XmlUtil.createDefaultCatalogResolver(Unknown Source)at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(Unknown Source)at com.sun.xml.internal.ws.client.WSServiceDelegate.init(Unknown Source)at com.sun.xml.internal.ws.client.WSServiceDelegate.init(Unknown Source)at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(Unknown Source)at javax.xml.ws.Service.init(Unknown Source)Googling has turned up pretty much nothing on this.I am creating a web service client from a given WSDL using a href=http://en.wikipedia.org/wiki/Apache_CXF rel=nofollow noreferrerApache CXF. I am running into problems however when trying to access the service, I get this exception:Can not initialize the default wsdl from ../resource/example.wsdlException in thread AWT-EventQueue-0 java.security.AccessControlException: access denied (java.util.PropertyPermission user.dir read)at java.security.AccessControlContext.checkPermission(Unknown Source)at java.security.AccessController.checkPermission(Unknown Source)at java.lang.SecurityManager.checkPermission(Unknown Source)at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)I am not signing my web start application, and would prefer not to since I am not accessing any resources from the client's machine. The a href=http://en.wikipedia.org/wiki/Web_Services_Description_Language rel=nofollow noreferrerWSDL mentioned is packaged within my jar. The problem is caused by this from the CXF generated client code: URL url = null; try { url = new URL(../resource/example.wsdl); } catch (MalformedURLException e) { System.err.println(Can not initialize the default wsdl from ../resource/example.wsdl); // e.printStackTrace(); } WSDL_LOCATION = url;How can I correctly point CXF to this WSDL? I am also worried about the WebService annotation on the class:@WebServiceClient(name = Example, wsdlLocation = ../resource/example.wsdl, targetNamespace = http://services.example.com/) Do I also need to change this?
Is Javaspaces supported on GWT? : Following a suggestion on a related post (a href=http://stackoverflow.com/questions/1955623/pattern-matching-frameworksee here), I was wondering if Javaspaces technology is supported on GWT?
Porting J2EE application from weblogic to Jboss, JTS? (weblogic.jdbc.jts.Driver) : My weblogic(8.1) application uses weblogic.jdbc.jts.Driver to connect to Oracle. I'd like to port this app to JBOSS(4.0) and quick googling did not yield the correct driver to replace this JDBC JTS driver with in order to connect from Jboss, ideas?
How to find second largest number using Scanner and for loop(no array) : So I can easily accomplish task to find largest number and then if can be divided by three, print out. But do not know how to find second largest number from users sequence.Thanks for any hints!public class SecondLargest { public static void main(String[] args) { int max = 0; Scanner scan = new Scanner(System.in); System.out.println(How many numbers?); int n = scan.nextInt(); System.out.println (Write numbers: ); for(int i=0; in; i++){ int c = scan.nextInt(); if(c=max amp;amp; c%3 == 0){ max = c; } else System.out.println(There is no such number.); } System.out.println(max); }}
Java Scanner question : How do you set the delimiter for a scanner to either ; or new line?I tried: Scanner.useDelimiter(Pattern.compile((\n)|;));But it doesn't work.
Is it possible to customize the namespace prefix that JAXB uses when marshalling to a String? : For example, I've got a simple schema which imports another schema. The second schema (urn:just:attributes, just-attributes.xsd) just defines an attribute group.?xml version=1.0 encoding=UTF-8?schema xmlns=http://www.w3.org/2001/XMLSchema targetNamespace=http://www.example.org/MySchema xmlns:tns=http://www.example.org/MySchema elementFormDefault=qualified xmlns:ja=urn:just:attributes import schemaLocation=just-attributes.xsd namespace=urn:just:attributes/ element name=MyElement complexType attributeGroup ref=ja:AttributeGroup/ /complexType /element/schemaI'm using the Metro xjc Ant task to generate classes off of this schema. The problem I'm running into is that the third party application I'm interacting with is peculiar about namespaces. This case I need a String value, so I have to serialize it. I use boilerplate code for this.private static T String marshal(T object) throws JAXBException{ OutputStream outputStream = new ByteArrayOutputStream(); JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.marshal(object, outputStream); return outputStream.toString();}Which gives me something along the lines of?xml version=1.0 encoding=UTF-8 standalone=yes?ns2:MyElement xmlns:ns1=urn:just:attributes xmlns:ns2=http://www.example.org/MySchema ns1:attrib1=1234 ns1:attrib2=5678/The problem I have is that this third party expects something like xmlns:thirdpartyns=urn:just:attributes, which is to say, they are parsing based on the name given to the namespace. It has to be thirdpartyns for their software to work.Does anyone know of a way around this, short of doing a find and replace in the resulting string? A custom binding rule perhaps?
Does Clojure have an equivalent of Java's import package.*? : Or do I have to specifically enumerate every class that I import? I'm just learning Clojure now, and it seems useful to be able to do something like this in the REPL:(import '(java.io *))Not that this is valid syntax, but it would be nice to have something that does the equivalent. It would save some typing, especially when tinkering around. In actual production code I always enumerate each class that I'm importing, regardless of the language, but it's pretty convenient not to have to do so.
How to use scala.None from Java code : blockquote Possible Duplicate: a href=http://stackoverflow.com/questions/9059511/accessing-scala-none-from-javaAccessing scala.None from Java /blockquoteIn Java you can create an instance of Some using the constructor, i.e. new Some(value), but None has no partner class. How do you pass None to a Scala function from Java?
Determine classes used by a Java application : How would you determine the classes (non Sun JDK classes) loaded / unused by a Java application?Background:I have an legacy Java webstart application that has gone through a lot of code changes and now has a lot of classes, most of which are not used. I would like to reduce the download size of the application by only deploying classes that will be used only instead of jaring the all the packages.I will also use the same process to completely delete these unused classes.
How to scan a file in a different directory in java? : How do you scan a file with java that isn't in the directory the java file is in?For example: The java file is located at C:\Files\JavaFiles\test.java However, the file I want to scan is located at C:\Data\DataPacket99\data.txtNote: I've already tried putting another java file in the C:\Data directory and using the test.java file as a class, but it doesn't work. It still tries to scan from the C:\Files\JavaFiles Directory.
Export an Oracle database, import it to a different user, stored procedures don't work : I export an oracle schema using exp userid=/ file=pt.dmp log=pt.log owner=FOO buffer=10000000 statistics=NONE direct=Yand then import it into a different schema on the same oracle instance on the same SID using imp userid=/ file=pt.dmp fromuser=FOO touser=paulWhen I try to access the stored procedures with the new user, I get ORA-29541: class PAUL.ESMQOracleStoredProc could not be resolvedAny idea why one user can resolve this but another one can't?
Getting a Scala Map from a Java Properties : I was trying to pull environment variables into a scala script using java Iterators and / or Enumerations and realised that Dr Frankenstein might claim parentage, so I hacked the following from the ugly tree instead:import java.util.Map.Entryimport System._val propSet = getProperties().entrySet().toArray()val props = (0 until propSet.size).foldLeft(Map[String, String]()){(m, i) = val e = propSet(i).asInstanceOf[Entry[String, String]] m + (e.getKey() - e.getValue())}For example to print the said same environmentprops.keySet.toList.sortWith(_ _).foreach{k = println(k+( * (30 - k.length))+ = +props(k))}Please, please don't set about polishing this t$#d, just show me the scala gem that I'm convinced exists for this situation (i.e java Properties -- scala.Map), thanks in advance ;@)
Java concurrency question - synchronizing on a collection : Will the following code snippet of a synchronized ArrayList work in a multi-threaded environment?class MyList { private final ArrayListString internalList = new ArrayListString(); void add(String newValue) { synchronized (internalList) { internalList.add(newValue); } } boolean find(String match) { synchronized (internalList) { for (String value : internalList) { if (value.equals(match)) { return true; } } } return false; }}I'm concerned that one thread wont be able to see changes by another thread.
Java casting / classloader issues : Here is the simplified version of the problem: SomeClass c = (SomeClass) obj.getSomeClassParent()not always but it happens sometimes to trigger exception org.somepackage.SomeClass can't be cast to org.somepackage.SomeClass How is this possible ? I suppose it has something to do with the fact that JAI imageio is native lib, but relay how can this happen ? I'm probably missing something but what ? I'm using JAI imageio version 1.1 dcm4che 2.0.21 DICOM libHere is the original code ImageInputStream iis = ImageIO.createImageInputStream(src); IteratorImageReader iter = ImageIO.getImageReadersByFormatName(DICOM); ImageReader reader = iter.next(); DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam();And the original exceptionorg.dcm4che2.imageio.plugins.dcm.DicomImageReadParam can't be cast to org.dcm4che2.imageio.plugins.dcm.DicomImageReadParamimg src=http://img215.imageshack.us/img215/3894/exception.jpg alt=Exception Image
Java InputStream != Readable : I am using java.util.Scanner for things such as nextInt(), and all was working fine as long as I was using a java.lang.Readable (one and only constructor argument). However, when I changed to using an InputStream instead, Scanner.nextInt() never returns. Do you know why?My implementation of the InputStream looks like this:private static class ConsoleInputStream extends InputStream { ... private byte[] buffer; private int bufferIndex; public int read() throws IOException { ... while (...) { if (buffer != null amp;amp; bufferIndex buffer.length) { return buffer[bufferIndex++]; // THE COMMENT! } ... } ... }}When I print the data by THE COMMENT I (correctly) get stuff like '1','2','\n' for 12\n, etc. Is there some Scanner hookup, unbeknown to me, that cause this behavior?
How to Call Java Code from MySQL? : I found an article from 2008 discussing how to a href=http://planet.mysql.com/entry/?id=13420 rel=nofollow noreferrercall Java code from MySQL. There were a lot of caveats and disclaimers because the process involved working with an experimental branch of MySQL.For a project I have in mind, it would be very useful to be be able to access Java libraries within MySQL, analogous to Oracle's a href=http://www.oracle.com/technology/tech/java/jsp/index.html rel=nofollow noreferrerJava Stored Procedures. Does this capability now exist as a standard feature of MySQL? If not, what open source RDBMSs support something similar to Oracle's Java Stored Procedures?
using java.util.Scanner to read a file byte by byte : I'm trying to read a one line file character by character using java.util.Scanner. However I'm getting this exception:Exception in thread main java.util.InputMismatchException: For input string: contents of my file at java.util.Scanner.nextByte(Scanner.java:1861) at java.util.Scanner.nextByte(Scanner.java:1814) at p008.main(p008.java:18) -- line where I do scanner.nextByte()Here's my code:public static void main(String[] args) throws FileNotFoundException { File source = new File(file.txt); Scanner scanner = new Scanner(source); while(scanner.hasNext()) { System.out.println((char)scanner.nextByte()); } scanner.close()}Does anyone have any ideas as to what I might be doing wrong?Edit: I realized I wrote hasNext() instead of hasNextByte(). However if I do that it doesn't print out anything.
Storing short strings and numeric values in resources in Android : I want to have some static numeric and text values as an application resource. For example my data is like this:Levels 5 First_Level 500 60 1 Second_Level 500 80 1 Third_Level 200 60 1 Fourth_Level 130 30 2 Final_Level 100 30 3... and another 300 lines...The format and order of the data is predefined and guaranteed to be valid.I could read it with java.util.Scanner, but it's extremely slow in Android, reading a 10 KB file takes minutes. It's slow because of the regular-expression-based pattern matching inside (when I traceview'ed it). What way would you suggest to store them?
Magic behind R.java file : Recently I have been having quite some problems with R.java file. Now I have decided to do a backup and delete the file to see what happens.Nothing happened, so I created an empty R.java file and hoped for the best. Now Eclipse seems to figure out that the file was tampered with and even issues a warning:R.java was modified manually! Reverting to generated version!And that's all there is. I tried building it manually but got no results. So, I have two questions:what should I do to force Eclipse to regenerate the filewhat is happening here? How is the file created, where is the code that is generating the file?I would appreciate any help. As usual the problem occurred just a few days before the deadline :)
java.lang.NoClassDefFoundError: com/google/common/base/internal/Finalizer$ShutDown (wrong name: com/google/common/base/internal/Finalizer) : Our application uses the MapMaker class from Google collections, and we're getting the exception below, but only on OS X 10.4 using webstart. It works fine when launched from an app bundle, and on OS X 10.5 and Windows.This has started happening since our upgrade from RC2 to RC5 (we skipped all the intervening versions). We've since upgraded to 1.0 final and still see the issue.I suspect some interaction with Sun's fix for a href=http://sunsolve.sun.com/search/document.do?assetkey=1-66-238905-1 rel=nofollow noreferrerthis security issue (which changed the way that URL.toString() works in webstart), but don't have any proof yet. Has anyone seen this problem before? Any help is greatly appreciated!java.lang.NoClassDefFoundError: com/google/common/base/internal/Finalizer$ShutDown (wrong name: com/google/common/base/internal/Finalizer)at java.lang.ClassLoader.defineClass1(Native Method)at java.lang.ClassLoader.defineClass(ClassLoader.java:620)at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)at java.net.URLClassLoader.access$100(URLClassLoader.java:56)at java.net.URLClassLoader$1.run(URLClassLoader.java:195)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:188)at java.lang.ClassLoader.loadClass(ClassLoader.java:306)at java.lang.ClassLoader.loadClass(ClassLoader.java:251)at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)at java.lang.Class.getDeclaredMethods0(Native Method)at java.lang.Class.privateGetDeclaredMethods(Class.java:2395)at java.lang.Class.getMethod0(Class.java:2642)at java.lang.Class.getMethod(Class.java:1579)at com.google.common.base.FinalizableReferenceQueue.getStartFinalizer(FinalizableReferenceQueue.java:308)at com.google.common.base.FinalizableReferenceQueue.clinit(FinalizableReferenceQueue.java:102)at com.google.common.collect.MapMaker$QueueHolder.clinit(MapMaker.java:836)at com.google.common.collect.MapMaker$SoftValueReference.init(MapMaker.java:1078)at com.google.common.collect.MapMaker$Strength$2.referenceValue(MapMaker.java:379)at com.google.common.collect.MapMaker$StrategyImpl.setValue(MapMaker.java:488)at com.google.common.collect.MapMaker$StrategyImpl.setValue(MapMaker.java:462)at com.google.common.collect.CustomConcurrentHashMap$Impl$Segment.put(CustomConcurrentHashMap.java:960)at com.google.common.collect.CustomConcurrentHashMap$Impl.put(CustomConcurrentHashMap.java:1438)`There doesn't appear to be anything interesting in the manifest:$ unzip -p google-collect.jar META-INF/MANIFEST.MFManifest-Version: 1.0Ant-Version: Apache Ant 1.7.0Created-By: 10.0-b19 (Sun Microsystems Inc.)
Metro UsernameToken Policy : I created a web services client prototype using api's available in weblogic 10.3. I've been told I need to use Metro 2.0 instead (it's already being used for other projects). The problem I have encounter is that the WSDL does not include any Security Policy information but a UsernameToken is required for each method call. In weblogic I was able to write my own policy xml file and instantiate my service with it (see below), however I can not seem to figure out how to do the same using Metro.Policy.xml ?xml version=1.0? wsp:Policy xmlns:wsp=http://schemas.xmlsoap.org/ws/2004/09/policy xmlns:sp=http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512 sp:SupportingTokens wsp:Policy sp:UsernameToken sp:IncludeToken=http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512/IncludeToken/AlwaysToRecipient wsp:Policy sp:WssUsernameToken10/ sp:HashPassword/ /wsp:Policy /sp:UsernameToken /wsp:Policy /sp:SupportingTokens /wsp:PolicyClient.java (Weblogic) ClientPolicyFeature cpf = new ClientPolicyFeature(); InputStream asStream = WebServiceSoapClient.class.getResourceAsStream(Policy.xml); cpf.setEffectivePolicy(new InputStreamPolicySource(asStream)); try { webService = new WebService(new URL(http://192.168.1.10/WebService/WebService.asmx?wsdl), new QName(http://testme.com, WebService)); } catch ( MalformedURLException e ) { e.printStackTrace(); } WebServiceSoap client = webService.getWebServiceSoap(new WebServiceFeature[] {cpf}); ListCredentialProvider credProviders = new ArrayListCredentialProvider(); String username = user; String password = pass; CredentialProvider cp = new ClientUNTCredentialProvider(username.getBytes(), password.getBytes()); credProviders.add(cp); MapString, Object rc = ((BindingProvider) client).getRequestContext(); rc.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders);... I am able to generate my Proxy classes using Metro however I can not figure out how to configure it to send the UsernameToken. I have attempted several different examples from the web which have not worked. Any help would be appreciated.
How to pick CXF over Metro on Glassfish : I'm having a href=https://issues.apache.org/jira/browse/CXF-2237 rel=nofollow noreferrerthe following problem (reported there by someone else) when running my enterprise application under Glassfish. Under Jetty it works fine.a href=http://java.sun.com/javase/6/docs/api/javax/xml/ws/spi/Provider.html rel=nofollow noreferrerjavax/xml/ws/spi/Provider mentions creating a META-INF/services/javax.xml.ws.spi.Provider resource, but this is already supplied with CXF and creating an additional resource file does not solve this problem under Glassfish.Does anyone know how to ensure that CXF is picked up under GlassFish?(I'm using a Maven Multi-modules project with CXF dependency 2.2.5)Thanks!TimEDIT #1Skipping the problem for now and just working with Metro, but I'd really like to know how to use CXF instead if anyone has any pointers.. If nothing works I might have to switch web application container (or look into Metro to fill my requirements)EDIT #2Some of the solutions detail the fix for war's by adding class-loader delegate=false/ to the sun-web.xml file. However, this does not work for non-war ee apps.
Is it possible to create an advanced login dialog for a Java Webstart application? : I implemented an advanced login dialog for a webstart application. I call it advanced because it consists of three screens: one for the actual login (user, password), one for password retrieval, and one for new user registration. The problem I am having is that the webstart support for login dialogs is somewhat poor. The server simply sends a callback object to the client asking for a username and password. The client can then show a dialog or not (depending on use case). Unfortunately the dialog does not seem have any other hooks or connections to the server (in my case Glassfish 2.1). Does anyone know how I can still implement the advanced features?Dirk
Try/catch in Java : Could someone please give me a hint why this try and catch is not working?It throws a scanner exception instead of printing the message I expect.import java.util.*;import java.io.*;import java.math.*;import javax.swing.*;public class Main { public static void main(String[] args) { Boolean test = true; while (test == true) { try { double x, y; String operator; Scanner scan = new Scanner(System.in); Scanner scan_2 = new Scanner(System.in); Scanner ScanOperator = new Scanner(System.in); System.out.println( Enter a double value: ); x = scan.nextDouble(); System.out.println( Enter another double value: ); y = scan_2.nextDouble(); System.out.println( Enter a operator for the operation you want to execute, or X if you want to quit: ); operator = ScanOperator.nextLine(); if (operator.equals(x) || operator.equals(X)) { test = false; System.out.println(No calculation was made!!!); } System.out.println(Calculation(operator, x, y)); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null,Input must be a number.); } } } public static double Calculation(String operator, double x, double y) { double result = 0; double myAdd = 0; double mySub = 0; double myMult = 0; double myDiv = 0; double myPower = 0; double myMod = 0; if (operator.equals(+)) { myAdd = x + y; result = myAdd; } else if (operator.equals(-)) { mySub = x - y; result = mySub; } else if (operator.equals(*)) { myMult = x * y; result = myMu } else if (operator.equals(/)) { myDiv = x / y; result = myDiv; } else if (operator.equals(^)) { myPower = Math.pow(x, y); result = myPower; } else if (operator.equals(%)) { myMod = x % y; result = myMod; } else { } return resu }}
How can i handle it with scanner (java)? : I have a question about scanner please;I working at a small company; we have a software; it generate a big text file; and we must get some useful information from it ; i want write a simple application with java for saving time; could you please guide me ?for example i want this output ;OutputRFID : 25BLUID : 562WifiID : 2610RFID : 33RFID Count : 2and for example ;this is my Text file, because each generated file with our software has 14000 lines :)--------------------------AAAAAAAAAAAA;RFID=25;BBBB;BBBBBBBB;BBBBBBBBBB;CCCCC;fffdsfdsfdfsd;BLUID=562;dfsdfsf;fgfdgdf;terter;fdgfdgtryt;trtretrre;WifiID=2610;trterytuytutyu;zxzxzxzxz;popopopwwepp;RFID:33;aasasds…gfdgfgfd;gfdgfdgfd;fdgfgfgfd;I test it with this source code but i can't handle it;Scanner scanner = new Scanner(i:\1.txt);scanner.findInLine(RFID=);if (scanner.hasNext())System.out.println(scanner.next());elseSystem.out.println(Error!);please help me ;Thanks a lot ...
Creating a desktop icon using JWS JNLP for a JavaFX app : I am trying to get a custom destop icon to be displayed for my app but for some reason no matter what I do the same default java icon shows up. I have tried everything I can think of and gone and compared my jnlp file with others whose icons seem to work ok. According to everything I have read the following should work fine. But of course, it doesn't:information titleMikesApp/title vendorMike/vendor homepage href=http://www.mikesapp.com// descriptionMikes App./description icon kind=shortcut href=res/icon64x64.png width=64 height=64/ offline-allowed/ shortcut desktop/ /shortcut/informationAny ideas would be greatly appreciated.
Java ImageIO: Can I convert a PNG-24 file to PNG-8? : The scenario is this:Users of the webapp can customize the website by choosing their own logo image, background colors and background images.Problem is that IE6 does not support transparent PNG. I've tried several client-side solutions, but all fall short on one aspect or the other (most don't support the css property background-repeat).I'm looking for the alternate solution of creating two separate images on the server, one for modern, transparent-png-compliant browsers and one for IE6.Question is, can I accomplish this with ImageIO? Basically, I would detect whether the image is in PNG-24 format and convert it to PNG-8 (which is supported on IE6).
How can i filtered with the best performance? (JAVA) : I'm working at a small office,I have an application,it's generate a big text file with 14000 lines;after each generate i must filter it and it's really boring;I wanna write an application with java till I'll can handle it as soon as possible.Please help me; I wrote an application with scanner (Of course with help :) ) but it's not goodbecase it was very slow;For example it's my file :SET CELL:NAME=CELL:0,CELLID=3;SET LSCID:NAME=LSC:0,NETITYPE=MDCS,T32=5,EACT=FILTER-NOFILTER-MINR-FILTER-NOFILTER,ENSUP=GV2amp;NCR,MINCELL=6,MSV=PFR,OVLHR=9500,OTHR=80,BVLH=TRUE,CELLID=3,BTLH=TRUE,MSLH=TRUE,EIHO=DISABLED,ENCHO=ENABLED,NARD=NAP_STLP,AMH=ENABLED(3)-ENABLED(6)-ENABLED(9)and I want this output (filter :)CELLID : 3ENSUP : GV2amp;NCRENCHO : ENABLEDMSLH : TRUE------------------------Count of CELLID : 2which solution is the best and the fastest than the other ? it's my source code :public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File(i:\\1\\2.txt)); scanner.useDelimiter(;|,); Pattern words = Pattern.compile((CELLID=|ENSUP=|ENCHO=)); while (scanner.hasNextLine()) { String key = scanner.findInLine(words); while (key != null) { String value = scanner.next(); if (key.equals(CELLID=)) System.out.print(CELLID: + value+\n); //continue with else ifs for other keys else if (key.equals(ENSUP=)) System.out.print(ENSUP: + value+\n); else if (key.equals(ENCHO=)) System.out.print(ENCHO: + value+\n); key = scanner.findInLine(words); } scanner.nextLine(); }}Thank you very much indeed ...
Java Shell wildcard tokenizer : My Java is extremely rusty and I'm stuck trying to make a user interface that simplifies the execution of shell scripts or batch files depending on whether it's Linus or Win32 respectively. The files have the following naming convention. module-verb-object-etc [args-list] mysql-connect-grid mysql-connect-rds mysql-dump-grid mysql-dump-grid-se314ultimately I would like it to parse unambiguous terms so I can:tokenize the commands (e.g delimited by -) amp; shorten them into simplified terms soemthing like foxpro's command window or cisco's IOS (eg my co gr executes mysql-connect-grid in unix and *.cmd in win32)and also in the style of IOS allow the user to enter abbreviated commands so that they can type in a question mark (?) and it will give them a hint as to the unique remaining (or next) command options (e.g. my? returns mysql amp; my ? returns connect, or dump). Othr return values would be ambiguous or unknown for commands that are not unique or could not be matched. It may seem trivial but there are many hundreds of commands in each folder and my users don't want to think... I wrote a function to pull the list of files from a directory amp; retun an array of fileanmes. Then I convert that into a 2 dimensional array using the method below which returns a dynamicly sized grid of potential commands. /********************************************************************************** * MAKE GRID: Parses array of filenames and tokenizes AWS cmds. * @param strs Array of filenames **********************************************************************************/ public static String [][] makeGrid(String strs[], boolean bPrint) { String tmpGrid[][]; int nMaxCols = 0; int nRows = uniqueCount(strs); int nGridRow = 0; tmpGrid = new String [nRows][]; for (int nRow=0; nRownRows; nRow++) { String cFilename = strs[nRow]; if (!cFilename.endsWith(.cmd) // just list unix files (filter for batch files) amp;amp; cFilename.indexOf(-) 0 ) // make sure there's a dash in the filename { String strTokens[] = tokenize(strs[nRow], -); // the dash is our token deliminator int nCols = strTokens.length; if (nColsnMaxCols) nMaxCols=nCols; tmpGrid[nGridRow] = new String [nCols]; for (int nCol=0; nColnCols; nCol++) { tmpGrid[nGridRow][nCol] = strTokens[nCol]; if (bPrint) System.out.print( +tmpGrid[nGridRow][nCol]); } nGridRow++; if (bPrint) System.out.println(); } //end-if } String[][] cmdGrid = new String[nGridRow][nMaxCols]; System.arraycopy(tmpGrid, 0, cmdGrid, 0, nGridRow); // removes null rows (amp;NPEs!) return cmdGrid; }This returns a 2-d array (below), so grid[Row-N][Col-0] is a match. I'd like to pull only distinct values where row[0] is a wildcard match for cmdToken[0] amp;amp; row[1] is like cmdToken[1] so that my users can piece together a command until my du gr ? returns ENTER, [se314] - if that makes sense...String[][] makeGrid: mysql dump grid se314 mysql connect grid mysql dump grid mysql connect rdsMy Challenge: I cant seem to get my head around my matcher function in java. If it was SQL it would be something like: SELECT DISTINCT col2 FROM cmd_Grid WHERE col1 LIKE 'cmdToken1%' or even better: recursively setting a int depthmark for each consecutive column`SELECT DISTINCT col+str(depthmark+1) FROM cmd_Grid WHERE col+str(depthmark) LIKE 'cmdMatchedTokens%' until you have an exact match. I found a package called joSQL that I tried out of desperation but I cant seem to get it to work in Java6. Anyway: I was also hoping for a pure java solution so that everything could be contained in a single class... Maybe using scanner or something to parse my multidimentional array for unique values... I know I'm probably making it way more complex than it needs to be. a gentle nudge in the right direction would be appreciated.TIA
Shared jars in apache-tomcat 6.0.20 : I'm pretty new to JWS.I have a web application ( several web services ) that I want to deploy using tomcat 6.0.20 on a linux system.Everything's ok if I generate a .war file with all used libraries inside and put it in the webapps directory, but I want to have these jars shared, and the .war file itself is way too big.First I tried the intuitive way - I created a link ( WEB-INF/lib ) to the directory containing the jars, but strangely it fails to deploy ( it starts if the directory is not a link ):SEVERE: Error configuring application listener of class com.sun.xml.ws.transport.http.servlet.WSServletContextListenerjava.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServletContextListener at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3877) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4429) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:526) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:630) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:556) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:491) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1206) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:314) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardHost.start(StandardHost.java:722) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:583) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)After that I created the $CATALINA_HOME/shared/lib directory, and moved the jars there ( I've deleted the WEB-INF/lib ) and it still displays the same error - it seems tomcat isn't looking for the jars anywhere else than the WEB-INF/lib directory. But on the other hand - why would creating a symbolic link make any difference?My CATALINA_HOME and JRE_HOME vars seems to be right.
Eclipse RCP classloading problem with Metro : I am attempting to invoke a web service using the a href=http://metro.java.net/ rel=nofollow noreferrerMetro library from within an Eclipse RCP application. I bundled the relevant Metro jars (webservices-tools.jar, webservices-rt.jar, and webservices-api.jar) into a plugin and made my main application plugin depend on this new Metro plugin.I also added the webservices-api.jar to my $JAVA_HOME/jre/lib/endorsed directory. According to the Metro website, this is required when using Metro with Java 1.6.Now when I invoke any web service, I get the following error:javax.xml.ws.WebServiceException: Provider com.sun.xml.ws.spi.ProviderImpl not foundat javax.xml.ws.spi.FactoryFinder.newInstance(FactoryFinder.jav a:38)at javax.xml.ws.spi.FactoryFinder.find(FactoryFinder.java:133)at javax.xml.ws.spi.Provider.provider(Provider.java:83)at javax.xml.ws.Service.init(Service.java:56) ... Caused by: java.lang.ClassNotFoundException: com.sun.xml.ws.spi.ProviderImplat java.net.URLClassLoader$1.run(URLClassLoader.java:200)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:188)at java.lang.ClassLoader.loadClass(ClassLoader.java:307)at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301 )at java.lang.ClassLoader.loadClass(ClassLoader.java:252)at org.eclipse.core.runtime.internal.adaptor.ContextFinder.load Class(ContextFinder.java:129)at java.lang.ClassLoader.loadClass(ClassLoader.java:252)at javax.xml.ws.spi.FactoryFinder.newInstance(FactoryFinder.jav a:34)... 43 moreThe class com.sun.xml.ws.spi.ProviderImpl resides in webservices-rt.jar, which is a part of my Metro plugin. Furthermore, I have verified that my application plugin code can successfully load this class, so I'm not sure why javax.xml.ws.spi.FactoryFinder can't.Since javax.xml.ws.spi.FactoryFinder resides in webservices-api.jar (the jar I had to put in the jre's endorsed directory), I suspect that this has something to do with endorsed code not being able to load classes from an Eclipse plugin.Is it the case that code loaded by the JVM from the endorsed directory cannot load classes from plugins? Is there any way to enable this?Java version: 1.6.0_16Eclipse version: Eclipse Java EE IDE for Web Developers Build id: 20090920-1017 (it doesn't display a version beyond that)Metro version: Bundled with Glassfish 2.1Any help is greatly appreciated. Thanks.
Fastest way of processing Java IO using ASCII lines : I'm working with an ASCII input/output stream over a Socket and speed is critical. I've heard using the right Java technique really makes a difference. I have a textbook that says using Buffers is the best way, but also suggests chaining with DataInputStreamReader.For output I'm using a BufferedOutputStream with OutputStreamWriter which seems to be fine. But I am unsure on what to use for the input stream. I'm working on new lines, so would Scanner be of any use? Speed is critical, I need to get the data off the network as fast as possible.Thanks.PH
Javax.swing timer repeats fine, but ActionListener doesn't do anything : I am trying to flash the background colour in a textfield. My timer setup is as follows: Flash flash = new Flash(); //set up timer tmr = new javax.swing.Timer(1000, new Flash()); tmr.addActionListener(flash); tmr.setInitialDelay(0); tmr.setRepeats(true); tmr.start(); My actionListener is as follows: static class Flash implements ActionListener { public void actionPerformed(ActionEvent evt) { if (flasher) { SpreademPanel.historyPnl.NameTxt.setBackground(Color.white); } else { SpreademPanel.historyPnl.NameTxt.setBackground(Color.pink); } flasher = !flasher; } //actionPerformed} //FlashNow, when I put this in debug and follow the action, the program does repeatedly step through flash and toggle between the two alternatives. But onscreen, only the first toggle occurs. After that, no action, although flash is still functioning.What is wrong here?Thanks in advance for any help.
Java: Subclassing a genericised class : I have a genericised class that I wish to subclass as follows:public class SomeTableT extends BaseTableEntry extends BaseTableT{ public SomeTable(int rows, int cols) { super(rows, cols, SomeTableEntry.class); //Does not compile: //Cannot find symbol: constructor BaseTable(int, int, java.lang.Classblah.blah.SomeTableEntry.class) }}... where the genericised superclass is:public class BaseTableT extends BaseTableEntry{ public BaseTable(int rows, int cols, ClassT clasz) { ... }...}I understand the compiler error, but cannot seem to find a workaround, other than to include an extra parameter in the SomeTable constructor.Any suggestions?Thanks!
Is it possible to have a 'background' Facebook App? : I need a Facebook application that kind of sit in the 'background' of user operations. Once the app is installed by the user, it will keep on sending the user's status updates, new friend connections etc to another web app of mine. It will keep on getting info no matter whether the app page is open or not.My question is -- is this possible? So far, I've played around a simple iFrame app written with the Java API. It seems that it can only perform data collections whenever the page is hit. EDIT: Privacy is definitely a valid concern here. But the application will definitely prompt for permission even if FB API is not built in to do so.
Using -javaagent with Linux 64 bit tomcat : I m using -javagent agent.jar to instrument java classes in tomcat. While using -javaagent:location of the jar, in manifest file of the jar we will mention the premain class which gets called first and from there we can start instrumenting Byte code . From my Premain class(which get first called ) I add shutdownhook class to JVM.Runtime.getRuntime().addShutdownHook(ws).wsis object of my Webserver class that extends Thread.In start() method of ws class i create a server socket new ServerSocket(port). While the JVM shutdown run() method of Ws (Shutdownhook) is called and i close the serversocket ss.close(). In 64 bit Linux machines the port remains unclosed. In 32 bit machines with tomcat 5 the method is properly called and closed. But in 64 bit linux OS machine shutdownHook never gets called and port which i opened for serversocket remains occupied when the Tomcat shutdown
Java Webstart intermittant JAR not updating : We use java Webstart to deploy a java application on our intranet. The application receives frequent updates. Once in awhile a user will launch the application from their desktop icon after we have updated the JARs / WAR on the webserver (timestamp changed) and Java Webstart will launch the old version instead of downloading a new one.Here is a paste of our JNLP, as you can see offline-allowed is on, but update check always and policy always. Also, download flag is eager. From my understanding these options should always result in a check of cache against timestamp on server and a download of the JAR file. I'm starting to get frustrated with Webstart! Has anyone seen similiar problems? Any solutions? I'm getting sick of walking people through clearing their webstart cache manually every third or fifth update.?xml version=1.0 encoding=utf-8?!DOCTYPE jnlp PUBLIC -//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0//EN http://java.sun.com/dtd/JNLP-6.0.dtdjnlp spec=1.0+ codebase=$$codebase href=$$name information titleTITLE/title vendorVENDOR/vendor descriptionOur Utility Application/description description kind=shortOur Utility Application PRD/description icon href=images/util_icon.png height=64 width=64/ offline-allowed/ shortcut online=true desktop / menu submenu=Utility Apps/ /shortcut /information security all-permissions / /security update check=always policy=always / resources !-- requires 1.6+ -- j2se version=1.6+ href=http://java.sun.com/products/autodl/j2se java-vm-args=-ea initial-heap-size=128m max-heap-size=512m / !-- application code, download jar before we start. -- jar href=OurUpdatedJarName.jar main=true download=eager / property name=configfile value=updatedJarName.config / /resources application-desc main-class=main.Client argument-D/argument /application-desc/jnlp
Redirecting Facebook 'offline_access' permission page : I am trying to get users' permission for 'offline_access' in an iFrame Facebook application coded with the Facebook Java API. I understand that I need to obtain an 'indefinite session key' after the users approves my application. Currently, I can accomplish what I want, but in a very awkward way that is probably not correct. There must be a better way to do this. Any thoughts/ideas would be appreciated!!What I've doneIn a servlet of my app, I check to see if the user currently has 'offline_access' permission. If they do, I get the url by Permission.authorizeUrl(Permission.OFFLINE_ACCESS). I then call response.redirect to get to the permissions page. Two problems I'm having are:The redirected permissions page is displayed within the iFrame. Hence, the Facebook book home menu bar etc. are displayed twice. i.e. looking like an app is embedded in another app. The user will be 'stuck' on the permission page once redirected there. I won't be able to obtain the 'indefinite session key' (by calling client.getCacheSessionKey) unless the user goes back to a page in my app manually. Possible Work-arounds??Is there a way to open/redirect to the permissions page in a new window? That way maybe I can have a thread in my servlet to keep checking whether the permission is set after the redirection. And then I can get the 'indefinite session key' once I have it and store it somewhere?Is there a way to set an URL for Facebook to go to after permission is set? (much like the pre-auth and post-auth URL settings?) Or somehow take control after the permission page is hit?Any other ways to setup my app maybe?? Being a newbie, I might've totally gotten the idea wrong...
how to run code compiled by JavaCompiler? : Is there any way to run program compiled by JavaCompiler? [javax.tools.JavaCompiler] My code: JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollectorJavaFileObject diagnostics = new DiagnosticCollectorJavaFileObject(); CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content)); task.call(); ListString returnErrors = new ArrayListString(); String tmp = new String(); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { tmp = String.valueOf(diagnostic.getLineNumber()); tmp += msg: + diagnostic.getMessage(null); returnErrors.add(tmp.replaceAll(\n, )); }Now i want to run that program with lifetime 1 sec and get output to string variable. Is there any way i could do that?
compiling and running user code with JavaCompiler and ClassLoader : I am writing web app for java learning. Using which users may compile their code on my serwer + run that code. Compiling is easy with JavaCompiler: JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollectorJavaFileObject diagnostics = new DiagnosticCollectorJavaFileObject(); CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content)); task.call(); ListString returnErrors = new ArrayListString(); String tmp = new String(); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { tmp = String.valueOf(diagnostic.getLineNumber()); tmp += msg: + diagnostic.getMessage(null); returnErrors.add(tmp.replaceAll(\n, )); }I manage to load class with code: JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null); try { URL[] urls = {new URL(file:///root/), new URL(file://C:\\serv\\Apache Tomcat 6.0.20\\bin\\)}; ClassLoader cl_old = Thread.currentThread().getContextClassLoader(); ClassLoader cl_new = new URLClassLoader(urls, cl_old); Class compiledClass = cl_new.loadClass(CLASS_NAME); Method myMethod = compiledClass.getMethod(METHOD_NAME); Object tmp = myMethod.invoke(null); } catch (Exception ex) { Logger.getLogger(ITaskCompile.class.getName()).log(Level.SEVERE, null, ex); }How can i protect my app from endless loop, and evil students ;)is there any way to run that code with a lifetime ?is there any risk with memory leaks, and what can i do to fix this.is this good solution, or can you suggest something better ? thx. Tzim
Java Scanner input unequal to itself? : I'm writing a loop that will exit when the Scanner receives the String value end. However, when test with an end value, the loop continues. Logically if file = the input, then if(file==end) is false, even though i typed in end! Are there visible errors in my code?String file = ; Scanner in = new Scanner(System.in); ArrayListInteger fileInput = new ArrayListInteger(); while(file!=end) { // Scan for filename/end program System.out.println(Provide the name of a file in the \bin/\ folder, i will assume it's .txt); file = in.nextLine(); System.out.println(. + file + .); if(file!=end) { file= bin/ + file + .txt; // start reading try { // If file found then carry on BufferedReader openFile = new BufferedReader(new FileReader(file)); fileInput = readIn(openFile); int lowerBound = getLower(fileInput); int upperBound = getUpper(fileInput); System.out.println(Lower Bound: + lowerBound); System.out.println(Upper Bound: + upperBound); // file not found } catch (FileNotFoundException e) { System.out.println(File not found!); } } } System.out.println(Goodbye!); System.exit(0);
facebook-java-api on red5, can they work together? : I have a Adobe Flash Builder GUI application that connects to Red5 to communicate.can i use the red5 to call facebook API calls? can anyone provide an example? all the examples that i can find are with tomcat.thanks!
facebook-java-api: fql_query returns null : I'm trying to fetch logged-in first name using fql_query.i tried the following code:import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import javax.servlet.http.*;import javax.servlet.*;import org.w3c.dom.Document;import com.google.code.facebookapi.FacebookException;import com.google.code.facebookapi.FacebookWebappHelper;import com.google.code.facebookapi.FacebookXmlRestClient;import com.google.code.facebookapi.IFacebookRestClient;import org.json.JSONException;public class Canvas extends HttpServlet { private static final String FACEBOOK_USER_CLIENT = facebook.user.client; private String api_key=API_KEY; private String secret=SECRET; @Override public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; HttpSession session = request.getSession(true); IFacebookRestClientDocument userClient = getUserClient(session); if(userClient == null) { // logger.debug(User session doesn't have a Facebook API client setup yet. Creating one and storing it in the user's session.); userClient = new FacebookXmlRestClient(api_key, secret); session.setAttribute(FACEBOOK_USER_CLIENT, userClient); } FacebookWebappHelperDocument facebook = new FacebookWebappHelperDocument(request, response, api_key, secret, userClient); String nextPage = request.getRequestURI(); nextPage = nextPage.substring(nextPage.indexOf(/, 1) + 1); //cut out the first /, the context path and the 2nd / // logger.trace(nextPage); boolean redirectOccurred = facebook.requireLogin(nextPage); if(redirectOccurred) { return; } redirectOccurred = facebook.requireFrame(nextPage); if(redirectOccurred) { return; } long facebookUserID; try { facebookUserID = userClient.users_getLoggedInUser(); } catch(FacebookException ex) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Error while fetching user's facebook ID);/* logger.error(Error while getting cached (supplied by request params) value + of the user's facebook ID or while fetching it from the Facebook service + if the cached value was not present for some reason. Cached value = {}, userClient.getCacheUserId());*/ return; } PrintWriter out = res.getWriter(); String query = Select name from user where uid= + facebookUserID; Document fqlDocument=null; try { fqlDocument = userClient.fql_query(query); } catch (FacebookException e) { out.println(error); } out.println(Hello, Brave new World: + facebookUserID + + fqlDocument); out.close(); } public static FacebookXmlRestClient getUserClient(HttpSession session) { return (FacebookXmlRestClient)session.getAttribute(FACEBOOK_USER_CLIENT); }}the resulted output is:Hello, Brave new World: MY_UID[#document: null]i reassured that the uid that i received is the correct one.using facebook-java-api 3.0.2 (latest version)why did i get an empty document from the query ?why did the query not throw any relevant exception if there was a problem?this is a code that i found on the net, is there any better method to implement my goals ?thanks for everything! i'm really new in this subject so i apologize for any un-relevant questions or information on the subject.
Calling clojure from java : Most of the top google hits for calling clojure from java are outdated and recommend using clojure.lang.RT to compile the source code. Could you help with a clear explanation of how to call Clojure from Java assuming you have already built a jar from the Clojure project and included it in the classpath?
Could not access php session variable once the tomcat restarts : I am developing an applicaton in java which needs to integrate some php files under tomcat server. I did everything successful, but the problem is that when i shutdown tomcat server it shows some error like Exception in thread JavaBridgeSessionTimer java.lang.NullPointerException at php.java.bridge.SessionFactory$SessionTimer.run(SessionFactory.java:157) at java.lang.Thread.run(Thread.java:619)Later if I start again I could not access any of the session variables from php files. I tried a simple php program which run within tomcat. This problem will get resolved once I restart the machine, but i don't want to do this frequently for any change in any configuration files in tomcat. session1.php?phpsession_start();?bodyhtmlform action=session2.php method=post ?php $_SESSION['name']=MyName; ? input type=submit value=Submit/form/bodysession2.php?phpsession_start();?htmlbody?php echo( $_SESSION['name'] ); ? /body/html
Programmatically compile Java class in a package stored in an arbitrary sub folder : I am looking to compile an application in Java, made up of a various number of java classes in a certain number of packages. At the command line, I can change to the folder containing the root package and type:javac rootpackage/subpackage/*.javaorjavac rootpackage/*/*.javato compile all the java classes in all the primary subpackages of my rootpackage. However I would like to be able to do this within a Java application. (The idea is that we provide an application to students which contains unit tests. The unit tests need to be run against their code, the application then creates a JAR file containing their source files which have been 'watermarked' with the test results. All this works ok, but we would like to make sure that the class files tested are created from the source files submitted, hence the idea to compile programmatically the java sources).The problem comes in that each student stores their root package in an arbitrary position, and I cannot seem to pass the location of the file to JavaCompiler (javax.tools).Is it possible, and if so, can someone give some hints on how to have an arbitrary placed root package compiled properly.CheersRichardMore Info:a student has a folder structure:/home/student/work/java/myproject/which contains the root package. They launch the application (possibly stored in this folder - and thus no problems- however more than likely stored elsewhere) which asks them for the folder that contains the root package. After entering, the students click a create JAR button, that compiles the files in their packages, runs the tests on the newly compiled files and then creates the JAR. Whilst thinking through this problem, it is possible that the solution is to tell the students to install our 'create JAR' application in the folder containing their root package.
Portable Java Web Start Cache Location : I'm trying to make a java web start application portable. It stores some stuff in the user's home directory, and also a bunch of stuff in the cache. I'm using portableapps.com's portable java, and I've got it to store the home folder stuf using -J-Duser.home=Data, but how do I change the web cache, preferrably to a folder called cache in the same directory.
Can a web service call another web service in the same application server : I'm using Netbeans 6.5 to generate the JAX-WS Metro service and Glassfish 2.1 as the application server.Assume I have two web services e.g....@WebMethod(operationName = doXXX)public String doXXX(@WebParam(name = id) String id... ...@WebMethod(operationName = doYYY)public String doYYY(@WebParam(name = result) String result... and I have a Web Service client (a Java application) that happily calls both.I now want method XXX to call method YYY i.e. I need to place the client proxy for YYY inside of web service XXX.How do I do this?
Java parsing many instances of substring from String : I am trying to write a small java program that will accept a file (using Scanner class), return the file as a String, and then search that string for any instance of a substring starting with Email: and ending with .edu. There will be many instances of this substring, each of which I want to parse out into an array or a new file.I know how to find a substring, but I do not know how to A) search for all instances of the substring and B) specify the start AND finish of the substring.Can someone help me with this logic?Thanks!
How can I make a WebMethod parameter required : We use the start from Java approach to creating JAX-WS 2.0 web services using the Metro 1.5 stack. When we point a standard tool like SoapUI at one of our web services it indicates that parameters to WebMethods are optional. The generated xsd shows minOccurs=0.I need a way to make WebMethod parameters required (maybe minOccurs=1 in the xsd) in the start from Java approach. I would think there is a Java annotation for this, but I haven't been able to find one. The XmlElement annotation has required attribute, but XmlElement cannot be applied to WebMethod parameters.Is there a way to make my WebMethod parameters required, short of manually editing the xsd and setting minOccurs to 1?
Specify own Formatter in configuration file of java logger : I wrote a Formatter (test.MyFormatter) by extending the class java.util.logging.Formatter;Now I want to use test.MyFormatter instead of java.util.logging.SimpleFormatter:in the configuration file i replaced the entry:java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatterwith java.util.logging.ConsoleHandler.formatter = test.MyFormatterunfortunately this is not working.can somebody explain me, if what I am doing is:correctif yes, why it not working?
jpegs are corrupted when resampled with java imageIO : The JPEG Images that ImageIO generated view correctly on windows file explorer, as well as safari webbrowser, but in FireFox, the resampled images are clipped.How do I use ImageIO without corrupting the resamples?The code should resize image keeping aspect ratio, as well as do jpeg compression, the convert it to a byte [] array, which could be written to a socket.some of my code. in this snippet, I tried adding Jui library, but still the same issue.public static BufferedImage imageistream;public void Resample(String child,double width,double height) throws Exception, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException, MissingParameterException, WrongParameterException{ String imagePath = ; if(this.is_mac_unix == true) { imagePath = this.path+/+child; } else { imagePath = this.path+\\+child; } PixelImage bmp = null; try { bmp = ToolkitLoader.loadViaToolkitOrCodecs(imagePath, true, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Resample resample = new Resample(); resample.setInputImage(bmp); double fixedRatio = width/height; if(((double)bmp.getWidth()/bmp.getHeight()) = fixedRatio) { resample.setSize((int)width,(int)(bmp.getHeight()/(bmp.getWidth()/width))); } else { resample.setSize((int)width,(int)(bmp.getWidth()/(bmp.getHeight()/height))); } resample.setFilter(Resample.FILTER_TYPE_LANCZOS3); resample.process(); PixelImage scaledImage = resample.getOutputImage(); Processor.imageistream = ImageCreator.convertToAwtBufferedImage(scaledImage); bmp = null; Runtime rt = Runtime.getRuntime(); rt.gc(); } ... ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(Processor.imageistream, jpg, baos); // ImageIO.write(Processor.imageistream, png, baos); Works! } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte bytes[] = baos.toByteArray(); ByteArrayInputStream is = new ByteArrayInputStream(bytes); OutputStream os = (OutputStream)obj[1]; OutputStreamWriter writer = (OutputStreamWriter)obj[0]; byte[] buf= new byte[4096]; int c; try { while (true) { c= is.read(buf); if (c= 0) break; os.write(buf, 0, c); } writer.close(); os.close(); is.close();
How to detect if file exists in jnlp without opening a file dialog box? : In my jnlp app I need to know if a user property file exists, if it does, load it, my code looks like this :File_Contents=File_Open_Service.openFileDialog(.,new String[]{.txt});String Text=readFromFile(File_Contents);InputStreamReader in=new InputStreamReader(File_Contents.getInputStream());Application_Props.load(in);Users don't know the name of the property file, so even if I open a dialog box, they won't know which file to choose, so my question is : in jnlp can I do something like : if (new File(abc.txt).exists) Load_Property() ? If it doesn't exist, go on without popping up a dialog box, if it exists, don't need to open a dialog box either, just read it in, if necessary, ask the user if it's ok to read in a file named abc.txt as a property file. How to achieve this in jnlp ? Any sample code ?PS : I'm not running it in all-permissions mode, because that requires a 3rd party cert. which cost a bit.
JNLP java.security.AccessControlException with TargetDataLine.open()? : I have the following line which caused this error message run under JNLP :java.security.AccessControlException: access denied (javax.sound.sampled.AudioPermission record) at java.security.AccessControlContext.checkPermission(Unknown Source)TargetDataLine targetDataLine.open(audioFormat);How to fix it ? Or does that mean in JNLP, we can't record sound ?PS : I'm not running it in all-permissions mode, because it requires a 3rd party paid cert. to sign the jar before I can submit my app to Sun's Java Store. I wonder if there's any other way, like using JNLP's FileSaveService / FileOpenService ?Frank
facebook java api: what is the replacement for all the feed_* methods? : I see all the feed_* methods are deprecated... (I am using version 3.0.2).What replaces them? How do I publish something to the user's feed.
Scanner vs. BufferedReader : As far I know, the two most common methods of reading character-based data from a file in Java is using Scanner or BufferedReader. I also know that the BufferedReader read files efficiently by using a buffer to avoid physical disk operations. My questions are:Does Scanner performs as well as BufferedReader?Why would you choose Scanner over BufferedReader or vice versa?
Convert Scala Set into Java (java.util.Set)? : I have a Set in Scala (I can choose any implementation as I am creating the Set. The Java library I am using is expecting a java.util.Set[String].Is the following the correct way to do this in Scala (using scala.collection.jcl.HashSet#underlying):import com.javalibrary.Animalsvar classes = new scala.collection.jcl.HashSet[String]classes += Amphibianclasses += ReptileAnimals.find(classes.underlying)It seems to be working, but since I am very new to Scala I want to know if this is the preferred way (any other way I try I am getting a type-mismatch error):error: type mismatch; found : scala.collection.jcl.HashSet[String] required: java.util.Set[_]
ASM (from ObjectWeb) not calculating MaxStack correctly even though ClassWriter( COMPUTE_MAX + COMPUTE_STACK ) is set : I am getting expected ClassVerifyErrors when attempting to load a class i have generated using ASM. On further inspection i can see that the jvm is correct and that the method is talking about has an invalid MAX_STACK value. THe strange thing is am using the auto calculate the stack and max local options so this should not be a problem...The method with the invalid option is very simple and yet the result is bad bytecode.I have written a class with the intended method and compared my asm generated class against what javac produces and the byte codes matchup with the only error being the max stack is 0 which is wrong while javac sets a value of 2.Id like to avoid having to calculate tha max stack/locals myself.
What happens if I miss facebook's callbacks? : What happens if I miss facebook's callback, because my app is down, or had an error or something? Will facebook retry later?
How to make Java read very big files using Scanner? : I'm using the following basic function which I copied from the net to read a text file public void read (){ File file = new File(/Users/MAK/Desktop/data.txt); System.out.println(Start); try { // // Create a new Scanner object which will read the data from the // file passed in. To check if there are more line to read from it // we check by calling the scanner.hasNextLine() method. We then // read line one by one till all line is read. // Scanner scanner = new Scanner(file); int lineCount = 0; if (scanner == null) { System.out.println(Null File); } else { System.out.println(scanner.toString()); } while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(Line + lineCount + contain : + line); lineCount++; } System.out.println(End of Try Bluck); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println(Exception Bluck); } System.out.println(End);}}It's working fine with medium and small size file (which contain 10 to 20 thousand line of data)However it failed to work with a file that contain 500 thousand line. I'm not getting an error (at least not seeing anyone). so what is going on? what should i do here to be able to ready such a big files?note: I already increased the heap for 2 GB on the test machine which run Windows Server 2008 with 4 GB ram. but this didn't help much!Please anyone can tell me what I should do here?Update 01The following is the outputblockquote Start java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E] End of Try Bluck End/blockquote
is there java.concurrent.util (or equivalent) for WeakHashMap? : Can the following piece of code be rewritten w/o using Collections.synchronizedMap() yet maintaining correctness at concurrency? Collections.synchronizedMap(new WeakHashMapClass, Object());i.e. is there something from java.util.concurrent one can use instead? Note that merely replacing with new ConcurrentHashMapClass, Object(new WeakHashMapClass, Object()));obviously won't work
Difference in using java.util.logging and Log4j Loggers : I am developing a java application for which i have to use a logging mechanism. And now i am confused to choose either java libraries logger or to go for Log4j logger. So i want to know when i can go for java logger and when i can go for log4j logger.
java.security.AccessControlException: access denied using Java Web Start : I am having some issues with accessing files using JWS (Java Web Start). The program adds a new label and image. The program runs fine on my local computer but gives me pages of errors when I run the program on my remote server using JWS. Here's a sample of the error:Exception in thread AWT-EventQueue-0 java.security.AccessControlException: access denied (java.io.FilePermission add2.png read) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source)This occurs even after making sure the images have read access.Ideas?
Java ImageIO: How can I read a BufferedImage from file, so that it uses DataBufferFloat? : I need to read a BufferedImage from file, which doesn't use DataBufferInt (as normally), but DataBufferFloat.Please note: I don't just need some standalone DataBufferFloat, but really a BufferedImage with underlying DataBufferFloat.The API around these things is very complex, I just can't find how to do this.Please help.EDITFound out what is not working:DataBufferDouble dbd = new DataBufferDouble(destWidth * destHeight * 4);// Exception here:// java.lang.IllegalArgumentException: Unsupported data type 5WritableRaster wr = WritableRaster.createPackedRaster( dbd, destWidth, destHeight, 32, new Point(0, 0));BufferedImage bi = new BufferedImage(ColorModel.getRGBdefault(), wr, false, (Hashtable?, ?) null);
Java Web Start Authentication Option : Ok, before you think that this is a simplistic request and that it must be out there; I've done about 2-3 hours of searching with no results. Is there a way to pass authentication information through Java Web Start (javaws) to access a password protected website?Essentially what I'm working towards is an auto-restart of a javaws application without having to re-implement what javaws does to pull the jar's down and then having to run Java on the downloaded application. I've really been trying to find information on this but no one wants to do the same thing I'm doing (mainly because if you have authentication then you would want someone to authenticate).The authentication method is basic and I've tried embedding the username/password into the URL to no avail. Any ideas?
Looking for a faster alternative to ImageIO : I'm attempting to encode a large quantity of BufferedImages to JPEG using the ImageWriter class in javax.imageio. Unfortunately, the encoding operation is quite slow (about 80 to 250 ms per image, not including writing to disk.) This encoding stage ends up being the slowest part of my app, so I'm hoping to optimize it.Does anyone know of an alternative to the ImageIO package that may be faster?
What is the difference between Metro 1.5 and 2.0? : In a web service client project I am working on, I noticed that the Metro stack has been released in a 2.0 version, where we use 1.4. The documentation is not very approachable for people not intimately familiar with the project.What is the reason for the version bump, and is it worth it upgrading to the latest version?
Performance and Functionality Difference between log4j and Logging Util class : I am newbie for the logging class in Java.util package, I have developed an Application and want to implement the logging mechanism at different levels, I am just thinking to which one to go for and identify the differences between these 2.I am looking1) logger should be easily maintainable, implementable.Can any one suggest on this.
Is there a robust java.util.logging handler implementation of syslog? : I'm looking into hooking up a 3rd party Java application to our log aggregation/analysis solution (probably Splunk, we haven't finalized our selection yet though). It seems to be easiest to hook the Splunk agent to syslog, so I'm looking for a way to redirect the application logs to a local syslog daemon on the server.The Java application uses java.util.logging, which unfortunately does not feature a syslog handler out of the box (I believe log4j does, though). Are there any proven libraries to do this? The log load isn't huge (probably 10-20 messages per minute from each process, up to 6 processes per host) but I'm concerned with reliability and durability (e.g. what happens when the daemon is down?...).Any help would be appreciated...
Is Skype4Java still being developed? : Looks like the a href=https://developer.skype.com/wiki/Java_API rel=nofollow noreferrerlast release of this was back in 9/30/06. Is there still active development going on? Has anyone built a commercial-quality product on top of this?
Multithreaded Java Program for Conway's game of life - contention at the border cells : I am learning concurrent programming in java, and writing a simulation for Game of Life.Here is what I am thinking:Use int[][] to store the states of the cellspartition the int[][] into t segments and use t worker threadsThe t threads will read from their segment, calculate new values for all the cells in their segment and update the cells.Once they finished calculation they wait at a barrier for other workers to finishwhen the barrier is crossed the main thread will update the UI.the workers proceed to calculate the next state.Now there is going to be contention at the common borders of the segments. If a thread overwrote the state of a border cell before its neighbor has read the previous value, the neighbor's calculation is going to be wrong. What are my options?Use callable instead of runnable and have the worker threads return the new value (instead of updating the segments themselves). The main thread can update the matrix after the barrier is crossed. This option involves copying the results returned by worker threads into the matrix. Use two barriers. The workers thread make a copy of the border cells from their neighbors' segments and wait at the first barrier. Once this barrier is passed, they proceed to calculate the next states and update the segments in place. Then they wait at the 2nd barrier. the main thread updates the UI.My question is, is there any other way to deal with the contention at the border cells that does not involve copying data or is more efficient that the above two options? May be using ReaderWriterLock, volatile variable or other synchronizing mechanism? UPDATE: So far the a href=http://stackoverflow.com/questions/2328985/multithreaded-java-program-for-conways-game-of-life-contention-at-the-border-c/2329383#2329383double buffering solution by Peter is the cleanest one. But I have a question. Since the two arrays are shared data and we are not using any synchronization (synchronized access or volatile variable), won't it create visibility problem? Could multiple CPUs cache the array values and update only a part of the array with each iteration? Then the threads will get stale values for the border cells. Is this possible? If not, why. If yes, how do I solve it? It seems a href=http://www.javamex.com/tutorials/volatile_arrays.shtml rel=nofollow noreferrerdeclaring two arrays volatile will not make their individual elements volatile.
Applet served by Java Web Start, resources requested to WEB Server before look in the JAR files : I am new here and I apologize for my bad English.I have a little problem with an Applet class served by Java Web Start technology. I have some platform dependent JAR files which Web Start download correctly, but when I get the content by getResourceAsStream(String fileName) method of ClassLoader object, first is made a GET request of fileName to WEB Server, after received a 404 Not Found response, the resource is loaded correctly from JAR file. The problem is that I have many files inside the JAR, so I have a lot of unnecessary load on the WEB Server and consequently I have to wait for long time before I can use the Applet.Searching on Google I have found some discussions where it was said to add the parameter codebase_lookup with value false, but this has not solved the problem. a href=http://java.sun.com/javase/6/docs/technotes/guides/plugin/developer_guide/special_attributes.html rel=nofollow noreferrerThis page, in relation to the codebase_lookup parameter, says that the default behavior of an Applet is to load resources from JAR file and then from the Applet codebase, in my case the behavior is the opposite.I also added the eager=true attribute for each JAR resource in the .jnlp file, but the behavior is always the same. The Applet was developed and built with NetBeans, the html and jnlp files generated are the following.launch.htmlapplet width=300 height=300 param name=jnlp_href value=launch.jnlp/ param name=codebase_lookup value=false//appletlaunch.jnlp?xml version=1.0 encoding=UTF-8 standalone=no?jnlp codebase=http://192.168.23.4/contact href=launch.jnlp spec=1.0+information titleContactNR/title vendorRoberto Santini/vendor homepage href=/ descriptionContactNR/description description kind=shortContactNR/description/informationresourcesj2se version=1.5+/jar eager=true href=ContactNR.jar main=true/jar eager=true href=lib/VDK.jar/security all-permissions//security/resourcesresources arch=amd64 os=Linux jar eager=true href=lib/liblinux64.jar//resourcesresources arch=x86_64 os=Linux jar eager=true href=lib/liblinux64.jar//resourcesresources arch=x86 os=Linux jar eager=true href=lib/liblinux.jar//resourcesresources arch=i386 os=Linux jar eager=true href=lib/liblinux.jar//resourcesresources os=Windows jar eager=true href=lib/libwin.jar//resourcesresources os=MacOs jar eager=true href=lib/libmac.jar//resourcesapplet-desc height=300 main-class=com.netresults.voip.ContactNR name=ContactNR width=300 param name=codebase_lookup value=false//applet-desc/jnlpCan someone help me?Thanks at all,Roberto.
PLS-00103 error when comping Oracle stored function : Given the following Java which is loaded into the database using loadjava:package grassie.example;public class Example { public static String test(){ return Hello World!; }}And given the following Oracle Stored Function:CREATE OR REPLACE FUNCTION TEST_FUNCTION RETURN VARCHAR2AS LANGUAGE JAVANAME 'grassie.example.Example.test() RETURN java.lang.String';Why does the function not compile with the following error?:Error(3,1): PLS-00311: the declaration of grassie.example.Example.test() RETURN java.lang.String is incomplete or malformedOracle client is 9.2.0.8.0, database is 9.2.0.8.0. Using SQL Developer 2.1.0.63edit: Ammended my question based on answers below.To further clarify, I created this simple test class and function because I am having problems with more complicated Java and stored functions, which accept and return various parameter types.
How can i deliver jetty with many webapps via jnlp? : i have a webapp (a href=http://sourceforge.net/projects/sf-mvn-plugins/files/m2-repo/net/sf/maven/plugins/example-captaincasa-jnlp/0.1-SNAPSHOT/example-captaincasa-jnlp-0.1-SNAPSHOT.war/download rel=nofollow noreferrerhttp://sourceforge.net/projects/sf-mvn-plugins/files/m2-repo/net/sf/maven/plugins/example-captaincasa-jnlp/0.1-SNAPSHOT/example-captaincasa-jnlp-0.1-SNAPSHOT.war/download) wich use jsf in a servlet container. This works fine with jetty-maven-plugin run-war target at my local pc. In the future i would like make more of this kind of weapps.Now i am looking for a way to deliver this webapps with jetty via jnlp. The end user should be have a zero installation but the webapps needs servlet container and my hoster does not support a servlet container or application server or so on.I don't like an embedded solution because in this case each webapp must be delivered with a separate jetty und run with a separate jetty - too big size - to many download size and so on.The architecture should be similar to this:img src=http://tmichel.users.sourceforge.net/files/Architecture.png alt=architectureExample: Bundle1 could contains jetty and deployed webapp1 and Bundle2 could contains jetty and deployed webapp1 and webapp2 (related to requirements of end user i would like deliver many variant of my webapps)But what is my question?1) Wich jars of jetty are needed? I would like these upload to my homepage for hosting.2) Wich jar should i use for jetty as main jar to start him via jnlp?3) Wich main class should i use to start jetty via jnlp?4) Wich parameter i could use to configure jetty to say this is war of webapp1 and this is war of webapp2.... or this is directory of weapps for hot deployment...?The important question for me is 1) If this is answered so i could run jetty local (without maven plugin) and via manual maybe i could solve the rest 2-4. Thanks for ideasThomas
Where are Java WebStart resources downloaded to? : Can't locate stored files, but they seem to be downloaded only for the first time i run JNLP file. I'm on Mac OS X 10.6.
How to debug Java Web Start applications? : I have a Java Web Start Application that I launch from live site by downloading a tailored JNLP file.The problem is that once the Java Web Start application has loaded, the application quits without any warning. I know that the certificate is OK since when I enable Show site certificate from server even if it is valid option from Java settings, it displays a message correspondigly.I have tried enabling all debugging settings from Java settings (Enable tracing, Enable logging, show applet lifecycle exceptions) and also Java console, but with no luck caching the problem.Could anyone with more experience on Java Web Start development/debugging give any tips?
Calling a .NET web service (WSE 3.0, WS-Security) from JAXWS-RI : I'm writing a JAXWS-RI client that must call a .NET Web Service that is using WS-Security. The service's WSDL does not contain any WS-Security info, but I have an example soap message from the service's authors and know that I must include wsse:Security headers, including X:509 tokens.I've been researching, and I've seen example of folks calling this type of web service from Axis and CXF (in conjunction with Rampart and/or WSS4J), but nothing about using plain JAXWS-RI itself. However, I'm (unfortunately) constrained to using JAXWS-RI by my gov't client. Does anyone have any examples/documentation of doing this from JAXWS-RI? I need to ultimately generate a SOAP header that looks something like the one below - this is a sample soap:header from a .NET client written by the service's authors. (Note: I've put the 'VALUE_HERE' string in places where I need to provide my own values)soapenv:Envelope xmlns:iri=http://EOIR/IRIES xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/ xmlns:xenc=http://www.w3.org/2001/04/xmlenc# soapenv:Header xmlns:wsa=http://www.w3.org/2005/08/addressing wsse:Security xmlns:wsse=http://docs.oasis-open.org/wss/2004/01/oasis-200401- wss-wssecurity-secext-1.0.xsd xenc:EncryptedKey Id=VALUE_HERE xenc:EncryptionMethod Algorithm=http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p/ ds:KeyInfo xmlns:ds=http://www.w3.org/2000/09/xmldsig# wsse:SecurityTokenReference wsse:KeyIdentifier EncodingType=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary ValueType=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3 VALUE_HERE /wsse:KeyIdentifier /wsse:SecurityTokenReference /ds:KeyInfo xenc:CipherData xenc:CipherValueVALUE_HERE/xenc:CipherValue /xenc:CipherData xenc:ReferenceList xenc:DataReference URI=#EncDataId-8/ /xenc:ReferenceList /xenc:EncryptedKey /wsse:Security
Scanner errors in ActionListener/actionPerformed class : Hey everyone, I'm working on a hex dump utility made in Java. I'm having some issues with the Scanner I'd be using before the hex/ascii logic.Right now I have the logic and a few other things excluded for debugging reasons, but if anyone knows what's going on I'd like to know! Hints greatly appreciated.package filedumputility;import javax.swing.*;import java.util.*;import java.awt.*;import java.awt.event.*;import java.io.*;public class FileDump extends JFrame {public FileDump() throws Exception{ setTitle(File Dump Utility); add(new DumpPanel());}//Main methodpublic static void main(String[] args) throws Exception { FileDump frame = new FileDump(); frame.setSize(500, 250); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setVisible(true);}//Class to creaste componentsclass DumpPanel extends JPanel { private JFileChooser fileChooser = new JFileChooser(); private JTextArea dumpArea = new JTextArea(11, 20); private JTextField fileName = new JTextField(16); private JButton newButton = new JButton(New File); private JButton clearButton = new JButton(Clear); private JButton dumpButton = new JButton(Dump File); private JScrollPane scrollPane = new JScrollPane(dumpArea); private JPanel p = new JPanel(); private Scanner input; //Class to add components and read the file public DumpPanel() throws Exception { p.setLayout(new FlowLayout()); setLayout(new BorderLayout()); add(p, BorderLayout.NORTH); p.add(fileName); p.add(dumpButton); p.add(newButton); p.add(clearButton); add(scrollPane, BorderLayout.SOUTH); dumpArea.setEditable(false); fileName.setEditable(false); //Create event for the new file button newButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { //Get the file java.io.File file = fileChooser.getSelectedFile(); //Set file name bar to the selected file fileName.setText(file.getName()); } } }); dumpButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { //Get the file java.io.File file = fileChooser.getSelectedFile(); //Create scanner Scanner input = new Scanner(file); } } }); clearButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ dumpArea.setText( ); fileName.setText( ); } }); }}}
Java: use scanner delimiter as token : I'm trying to find a good way to get a Scanner to use a given delimiter as a token. For example, I'd like to split up a piece of text into digit and non-digit chunks, so ideally I'd just set the delimiter to \D and set some flag like useDelimiterAsToken, but after briefly looking through the API I'm not coming up with anything. Right now I've had to resort to using combined lookaheads/lookbehinds for the delimiter, which is somewhat painful:scanner.useDelimiter(((?=\\d)(?=\\D)|(?=\\D)(?=\\d)));This looks for any transition from a digit to a non-digit or vice-versa. Is there a more sane way to do this?
Regular Expression to Match | : Hey guys, I am trying to use Java's a href=http://www.ensta.fr/~diam/java/online/jdk/150/api/java/util/Scanner.html#useDelimiter%28java.lang.String%29 rel=nofollow noreferreruseDelimiter method on it's Scanner class to do some simple parsing. Basically each line is a record delimited by | , so for example:2 | John Doe3 | Jane Doe4 | Jackie ChanThe method takes as a parameter a regular expression for which to match for. Can someone please provide me with the regular expression that would match | (A vertical bar separated by one space on both sides).Thanks, I would really appreciate it!
Java: scanning string for a pattern : This is probably a quicky. Why does this code not return anything?import java.util.Scanner;public class MainClass {public static void main(String[] args) { try { Scanner sc = new Scanner(asda ASA adad); String pattern = [A-Z]+; while ((sc.hasNext(pattern))) { System.out.println(sc.next(pattern)); } sc.close(); } catch (Exception e) { e.printStackTrace(); }}}
java Web Start is running slower than normal application running : I'm having trouble with Web Start.There is no problem if I start the application from IntelliJ.With Web Start it's working ok most of the time but at a point I'm loading 10000 records from database and there it's getting very slow.What can I do?Thanks,
How to obtain position in file (byte-position) from java scanner? : How to obtain a position in file (byte-position) from the java scanner?Scanner scanner = new Scanner(new File(file));scanner.useDelimiter(abc);scanner.hasNext();String result = scanner.next();and now: how to get the position of result in file (in bytes)? Using scanner.match().start() is not the answer, because it gives the position within internal buffer.
How to learn about Threads, Especially in Java : I have always been kind of confused by threads, and my class right now makes heavy use of them. We are using java.util.concurrent but I don't even really get the basics. UpDownLatch, Futures, Executors; these words just fly over my head. Can you guys suggest any resources to help learn what I need from the ground up?Thanks a lot in advance!
Unable to read JPEG image using ImageIO.read(File file) : I'm having problems reading this one JPEG file using ImageIO.read(File file) - it throws an exception with the message Unsupported Image Type.I have tried other JPEG images, and they seem to work fine.The only differance I've been able to spot is that this file seems to include a thumbnail - is that known to cause problems with ImageIO.read()?img src=https://i.imgur.com/AD5NOgEm.jpg alt=Troublesome imageEDIT:Added the resulting image:img src=https://i.imgur.com/NCdLB7hm.jpg alt=Strange colors
Java/ImageIO Validate format before reading the entire file? : I'm developing a Web application that will let users upload images. My concern is the file´s size, specially if they are invalid formats.I'm wondering if there´s a way in java (or a third party library) to check the allowed files formats (jpg, gif and png) before reading the entire file.
Automatically clearing the Java Web Start Cache : I have a Java Web Start application. I specify the resource (jars, images, etc) version and change every time there is a new version. Unfortunately sometimes the resources are not always updated when there is a new version.Is there any automated (possibly include in the application) way of clearing the web start cache?
Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.(I)V : I am developing a small Spring application. I have to store the details of the student information in the database. I have developed one SimpleFormController. I have used NetBeans + Hibernate mapping + Spring. When I deploy the project, the following errors occurs.My spring-config-db-applicationContext.xml is shown below:?xml version=1.0 encoding=UTF-8?!DOCTYPE beans PUBLIC -//SPRING//DTD BEAN//ENhttp://www.springframework.org/dtd/spring-beans.dtdbeans!-- Hibernate session factory -- bean id=dataSource class=org.springframework.jdbc.datasource.DriverManagerDataSource constructor-arg index=0 value${driverClassName}/value /constructor-arg constructor-arg index=1 value${url}/value /constructor-arg constructor-arg index=2 value${username}/value /constructor-arg constructor-arg index=3 value${password}/value /constructor-arg /bean bean id=sessionFactory class=org.springframework.orm.hibernate3.LocalSessionFactoryBean property name=dataSource ref bean=dataSource/ /property !-- property name=configLocation valueWEB-INF/classes/hibernate.cfg.xml/value /property -- property name=mappingResources list valuehibernate.cfg.xml/value /list /property !-- property name=configurationClass valueorg.hibernate.cfg.AnnotationConfiguration/value /property -- property name=hibernateProperties props prop key=hibernate.dialect${dialect}/prop prop key=hibernate.show_sqltrue/prop !--prop key=hibernate.hbm2ddl.autocreate/prop-- /props /property /bean bean id=hibernateTemplate class=org.springframework.orm.hibernate3.HibernateTemplate property name=sessionFactory ref bean=sessionFactory/ /property /bean bean id=transactionManager class=org.springframework.orm.hibernate3.HibernateTransactionManager property name=sessionFactory ref bean=sessionFactory/ /property /bean/beansFollowing error is occurs:ERROR (org.springframework.web.context.ContextLoader:213) - Context initialization failedorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in URL [jndi:/localhost/Student/WEB-INF/classes/config/spring-db-applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.init(I)V at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1395) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:289) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:286) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:188) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:526) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:730) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:387) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:270) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:627) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:511) at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1231) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:297) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:836) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:761) at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1471) at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:824) at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:350) at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:196) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:525) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619)Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.init(I)V at net.sf.cglib.core.DebuggingClassWriter.init(DebuggingClassWriter.java:47) at net.sf.cglib.core.DefaultGeneratorStrategy.getClassWriter(DefaultGeneratorStrategy.java:30) at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:24) at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216) at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108) at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104) at net.sf.cglib.proxy.Enhancer.clinit(Enhancer.java:69) at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:117) at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(CGLIBProxyFactory.java:43) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:162) at org.hibernate.tuple.entity.AbstractEntityTuplizer.init(AbstractEntityTuplizer.java:135) at org.hibernate.tuple.entity.PojoEntityTuplizer.init(PojoEntityTuplizer.java:55) at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.init(EntityEntityModeToTuplizerMapping.java:56) at org.hibernate.tuple.entity.EntityMetamodel.init(EntityMetamodel.java:302) at org.hibernate.persister.entity.AbstractEntityPersister.init(AbstractEntityPersister.java:434) at org.hibernate.persister.entity.SingleTableEntityPersister.init(SingleTableEntityPersister.java:108) at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:61) at org.hibernate.impl.SessionFactoryImpl.init(SessionFactoryImpl.java:238) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1304) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:813) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:731) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1454) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1392) ... 48 moreMar 12, 2010 5:32:28 PM org.apache.catalina.core.StandardContext startSEVERE: Error listenerStart
Running a Java program with input from a file : I am writing a program that reads the input from a file and then prints it to the screen. When I run it without taking the input from the file, it works perfectly fine. However, every time I try to run it from the file it gives me an Exception in thread main java.util.NoSuchElementException: No line found at error that occurs every place the input is suppose to be read. I have no idea what is going on.This program is suppose to take the input from the user, create a Photo object, and then print the information to the screen. Everything runs fine when I am entering the information manually but when I try to use java PhotoTest test.dat to get the input for a file it gives this error message:Exception in thread main java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1516) at PhotoTest.readPhoto(PhotoTest.java:31) at PhotoTest.main(PhotoTest.java:74)My code that has input:private static Photo readPhoto(Scanner scanner) throws ParseException{ Date dateTaken; Scanner scan = new Scanner(System.in); String subject = scan.nextLine(); subject = subject.trim(); String location = scan.nextLine(); location = location.trim(); String date = scan.nextLine(); date = date.trim(); if (date.equals()){ //if the date is empty it is set to null dateTaken = null; } else { //if a date is entered, it is then parsed DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); dateTaken = df.parse(date); } String file = scan.nextLine(); file = file.trim(); File photoFile = new File(file); //creates a Photo object from the information entered Photo Photo = new Photo(subject, location, dateTaken, photoFile); return Photo;}public static void main(String[] args) throws ParseException{ boolean endprogram = false; Scanner scan = new Scanner(System.in); //creates a loop so that the user may enter as many photos as they wish while (!endprogram) { System.out.println(Would you like to enter a photo (y/n)?); //if the input is anything other than y, the program ends if(!scan.next().equalsIgnoreCase(y)) { endprogram = true; } else { System.out.println(readPhoto(scan)); } }}
What web server should I use if I want to run Java code behind it? : At the moment, I have lot's of Java which does all kind of nifty stuff and I'm happy with it. The code is command line driven which have been great so far, but I recently decided I want to make the functionality available through web-services. Since my is complex and I'm happy with the way it's written , I don't want go through the pain of porting it to other languages. So I set out on a google journey to find out what web servers exist (on a Linux machine, though it's interesting to hear the answer without that limitation).From what I could find, it seems that there are two viable options: a href=http://tomcat.apache.org/ rel=nofollow noreferrerApache Tomcat and a href=http://www.sun.com/software/products/web_srvr/index.xml rel=nofollow noreferrerSun Java Server. What are the reason to choose one on top of the other? what are the strength of each and what are the weaknesses? Or, perhaps, there is a third one which is much easier, flexible and less cumbersome. Anyone?
java: Read text file and store the info in an array using scanner class : I have a text file include Student Grades like:Kim $ 40 $ 45Jack $ 35 $ 40I'm trying to read this data from the text file and store the information into an array list using Scanner Class. Could any one guide me to write the code correctly?Codeimport java.io.*;import java.util.*;public class ReadStudentsGrade {public static void main(String[] args) throws IOException { ArrayList stuRec = new ArrayList(); File file = new File(c:\\StudentGrade.txt); try { Scanner scanner = new Scanner(file).useDelimiter($); while (scanner.hasNextLine()) { String stuName = scanner.nextLine(); int midTirmGrade = scanner.nextInt(); int finalGrade = scanner.nextInt(); System.out.println(stuName + + midTirmGrade + + finalGrade); } } catch (FileNotFoundException e) { e.printStackTrace(); }}Runtime error:Exception in thread main java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at writereadstudentsgrade.ReadStudentsGrade.main(ReadStudentsGrade.java:26)
Volatile guarantees and out-of-order execution : IMPORTANT EDIT I know about the happens before in the thread where the two assignments are happening my question is would it be possible for another thread to be reading b non-null while a is still null. So I know that if you're calling doIt() from the same thread as the one where you previously called setBothNonNull(...) then it cannot throw a NullPointerException. But what if one is calling doIt() from another thread than the one calling setBothNonNull(...) ?Note that this question is solely about the volatile keyword and the volatile guarantees: it is not about the synchronized keyword (so please don't answer you must use synchronize for I don't have any issue to solve: I simply want to understand the volatile guarantees (or lack of guarantees) regarding out-of-order execution).Say we have an object containing two volatile String references that are initialized to null by the constructor and that we have only one way to modify the two String: by calling setBoth(...) and that we can only set their references afterwards to non-null reference (only the constructor is allowed to set them to null).For example (it's just an example, there's no question yet):public class SO { private volatile String a; private volatile String b; public SO() { a = null; b = null; } public void setBothNonNull( @NotNull final String one, @NotNull final String two ) { a = one; b = two; } public String getA() { return a; } public String getB() { return b; }}In setBothNoNull(...), the line assigning the non-null parameter a appears before the line assigning the non-null parameter b.Then if I do this (once again, there's no question, the question is coming next):doIt() { if ( so.getB() != null ) { System.out.println( so.getA().length ); }}Am I correct in my understanding that due to out-of-order execution I can get a NullPointerException?In other words: there's no guarantee that because I read a non-null b I'll read a non-null a?Because due to out-of-order (multi)processor and the way volatile works b could be assigned before a? volatile guarantees that reads subsequent to a write shall always see the last written value, but here there's an out-of-order issue right? (once again, the issue is made on purpose to try to understand the semantics of the volatile keyword and the Java Memory Model, not to solve a problem).
Problem with Java Scanner sc.nextLine(); : sry about my english :)Im new to Java programming and i have a problem with Scanner. I need to read an Int, show some stuff and then read a string so i use sc.nextInt(); show my stuff showMenu(); and then try to read a string palabra=sc.nextLine();Some one told me i need to use a sc.nextLine(); after sc.nextInt(); but i dont understand why do you have to do it :(Here is my code:public static void main(String[] args) { // TODO code application logic here Scanner sc = new Scanner(System.in); int respuesta = 1; showMenu(); respuesta = sc.nextInt(); sc.nextLine(); //Why is this line necessary for second scan to work? switch (respuesta){ case 1: System.out.println(=== Palindromo ===); String palabra = sc.nextLine(); if (esPalindromo(palabra) == true) System.out.println(Es Palindromo); else System.out.println(No es Palindromo); break; }}Ty so much for your time and Help :D
Long primitive or AtomicLong for a counter? : I have a need for a counter of type long with the following requirements/facts:Incrementing the counter should take as little time as possible.The counter will only be written to by one thread.Reading from the counter will be done in another thread.The counter will be incremented regularly (as much as a few thousand times per second), but will only be read once every five seconds.Precise accuracy isn't essential, only a rough idea of the size of the counter is good enough.The counter is never cleared, decremented.Based upon these requirements, how would you choose to implement your counter? As a simple long, as a volatile long or using an AtomicLong? Why?At the moment I have a volatile long but was wondering whether another approach would be better. I am also incrementing my long by doing ++counter as opposed to counter++. Is this really any more efficient (as I have been led to believe elsewhere) because there is no assignment being done?Thanks in advanceRich
What are the interets of synthetic methods? : ProblemOne friend suggested an interesting problem. Given the following code:public class OuterClass { private String message = Hello World; private class InnerClass { private String getMessage() { return message; } }}From an external class, how may I print the message variable content? Of course, changing the accessibility of methods or fields is not allowed.(the source a href=http://thecodersbreakfast.net/index.php?post/2010/03/15/Java-Quiz-35 rel=nofollow noreferrerhere, but it is a french blog)SolutionThe code to solve this problem is the following:try { Method m = OuterClass.class.getDeclaredMethod(access$000, OuterClass.class); OuterClass outerClass = new OuterClass(); System.out.println(m.invoke(outerClass, outerClass));} catch (Exception e) { e.printStackTrace();}Note that the access$000 method name is not really standard (even if this format is the one that is a href=http://www.retrologic.com/innerclasses.doc10.html#19265 rel=nofollow noreferrerstrongly recommanded), and some JVM will name this method access$0. Thus, a better solution is to check for synthetic methods:Method method = null;int i = 0;while ((method == null) amp;amp; (i OuterClass.class.getDeclaredMethods().length)) { if (OuterClass.class.getDeclaredMethods()[i].isSynthetic()) { method = OuterClass.class.getDeclaredMethods()[i]; } i++;}if (method != null) { try { System.out.println(method.invoke(null, new OuterClass())); } catch (Exception e) { e.printStackTrace(); }}So the interesting point in this problem is to highlight the use of synthetic methods. With these methods, I can access a private field as it was done in the solution. Of course, I need to use reflection, and I think that the use of this kind of thing can be quite dangerous...QuestionWhat is the interest - for me, as a developer - of a synthetic method? What can be a good situation where using the synthetic can be useful?
Scala and the Java Memory Model : The Java Memory Model (since 1.5) treats final fields differently to non-final fields. In particular, provided the this reference doesn't escape during construction, writes to final fields in the constructor are guaranteed to be visible on other threads even if the object is made available to the other thread via a data race. (Writes to non-final fields aren't guaranteed to be visible, so if you improperly publish them, another thread could see them in a partially constructed state.)Is there any documentation on how/if the Scala compiler creates final (rather than non-final) backing fields for classes? I've looked through the language specification and searched the web but can't find any definitive answers. (In comparison the @scala.volatile annotation is documented to mark a field as volatile)
DailyRollingFileHandler ---- Files should be rotated on a daily basis : We have a requirment which requires to have an Handler that is extended from Java logging and allows to have the files rotated on daily basis.Currently Java util logging do have the support of rotation based on file size by using File Handler. It doesnt support rotation on daily basis. a href=http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6350749 rel=nofollow noreferrerhttp://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6350749So , what we are looking is for such an appender that allows daily rotation . We would like to write such handler and which is the appropriate handler to extend for ... StreamHandler or FileHandler ?And other questions are , is there way we can configure 2 different files for a single handler say FileHandler say for eg , we would like some kind of messages need to be captured in one file and other messages in other file.Would appreciate for any comments.
Java/Groovy File IO Replacing an Image File with it's own Contents - Why Does This Work? : I have some JPG files that need to be replaced at runtime with a JFIF standardized version of themselves (we are using a vendor that gives us JPG that do not have proper headers so they don't work in certain applications)... I am able to create a new file from the existing image, then get a buffered image from that file and write the contents right back into the file without having to delete it and it works...imageSrcFolder.eachFileMatch ( ~/.*\.jpg/, { BufferedImage bi = ImageIO.read( it ) ImageIO.write( bi, jpg, it )});The question I have is why? Why doesn't the file end up doubled in size? Why don't I have to delete it first? Why am I able to take a file object to an existing file and then treat it as if it were a brand new one? It seems that what I consider to be a file is not what the File object in java actually is, or else this wouldn't work at all.My code does exactly what I want it to do, but I'm not convinced it always will... it just seems way too easy
Java LockSupport Memory Consistency : Java 6 API question. Does calling LockSupport.unpark(thread) have a happens-before relationship to the return from LockSupport.park in the just-unparked thread? I strongly suspect the answer is yes, but the Javadoc doesn't seem to mention it explicitly.
Load a canvas from a main class - Java : I have a MyCanvas class that extends JComponent. On this canvas I have drawn a couple of things and has its own main method. public static void main(String args[]) { JFrame mainFrame = new JFrame(Graphics demo); mainFrame.getContentPane().add(new Canvas0_1()); mainFrame.pack(); mainFrame.setVisible(true); }How do I call to load the canvas from my program's other main method. Is this possible?
How do I keep a Scanner from throwing exceptions when the wrong type is entered? : Here's some sample code: import java.util.Scanner;class In{ public static void main (String[]arg) { Scanner in = new Scanner (System.in) ; System.out.println (how many are invading?) ; int a = in.nextInt() ; System.out.println (a) ; } }If I run the program and give it an int like 4, then everything goes fine. On the other hand, if I answer too many it doesn't laugh at my funny joke. Instead I get this(as expected):Exception in thread main java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:819) at java.util.Scanner.next(Scanner.java:1431) at java.util.Scanner.nextInt(Scanner.java:2040) at java.util.Scanner.nextInt(Scanner.java:2000) at In.main(In.java:9)Is there a way to make it ignore entries that aren't ints or re prompt with How many are invading? I'd like to know how to do both of these.
how to append timestamp to file name for java.util.logging.FileHandler.pattern : Hi I was wondering if anyone knows a way to append a timestamp to the log file name specified through logging.properties java.util.logging.FileHandler.patternseems like something pretty straight forward but I cant seem to find a solution to this anywhere. Thanks
Is it possible to specify the Java U version when using Web Start? : I have a Java WebStart application for which I want to specify that the client use JRE 1.6.0_17 or later.To the JNLP file I've tried adding:j2se version=1.6.0_17+/ or j2se version=1.6.0_17/ But when downloading JNLP file I'm given the message:The application has requested a version of the JRE(version 1.6.0_17) that is not installeddespite the fact that:java -version reports the version number on the machine as 1.6.0_17 Changing the jnlp file to use and calling System.getProperty(java.version) reports the version that it is actually using to be 1.6.0_17Looking through the a href=http://java.sun.com/javase/technologies/desktop/javawebstart/download-spec.html rel=nofollow noreferrerspec section 4.6.1 indicates that there is some difference between platform version and product version, but it isn't clear to me how I would go about using the product version (or even if I should). Any help or pointers would be appreciated.
How do i change this method to get strings instead of ints : here is the original code: public static int getInt () { Scanner in = new Scanner (System.in) ; if (in.hasNextInt()) { int a = in.nextInt() ; return a ; } else { System.out.println (try again:) ; return getInt () ; }}This checks and sees if the input it receives is an int. If it is then it returns the int, if not it tells you to try again and re-runs. This is what i tried to do to change it: public static String getIns () { Scanner in = new Scanner (System.in) ; if (in.hasNextString()) { String a = in.nextString() ; return a ; } else { System.out.println (try again:) ; return getIns () ; } }This doesn't work though. I looked through the documentation for the scanner class and i think the problem is that there is no such method as in.hasNextString or in.nextString What methods from the scanner class can i use to do what i intend these to do?
appassembler and long classpath : I am using maven appassembler to create my assembly. My classpath is too long and I get The input line is too long. The suggestion a href=http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/faq.html rel=nofollow noreferrerhere is to use booter windows platform, but I'm constrained to use Java Service Wrapper. Any way I can use java6 wildcarded classpath and java service wrapper?
Tomcat 6 thread safe email queue (javax.mail.*) : Hi I have design/architecture question. I would like to send emails from one of my jsp pages. I have one particular issue that has been a little bit of a problem. there is an instance where one of the pages will need to send around 50 emails at near the same time. I would like the messages sent to a queue where a background thread will actually do the email sending. What is the appropriate way to solve this problem? If you know of a tutorial, example code or tomcat configuration is needed please let me know.Thanks,
Java Web Start vs Embedded Java Applet : I'm going to deploy my Java game to show it to my friends and whatnot, but I'm having trouble deciding between Java Web Start and applets.Under what conditions is one preferable over another and what advantages/disadvantages are there?
How can I disable the default console handler, while using the java logging API? : Hi I am trying to implement the java logging in my application. I want to use two handlers.A file handler and my own console handler. Both of my handlers work fine. My logging is send to a file and to the console . My logging is also sent to the default console handler, which i do not want. If you run my code you will see extra two line sent to the console. I don't want to use the default console handler. Does anyone know how to disable the default console handler. I only want to use the two handlers I have created.Handler fh = new FileHandler(test.txt);fh.setFormatter(formatter);logger.addHandler(fh);Handler ch = new ConsoleHandler();ch.setFormatter(formatter);logger.addHandler(ch);import java.util.Date;import java.util.logging.ConsoleHandler;import java.util.logging.FileHandler;import java.util.logging.Formatter;import java.util.logging.Handler;import java.util.logging.Level;import java.util.logging.LogManager;import java.util.logging.LogRecord;import java.util.logging.Logger;public class LoggingExample { private static Logger logger = Logger.getLogger(test); static { try { logger.setLevel(Level.INFO); Formatter formatter = new Formatter() { @Override public String format(LogRecord arg0) { StringBuilder b = new StringBuilder(); b.append(new Date()); b.append( ); b.append(arg0.getSourceClassName()); b.append( ); b.append(arg0.getSourceMethodName()); b.append( ); b.append(arg0.getLevel()); b.append( ); b.append(arg0.getMessage()); b.append(System.getProperty(line.separator)); return b.toString(); } }; Handler fh = new FileHandler(test.txt); fh.setFormatter(formatter); logger.addHandler(fh); Handler ch = new ConsoleHandler(); ch.setFormatter(formatter); logger.addHandler(ch); LogManager lm = LogManager.getLogManager(); lm.addLogger(logger); } catch (Throwable e) { e.printStackTrace(); } } public static void main(String[] args) { logger.info(why does my test application use the standard console logger ?\n + I want only my console handler (Handler ch)\n + how can i turn the standard logger to the console off. ??); }}
Null Pointer Exception while using Java Compiler API : MyClass.java:package test;public class MyClass { public void myMethod(){ System.out.println(My Method Called); }}Listing for SimpleCompileTest.java that compiles the MyClass.java file.SimpleCompileTest.java:package test;import javax.tools.*;public class SimpleCompileTest { public static void main(String[] args) {String fileToCompile = test + java.io.File.separator +MyClass.java;JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();int compilationResult = compiler.run(null, null, null, fileToCompile); if(compilationResult == 0){ System.out.println(Compilation is successful); }else{ System.out.println(Compilation Failed); } }}I am executing the SimpleCompileTest class and getting a NullPointerException. The ToolProvider.getSystemJavaCompiler() is returning null. Can someone tell me what is wrong with the code
ConcurrentLinkedQueue$Node remains in heap after remove() : I have a multithreaded app writing and reading a ConcurrentLinkedQueue, which is conceptually used to back entries in a list/table. I originally used a ConcurrentHashMap for this, which worked well. A new requirement required tracking the order entries came in, so they could be removed in oldest first order, depending on some conditions. ConcurrentLinkedQueue appeared to be a good choice, and functionally it works well.A configurable amount of entries are held in memory, and when a new entry is offered when the limit is reached, the queue is searched in oldest-first order for one that can be removed. Certain entries are not to be removed by the system and wait for client interaction.What appears to be happening is I have an entry at the front of the queue that occurred, say 100K entries ago. The queue appears to have the limited number of configured entries (size() == 100), but when profiling, I found that there were ~100K ConcurrentLinkedQueue$Node objects in memory. This appears to be by design, just glancing at the source for ConcurrentLinkedQueue, a remove merely removes the reference to the object being stored but leaves the linked list in place for iteration.Finally my question: Is there a better lazy way to handle a collection of this nature? I love the speed of the ConcurrentLinkedQueue, I just cant afford the unbounded leak that appears to be possible in this case. If not, it seems like I'd have to create a second structure to track order and may have the same issues, plus a synchronization concern.
How to secure Java webservices with login and session handling : I'd like to secure my (Java metro) webservice with a login.Here's how I'm planning to do that:Steps required when calling a webservice method are:call login(user,pwd), receive a session token1.1 remember the tokencall servicemethod (token, arg1, arg2...)webservice checks if the token is known, if not throw exception otherwise proceedlogout or timeout after x time periods of inactivitymy questions:1. what's your opinion on this approach? does it make sense?2. are there any libraries which take the burden of writing a session handling (maybe with database persistence to survive app restarts)(the solution should be simple and easily usable with Java and .NET clients)thanks!
How to generate R.java manually on Linux platform : I am developing android application on Linux platform because i have to make a system.img with a application.When adding a drawable resource and building the project with mm command, i met a below error.blockquote cannot find symbol R.drawable.icon_send_type/blockquoteAt above error, the icon_send_type is the added resource.This error occurred because the mm command did not generate R.java.So, I want to know how to generate R.java by a manual on Linux platform.
How should I parse this simple text file in Java? : I have a text file that looks like this:grn129 agri-ac-214 ahsshud114 ahsslov1150 ahsslov1160 ahsslov1170 ahsslov1210 ahssWhat is the best way to parse this file using Java if I want to create a HashMap with the first column as the key and the second column as the value.Should I use the Scanner class? Try to read in the whole file as a string and split it?What is the best way?
How do I pull `static final` constants from a Java class into a Clojure namespace? : I am trying to wrap a Java library with a Clojure binding. One particular class in the Java library defines a bunch of static final constants, for example:class Foo { public static final int BAR = 0; public static final int SOME_CONSTANT = 1; ...}I had a thought that I might be able to inspect the class and pull these constants into my Clojure namespace without explicitly def-ing each one. For example, instead of explicitly wiring it up like this:(def foo-bar Foo/BAR)(def foo-some-constant Foo/SOME_CONSTANT)I'd be able to inspect the Foo class and dynamically wire up foo-bar and foo-some-constant in my Clojure namespace when the module is loaded.I see two reasons for doing this:A) Automatically pull in new constants as they are added to the Foo class. In other words, I wouldn't have to modify my Clojure wrapper in the case that the Java interface added a new constant.B) I can guarantee the constants follow a more Clojure-esque naming conventionI'm not really sold on doing this, but it seems like a good question to ask to expand my knowledge of Clojure/Java interop. Thanks
Java package scanner - find all classes with a given interface : In C# you can easily read all classes from a given assembly.I'm looking for equivalent feature in Java. I need this to automatically bind EJB beans to my Guice Module.
Scanner method to get a char : What is the Scanner method to get a char returned by the keyboard in Java. like nextLine() for String, nextInt() for int, etc.
An equivalent of -javaagent in C#? Or: ways to use a java framework in C# : This is probably something I should be able to figure out by myself, but I'm not having much luck so I figured I'd ask.The issue: I'm translating a system from java to C# and they use a href=http://sites.google.com/site/deucestm/ rel=nofollow noreferrera java framework that I'd really like to use, since it takes care of the most complex parts of the system, which I would otherwise have to implement myself. I have the source code of this framework.I know there are several possibilities for using java libraries in C# (although I'm not familiar with any of them, so I'd appreciate suggestions). So far I've thought of using a href=http://www.ikvm.net/uses.html rel=nofollow noreferrerIKVM.NET to generate a .dll, but I'm not sure what to do next, because in java in order to run the framework with your code a href=http://sites.google.com/site/deucestm/documentation/getting-started rel=nofollow noreferreryou're supposed to use the option -javaagent by adding-javaagent:bin/deuceAgent.jar (where deuceAgent is the framework)to your java command line. I don't know what the equivalent in C# would be once I have my .dll, or whether there's an equivalent at all.Any help? Thanks so much.
EOFException in ObjectInputStream Only happens with Webstart not by java(w).exe? : Anyone familiar with the differences in starting with Webstart(javaws.exe) compared to starting the app. using java.exe or javaw.exe regarding streams ?This is the exception which i ONLY get when using Webstart :java.io.EOFException at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) at java.io.ObjectInputStream.readStreamHeader(Unknown Source) at java.io.ObjectInputStream.init(Unknown Source) at fasttools.jtools.dss.api.core.remoting.thinclient.RemoteSocketChannel.init(RemoteSocketChannel.java:77)This is how i setup the connections on both sides//==Server side==//Thread{ Socket mClientSocket = cServSock.accept();new DssServant(mClientSocket).start();//}DssServant(Socket socket) throws DssException { try { OutputStream mOutputStream = new BufferedOutputStream( socket.getOutputStream() ); cObjectOutputStream = new ObjectOutputStream(mOutputStream); cObjectOutputStream.flush(); //publish streamHeader InputStream mInputStream = new BufferedInputStream( socket.getInputStream() ); cObjectInputStream = new ObjectInputStream(mInputStream); .. } catch (IOException e) { .. } ..}//==Client side==public RemoteSocketChannel(String host, int port, IEventDispatcher eventSubscriptionHandler) throws DssException { cHost = host; port = (port == 0 ? DssServer.PORT : port); try { cSocket = new Socket(cHost, port); OutputStream mOutputStream = new BufferedOutputStream( cSocket.getOutputStream() ); cObjectOut = new ObjectOutputStream(mOutputStream); cObjectOut.flush(); //publish streamHeader InputStream mInputStream = new BufferedInputStream( cSocket.getInputStream() ); cObjectIn = new ObjectInputStream(mInputStream); } catch (IOException e) { .. } ..}[EDIT]Webstart console says:Java Web Start 1.6.0_19Using JRE version 1.6.0_19-b04 Java HotSpot(TM) Client VMServer is running same 1.6u19[EDIT]JNLP contains:?xml version=1.0 encoding=utf-8?jnlp spec=1.0+ codebase=http://127.0.0.1:8080/ information title../title vendor../vendor homepage href=http://127.0.0.1:8080/index.html/ description../description icon href=/jws/../ icon kind=splash href=/jws/...jpg/ offline-allowed/ /information security all-permissions/ /security resources j2se version=1.6+ initial-heap-size=128M max-heap-size=512M/ jar href=http://127.0.0.1:8080/lib/xx.jar/ jar href=http://127.0.0.1:8080/lib/yy.jar/ /resources application-desc main-class=.. argument-host/argument argument127.0.0.1/argument argument-port/argument argument4359/argument argument-httpport/argument argument8080/argument /application-desc/jnlpThanks
I am having trouble using FileReader to write a txt file to an array (Java), what am I doing wrong? : Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader(rates.txt))); for (int i=0; i9; i++){ while(s.hasNext()){rates[i] = s.next();} System.out.println(rates[i]); } }catch (IOException e){ System.out.println(e); } finally { if (s != null) { s.close(); } }When I run this code, it reads the last chunk of characters in my txt file, places them in rates[0], sticks null in 1-9. I'm not sure why it's reading the end of my file first. The contents of the txt are below..USD 1.34EUR 1.00JPY 126.28GBP 0.88INR 60.20It reads the 60.20, which is all it is recording in the array. Any help would be appreciated. I guess I could give you the results of running this code:run:60.20nullnullnullnullnullnullnullnullBUILD SUCCESSFUL (total time: 0 seconds)
JNLP desktop shortcut creation with Windows 7 : cannot create shortcut : we have an Java application deployed with Java Web Start (JNLP) that does a desktop shortcut.One client has issue with Windows 7 : in the end of startup/installation there is a message cannot create shortcut. With our own Windows 7 machine we don't have problems and unfortunately we don't have much details yet. But if somebody has encountered similar issue or has some ideas to try, they are welcome =)Java version used at the client is 6u18.Br, Touko
how to take user input in Array using java? : how to take user input in Array using Java? i.e we are not initializing it by ourself in our program but the user is going to give its value..please guide!!
Manipulating PNGs in Java : Is there an easy way to manipulate PNGs in Java? I know I can read into a BufferedImage and write that back out, but I need to add clear pixels around the edge of an image. Is there an easy way to do this?
In java web start where does the jar file get downloaded to? : As per Java web start where does the jar file get downloaded on a client machine?
Android java.util.concurrent.ConcurrentLinkedQueue : I want to use ConcurrentLinkedQueue in an android application, have written the code, but now I'm getting an error when the project builds:Conversion to Dalvik format failed with error 2I'm using Eclipse with the lastest version of the ADT plugin.Any ideas how I can fix this problem?
Java web start - Unable to load resource : I've got a jar that loads great with java web start when I browse through the IP address of the server.Once I try the server name instead I get the following exception:com.sun.deploy.net.FailedDownloadException: Unable to load resource: at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source) at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source) at com.sun.javaws.LaunchDownload$DownloadTask.call(Unknown Source) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)The wrapped exception:java.io.FileNotFoundException: at sun.reflect.GeneratedConstructorAccessor2.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source) at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source) at com.sun.deploy.net.BasicHttpRequest.doGetRequest(Unknown Source) at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source) at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source) at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source) at com.sun.javaws.LaunchDownload$DownloadTask.call(Unknown Source) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)Caused by: java.io.FileNotFoundException: at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) ... 15 moreJNLP:?xml version=1.0 encoding=utf-8?jnlp spec=1.0+ codebase=http://servername/Site/Views/.. href= information titletitle/title vendorvendor/vendor descriptiondescription/description description kind=shortshort/description icon href=../../icon.gif / /information security all-permissions/ /security resources j2se version=1.5+ java-vm-args=-Xmx1000M -Xms150M initial-heap-size=150M max-heap-size=1000M / j2se version=1.4.2+ href=http://java.sun.com/products/autodl/j2se java-vm-args=-Xmx1000M -Xms150M initial-heap-size=150M max-heap-size=1000M / jar href=/file.jar/ /resources application-desc main-class=com.... argumentCD6B172DEC34924D83EA64A61A6550BE1271325929392/argument argumenthttp://servername/file.asp/argument argument/Site/argument /application-desc/jnlpAny idea what should I look for?
Using Glassfish libraries in proprietary software : I would like to use some parts of Glassfish in a proprietary software that are under a CDDL + GPLv2 license. Am I allowed to do that? I haven't modified anything in the code of these libraries, so is this OK, or my software, because it uses these libraries, is still considered derivative work, and thus a big no-no?I mean, according to a href=http://jaxb.java.net/ rel=nofollow noreferrerhttp://jaxb.java.net/, JAXB is also under CDDL + GPLv2, but I know I can freely use that in proprietary software. Is this because CDDL + GPLv2 actually allows that, or is it distributed under a different license when bundled with the JRE?
How to resolve Line End Reading with Scanner Class in Java : I am not an experienced Java programmer and i'm trying to write some text to a file and then read it with Scanner. I know there are lots of ways of doing this, but i want to write records to file with delimiters, then read the pieces.The problem is so small. When I look the output some printing isn't seen(shown in below). I mean the bold line in the Output that is only written Scanner. I would be appreciated if anyone can answer why String: isn't seen there. (Please answer just what i ask)I couldn't understand if it is a simple printing problem or a line end problem with \r\n.Here is the code: import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner;public class Tmp { public static void main(String args[]) throws IOException { int i; boolean b; String str; FileWriter fout = new FileWriter(test.txt); fout.write(Testing|10|true|two|false\r\n); fout.write(Scanner|12|one|true|); fout.close(); FileReader fin = new FileReader(Test.txt); Scanner src = new Scanner(fin).useDelimiter([|\\*]); while (src.hasNext()) { if (src.hasNextInt()) { i = src.nextInt(); System.out.println(int: + i); } else if (src.hasNextBoolean()) { b = src.nextBoolean(); System.out.println(boolean: + b); } else { str = src.next(); System.out.println(String: + str); } } fin.close(); }} Here is the output:String: Testingint: 10boolean: trueString: twoString: falseScannerint: 12String: oneboolean: true
Copying JNLP app to computer lacking Internet access : How might I go about running a JNLP app on a machine that has no Internet access? Is there a way to copy the app's files from a machine where the app has already been downloaded and run?
Insert one DefaultStyledDocument into another DefaultStyledDocument : I want to insert one DefaultStyledDocument into another DefaultStyledDocument. How do I do this? I know of this method:AbstractDocument.insertString(int offs, String str, AttributeSet a)What I really want is something like this:DefaultStyledDocument.insertDocument(int offs, AbstractDocument doc)Is there a way of doing this?
how to display a JFrame from an applet? : I have this class called PollFrame that extends JFrame in a file called PollFrame.java . PollFrame contains a form. I have an applet, which has a button in it. When the button is clicked, I want the PollFrame to be displayed. I set the ActionPerformed as:Pollframe poll = new PollFrame(); // This initializes the formpoll.setVisible(true);However, when I click the button, I get the following error :Exception in thread AWT-EventQueue-2 java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM.0) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at java.lang.SecurityManager.checkExit(Unknown Source) at javax.swing.JFrame.setDefaultCloseOperation(Unknown Source) at com.org.pollFrame.initComponents(pollFrame.java:54) at com.org.pollFrame.init(pollFrame.java:11) at com.org.EmployeeApplet.requestRoomActionPerformed(EmployeeApplet.java:216) at com.org.EmployeeApplet.access$300(EmployeeApplet.java:7) at com.org.EmployeeApplet$4.actionPerformed(EmployeeApplet.java:71) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)I am guessing fromt he above error that calling another class file from an applet is prohibited. Is there any way I can display the PollFrame from the applet?
Is classOf[] in Scala 2.8 different from 2.7? : I have an interface from Javapublic class IJava{ ... public java.lang.Class getType(); ...}It is inherited in Scalaclass CScala{ def getType() = classOf[Foo]}It worked in Scala 2.7.7. But in 2.8.0.RC1, I gettype mismatch; found : java.lang.Class[Foo](classOf[Foo]) required: java.lang.ClassHow do I get java.lang.Class in Scala 2.8?
Java - How do I get last line using Scanner? : while( inStream.hasNextLine() ) { ... lineList.add( inStream.nextLine() ); } ...lineList is an ArrayList. The code is reading everything nicely except it won't grab the last line. The last two lines in the text file end like this:a sentence here...a blank line here. the blank line is the last lineI'm assuming it won't grab it since hasNextLine() is not detecting another line after this one?What's a way to grab the last line? I thought reading until it was EOF and then catching the exception might work but there doesn't seem to be a way to do that.EDIT: MORE INFOpublic void readLines(){ lineList = new ArrayList(); try { inStream = new Scanner( new File( fileName ) ); } catch( FileNotFoundException e ) { System.out.println( Error opening the file. Try again. ); } if ( inStream != null ) { while( inStream.hasNextLine() ) { ++originalLines; lineList.add( inStream.nextLine() ); } inStream.close(); }}There's the whole method. Anything wrong?EDIT: EVEN MORE INFO public static void main(String[] args){ Scanner inStream = null; String test = ; inStream = new Scanner( test ); while( inStream.hasNextLine() ) { System.out.println( inStream.nextLine() ); }}It will not pick up an empty string but it will pick up a whitespace
Working with mongodb from Java : I have launch mongodb server:[demas@arch.local.net][~]% mongod --dbpatmongod --dbpath /home/demas/temp/ Mon Apr 19 09:44:18 Mongo DB : starting : pid = 4538 port = 27017 dbpath = /home/demas/temp/ master = 0 slave = 0 32-bit ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data** see http://blog.mongodb.org/post/137788967/32-bit-limitations for moreMon Apr 19 09:44:18 db version v1.4.0, pdfile version 4.5Mon Apr 19 09:44:18 git version: nogitversionMon Apr 19 09:44:18 sys info: Linux arch.local.net 2.6.33-ARCH #1 SMP PREEMPT Mon Apr 5 05:57:38 UTC 2010 i686 BOOST_LIB_VERSION=1_41Mon Apr 19 09:44:18 waiting for connections on port 27017Mon Apr 19 09:44:18 web admin interface listening on port 28017I have created documents by console client:[demas@arch.local.net][~]% mongoMongoDB shell version: 1.4.0url: testconnecting to: testtype help for help db.some.find(); { _id : ObjectId(4bcbef3c3be43e9b7e04ef3d), name : mongo } { _id : ObjectId(4bcbef423be43e9b7e04ef3e), x : 3 }Now I am trying to work with MongoDb from Java:import com.mongodb.*;import java.net.UnknownHostException;public class test1 { public static void main(String[] args) { System.out.println(Start); try { Mongo m = new Mongo(localhost, 27017); DB db = m.getDB(test); DBCollection coll = db.getCollection(some); coll.insert(makeDocument(10, James, male)); System.out.println(Finish); } catch (UnknownHostException ex) { ex.printStackTrace(); } catch (MongoException ex) { ex.printStackTrace(); } } public static BasicDBObject makeDocument(int id, String name, String gender) { BasicDBObject doc = new BasicDBObject(); doc.put(id, id); doc.put(name, name); doc.put(gender, gender); return doc; } }But execution stops on line coll.insert(): [demas@arch.local.net][~/dev/study/java/mongodb]% javac test1.java [demas@arch.local.net][~/dev/study/java/mongodb]% java test1 StartThere are not messages from mogodb server regarding accepted connection. Why?
Spring + JWS + Tomcat : Is it possible to bundle Tomcat with a Spring application with Java WebStart amp; how ?
Calling Python from Java through scripting engine (jython)? : I'm trying to call Jython from a Java 6 application using javax.script:import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;import javax.script.ScriptException;public class jythonEx{ public static void main (String args[]) throws ScriptException { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine pyEngine = mgr.getEngineByName(python); try { pyEngine.eval(print \Python - Hello, world!\); } catch (Exception ex) { ex.printStackTrace(); } }}This is causing a NullPointerException:java.lang.NullPointerException at jythonEx.main(jythonEx.java:12)Does anyone have any idea what I'm doing wrong here?Edit:Thanks for the responses! I added jython.jar to the classpath and it runs properly:java -cp ./;jython.jar jythonEx
How to build your non-gui Java program into a console program : I dont know how to describe it well, but i will try. Ok, i want to be able to build my java program so that when it opens, it will look and work exactly as it does in the console. So it reads the Scanner class and prints normally, and does everything it would do if it was in the console. Ive looked around for this and havent found anything. I can make a gui java program fairly easily, but i would rather have a terminal, console like program, that works exactly as the java console, thanks.
How could I embed a html/css/js view in a webstart application : I would like to use a html/css/js view in my webstart project without requesting all permissions.I figured out that I could use the java HTTPServer to process the requests but I need a way to avoid using real sockets, so that the HTTPServer instantiation doesn't ask for some permission.Do you know any projects that achieve that ? and if not, what should I do to get an HTTPServer completely working locally (without hitting boundaries...) ?edit: maybe an HTTPServer is too much, I maybe only need a HttpHandler..
Java.util.scanner error handling : I'm helping a friend with a java problem. However, we've hit a snag. We're using Java.Util.Scanner.nextInt() to get a number from the user, asking continiously if the user gives anything else. Only problem is, we can't figure out how to do the error handeling. What we've tried:do { int reloop = 0; try { number = nextInt(); } catch (Exception e) { System.out.println (Please enter a number!); reloop ++; }} while(reloop != 0);Only problem is, this loops indefinatly if you enter in something not a number.Any help?
JFrame that has multiple layers : I have a window that has two layers: a static background and a foreground that contains moving objects. My idea is to draw the background just once (because it's not going to change), so I make the changing panel transparent and add it on top of the static background. Here is the code for this:public static void main(String[] args) { JPanel changingPanel = new JPanel() { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.fillRect(100, 100, 100, 100); } }; changingPanel.setOpaque(false); JPanel staticPanel = new JPanel(); staticPanel.setBackground(Color.BLUE); staticPanel.setLayout(new BorderLayout()); staticPanel.add(changingPanel); JFrame frame = new JFrame(); frame.add(staticPanel); frame.setSize(800, 600); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);}This piece of code gives me the correct image I want, but every time I repaint changingPanel, staticPanel gets repainted as well (which is obviously against the whole idea of painting the static panel just once). Can somebody show me what's wrong?FYI I am using the javax.swing.Timer to recalculate and repaint the changing panel 24 times every second.
get entire line with java.util.scanner.hasNext(regex) : I'm doing something in Java that requires input to be matched against the pattern ^[1-5]$. I should have a while loop looping through each line of input, checking it against the pattern, and outputting an error message if it does not. Sudo code: while (regex_match(/^[^1-5]$/,inputLine)) { print (Please enter a number between 1 and 5! ); getNextInputLine();} I can use java.util.Scanner.hasMatch(^[^1-5]$), but that will only match a single token, not the entire line. Any idea on how to make hasMatch match against the entire line? (Setting the delimiter to \n or \0 doesn't work.)Edit: If this isn't possible, is there some other way to do it?
Imageiio can't create imageinput stream : When using imageio.imageio.read iget a can't create ImageInputStream. I have a catch exception around it so the program survives but i was wondering if theres a way to put an if statement round it that checks to see if it falied and then attempt to read it again if it did. basically asking if there is a test for exceptions?
how to configure my own formatter in java logging property file : For my java project, i am using the java logging api. I want to log everything using a property file. Before using this file (log.properties), I configured my onwn formatter in the java code. (see below)Now I want to configure my own fomatter in the propertie file, instead of the java code. does someone know how to do that ?Formatter formatter = new Formatter() { @Override public String format(LogRecord arg0) { StringBuilder b = new StringBuilder(); b.append(new Date()); b.append( ); b.append(arg0.getSourceClassName()); b.append( ); b.append(arg0.getSourceMethodName()); b.append( ); b.append(arg0.getLevel()); b.append( ); b.append(arg0.getMessage()); b.append(System.getProperty(line.separator)); return b.toString(); } };fomatter in the java codeblockquote ..... ..... java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter java.util.logging.FileHandler.level=WARNING **java.util.logging.??? = how can i configure my own formater in the property file with this information: data, clasename, methodename, level .etc.****/blockquoteformatter in de log.proprties
How to restart the Java Process with -Djava.library.path? : I have an application that is started with JWS. The first time user launches this application he has to choose a path where Berkeley DB XML is installed. I do need this to set the native library path and restart the application with -Djava.library.path parameter. Berkeley DB XML java bindings uses JNI to make calls to the database. Since our users may have different OS I cannot rely on a default location. So, I have a problem with getting current classpath. When I print out java.class.path it only gives me /System/Library/Frameworks/JavaVM.framework/Resources/Deploy.bundle/Contents/Home/lib/deploy.jar. I have three jars that I cannot find in my sys props.on my Mac.I hope this was understandable and thanks for any tips beforehand.
Change root package of Java JAR : I am writing a Java Agent which makes use of the Java ASM library for handling byte code. This is a common library and I want to be sure about the version of ASM which my code is using at runtime.What is the easiest and most automated way to take the ASM classes and process them into a private copy where all the classes have been relocated into a new root package. To be specific, I want to take the ASM jars and turn org.objectweb.asm.* into org.myproject.internal.org.objectweb.asm.*Please remember that I am mostly interested in an automated solution. I know that I could get the sources for ASM and do this manually or with a script and then recompile the jars but this feels like a lot of overhead.
is appassembler plugin broken for java service wrapper on windows 64bit? : I'm developing on 32bit windows and am using appassembler to create a java service wrapper assembly, and it works ok. But I need to also create a 64bit assembly for deployment to a dev server. In the following config I have substituted the 32bit platform with the 64bit, see the includes section. But it no longer places the wrapper jar and dll in the lib folder. If I omit the includes completely, I get linux, solaris, Mac OSX and Win32 libraries, but no win64.Anyone got this working? plugin groupIdorg.codehaus.mojo/groupId artifactIdappassembler-maven-plugin/artifactId version1.1-SNAPSHOT/version configuration target${project.build.directory}/appassembler/target repositoryLayoutflat/repositoryLayout defaultJvmSettings initialMemorySize256M/initialMemorySize maxMemorySize1024M/maxMemorySize /defaultJvmSettings daemons daemon idMyApp/id mainClasscom.foo.AppMain/mainClass platforms platformjsw/platform /platforms generatorConfigurations generatorConfiguration generatorjsw/generator includes includewindows-x86-64/include /includes configuration property nameset.default.REPO_DIR/name value../../repo/value /property /configuration /generatorConfiguration /generatorConfigurations /daemon /daemons /configuration executions execution goals goalgenerate-daemons/goal goalcreate-repository/goal /goals /execution /executions /plugin
Slow Startup for Java Web Start Application : I'm using the Netbeans IDE to develop a Java Web Start application that will launch from the web and then use the EclipseLink JPA to access a remote MySQL database. I'm using the Swing Application Framework to manage life cycle for my app. When I launch the application from Netbeans it takes about 7 second for my application to load, but when I use the Netbeans IDE to create a Web Start distribution package (with the JAR and JNLP files) it takes about 60 seconds to launch. Also, the verifying application/downloading application progressbar window seems to run every time I launch the app even though a copy of it has already been cached. From the users point of view, one first sees my splash screen for 1 to 2 seconds, then the verifying application/downloading application progressbar window for 5 to 20 seconds and then nothing for a good 40 seconds before the application launches. The app code is written such that it should show itself BEFORE the JPA starts loading the persistence unit (so I doubt that's the problem), but I thought I'd mention it just in case.Update: Method createEntityManagerFactory Slow With Web StartHaving looked into this further, I've found that the method createEntityManagerFactory--which is necessary for EclipseLink to connect to MySQL--takes aboutn 5 seconds to execute when I run the applicaiton from Netbeans or when I remotely log in to my server to launch the JNLP there, but when I run the application via the web the same line takes 35 seconds (hugely delaying startup). Interestingly, this time gets even worse as my internet connection speed gets worse. Below is a copy of the JNLP file I'm using.Does anyone have any idea what may be causing such a delay??xml version=1.0 encoding=UTF-8 standalone=no? MyApp My App Vendor My App Description MyApp
Java: Detecting image format, resize (scale) and save as JPEG : This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please?Thank youimport java.awt.Color;import java.awt.Graphics2D;import java.awt.Image;import java.awt.RenderingHints;import java.awt.geom.Rectangle2D;import java.awt.image.BufferedImage;import java.io.BufferedInputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import javax.imageio.ImageIO;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = jpeg; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println(Thumb width Buffered: + thumbWidth + || Thumb height Buffered: + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println(Target width: + targetWidth + || Target height: + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println(Thumb width: + thumbWidth + || Thumb height: + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } }}
Web Start Application built on NetBeans Platform doesn't create desktop shortcut start menu item : I've created a NetBeans Platform application that is launched using Java Web Start. I built the WAR file using the 'Build JNLP Application'-command in Netbeans 6.8.I've added a desktop shortcut and menu item to the JNLP file, but for some reason, these are not created when the application is launched.However, when I go to:blockquote Control Panel - Java - Temporary Internet Files - View - Select my application Click 'Install shortcuts to the selected application'/blockquotethe desktop and menu shortcuts are created correctly.Also, in the Java Console, the Shortcut Creation option is set to the following (the default, I presume):Prompt user if hintedBelow is a snippet of my JNLP file:jnlp spec=6.0+ codebase=$$codebase information title${app.title}/title vendorSomeVendor (Pty) Ltd/vendor descriptionSome description/description icon href=${app.icon}/ shortcut online=true desktop/ menu submenu=MyApp/ /shortcut /information ...I'm stumped. Does anybody have an explanation for this?ThanksPS This is on both Windows XP and Windows 7. NetBeans version: 6.8
ScheduledThreadPoolExecutor executing a wrong time because of CPU time discrepancy : I'm scheduling a task using a ScheduledThreadPoolExecutor object. I use the following method:public ScheduledFuture? schedule(Runnable command, long delay,TimeUnit unit) and set the delay to 30 seconds (delay = 30,000 and unit=TimeUnit.MILLISECONDS). Sometimes my task occurs immediately and other times it takes 70 seconds.I believe the ScheduledThreadPoolExecutor uses CPU specific clocks. When i run tests comparing System.currentTimeMillis(), System.nanoTime() [which is CPU specific] i see the followingschedule: 1272637682651ms, 7858346157228410nsexecute: 1272637682667ms, 7858386270968425nsdifference is 16ms but 4011374001ns (or 40,113ms)so it looks like there is discrepancy between two CPU clocks of 40 secondsHow do i resolve this issue in java code? Unfortunately this is a clients machine and i can't modify their system.
Logger vs. System.out.println : I'm using the PMD plugin for eclipse and it gives me an error when using System.out.println() with the explanation:blockquote System.(out|err).print is used, consider using a logger./blockquoteMy question is - What is a Logger? How is it used to print to the screen? Why is it better?
Java 1.5.0_16 corrupted colours when saving jpg image : i have a loaded image from disk (stored as a BufferedImage), which i display correctly on a JPanel but when i try to re-save this image using the command below, the image is saved in a reddish hue.ImageIO.write(image, jpg, fileName);Note! image is a BufferedImage and fileName is a File object pointing to the filename that will be saved which end in .jpg.I have read that there were problems with ImageIO methods in earlier JDKs but i'm not on one of those versions as far as i could find. What i am looking for is a way to fix this issue without updating the JDK, however having said that i would still like to know in what JDK this issue was fixed in (if it indeed is still a bug with the JDK i'm using).Thanks.
Developing for Android in Eclipse: R.java not regenerating : I've found out that my R.java is never updated, so it doesn't contain information about my new resources, so I decided to delete it and thought that Eclipse would generate a new one. But that didn't happen, and I don't have R.java now. How can I regenerate one?I'm using Windowsnbsp;7. From one of the comments: Doing Project - Clean is what caused the problem for me. Cleaning deletes R.java...and for whatever reason the plugin is not regenerating the file.
How to find which attribute extensions an OpenId provider supports? : I have been looking at a href=http://code.google.com/p/openid4java/wiki/SampleConsumer rel=nofollow noreferrerhttp://code.google.com/p/openid4java/wiki/SampleConsumer and it is hardcoded to work with type fetch_request. Does it matter which type one wants, is there a way to tell or can one just use Fetch requests.
roll out of java web start clients : We are about to roll out a client server application build with java web start. Our main server is located in a country in Europe and we will have many users downloading our client the first day from all over the world. Since the client application is quite big in MB our wan will be utilized a lot. Is there a way to cache or pre- distribute java web start clients to servers closer to the user (for example a local server)?Thanks.
Java Scanner won't follow file : Trying to tail / parse some log files. Entries start with a date then can span many lines.This works, but does not ever see new entries to file.File inputFile = new File(C:/test.txt);InputStream is = new FileInputStream(inputFile);InputStream bis = new BufferedInputStream(is);//bis.skip(inputFile.length());Scanner src = new Scanner(bis);src.useDelimiter(\n2010-05-01 );while (true) { while(src.hasNext()){ System.out.println([ + src.next() + ]); }}Doesn't seem like Scanner's next() or hasNext() detects new entries to file. Any idea how else I can implement, basically, a tail -f with custom delimiter.ok - using Kelly's advise i'm checking amp; refreshing the scanner, this works. Thank you !!if anyone has improvement suggestions plz do!File inputFile = new File(C:/test.txt);InputStream is = new FileInputStream(inputFile);InputStream bis = new BufferedInputStream(is);//bis.skip(inputFile.length());Scanner src = new Scanner(bis);src.useDelimiter(\n2010-05-01 );while (true) { while(src.hasNext()){ System.out.println([ + src.next() + ]); } Thread.sleep(50); if(bis.available() 0){ src = new Scanner(bis); src.useDelimiter(\n2010-05-01 ); }}
Metro StreamBuffer namespace error - am I understanding this correctly? : All, I'm (still) working on calling a WSE 3.0 .NET web service from Java/Metro 2.0. We've got the security requirements set so that we're encrypting the body amp; header of the messages amp; signing the headers. I'm able to send a request to their service amp; get a response, but Metro is unable to validate the signature amp; throws an error from the WSIT code. I got the latest WSIT code from CVS amp; here's a code snippet of the method that's blowing up:from com.sun.xml.ws.security.opt.impl.incoming.GenericSecuredHeader:private XMLStreamBuffer completeHeader;public void writeTo(XMLStreamWriter w) throws XMLStreamException { try { // TODO what about in-scope namespaces completeHeader.writeToXMLStreamWriter(w); } catch (Exception e) { throw new XMLStreamException(e); } }As you can see, there's a TODO in there, that I think indicates that the method can't handle the situation I have, but I'm not sure I know what they mean by 'in-scope' namespaces.Here's the snippet of XML from the web service response that it's breaking on:wsa:Action wsu:Id=Id-46282a5d-c7fa-403c-8ac9-f7df0dfdb0cfhttp://someAction/wsa:ActionSignature xmlns=http://www.w3.org/2000/09/xmldsig#SignedInfods:CanonicalizationMethod Algorithm=http://www.w3.org/2001/10/xml-exc-c14n# xmlns:ds=http://www.w3.org/2000/09/xmldsig# /SignatureMethod Algorithm=http://www.w3.org/2000/09/xmldsig#rsa-sha1 /Reference URI=#Id-46282a5d-c7fa-403c-8ac9-f7df0dfdb0cfTransformsTransform Algorithm=http://www.w3.org/2001/10/xml-exc-c14n# //TransformsDigestMethod Algorithm=http://www.w3.org/2000/09/xmldsig#sha1 /DigestValue/2ivNKDpYSLqPWHzrSxN/RuZ/e8=/DigestValue/ReferenceIn the stack trace (included below), it complains about not being able to validate the reference URI=#Id-46282a5d-c7fa-403c-8ac9-f7df0dfdb0cf. What I'm unclear on is - is it failing because the Reference element doesn't have a namespace attribute or prefix? Should they be allowed to inherit the namespace from the parent Signature element, or can the StreamBuffer classes not handle that?To contrast, here's a similar XML snippet from my request (generated by WSIT), where the ds prefix is xmlns:ds=http://www.w3.org/2000/09/xmldsig#ds:Signature xmlns:ns10=http://www.w3.org/2003/05/soap-envelope xmlns:ns11=http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512 xmlns:ns12=http://schemas.xmlsoap.org/ws/2006/02/addressingidentity Id=_1ds:SignedInfods:CanonicalizationMethod Algorithm=http://www.w3.org/2001/10/xml-exc-c14n#exc14n:InclusiveNamespaces PrefixList=wsse S//ds:CanonicalizationMethodds:SignatureMethod Algorithm=http://www.w3.org/2000/09/xmldsig#rsa-sha1/ds:Reference URI=#_5002ds:Transformsds:Transform Algorithm=http://www.w3.org/2001/10/xml-exc-c14n#exc14n:InclusiveNamespaces PrefixList=S//ds:Transform/ds:Transformsds:DigestMethod Algorithm=http://www.w3.org/2000/09/xmldsig#sha1/ds:DigestValuevtf9n+OcI1nT0exavD4/ZQy6jm8=/ds:DigestValue/ds:ReferenceWhen Metro generates these blocks, everything has a namespace prefix. If you're still reading this far - thank you! Here's some snippets from the stack trace:Error occurred while trying to cache START_ELEMENTcom.sun.xml.stream.buffer.stax.StreamReaderBufferProcessor$InternalNamespaceContext[16:12:54.026] WSS1759: Following error null occured while performing canonicalization null[16:12:54.026] javax.xml.stream.XMLStreamException[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.GenericSecuredHeader.writeTo(GenericSecuredHeader.java:303)[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.StreamWriterData.write(StreamWriterData.java:101)[16:12:54.026] at com.sun.xml.ws.security.opt.crypto.dsig.Exc14nCanonicalizer.transform(Exc14nCanonicalizer.java:153)[16:12:54.026] at com.sun.xml.ws.security.opt.crypto.dsig.Transform.transform(Transform.java:182)[16:12:54.026] at com.sun.xml.ws.security.opt.crypto.dsig.Reference.transform(Reference.java:183)[16:12:54.026] at com.sun.xml.ws.security.opt.crypto.dsig.Reference.validate(Reference.java:102)[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.processor.SignedInfoProcessor.processReference(SignedInfoProcessor.java:422)[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.processor.SignedInfoProcessor.processReferences(SignedInfoProcessor.java:385)[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.processor.SignedInfoProcessor.process(SignedInfoProcessor.java:189)[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.Signature.process(Signature.java:206)[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.SecurityRecipient.handleSecurityHeader(SecurityRecipient.java:466)[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.SecurityRecipient.cacheHeaders(SecurityRecipient.java:281)[16:12:54.026] at com.sun.xml.ws.security.opt.impl.incoming.SecurityRecipient.validateMessage(SecurityRecipient.java:223)[16:12:54.026] at com.sun.xml.wss.jaxws.impl.SecurityTubeBase.verifyInboundMessage(SecurityTubeBase.java:462)[16:12:54.026] at com.sun.xml.wss.jaxws.impl.SecurityClientTube.processClientResponsePacket(SecurityClientTube.java:412)[16:12:54.026] at com.sun.xml.wss.jaxws.impl.SecurityClientTube.processResponsejavax.xml.ws.WebServiceException: com.sun.xml.wss.impl.WssSoapFaultException: WSS1722: Error occurred while validating Reference with URI: #Id-46282a5d-c7fa-403c-8ac9-f7df0dfdb0cf
Make WebStart Java desktop application to start on system startup on Windows and Mac : I developed small cross-platform (Windows and Mac) SWT desktop application. It is distributed with WebStart. So far so good, everything works.I've got a new requirement to make my app start on system startup (with no user interaction). What is the best way to accomplish that?In JNLP file I've got this:shortcut online=false desktop/ menu submenu=CompanyName//shortcutOn Windows WebStart creates a desktop link [app_name].lnk and it points tojavaws.exe and then some Java cache file as a parameter with funny name like ..\Sun\Java\Deployment\cache\6.0\4\2c0a6a781-213476. I can possibly programmatically find that link on user's machine by name... erm... and then copy it into user's Startup folder. I can see a problem here though as user can disable WebStart desktop shortcut creation option all together.On Mac WebStart pops up a dialog to prompt user for the location where to create an [app_name].app (user is allowed to change link name there!) file that launches an application. On Mac I don't event know where the Startup folder is located (a href=http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html#//apple_ref/doc/uid/20002134-SW2 rel=nofollow noreferrerand it seems to be much more complex there).Is there Java library out there that abstracts start app on system startup concept on different platforms as SWT does for GUI abstraction?
java web start security warning : I have a web application that downloads a jar file from the web server using java web start. The jar is signed using J2SE security tool. However, I get the security warning The application digital signature cannot be verified. Do you want to run the application?Am I missing something that is causing this??
Metro web services on Google App Engine : Has anyone tried to implement Metro web services on GAE-Java. It is not lsited on a href=http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine rel=nofollow noreferrerhttp://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine and I would like to know if GAE will support it
How to import a WCF web service using a Java client : I have a WCF web service using wsHttpBinding that I am consuming from a Java client. I generated code from the WSDL using wsimport. The java client appears to be creating the service fine but when I call a method on the service the client just spins. MyService s = new MyService();IMyService i = s.getWSHttpBindingIMyService();returnedValue = i.getSomething(2); // method callCan a java client communicate with a WCF webservice that is using wsHttpBinding? And what is the best way of doing so?Any help will be appreciated.
Loading .eml files into javax.mail.Messages : I'm trying to unit test a method which processes javax.mail.Message instances.I am writing a converter to change emails which arrive in different formats and are then converted into a consistent internal format (MyMessage). This conversion will usually depend on the from-address or reply-address of the email, and the parts of the email, the subject, and the from- and reply-addresses will be required for creating the new MyMessage.I have a collection of raw emails which are saved locally as .eml files, and I'd like to make a unit test which loads the .eml files from the classpath and converts them to javax.mail.Message instances. Is this possible, and if so, how would it be done?
DefaultStyledDocument.styleChanged(Style style) may not run in a timely manner? : I'm experiencing an intermittent problem with a class that extends javax.swing.text.DefaultStyledDocument. This document is being sent to a printer. Most of the time the formatting of the document looks correct, but once in a while it doesn't. It looks like some of the changes in the formatting have not been applied.I took a look at the DefaultStyledDocument.styleChanged(Style style) code:/** * Called when any of this document's styles have changed. * Subclasses may wish to be intelligent about what gets damaged. * * @param style The Style that has changed. */protected void styleChanged(Style style) { // Only propagate change updated if have content if (getLength() != 0) { // lazily create a ChangeUpdateRunnable if (updateRunnable == null) { updateRunnable = new ChangeUpdateRunnable(); } // We may get a whole batch of these at once, so only // queue the runnable if it is not already pending synchronized(updateRunnable) { if (!updateRunnable.isPending) { SwingUtilities.invokeLater(updateRunnable); updateRunnable.isPending = true; } } }}/** * When run this creates a change event for the complete document * and fires it. */class ChangeUpdateRunnable implements Runnable { boolean isPending = false;public void run() { synchronized(this) { isPending = false; } try { writeLock(); DefaultDocumentEvent dde = new DefaultDocumentEvent(0, getLength(), DocumentEvent.EventType.CHANGE); dde.end(); fireChangedUpdate(dde); } finally { writeUnlock(); }}}Does the fact that SwingUtilities.invokeLater(updateRunnable) is called, rather than invokeAndWait(updateRunnable), mean that I can't count on my formatting changes appearing in the document before it is rendered?If that is the case, is there a way to ensure that I don't proceed with rendering until the updates have occurred?
Clob as param for PL/SQL Java Stored Procedure : I have a java stored procedure that takes in a clob representing a chunk of javascript and mins it. The structure of the function calling the JSP is as follows:function MIN_JS(pcl_js in clob) return clob as language java name 'JSMin.min(oracle.sql.CLOB) return oracle.sql.CLOB';In the actual JSP, I have the following:import oracle.sql.CLOB;public class JSMin {...public static min(CLOB js) {...}The problem I'm having is that whenever I pass a clob to JS_MIN, it is always interpreted as null inside the JSP. I've checked the clob before calling JS_MIN annd it definitely has contents. Any ideas as to what I'm missing? Any help is greatly appreciated.
Write binary stream to browser using PHP : BackgroundTrying to stream a PDF report written using iReport through PHP to the browser. The general problem is: how do you write binary data to the browser using PHP?Working Codeheader('Cache-Control: no-cache private');header('Content-Description: File Transfer');header('Content-Disposition: attachment, filename=climate-report.pdf');header('Content-Type: application/pdf');header('Content-Transfer-Encoding: binary');$path = realpath( . ) . /output.pdf;$em = java('net.sf.jasperreports.engine.JasperExportManager');$result = $em-exportReportToPdf($pm);header('Content-Length: ' . strlen( $result ) );$fh = fopen( $path, 'w' );fwrite( $fh, $result );fclose( $fh );readfile( $path );Non-working Codeheader('Cache-Control: no-cache private');header('Content-Description: File Transfer');header('Content-Disposition: attachment, filename=climate-report.pdf');header('Content-Type: application/pdf');header('Content-Transfer-Encoding: binary');$path = realpath( . ) . /output.pdf;$em = java('net.sf.jasperreports.engine.JasperExportManager');$result = $em-exportReportToPdf($pm);header('Content-Length: ' . strlen( $result ) );echo $resuQuestionHow can I take out the middle step of writing to the file and write directly to the browser so that the PDF is not corrupted?UpdatePDF file sizes:Working: 594778 bytesNon-working: 1059365 bytesThank you!
Java class in DB : Can anyone explain why was idea to store Java class in Db? What it is good for? And how to create stored procedure with Java class?Best regards!
Java Webstart Truststore SSL : Need some guidance. I have java webstart app and I want it to connect to a server via SSL.just adding a property like:System.setProperty(javax.net.ssl.trustStore,my.keystore);But since a JAWS program is downloaded from server didn't work and don't have a my.keystore on local file system. So decided to distribute the certificate to all clients.I did the following and it worked.Read this trust store as a stream (use getResourceAsStream method).Save it in any file on the client machine (sometemp)Call System.setProperty (javax.net.ssl.trustStore, trustStorePath);But I am sure there must be better solutions than this.. Any ideas to make it better? public boolean validateUserFromActiveDirectory(String userId) { final String MEMBER_GROUP = CN=asdadasd,OU=asdasdasd Accounts,OU=adasdas,OU=asdasdas,DC=asdasdas,DC=asdasdas,DC=adasdasd,DC=asdasdasd; String employeeNumber = ; final String LDAP_INIT_CTX = com.sun.jndi.ldap.LdapCtxFactory; final String LDAP_URL = ldap://xx-ssssssss.eee.eee.eeeee.eeeee:636; final String MY_ATTRS[] = { employeeNumber }; String adminPassword = somepassword; String securityProtocol = ssl; boolean isValidUser = false; try { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_INIT_CTX); env.put(Context.PROVIDER_URL, LDAP_URL); env.put(Context.SECURITY_AUTHENTICATION, simple); env.put(Context.REFERRAL, follow); env.put(Context.SECURITY_PRINCIPAL, MEMBER_GROUP); env.put(Context.SECURITY_CREDENTIALS, adminPassword); env.put(Context.SECURITY_PROTOCOL, securityProtocol); //C:\Documents and Settings\yourusername\Local Settings\Temp File tf = File.createTempFile(someTruststore, .jks); tf.deleteOnExit(); byte buffer[] = new byte[0x1000]; ClassLoader cl = JNDI.class.getClassLoader(); InputStream in = cl.getResourceAsStream( someTruststore.jks); FileOutputStream out = new FileOutputStream(tf); int cnt; while ((cnt = in.read(buffer)) != -1) out.write(buffer, 0, cnt); in.close(); out.close(); System.setProperty(javax.net.ssl.trustStore, tf .getAbsolutePath()); DirContext context = new InitialLdapContext(env, null); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration results = context.search( XX=ent,XX=abc,XX=aaaaa,XX=aaaa, (sAMAccountName= + userId + ), searchControls); if (results != null amp;amp; results.hasMore()) { //some logic } } } catch (Exception e) { e.printStackTrace(); } return isValidUser; }-Padur===========================**=============/*** */package util;/** * @author spaduri * */import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import javax.net.SocketFactory;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;public class CustomSSLSocketFactory extends SSLSocketFactory { private SSLSocketFactory factory; public CustomSSLSocketFactory() { try { SSLContext sslcontext = null; // Call getKeyManagers to get suitable key managers KeyManager[] kms=getKeyManagers(); if (sslcontext == null) { sslcontext = SSLContext.getInstance(SSL); sslcontext.init(kms, new TrustManager[] { new CustomTrustManager() }, new java.security.SecureRandom()); } factory = (SSLSocketFactory) sslcontext.getSocketFactory(); } catch (Exception ex) { ex.printStackTrace(); } } public static SocketFactory getDefault() { return new CustomSSLSocketFactory(); } public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException { return factory.createSocket(socket, s, i, flag); } public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException { return factory.createSocket(inaddr, i, inaddr1, j); } public Socket createSocket(InetAddress inaddr, int i) throws IOException { return factory.createSocket(inaddr, i); } public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException { return factory.createSocket(s, i, inaddr, j); } public Socket createSocket(String s, int i) throws IOException { return factory.createSocket(s, i); } public String[] getDefaultCipherSuites() { return factory.getSupportedCipherSuites(); } public String[] getSupportedCipherSuites() { return factory.getSupportedCipherSuites(); } protected KeyManager[] getKeyManagers() throws IOException, GeneralSecurityException { // First, get the default KeyManagerFactory. String alg=KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory kmFact=KeyManagerFactory.getInstance(alg); // Next, set up the KeyStore to use. We need to load the file into // a KeyStore instance. ClassLoader cl = CustomSSLSocketFactory.class.getClassLoader(); // read the file someTrustStore from the jar file from a classpath InputStream in = cl.getResourceAsStream(ssl/someTruststore.jks); //FileInputStream fis=new FileInputStream(adentTruststore.jks); KeyStore ks=KeyStore.getInstance(jks); ks.load(in, null); in.close(); // Now we initialise the KeyManagerFactory with this KeyStore kmFact.init(ks, null); // And now get the KeyManagers KeyManager[] kms=kmFact.getKeyManagers(); return kms; }}package util;import java.security.cert.X509Certificate;import javax.net.ssl.X509TrustManager;public class CustomTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] cert, String authType) { return; } public void checkServerTrusted(X509Certificate[] cert, String authType) { return; } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }}Laz appreciate your patience, trying to learn when I get some time.I started writing my own CustomSSLSocketFactory..right now I am bypassing security...based on the example by platinum solutions.If I do that ...will the information pass as a clear text on the network?Now I wonder what should I do with the truststore file I am having sometruststore.jks file. What should I do with that ..Do I have wrie my own custom trustmanager software ?Please guide me in correct direction.-padur
How to show and deploy a PDF document from Java using WebStart : I want to show a PDF document from a Java (Swing) application in a system independent manner (provided that a PDF viewer is properly installed on the target system).Also I'd like to deploy this PDF document using Java WebStart.Could you please tell me the standard way to achieve this? (I confess, I'm to lazy/busy to look up the details ...) Thanks!
Can anyone say Stored procedures pros and cons AND Java Stored Procedures pros and con? : Can anyone say Stored procedures pros and cons AND Java Stored Procedures pros and con? And how to test it.Best regards!
Downloading Spreadsheets From Google Docs : I am working on an Android app that uses the gdata-java-client to download documents for display only. So far I have an application that authenticates with the services and displays a list of user documents. When the user selects a document another query is made for the documents itself. A request for txt, html, rtf and doc files works well, however when I request a spreadsheet in either .csv or .xsl format the result is unexpected. I'm using an HTTPResponse object to store the result of a an HTTPRequest. When I request a document in .csv or .xsl format the HTTPResponse.parseAsString() method produces an entire html page which appears to be the Google Docs home page. Sounds strange, but the result is the actual html for the login page. The HTTPResponse.getStatusMessage returns a 200. Seems like I am missing something simple here. Is there another property of the HTTPResponse that contains the .csv data? I am pretty sure that I am using the correct uri for downloading spreadsheets because it works when I download through my browser. In any case here is an example uri:https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=0AsE_6_YIr797dHBTUWlHMUFXeTV4ZzJlUGxWRnJXancamp;exportFormat=csvThanks in advance for any help :)
How to edit a .txt file in Java : i think i can use Scanner to read a .txt file but how can i write or even create a new text file?
Are there any good Java API for facebook? : I've played around a bit with twitter4j and found it absolutely wonderful. Now I've been looking into the equivalent for facebook but so far haven't had much luck finding a decent project.I looked into a href=http://code.google.com/p/facebook-java-api/ rel=nofollow noreferrerfacebook-java-api but it appears that they break their API from release to release. I consider this unacceptable.I'm currently playing around a bit with a href=http://restfb.com/ rel=nofollow noreferrerRestFB and the API seems decent so far but I've been having some connection problems.I'm just looking for a simple library that lets me post status updates, send direct messages and get a list of friends through minimal coding effort.Has anyone had any success using a java API for facebook and if so, what are you using? Thanks.
Has anyone gotten jax-ws-catalog.xml to resolve schemaLocation locally on Metro? : I have added a jax-ws-catalog.xml to my .war file in order to resolve the schemaLocation locally instead of remotely in . I've followed the example ata href=http://metro.java.net/guide/ch02.html#developing-client-application-with-locally-packaged-wsdl rel=nofollow noreferrerMetro User Guide: 2.10. Developing client application with locally packaged WSDLWhen I deploy the .war and use soapUI to validate the web service it gets stuck trying to access the schemaLocation http://somehost:8080/CMDB/schemas/common/1.0/CMDBCommonTypes.xsdThe schema and wsdl both validate in Eclipse (using XML Catalog tool for Eclipse). (I can post the contents of my jax-ws-catalog.xml and the relevant xsd and wsdl if that will help.A Google search turns up lots of other problems with jax-ws-catalog.xml not working in the Metro stack.Has anyone gotten a jax-ws-catalog.xml to work in Metro?
Java Webstart...interaction with browsers on different platforms : This post is similar to a href=http://stackoverflow.com/questions/1119591/launching-a-browser-window-from-java-webstart-jnlp-in-java-6u13this post, but not exactly, so I'm asking this question.How does one go about, From a Java WebStart app:launch a new browser window with a target URL?bring an existing browser window intofocus with a target URL?Is the solution OS/platform independent? Does it matter which browser you're talking to?
filling array gradually with data from user : I'm trying to fill an array with words inputted by user. Each word must be one letter longer than previous and one letter shorter than next one. Their length is equal to table row index, counting from 2. Words will finally create a one sided pyramid, like :AABABCABCDScanner sc = new Scanner(System.in);System.out.println(Give the height of array: );height = sc.nextInt();String[] words = new String[height];for(int i=2; iheight+2; i++){ System.out.println(Give word with +i+ letters.); words[i-2] = sc.next(); while( words[i-2].length()i-2 || words[i-2].length()words[i-3].length() ){ words[i-2] = sc.next(); }}How can I limit words read from scanner to fill the requirements?Currently the while loop doesn't influence scanner at all :/This is not a homework. I'm trying to create a simple application and then gui for it.
Why are public static final array a security hole? : Effective java says:blockquote // Potential security hole! static public final Thing[] VALUES = { ... };/blockquoteCan somebody tell me what is the security hole?
Why would I want to use anything other than WCF? : After completing several small projects with WCF, I'm quite happy with what it can do.However, having spent a brief amount of time looking into the alternatives, I'm struggling to find exactly what benefits/drawbacks I would experience from using Java based web services such as AXIS2 or Metro?Obviously open-source is perhaps one of them and also breaking away from Windows Server/IIS, but I can't see much more?
How can I define a clojure type that implements the servlet interface? : I'm attempting to use deftype (from the bleeding-edge clojure 1.2 branch) to create a java class that implements the java Servlet interface. I would expect the code below to compile (even though it's not very useful).(ns foo [:import [javax.servlet Servlet ServletRequest ServletResponse]])(deftype servlet [] javax.servlet.Servlet (service [this #^javax.servlet.ServletRequest request #^javax.servlet.ServletResponse response] nil))But it doesn't compile. The compiler produces the message:Mismatched return type: service, expected: void, had: java.lang.Object [Thrown class java.lang.IllegalArgumentException]Which doesn't make sense to me, because I'm returning nil. So the fact that the return type of the method is void shouldn't be a problem. For instance, for the java.util.Set interface:(deftype bar [#^Number n] java.util.Set (clear [this] nil))compiles without issue.So what am I doing wrong with the Servlet interface?To be clear: I know that the typical case is to subclass one of the servlet abstract classes rather than implement this interface directly, but it should still be possible to do this. Stack Trace:The stack trace for the (deftype servlet... is:Mismatched return type: service, expected: void, had: java.lang.Object [Thrown class java.lang.IllegalArgumentException]Restarts: 0: [ABORT] Return to SLIME's top level.Backtrace: 0: clojure.lang.Compiler$NewInstanceMethod.parse(Compiler.java:6461) 1: clojure.lang.Compiler$NewInstanceExpr.build(Compiler.java:6119) 2: clojure.lang.Compiler$NewInstanceExpr$DeftypeParser.parse(Compiler.java:6003) 3: clojure.lang.Compiler.analyzeSeq(Compiler.java:5289) 4: clojure.lang.Compiler.analyze(Compiler.java:5110) 5: clojure.lang.Compiler.analyze(Compiler.java:5071) 6: clojure.lang.Compiler.eval(Compiler.java:5347) 7: clojure.lang.Compiler.eval(Compiler.java:5334) 8: clojure.lang.Compiler.eval(Compiler.java:5311) 9: clojure.core$eval__4350.invoke(core.clj:2364) 10: swank.commands.basic$eval_region__673.invoke(basic.clj:40) 11: swank.commands.basic$eval_region__673.invoke(basic.clj:31) 12: swank.commands.basic$eval__686$listener_eval__687.invoke(basic.clj:54) 13: clojure.lang.Var.invoke(Var.java:365) 14: foo$eval__2285.invoke(NO_SOURCE_FILE) 15: clojure.lang.Compiler.eval(Compiler.java:5343) 16: clojure.lang.Compiler.eval(Compiler.java:5311) 17: clojure.core$eval__4350.invoke(core.clj:2364) 18: swank.core$eval_in_emacs_package__320.invoke(core.clj:59) 19: swank.core$eval_for_emacs__383.invoke(core.clj:128) 20: clojure.lang.Var.invoke(Var.java:373) 21: clojure.lang.AFn.applyToHelper(AFn.java:169) 22: clojure.lang.Var.applyTo(Var.java:482) 23: clojure.core$apply__3776.invoke(core.clj:535) 24: swank.core$eval_from_control__322.invoke(core.clj:66) 25: swank.core$eval_loop__324.invoke(core.clj:71) 26: swank.core$spawn_repl_thread__434$fn__464$fn__465.invoke(core.clj:183) 27: clojure.lang.AFn.applyToHelper(AFn.java:159) 28: clojure.lang.AFn.applyTo(AFn.java:151) 29: clojure.core$apply__3776.invoke(core.clj:535) 30: swank.core$spawn_repl_thread__434$fn__464.doInvoke(core.clj:180) 31: clojure.lang.RestFn.invoke(RestFn.java:398) 32: clojure.lang.AFn.run(AFn.java:24) 33: java.lang.Thread.run(Thread.java:637)
How do I send an email with embedded images and regular attachments in JavaMail? : I'd like to know how to build an SMTP multipart message in the correct order so that it will render correctly on the iPhone mail client (rendering correctly in GMail).I'm using Javamail to build up an email containing the following parts:A body part with content type text/html; UTF-8An embedded image attachment.A file attachmentI am sending the mail via GMail SMTP (via SSL) and the mail is sent and rendered correctly using a GMail account, however, the mail does not render correctly on the iPhone mail client. On the iPhone mail client, the image is rendered before the Before Image text when it should be rendered afterwards. After the Before Image text there is an icon with a question mark (I assume it means it couldn't find the referenced CID). I'm not sure if this is a limitation of the iPhone mail client or a bug in my mail sending code (I strongly assume the latter).I think that perhaps the headers on my parts might by incorrect or perhaps I am providing the multiparts in the wrong order. I include the text of the received mail as output by gmail (which renders the file correcMessage-ID: 3977333.1.1274154021787.JavaMail.Chris@smtp.gmail.comSubject: =?UTF-8?Q?Test_from_=E3=82=AF=E3=83=AA=E3=82=B9?=MIME-Version: 1.0Content-Type: multipart/mixed; boundary=----=_Part_0_20870565.1274154021755------=_Part_0_20870565.1274154021755Content-Type: application/octet-streamContent-Transfer-Encoding: base64Content-ID: 20100518124021763_368238_0iVBORw0K ----- TRIMMED FOR CONCISENESS6p1VVy4alAAAAABJRU5ErkJggg==------=_Part_0_20870565.1274154021755Content-Type: text/html; charset=UTF-8Content-Transfer-Encoding: 7bithtmlheadtitleEmployees Favourite Foods/titlestyle body { font: normal 8pt arial; } th { font: bold 8pt arial; white-space: nowrap; } td { font: normal 8pt arial; white-space: nowrap; }/style/headbody Before Imagebrimg src=cid:20100518124021763_368238_0 After Imagebrtable border=0trth colspan=4Employees Favourite Foods/th/trtrth align=leftName/thth align=leftAge/thth align=leftTel.No/thth align=leftFav.Food/th/trtr style=background-color:#e0e0e0tdChris/tdtd34/tdtd555-123-4567/tdtdPancakes/td/tr/table/body/html------=_Part_0_20870565.1274154021755Content-Type: text/plain; charset=us-ascii; name=textfile.txtContent-Transfer-Encoding: 7bitContent-Disposition: attachment; filename=textfile.txtThis is a textfile with numbers counting from one to ten beneath this line:onetwothreefourfivesixseveneightnineten(no trailing carriage return)------=_Part_0_20870565.1274154021755--Even if you can't assist me with this, I would appreciate it if any members of the forum could forward me a (non-personal) mail that includes inline images (not external hyperlinked images though). I just need to find a working sample then I can move past this.Thanks,Chris.
JavaFX: JNLP file error : I'm getting the following error when I upload a JavaFX app to a website, but I don't get it locally.I'm presuming that I'm missing something like the 'codebase' tag, but I'm not sure where it goes, can anyone help me out please?Java Console error:exception: JNLP file error: iShout_Foxpro_browser.jnlp. Please make sure the file exists and check if codebase and href in the JNLP file are correct..java.io.FileNotFoundException: JNLP file error: iShout_Foxpro_browser.jnlp. Please make sure the file exists and check if codebase and href in the JNLP file are correct.at sun.plugin2.applet.JNLP2Manager.loadJarFiles(Unknown Source)at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)at java.lang.Thread.run(Unknown Source)Exception: java.io.FileNotFoundException: JNLP file error: iShout_Foxpro_browser.jnlp. Please make sure the file exists and check if codebase and href in the JNLP file are correct.HTML file source...htmlheadmeta http-equiv=Content-Type content=text/html; charset=utf-8titleapp_one/title/headbodyscript src=http://dl.javafx.com/1.3/dtfx.js/scriptscriptjavafx( { archive: app_one.jar, draggable: true, width: 480, height: 320, code: app.Main, name: app_one });
java web start problem with sign file : Unsigned application requesting unrestricted access to systemUnsigned resource: http://*/kis/adfjars/sqlj/lib/runtime12.jarException: jar href=http://*/kis/adfjars/jlib/oracle-el.jar download=eager main=false/ jar href=http://*/kis/adfjars/jlib/share.jar download=eager main=false/ jar href=http://*/kis/adfjars/lib/dms.jar download=eager main=false/ jar href=http://*/kis/adfjars/lib/xmlparserv2.jar download=eager main=false/ jar href=http://*/kis/adfjars/ord/jlib/ordim.jar download=eager main=false/ jar href=http://*/kis/adfjars/sqlj/lib/runtime12.jar download=eager main=false/ /resources library-desc unique-id=null//jnlp ] at com.sun.javaws.LaunchDownload.checkSignedResourcesHelper(Unknown Source) at com.sun.javaws.LaunchDownload.checkSignedResources(Unknown Source) at com.sun.javaws.Launcher.continueLaunch(Unknown Source) at com.sun.javaws.Launcher.handleApplicationDesc(Unknown Source) at com.sun.javaws.Launcher.handleLaunchFile(Unknown Source) at com.sun.javaws.Launcher.run(Unknown Source) at java.lang.Thread.run(Unknown Source)but when i deploy second time to oc4j then start working. Sometimes work for first time. Any idea why? All other files are signed only this file has problem, but not always.Thx
Can ASM method-visitors be used with interfaces? : I need to write a tool that lists the classes that call methods of specified interfaces. It will be used as part of the build process of a large java application consisting of many modules. The goal is to automatically document the dependencies between certain java modules.I found several tools for dependency analysis, but they don't work on the method level, just for packages or jars. Finally I found ASM, that seems to do what I need.The following code prints the method dependencies of all class files in a given directory:import java.io.*;import java.util.*;import org.objectweb.asm.ClassReader;public class Test { public static void main(String[] args) throws Exception { File dir = new File(args[0]); ListFile classFiles = new LinkedListFile(); findClassFiles(classFiles, dir); for (File classFile : classFiles) { InputStream input = new FileInputStream(classFile); new ClassReader(input).accept(new MyClassVisitor(), 0); input.close(); } } private static void findClassFiles(ListFile list, File dir) { for (File file : dir.listFiles()) { if (file.isDirectory()) { findClassFiles(list, file); } else if (file.getName().endsWith(.class)) { list.add(file); } } }}import org.objectweb.asm.MethodVisitor;import org.objectweb.asm.commons.EmptyVisitor;public class MyClassVisitor extends EmptyVisitor { private String className; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { this.className = name; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { System.out.println(className + . + name); return new MyMethodVisitor(); }}import org.objectweb.asm.commons.EmptyVisitor;public class MyMethodVisitor extends EmptyVisitor { @Override public void visitMethodInsn(int opcode, String owner, String name, String desc) { String key = owner + . + name; System.out.println( + key); }}The Problem:The code works for regular classes only! If the class file contains an interface, visitMethod is called, but not visitMethodInsn. I don't get any info about the callers of interface methods.Any ideas?
Java Scanner newline parsing with regex (Bug?) : I'm developing a syntax analyzer by hand in Java, and I'd like to use regex's to parse the various token types. The problem is that I'd also like to be able to accurately report the current line number, if the input doesn't conform to the syntax.Long story short, I've run into a problem when I try to actually match a newline with the Scanner class. To be specific, when I try to match a newline with a pattern using the Scanner class, it fails. Almost always. But when I perform the same matching using a Matcher and the same source string, it retrieves the newline exactly as you'd expect it too. Is there a reason for this, that I can't seem to discover, or is this a bug, as I suspect?FYI: I was unable to find a bug in the Sun database that describes this issue, so if it is a bug, it hasn't been reported.Example Code:Pattern newLinePattern = Pattern.compile((\\r\\n?|\\n), Pattern.MULTILINE);String sourceString = \r\n\n\r\r\n\n;Scanner scan = new Scanner(sourceString);scan.useDelimiter();int count = 0;while (scan.hasNext(newLinePattern)) { scan.next(newLinePattern); count++;}System.out.println(found +count+ newlines); // finds 7 newlinesMatcher match = newLinePattern.matcher(sourceString);count = 0;while (match.find()) { count++;}System.out.println(found +count+ newlines); // finds 5 newlines
Java Client interoperating with WSE 3.0 Web Service : I have a Interoperable Security Token Service (STS) that authenticates the User and then issues a SAML token. I also have transaction services that expects the SAML token in the incoming SOAP request header.For a client to make a call to transaction service, it first needs to authenticate with the STS, get the SAML token and then make a call to the transaction services. The STS is an interoperable service and can be invoked from a Java client. The Transaction services are build using WSE 3.0 framework, but the WSDL that it generates is not good enough for a Java client to understand it. I want my Java client to explicitly call the STS and then using the received SAML token make a call to Transaction Services. I tried with Netbeans and Metro WSIT toolkit. I was able to call the Transaction Services if it were implemented using WCF. With WCF Transaction Service the WSDL generated has complete information using which the Java client can figure out how to call to STS and then call the WCF Transaction service. How can my Java client explicitly call the STS and then in turn call the WSE 3.0 transaction services?
Scanner cuts off my String after about 2400 characters : I've got some very basic code likewhile (scan.hasNextLine()){ String temp = scan.nextLine(); System.out.println(temp);}where scan is a Scanner over a file.However, on one particular line, which is about 6k chars long, temp cuts out after something like 2470 characters. There's nothing special about when it cuts out; it's in the middle of the word Australia. If I delete characters from the line, the place where it cuts out changes; e.g. if I delete characters 0-100 in the file then Scanner will get what was previously 100-2570.I've used Scanner for larger strings before. Any idea what could be going wrong?
How to set time zone of a java.util.Date? : I have parsed a java.util.Date from a String but it is setting the local time zone as the time zone of the date object.The time zone is not specified in the String from which Date is parsed. I want to set a specific time zone of the date object.How can I do that?
How to use Scanner to read silently from STDIN in Java? : I want to make a Java program that reads a Password from STDIN silently. I mean, without outputting any pressed chars to the terminal and keeping it hidden from commandline history and the operating system processlist ps.
Cannot remove JAR from cache : I have created a new JAR but I cannot see my changes made. It seems like its caching the old JAR.When I do a javaws -viewer I see the date modified column for that JAR as April 7, which is old. Is there another way to remove java JARS from cache?I know it works on my local machine with same JARS. And the date modified field is May 23. I'm testing on a TEST server where this problem is occurring.Any ideas why?Thank you.
Error message for failed new ImageIcon(url) : I try to load an image with:ImageIcon imageIcon = new ImageIcon(url);if I query the load status:imageIcon.getImageLoadStatus(); it returns MediaTracker.ERROREDIs there a way to get an error message saying what the problem was?
Glassfish JAX-WS side by side SSL / insecure EJB webservice : Is it possible to run a single @WebService bean as both secure and insecure at the same time, preferably using the same URL except for the http/https protocol difference?I am able to run the service either secure or insecure using:transport-guaranteeCONFIDENTIAL/transport-guaranteeortransport-guaranteeNONE/transport-guaranteeinside sun-ejb-jar.xmlIE.ejb ejb-nameMyEJB/ejb-name webservice-endpoint port-component-nameMyWebService/port-component-name transport-guaranteeCONFIDENTIAL/transport-guarantee /webservice-endpoint/ejbSuggestions?
How to use Scanner to accept only valid int as input : I'm trying to make a small program more robust and I need some help with that.Scanner kb = new Scanner(System.in);int num1;int num2 = 0;System.out.print(Enter number 1: );num1 = kb.nextInt();while(num2num1){System.out.print(Enter number 2: );num2 = kb.nextInt();}Number 2 has to be greater than number 1Also I want the program to automatically check and ignore if the user enters a character instead of a number. Because right now when a user enters for example r instead of a number the program just exits.
Can't get Java Web Start to work in Eclipse : I'm attempting to get Java Web Start to work on an application by using the Web Start Plugin for Eclipse (a href=http://webstart.sourceforge.net/ rel=nofollow noreferrerhttp://webstart.sourceforge.net/). I tried following the tutorial, but when I completed it and went to launch the JNLP file, it failed with an Application Error, saying Unexpected exception: java.util.NoSuchElementException. The launch file displayed is:?xml version=1.0 encoding=UTF-8?jnlp codebase=file:/C:/Documents and Settings/10boyedevi/Desktop/School/AP Computer Science/Eclipse Workspace/ACSLLand/localhost/club/ href=file:/C:/Documents and Settings/10boyedevi/Desktop/School/AP Computer Science/Eclipse Workspace/ACSLLand/localhost/club/_local_club.jnlp information titleACSLLand/title vendorAP Comp Sci 2009-2010/vendor description kind=defaultA game./description /information security all-permissions/ /security resources arch=x86 os=Windows j2se version=1.3+/ jar href=ASCLLand.jar main=true/ /resources application-desc main-class=ascllandgame.ASCLLand//jnlpand the exception stack trace is:java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at ascllandgame.ASCLLand.main(ASCLLand.java:16) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.sun.javaws.Launcher.executeApplication(Unknown Source) at com.sun.javaws.Launcher.executeMainClass(Unknown Source) at com.sun.javaws.Launcher.doLaunchApp(Unknown Source) at com.sun.javaws.Launcher.run(Unknown Source) at java.lang.Thread.run(Unknown Source)
Memory Size Allocation on GPU - opengl texture loading question : I'm loading pixels from an image which is 32 w by 32 height. The format I'm loading them in is ARGB via java. When I bind this to the video card, I can expect that the video card might use somewhere around 32*32*4 bytes, or 4K. Similarly, 1024 w, 1024 h would be 1024*1024*4 = 4MB. Is my understanding correct? Now I understand where all the memory goes!
Parse Text using scanner useDelimiter : Looking to parse the following text file:Sample text file:2008-10-07text entered by userTed Parlor2008-11-26additional text entered by userTed ParlorI would like to parse the above text so that I can have three variables:v1 = 2008-10-07v2 = text entered by userv3 = Ted Parlorv1 = 2008-11-26v2 = additional text entered by userv3 = Ted ParlorI attempted to use scanner and useDelimiter, however, I'm having issue on how to set this up to have the results as stated above. Here's my first attempt:import java.io.*;import java.util.Scanner;public class ScanNotes { public static void main(String[] args) throws IOException { Scanner s = null; try { //String regex = (?=\\)([^\\*)(?=\\); s = new Scanner(new BufferedReader(new FileReader(cur_notes.txt))); s.useDelimiter([]+); while (s.hasNext()) { String v1 = s.next(); String v2= s.next(); System.out.println(v1= + v1 + v2= + v2); } } finally { if (s != null) { s.close(); } } }}The results is as follows:v1= 2008-10-07text entered by user v2=Ted Parlor What I desire is:v1= 2008-10-07 v2=text entered by user v3=Ted Parlorv1= 2008-11-26 v2=additional text entered by user v3=Ted ParlorAny help that would allow me to extract all three strings separately would be greatly appreciated.
java.util.logging: how to suppress date line : I'm trying to suppress output of the date line durinng logging when using the default logger in java.util.logging. For example, here is a typical output:Jun 1, 2010 10:18:12 AM gamma.utility.application infoINFO: ping: db-time=2010-06-01 10:18:12.0, local-time=20100601t101812, duration=180000Jun 1, 2010 10:21:12 AM gamma.utility.application infoINFO: ping: db-time=2010-06-01 10:21:12.0, local-time=20100601t102112, duration=180000I would like to get rid of the Jun 1, 2010... lines, they just clutter my log output. How can I do this?
How can CopyOnWriteArrayList be thread-safe? : I've taken a look into a href=http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/4797cd0713b4/src/share/classes/java/util/concurrent/CopyOnWriteArrayList.java rel=nofollow noreferrerOpenJDK source code of a href=http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html rel=nofollow noreferrerCopyOnWriteArrayList and it seems that all write operations are protected by the same lock and read operations are not protected at all. As I understand, under JMM all accesses to a variable (both read and write) should be protected by lock or reordering effects may occur.For example, set(int, E) method contains these lines (under lock):/* 1 */ int len = elements.length;/* 2 */ Object[] newElements = Arrays.copyOf(elements, len);/* 3 */ newElements[index] = element;/* 4 */ setArray(newElements);The get(int) method, on the other hand, only does return get(getArray(), index);.In my understanding of JMM, this means that get may observe the array in an inconsistent state if statements 1-4 are reordered like 1-2(new)-4-2(copyOf)-3.Do I understand JMM incorrectly or is there any other explanations on why CopyOnWriteArrayList is thread-safe?
Where are the downloaded jars in a Java Web Start Application? : I have an Eclipse application loaded using Web Start.I know that the Eclipse Plugins must be stored somewhere as jars. In which location are they stored when such an application is downloaded using Java Web Start?I am expecting the JAR files to be somewhere on the user directory, but I haven't been able to track them yet.Thanks!
How do I make defensive copy of an object? : How do I make defensive copies of a Mutable Object which contains a mutable field in an Immutable Object?class ImmutableObject { private final MutableObject immutable_field; ImmutableObject(MutableObject y) { this.immutable_field = y; }}class MutableObject { public int mutable_field;}The MutableObject does not have a constructor that lets me set the field.The MutableObject's current state should be captured in the Immutable Object and never changed.
Java: CSV file read write : I'm reading 2 csv files: store_inventory amp; new_acquisitions.I want to be able to compare the store_inventory csv file with new_acquisitions. 1) If the item names match just update the quantity in store_inventory.2) If new_acquisitions has a new item that does not exist in store_inventory, then add it to the store_inventory.Here is what i have done so far but its not very good. I added comments where i need to add taks 1 amp; 2.Any advice or code to do the above tasks would be great! thanks. File new_acq = new File(/src/test/new_acquisitions.csv); Scanner acq_scan = null; try { acq_scan = new Scanner(new_acq); } catch (FileNotFoundException ex) { Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex); } String itemName; int quantity; Double cost; Double price; File store_inv = new File(/src/test/store_inventory.csv); Scanner invscan = null; try { invscan = new Scanner(store_inv); } catch (FileNotFoundException ex) { Logger.getLogger(mainpage.class.getName()).log(Level.SEVERE, null, ex); } String itemNameInv; int quantityInv; Double costInv; Double priceInv; while (acq_scan.hasNext()) { String line = acq_scan.nextLine(); if (line.charAt(0) == '#') { continue; } String[] split = line.split(,); itemName = split[0]; quantity = Integer.parseInt(split[1]); cost = Double.parseDouble(split[2]); price = Double.parseDouble(split[3]); while(invscan.hasNext()) { String line2 = invscan.nextLine(); if (line2.charAt(0) == '#') { continue; } String[] split2 = line2.split(,); itemNameInv = split2[0]; quantityInv = Integer.parseInt(split2[1]); costInv = Double.parseDouble(split2[2]); priceInv = Double.parseDouble(split2[3]); if(itemName == itemNameInv) { //update quantity } } //add new entry into csv file }Thanks again for any help. =]
Java Scanner class reading strings : I've created a scanner class to read through the text file and get the value what I'm after. Let's assume that I have a text file contains.blockquote List of people: length 3 1 : Fnjiei : ID 7868860 : Age 18 2 : Oipuiieerb : ID 334134 : Age 39 3 : Enekaree : ID 6106274 : Age 31/blockquoteI'm trying to get a name and id number and age, but everytime I try to run my code it gives me an exception. Here's my code. Any suggestion from java gurus?:) It was able to read one single line....... but no more than a single line of text. public void readFile(String fileName)throws IOException{ Scanner input = null; input = new Scanner(new BufferedReader(new FileReader(fileName))); try { while (input.hasNextLine()){ int howMany = 3; System.out.println(howMany); String userInput = input.nextLine(); String name = ; String idS = ; String ageS = ; int id; int age; int count=0; for (int j = 0; j = howMany; j++){ for (int i=0; i userInput.length(); i++){ if(count 2){ // for name if(Character.isLetter(userInput.charAt(i))){ name+=userInput.charAt(i); // store the name }else if(userInput.charAt(i)==':'){ count++; i++; } }else if(count == 2){ // for id if(Character.isDigit(userInput.charAt(i))){ idS+=userInput.charAt(i); // store the id } else if(userInput.charAt(i)==':'){ count++; i++; } }else if(count == 3){ // for age if(Character.isDigit(userInput.charAt(i))){ ageS+=userInput.charAt(i); // store the age } } id = Integer.parseInt(idS); // convert id to integer age = Integer.parseInt(ageS); // convert age to integer Fighters newFighters = new Fighters(id, name, age); fighterList.add(newFighters); } userInput = input.nextLine(); } } }finally{ if (input != null){ input.close(); } }}My appology if my mere code begs to be changed.Edited It gives me a number format exception!!! I dont know how many empty space would be there between these values.
Difference between FetchType LAZY and EAGER in Java Persistence API? : I am a newbie to Java Persistence API and Hibernate. What is the difference between a href=http://docs.oracle.com/javaee/7/api/javax/persistence/FetchType.html rel=nofollow noreferrerFetchType.LAZY and a href=http://docs.oracle.com/javaee/7/api/javax/persistence/FetchType.html rel=nofollow noreferrerFetchType.EAGER in Java Persistence API?
WCF client encrypt message to JAVA WS using username_token with message protection client policy : I am trying to create a WCF client APP that is consuming a JAVA WS that uses username_token with message protection client policy. There is a private key that is installed on the server and a public certificate file was exported from the JKS keystore file. I have installed the public key into certificate store via MMC under Personal certificates. I am trying to create a binding that will encrypt the message and pass the username as part of the payload. I have been researching and trying the different configurations for about a day now. I found a similar situation on the msdn forum:a href=http://social.msdn.microsoft.com/Forums/en/wcf/thread/ce4b1bf5-8357-4e15-beb7-2e71b27d7415 rel=nofollow noreferrerhttp://social.msdn.microsoft.com/Forums/en/wcf/thread/ce4b1bf5-8357-4e15-beb7-2e71b27d7415This is the configuration that I am using in my app.config customBinding binding name=certbinding security authenticationMode=UserNameOverTransport secureConversationBootstrap / /security httpsTransport requireClientCertificate=true / /binding /customBinding endpoint address=https://localhost:8443/ZZZService?wsdl binding=customBinding bindingConfiguration=cbinding contract=XXX.YYYPortType name=ServiceEndPointCfg /And this is the client code that I am using, this is where I am setting the client certificate: EndpointAddress endpointAddress = new EndpointAddress(url + ?wsdl); P6.WCF.Project.ProjectPortTypeClient proxy = new P6.WCF.Project.ProjectPortTypeClient(ServiceEndPointCfg, endpointAddress); proxy.ClientCredentials.UserName.UserName = UserName; proxy.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, 67 87 ba 28 80 a6 27 f8 01 a6 53 2f 4a 43 3b 47 3e 88 5a c1); var projects = proxy.ReadProjects(readProjects);This is the .NET CLient error I get: Error Log:Invalid security information.On the Java WS side I trace the log :SEVERE: Encryption is enabled but there is no encrypted key in the request.I traced the SOAP headers and payload and did confirm the encrypted key is not there.Headers: {expect=[100-continue], content-type=[text/xml; charset=utf-8], connection=[Keep-Alive], host=[localhost:8443], Content-Length=[731], vsdebuggercausalitydata=[uIDPo6hC1kng3ehImoceZNpAjXsAAAAAUBpXWdHrtkSTXPWB7oOvGZwi7MLEYUZKuRTz1XkJ3soACQAA], SOAPAction=[], Content-Type=[text/xml; charset=utf-8]}Payload: s:Envelope xmlns:s=http://schemas.xmlsoap.org/soap/envelope/ xmlns:u=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsds:Headero:Security s:mustUnderstand=1 xmlns:o=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsdo:UsernameToken u:Id=uuid-5809743b-d6e1-41a3-bc7c-66eba0a00998-1o:Usernameadmin/o:Usernameo:Passwordadmin/o:Password/o:UsernameToken/o:Security/s:Headers:Body xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchemaReadProjects xmlns=http://xmlns.dev.com/WS/Project/V1FieldObjectId/FieldFilterId='WS-Demo'/Filter/ReadProjects/s:Body/s:EnvelopeI have also tryed some other bindings but with no success: basicHttpBinding binding name=basicHttp security mode=TransportWithMessageCredential message clientCredentialType=Certificate/ /security /binding /basicHttpBinding wsHttpBinding binding name=wsBinding security mode=Message message clientCredentialType=UserName negotiateServiceCredential=false / /security /binding /wsHttpBindingYour help will be greatly aprreciatted! Thanks!update2:More information, I was able to get further but still no cigar :(I modified the app.config binding section the authenticationMode to UserNameForCertificate and specified the textMessageEncoding to use Soap1.1 binding name=certbinding security authenticationMode=UserNameForCertificate includeTimestamp=false secureConversationBootstrap / /security textMessageEncoding messageVersion=Soap11 / httpsTransport requireClientCertificate=true / /bindingmodified the endpoint entry to include identity to get around some certificates warning caused due to mismatch of dns entries, that got me further.client endpoint address=https://localhost:8443/p6ws/services/ProjectService?wsdl binding=customBinding bindingConfiguration=certbinding contract=P6.WCF.Project.ProjectPortType name=ProjectServiceEndPointCfg identity dns value=localhost/ /identity /endpointSpecified in the client code ServiceCertificate P6.WCF.Project.ProjectPortTypeClient proxy = new P6.WCF.Project.ProjectPortTypeClient(ProjectServiceEndPointCfg); proxy.ClientCredentials.UserName.UserName = UserName; proxy.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust; proxy.ClientCredentials.ServiceCertificate.Authentication.TrustedStoreLocation = System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine; proxy.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, 67 87 ba 28 80 a6 27 f8 01 a6 53 2f 4a 43 3b 47 3e 88 5a c1); proxy.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, 67 87 ba 28 80 a6 27 f8 01 a6 53 2f 4a 43 3b 47 3e 88 5a c1);Now tracing the SOAP I get an encrypted message:Payload: s:Envelope xmlns:s=http://schemas.xmlsoap.org/soap/envelope/ xmlns:u=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsds:Headero:Security s:mustUnderstand=1 xmlns:o=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsdu:Timestamp u:Id=uuid-c011a1a6-3878-4bbd-b6d1-84c7bf1539fe-2u:Created2010-06-07T22:22:52.250Z/u:Createdu:Expires2010-06-07T22:27:52.250Z/u:Expires/u:Timestampe:EncryptedKey Id=uuid-c011a1a6-3878-4bbd-b6d1-84c7bf1539fe-1 xmlns:e=http://www.w3.org/2001/04/xmlenc#e:EncryptionMethod Algorithm=http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1pDigestMethod Algorithm=http://www.w3.org/2000/09/xmldsig#sha1 xmlns=http://www.w3.org/2000/09/xmldsig#//e:EncryptionMethodKeyInfo xmlns=http://www.w3.org/2000/09/xmldsig#o:SecurityTokenReferenceo:KeyIdentifier ValueType=http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1Z4e6KICmJ/gBplMvSkM7Rz6IWsE=/o:KeyIdentifier/o:SecurityTokenReference/KeyInfoe:CipherDatae:CipherValueDdoi36zRBd+82HQ5rPFxhNXu1nCI8qxRiMtTIm2ldE69AgVbdRtXsHiLKXN6Tsk96U4NjVG/OkCELn7PLHX2CGY/+MH7fDro667RMdOyjlLBzjefO1m/JLTrdGPaHEQmVub/UtriIvwCm4sY8YE35g6Ej8FhABgqQlsvwBi6f3g=/e:CipherValue/e:CipherData/e:EncryptedKeyc:DerivedKeyToken u:Id=_0 xmlns:c=http://schemas.xmlsoap.org/ws/2005/02/sco:SecurityTokenReferenceo:Reference URI=#uuid-c011a1a6-3878-4bbd-b6d1-84c7bf1539fe-1//o:SecurityTokenReferencec:Offset0/c:Offsetc:Length24/c:Lengthc:NoncekA1uT+jG8DCnw4PWLCpBJA==/c:Nonce/c:DerivedKeyTokenc:DerivedKeyToken u:Id=_1 xmlns:c=http://schemas.xmlsoap.org/ws/2005/02/sco:SecurityTokenReferenceo:Reference URI=#uuid-c011a1a6-3878-4bbd-b6d1-84c7bf1539fe-1//o:SecurityTokenReferencec:Nonce9Y5iCPnq9mKvRzE91EbecA==/c:Nonce/c:DerivedKeyTokene:ReferenceList xmlns:e=http://www.w3.org/2001/04/xmlenc#e:DataReference URI=#_3/e:DataReference URI=#_4/e:DataReference URI=#_5//e:ReferenceListe:EncryptedData Id=_5 Type=http://www.w3.org/2001/04/xmlenc#Element xmlns:e=http://www.w3.org/2001/04/xmlenc#e:EncryptionMethod Algorithm=http://www.w3.org/2001/04/xmlenc#aes256-cbc/KeyInfo xmlns=http://www.w3.org/2000/09/xmldsig#o:SecurityTokenReferenceo:Reference URI=#_1//o:SecurityTokenReference/KeyInfoe:CipherDatae:CipherValueUE2UhcjwBsETg0Ndu26Gwdvp1UQk6sLJTT8KtSO7B5oykoBGazhrzu5XAQMCQfnlnZM+u8Gq3BLiEtIHb3SWue3i18yr20z8ZwVoHwI/TSNBjdOcfvyD7PF2YxFg/wYMKgY8dnRi8XVO/zWmVLbyd2GT7N1GoaaknkdECjWjVrkdsKlP8/AyprxgRnNJmqTcXUUoamwEeMeU0Y8qfKj3sUreVmPEXOe646JP2SF6pTyVnKSEjL1+TDbhiwOemienKZyNFj+C+JuUQLp/89Cb3hYedb6jWm7JZ1YO8bUy6CqI9Ux6mFxR2n12sDDZ1o1RoxEbR7jHsJJTP0MU2O6TmU4AquJgcldHS60joZy8iCXg24NHoERVI6BnQrEN4WT19E/HkInsUVQSBYTYpRTI1ZyimOX6Y9dgGDxH7tKY4fY=/e:CipherValue/e:CipherData/e:EncryptedDatae:EncryptedData Id=_4 Type=http://www.w3.org/2001/04/xmlenc#Element xmlns:e=http://www.w3.org/2001/04/xmlenc#e:EncryptionMethod Algorithm=http://www.w3.org/2001/04/xmlenc#aes256-cbc/KeyInfo xmlns=http://www.w3.org/2000/09/xmldsig#o:SecurityTokenReferenceo:Reference URI=#_1//o:SecurityTokenReference/KeyInfoe:CipherDatae:CipherValueqxX35B+cNLG64jgBkmop3+G1rVaQuJnkEyzENod9BvRzXAyqApPX7d3hW3KicJYdk077Ks+AXZE26HO85BqwsdxeNfx1ECXM6YdpxZzHtgqMMfGhaEZI3fh4dgxw3XLnEPa+D2N2lG4qPpxKk/s1M19acAKkaCcgu3NRZbuSHx+jXt3+oZjhITSz5ij5n7FlvKLzyI78/TOWJSrrIOuDBn9mBg1M4TL24USzt1iCGOWQjESSLkQR4u047t5TOZ14SHpdyyr9ZRc+f0QiDZi6Eg2nf+zP5dwSBuqO6KDf0Ws+4jr/g3Y8fczKcbl/gBm0TS/vrMq+uMNSYjLz85CxBZh0xqCJLcTbVKUlqjVHtq+lstSITR1R/mw/j2e1ReHzIGFAfyTS12V7Vygf2tDNbq4fxyafMHPibSDrvQ2brvS6Na04FChyIU2QAoC7Dh9e+gs1IAnLrUCyhmv05kkCxMduN1WAAysRzaghQzn8GzgkmjaiHeqtdI2XOGA6PiAvEcJqBlvL9Z/sxSPiz5K4e4j7TK/yM8ACvKD4O1nAhsSeuX+eW6rrjEW8AfrTJDVV13XHtD/E7o8jqwVUD/rZZaYQJBJGp9axgDhHTGtBDG/sKL+GWEg3/iGnLv+l/NSRMEh3m8tSCBhzePmwJy6iUq2dWYbRUsBL1yeRjutSG+HsZHQjpjmwk2+akYTEk6FoI4MEZEplE3ksNzZUxmdN8cmjNndvYZ1jXKEvzO9loGFzE+77pQyld5IRN6l06BwE7cPc9McXRu84JRvqmEXj+bpwNMGAdM4/NOOinsDDguObue6A3hrbSHZ0dnFmNzaw9qfv+PHWPHB/pWiAmJ3ZY/jBpjucZq4hczIkBlzV5QKbeatIw11ej+1Tluc5maF/FXeuvvrQCrfxVuXF2n+1x+1jXqRQfmRCVdoW5kuokLdCG0cGYt0EZeiuo8rzwNa81fgcjFX7jbcNBTIKZUhWvEXdG6pqryhz2qrpO791XGd/wIkNzUMbCfbDgKtq+zQJLoF102kzFV153h6c0r3jfZS87NBzAVQZ87aYzw1BkQubYhe8tgMtkQAQ0FR25MxzG9i4w8IoT7B3o/Y9YXDIpMY6b1dFhMp0ExUfiHYHl5MypG2hPuzHWf/Ko3yjIiHYd+d6o/9wZCyAK5Uz8/XVgM1OK+94Swkx5LeLQXtjfNu7nC2HXVeGBDypMH+/1IIxwG97We3h2JHU9J9I88l9Xk2Q8gF5TR/1K61umgMscZDWG/g+zwat0mUQtaP8L5yYxTaSCyfP/oxkjBlqyIbEoXs40nyZMnMgAnSDXMznAogPRhueKvJ1u+TzEeqMZntdYNRqL6iY/eMhZJbiwaCh74+V3ccg79R1c6L0/CIMHX0cdxpteUJbMVk8Ocegkp51efkHPd/ZVck0hX7l+u5aqGONngBd/ylYbv2+TMzCV7bJAvD/Khlvs2vLUN8KYyT8jmuBF1PygiyEJ9bXhf6B3xCnc6REtVwZa76l5MiyOQ+8pBPOHbmiFUD0CdbsiBjlQVwh+G/bAkCvV1qXOCK89MKHiaMro7CTrdplTJi5z7X/Pm2/Cfbe14ieXfm8SZ0Bnb+hVW17x+EgXOyxTywBW6sJlQqZAXtg55RlIvds3whZnD8btOQcwy71oZx7r+lscjjQjBL1OucJ05b525iJMIF41EI1iJ7sc1x39Vm0dNAtGh9fubWpUnyRimGMiLV3MNtjws7OzQsun/aLLHqqSy4lAQ0drDc4OCvOeBsCUgI=/e:CipherValue/e:CipherData/e:EncryptedData/o:Security/s:Headers:Body u:Id=_2 xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchemae:EncryptedData Id=_3 Type=http://www.w3.org/2001/04/xmlenc#Content xmlns:e=http://www.w3.org/2001/04/xmlenc#e:EncryptionMethod Algorithm=http://www.w3.org/2001/04/xmlenc#aes256-cbc/KeyInfo xmlns=http://www.w3.org/2000/09/xmldsig#o:SecurityTokenReference xmlns:o=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsdo:Reference URI=#_1//o:SecurityTokenReference/KeyInfoe:CipherDatae:CipherValue07kyxqZy7AXCol4rmwkY9wDC4LVTFqVlGMD7smF5F68L00ndc6yEvuvTKJlb9wN1u0gPfgpIpvMBL2+aio8r2e/uHiseFSEGJhiOtWjpZutmaRkZyJ8xkph2sOO1EUxWUb3X+c32PMTs2RxCGncMBQczf/zXCv9IzWCxZymv8mcIkY2F95N2/6aqWCAqOQxnbOHAH6H13hHv/RCw6kHBNV7abtoY3q9xIFfh98nkf4a5u+jfl8KzMtsSI86kiLCVgMSfS8wSHVdhimkfwT+WSk1PJAqw47WR5ZsbGdHWofbS4fc59djSIwkaWZaJ5Z4biS3rbqSuPzk76F3ItLMWXQ==/e:CipherValue/e:CipherData/e:EncryptedData/s:Body/s:EnvelopeHowever on the JAVA WS side I get this error message:blockquote org.apache.cxf.binding.soap.SoapFault: Username token not found while trying to perform authentication./blockquoteAnd the spec that the JAVA Ws uses expects to encrypt the message and pass the username as part of the payload. Any suggestions on how to make sure the username also gets passed now? As you on the above client code I am setting the UserName. proxy.ClientCredentials.UserName.UserName = UserName;
Java stored procedure : I have the following Java stored procedure:CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED RetreiveLdap ASimport java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Hashtable;import javax.naming.Context;import javax.naming.NamingEnumeration;import javax.naming.NamingException;import javax.naming.directory.DirContext;import javax.naming.directory.InitialDirContext;import javax.naming.directory.SearchControls;import javax.naming.directory.SearchResupublic class RetreiveLdap { // LDAP CONFIG public static String CONTEXT = com.sun.jndi.ldap.LdapCtxFactory; public static String HOST = ldap://192.168.30.12:389; public static String USER = cn=root,dc=company; public static String PASSWORD = pa55w0rd; public static String BASE = dc=company; // Reads from LDAP public static void readConfig() throws NamingException, SQLException { try { addUser(tmp, tmp); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, CONTEXT); env.put(Context.PROVIDER_URL, HOST); env.put(Context.SECURITY_PRINCIPAL, USER); env.put(Context.SECURITY_CREDENTIALS, PASSWORD); DirContext ctx = new InitialDirContext(env); SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = (objectClass=person); NamingEnumeration items = ctx.search(BASE, filter, sc); System.out.println(STARTING...); while (items != null amp;amp; items.hasMore()) { SearchResult sr = (SearchResult) items.next(); String cn = (String) sr.getAttributes().get(cn).get(); String sn = (String) sr.getAttributes().get(sn).get(); System.out.println(WORKING...); // save to table addUser(cn, sn); } } catch (Exception e) { e.printStackTrace(); } } // Add LDAP user to DB. public static void addUser(String cn, String sn) { try { Connection conn = DriverManager .getConnection(jdbc:default:connection:); String sql = INSERT INTO ldapuser + (cn,sn) + VALUES(?,?); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, cn); pstmt.setString(2, sn); pstmt.executeUpdate(); pstmt.close(); } catch (SQLException e) { System.err.println(ERROR: + e.getMessage()); } }}/And I create a procedure that will run the above like;CREATE OR REPLACE PROCEDURE read_ldap AS LANGUAGE JAVA NAME 'RetreiveLdap.readConfig()';/Now, when I run this class normally from java it works fine, it retrieves the list of LDAP user and saves them into the DB, (of course without the create or replace...)But when I run it as a procedure in Oracle the users form LDAP do not get added to the table. I have added the addUser(tmp, tmp); just to see if my codes executes well, and with this line a user does get inserted, but none in the while loopIs there a way to see some errors, when I run this procedure?
Is there a 100% Java alternative to ImageIO for reading JPEG files? : We are using Java2D to resize photos uploaded to our website, but we run into an issue (a seemingly old one, cf.: a href=http://forums.sun.com/thread.jspa?threadID=5425569 rel=nofollow noreferrerhttp://forums.sun.com/thread.jspa?threadID=5425569) - a few particular JPEGs raise a CMMException when we try to ImageIO.read() an InputStream containing their binary data:java.awt.color.CMMException: Invalid image format at sun.awt.color.CMM.checkStatus(CMM.java:131) at sun.awt.color.ICC_Transform.init(ICC_Transform.java:89) at java.awt.image.ColorConvertOp.filter(ColorConvertOp.java:516) at com.sun.imageio.plugins.jpeg.JPEGImageReader.acceptPixels(JPEGImageReader.java:1114) at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(Native Method) at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1082) at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:897) at javax.imageio.ImageIO.read(ImageIO.java:1422) at javax.imageio.ImageIO.read(ImageIO.java:1326) ...(snipped the remainder of the stack trace, which is our ImageIO.read() call, servlet code and such)We narrowed it down to photos taken on specific cameras, and I selected a photo that triggers this error: a href=http://img214.imageshack.us/img214/5121/estacaosp.jpg rel=nofollow noreferrerhttp://img214.imageshack.us/img214/5121/estacaosp.jpg. We noticed that this only happens with Sun's JVM (on Linux and Mac, just tested it on 1.6.0_20) - a test machine with OpenJDK reads the same photos without a hitch, possibly due to a different implementation of the JPEG reader.Unfortunately, we are unable to switch JVMs in production, nor to use native-dependent solutions such as ImageMagick ( a href=http://www.imagemagick.org/ rel=nofollow noreferrerhttp://www.imagemagick.org/ ).Considering that, my question is: Does a replacement for ImageIOs JPEG reader which can handle photos such as the linked one exist? If not, is there another 100% pure Java photo resizing solution which we can use?Thank you!
Tomcat6 ignores logging.properties partially : I'm using Tomcat 6, and this is my logging.properties:handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler.level=FINEorg.apache.catalina.core.ApplicationContext.level = OFForg.apache.juli.FileHandler.level = ALLorg.apache.juli.FileHandler.directory = ${catalina.base}/logsorg.apache.juli.FileHandler.prefix = mylog.java.util.logging.ConsoleHandler.level = FINEjava.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatterOn the one hand, Tomcat seems to read this file, as it correctly saves the logfiles with the prefix mylog and prints only messages with log-level FINE and above. On the other hand, it keeps on writing log messages like this:Jun 8, 2010 9:53:30 PM org.apache.catalina.core.ApplicationContext logSEVERE: Error writing messagesClientAbortException: java.net.SocketException: Broken pipeI actually wanted to suppress all log messages from this class, as they flood my logfile, and the error is irrelevant for me. So why is the following line ignored?org.apache.catalina.core.ApplicationContext.level = OFFIs there any other way to suppress the log output of this class?
How to specify a JRE range in jnlp file? : We have a java app which uses Java Web Start. The jnlp file is configured with [j2se version=1.5+]. So if JRE 1.5 and 1.6 are installed, the app is run on 1.6.Now, we have requirement where the app should be restricted to run only within the range - JRE 1.5.0_07 through JRE 1.5.0_17 [j2se version=1.5*] will not work - it will always launch the app with the latest jre from 1.5 family.I can request an exact product version by including the href attribute. [j2se version=1.5.0_14 href=http://java.sun.com/products/autodl/j2se/]But how do I specify a specific range of JREs in the jnlp file so that JWS picks up a JRE from that range only? So if 1.5.0_07, 1.5.0_17 and JRE 6 are installed, it should run the app on 1.5.0_17. Is there a good way to accomplish this?
Visibility of properties in scala class : I defined a property in the constructor of my class the following way:class Step(val message:String = )When I try access to message value from Java code y get a visbility error. Why?
Connection details timeouts in a java web service client : I have to implement a webservice client to a given WSDL file.I used the SDK's 'wsimport' tool to create Java classes from the WSDL as well as a class that wrap's the webservice's only method (enhanceAddress(auth, param, address)) into a simple java method. So far, so good. The webservice is functional and returning results correcty. The code looks like this:try { EnhancedAddressList uniservResponse = getWebservicePort().enhanceAddress(m_auth, m_param, uniservAddress); //Where the Port^ is the HTTP Soap 1.2 Endpoint}catch (Throwable e) { throw new AddressValidationException(Error during uniserv webservice request., e);}The Problem now: I need to get Information about the connection and any error that might occur in order to populate various JMX values (such as COUNT_READ_TIMEOUT, COUNT_CONNECT_TIMEOUT, ...)Unfortunately, the method does not officially throw any Exceptions, so in order to get details about a ConnectException, i need to use getCause() on the ClientTransportException that will be thrown.Even worse: I tried to test the read timeout value, but there is none. I changed the service's location in the wsdl file to post the request to a php script that simply waits forever and does not return. Guess what: The web service client does not time out but waits forever as well (I killed the app after 30+ minutes of waiting). That is not an option for my application as i eventually run out of tcp connections if some of them get 'stuck'.The enhanceAddress(auth, param, address) method is not implemented but annotated with javax.jws.* Annotations, meaning that i cannot see/change/inspect the code that is actually executed.Do i have any option but to throw the whole wsimport/javax.jsw-stuff away and implement my own soap client?
Improving field get and set performance with ASM or Javassist : I would like to avoid reflection in an open source project I am developing. Here I have classes like the following.public class PurchaseOrder { @Property private Customer customer; @Property private String name;}I scan for the @Property annotation to determine what I can set and get from the PurchaseOrder reflectively. There are many such classes all using java.lang.reflect.Field.get() and java.lang.reflect.Field.set().Ideally I would like to generate for each property an invoker like the following.public interface PropertyAccessorS, V { public void set(S source, V value); public V get(S source);}Now when I scan the class I can create a static inner class of PurchaseOrder like so.static class customer_Field implements PropertyAccessorPurchaseOrder, Customer { public void set(PurchaseOrder order, Customer customer) { order.customer = customer; } public Customer get(PurchaseOrder order) { return order.customer; }}With these I totally avoid the cost of reflection. I can now set and get from my instances with native performance. Can anyone tell me how I would do this. A code example would be great. I have searched the net for a good example but can find nothing like this. The ASM and Javasist examples are pretty poor also.The key here is that I have an interface that I can pass around. So I can have various implementations, perhaps one with Java Reflection as a default, one with ASM, and one with Javassist?Any help would be greatly appreciated.
Unable to acquire image through ImageIO.read(url) because of connection timed out : The following code always seems to fail: URL url = new URL(http://userserve-ak.last.fm/serve/126/8636005.jpg); Image img = ImageIO.read(url); System.out.println(img);I've checked the url, and it is a valid jpg image. The error I get is:blockquote Exception in thread main javax.imageio.IIOException: Can't get input stream from URL! at javax.imageio.ImageIO.read(ImageIO.java:1385) at maestro.Main2.main(Main2.java:25) Caused by: java.net.ConnectException: Connection timed out at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:310) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:176) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:163) at java.net.Socket.connect(Socket.java:546) at java.net.Socket.connect(Socket.java:495) at sun.net.NetworkClient.doConnect(NetworkClient.java:174) at sun.net.www.http.HttpClient.openServer(HttpClient.java:409) at sun.net.www.http.HttpClient.openServer(HttpClient.java:530) at sun.net.www.http.HttpClient.(HttpClient.java:240) at sun.net.www.http.HttpClient.New(HttpClient.java:321) at sun.net.www.http.HttpClient.New(HttpClient.java:338) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:814) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:755) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:680) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1005) at java.net.URL.openStream(URL.java:1029) at javax.imageio.ImageIO.read(ImageIO.java:1383) ... 1 more Java Result: 1/blockquoteWhat does this mean?Funny thing is, if I change my internet-connection to that of the neighbour's wireless, it suddenly works.
JAXB marshals XML differently to OutputStream vs. StringWriter : I apologize if this has been answered, but the search terms I have been using (i.e. JAXB @XmlAttribute condensed or JAXB XML marshal to String different results) aren't coming up with anything.I am using JAXB to un/marshal objects annotated with @XmlElement and @XmlAttribute annotations. I have a formatter class which provides two methods -- one wraps the marshal method and accepts the object to marshal and an OutputStream, the other just accepts the object and returns the XML output as a String. Unfortunately, these methods do not provide the same output for the same objects. When marshaling to a file, simple object fields internally marked with @XmlAttribute are printed as: element value=VALUE/elementwhile when marshaling to a String, they are: element value=VALUE/I would prefer the second format for both cases, but I am curious as to how to control the difference, and would settle for them being the same regardless. I even created one static marshaller that both methods use to eliminate different instance values. The formatting code follows:/** Marker interface for classes which are listed in jaxb.index */public interface Marshalable {}/** Local exception class */public class XMLMarshalException extends BaseException {}/** Class which un/marshals objects to XML */public class XmlFormatter { private static Marshaller marshaller = null; private static Unmarshaller unmarshaller = null; static { try { JAXBContext context = JAXBContext.newInstance(path.to.package); marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, UTF-8); unmarshaller = context.createUnmarshaller(); } catch (JAXBException e) { throw new RuntimeException(There was a problem creating a JAXBContext object for formatting the object to XML.); } } public void marshal(Marshalable obj, OutputStream os) throws XMLMarshalException { try { marshaller.marshal(obj, os); } catch (JAXBException jaxbe) { throw new XMLMarshalException(jaxbe); } } public String marshalToString(Marshalable obj) throws XMLMarshalException { try { StringWriter sw = new StringWriter(); return marshaller.marshal(obj, sw); } catch (JAXBException jaxbe) { throw new XMLMarshalException(jaxbe); } }}/** Example data */@XmlType@XmlAccessorType(XmlAccessType.FIELD)public class Data { @XmlAttribute(name = value) private String internalString;}/** Example POJO */@XmlType@XmlRootElement(namespace = project/schema)@XmlAccessorType(XmlAccessType.FIELD)public class Container implements Marshalable { @XmlElement(required = false, nillable = true) private int number; @XmlElement(required = false, nillable = true) private String word; @XmlElement(required = false, nillable = true) private Data data;}The result of calling marshal(container, new FileOutputStream(output.xml)) and marshalToString(container) are as follows:Output to file ?xml version=1.0 encoding=UTF-8 standalone=yes? ns2:container xmlns:ns2=project/schema number1/number wordstackoverflow/word data value=This is internal/data /ns2:containerandOutput to String ?xml version=1.0 encoding=UTF-8 standalone=yes? ns2:container xmlns:ns2=project/schema number1/number wordstackoverflow/word data value=This is internal/ /ns2:container
Can I invoking java web start in program? : I want to make use of the java web start advantage,but I dont want our customer face the java web start loading Screen,it seems ugly...and also customer maybe not install jre and the jre-install maybe fussy to them..so I want to package our application and jre into setup file using installanywhere. when user start our program,I want to invoking web start API to do the work like version compare,and offer outself loading screen ..so,Can I invoking web start in my program?and how?Best regardsL.J.W
Where does java.util.logging.Logger store their log : This might be a stupid question but I am a bit lost with java Logger private static Logger logger = Logger.getLogger(order.web.OrderManager);logger.info(Removed order + id + .);Where do I see the log? Also this quote from java.util.logging.Logger library: blockquote On each logging call the Logger initially performs a cheap check of the request level (e.g. SEVERE or FINE) against the effective log level of the logger. If the request level is lower than the log level, the logging call returns immediately. After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers.`/blockquoteDoes this mean that if I have 3 request level log:logger.log(Level.FINE, Something);logger.log(Level.WARNING, Something);logger.log(Level.SEVERE, Something);And my log level is SEVERE, I can see all three logs, and if my log level is WARNING, then I can't see SEVERE log, is that correct? And how do I set the log level?
Copy image to BLOB from client pc aka Java function in Oracle : I've been stuck with this for past two days. I've go java function stored in Oracle system which is supposed to copy image from local drive do remote database and store it in BLOB - it's called CopyBLOB and looks like this: import java.sql.*; import oracle.sql.*; import java.io.*;public class CopyBLOB { static int id; static String fileName = null; static Connection conn = null; public CopyBLOB(int idz, String f) { id = idz; fileName = f; } public static void copy(int ident, String path) throws SQLException, FileNotFoundException { CopyBLOB cpB = new CopyBLOB(ident, path); cpB.getConnection(); cpB.callUpdate(id, fileName); } public void getConnection() throws SQLException { DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); try { conn = DriverManager.getConnection(jdbc:oracle:thin:@oraserv.ms.mff.cuni.cz:1521:db, xxx, xxx); } catch (SQLException sqlex) { System.out.println(SQLException while getting db connection: +sqlex); if (conn != null) conn.close(); } catch (Exception ex) { System.out.println(Exception while getting db connection: +ex); if (conn != null) conn.close(); } } public void callUpdate(int id, String file ) throws SQLException, FileNotFoundException { CallableStatement cs = null; try { conn.setAutoCommit(false); File f = new File(file); FileInputStream fin = new FileInputStream(f); cs = (CallableStatement) conn.prepareCall( begin add_image(?,?); end; ); cs.setInt(1, id ); cs.setBinaryStream(2, fin, (int) f.length()); cs.execute(); conn.setAutoCommit(true); } catch ( SQLException sqlex ) { System.out.println(SQLException in callUpdateUsingStream method of given status : + sqlex.getMessage() ); } catch ( FileNotFoundException fnex ) { System.out.println(FileNotFoundException in callUpdateUsingStream method of given status : + fnex.getMessage() ); } finally { try { if (cs != null) cs.close(); if (conn != null) conn.close(); } catch ( Exception ex ) { System.out.println(Some exception in callUpdateUsingStream method of given status : + ex.getMessage( ) ); } } }}The wrapper function is defined in package MyPackage as folows: procedure image_adder( id varchar2, path varchar2 ) AS language java name 'CopyBLOB.copy(java.lang.String, java.lang.String)';And the inserting function called image_add is as simple as this:procedure add_image( id numeric(10), pic blob) AS BEGIN insert into pictures values (seq_pic.nextval, id, pic); END add_image;Now the problem: When I type call MyPackage.image_adder(1, 'd:\samples\img.jpg');I get the ORA-29531 Error: No method copy in class CopyBLOB.Can you help me, please?
Java service wrapper and additional application command line parameters : I'm currently using a href=http://wrapper.tanukisoftware.org/doc/english/download.jsp rel=nofollow noreferrerjava service wrapper to wrap a java application that I've developed. I'm needing to ability to pass in additional command line parameters to my application through the java service wrapper.Pretend my app is called myapp and I've setup java service wrapper so that the script I run to start is called myapp. I'd like to be able to do something like this:./myapp start Parameter1 parameter2and have those additional parameters get passed into my application. Any ideas how to do this? I'm finding that googling and looking at the documentation is only pulling up how to use command line arguments to setup java service wrapper. I've had difficulty finding anything about passing command line arguments to your application except for having them hard coded in your wrapper.conf file.Right now I feel like my option is to take the additional command line parameters, set them to environment variables and have those hard coded in the wrapper.conf. I'd prefer not to go down that road though and am hoping I've overlooked something.
Is there known issues for JWS applications on Windows 7? : I've got a JWS application which works perfectly on Windows XP but fails to start on Windows 7. The problem is that Java is not able to find the native library which is embeded in a JAR bundle:UnsatisfiedLinkError: no xxxxxx.dll in java.library.pathThe problem is not in the DLL (missing dependency for example) because if I put it in C:\windows\system32\, the JWS application works.So I want to know if there are some known issues which can explain that Java is not able to load/find a well-served native library on Windows 7?
Compatibility between Scala closures and Java 8 closures : After reading some OpenJDK mailinglist entries, it seems that the Oracle developers are currently further removing things from the closure proposal, because earlier design mistakes in the Java language complicate the introduction of the Java closures.Considering that Scala closures are much more powerful than the closures planned for Java 8, I wonder if it will be possible to e. g. call a Java method taking a closure from Scala, defining a closure in Java and giving it to a Scala function etc.?So will Java closures be represented like their Scala counterparts in bytecode or differently?Will it be possible to close the gap of functionality between Java/Scala closures?
How can I RUN JAVAWS command line in text-mode Linux environment? : I want to RUN JAVAWS command line in text-mode Linux environment and I have not X.Is it possible? Tanx
MPXJ in .NET converting java Date to .NET DateTime : I'm using the MPXJ library in .NET for parsing MS Project (MPP) files, and it's working great. The one issue I'm having is trying to translate the task Start and Finish date into .NET DateTime to use with my data models.I am going through all the tasks and calling task.getFinish() and task.getStart() that both return javva.util.Date objects.When I use task.getFinish().getYear(), task.getFinish().getMonth(), etc. to build up a new DateTime object it warns me that they are obsolete.What is the best way to get the start and finish dates from MPXJ into a .NET DateTime object?Thanks.
Validating input using java.util.Scanner : I'm taking user input from System.in using a java.util.Scanner. I need to validate the input for things like:It must be a non-negative numberIt must be an alphabetical letter... etcWhat's the best way to do this?
bridge methods explaination : If I do an override of a clone method the compiler create a bridge method toguarantee a correct polymorphism (THIS IS THE CLASS DECOMPILED)class Point{ Point() { } protected Point clone() throws CloneNotSupportedException { return this; // not good only for example!!! } protected volatile Object clone() throws CloneNotSupportedException { return clone(); }}so when is invoked the clone method the bridge method is invoked and inside it is invoked the correct clone method. But my question is when into the bridge method is called return clone() how do the VM to say that it must invoke Point clone() and not itself again???
Can you jump a scanner to a location in file or scan backwards? : I have a very large text file and I need to gather data from somewhere near the end. Maybe Scanner isn't the best way to do this but it would be very wasteful to start at the top and grab 6000 lines before getting to the part of the file I am interested in. Is there a way to either tell Scanner to jump to say 7/8ths down the document or start from the bottom and scan upwards grabbing line by line?Thanks
Non class files with Java Web Start : How do you distribute other files needed by your application that aren't in a jar file? For example, the application at a href=http://www.javabeginner.com/java-swing/java-swing-shuffle-game rel=nofollow noreferrerhttp://www.javabeginner.com/java-swing/java-swing-shuffle-game . The download contains Shuffle.jar, Shuffle.bat, Score.dat, and an images folder with 3 images in it. I can see possibly putting the images directly in Shuffle.jar, but you wouldn't want to put Score.dat in the jar file because it changes. Is there somewhere you could identify this type of file in the jnlp?
Does a java agent run in a separate thread? : I feel that this is something I should know, but does a java agent (specified with -javaagent) run in a separate thread? I've read that a href=http://www.javalobby.org/java/forums/t19309.html rel=nofollow noreferrera Java agent is a pluggable library that runs embedded in a JVM and intercepts the classloading process, but I want to make sure: does it really intercept them (which sounds like it's running in another thread and monitoring class loads) or is it notified by the JVM (the JVM invokes it to resolve the class load; there isn't a separate thread for it)?Again, I get the feeling that I should be able to figure it out, but be nice to me, I'm working too hard and my brain is kinda fried :PThanks!
What port is used by Java Web Start? : May I know what port is used by Java Web Start? If I want to connect a Java Web Start client to a Java Web Start server, what port I need to open at the server side so that the client can connect to it?I want to set up a firewall in the server machine but I don't know which port I should open.Thanks.
JDK 6: Is there a way to run a new java process that executes the main method of a specified class : I'm trying to develop an application that just before quit has to run a new daemon process to execute the main method of a class.I require that after the main application quits the daemon process must still be in execution.It is a Java Stored Procedure running on Oracle DB so I can't use Runtime.exec because I can't locate the java class from the Operating System Shell because it's defined in database structures instead of file system files.In particular the desired behavior should be that during a remote database session I should be able tocall the first java method that runs the daemon process and quits leaving the daemon process in execution stateand then (having the daemon process up and the session control, because the last call terminated) consequentially call a method that communicates with the daemon process (that finally quits at the end of the communication)Is this possible?ThanksUpdateMy exact need is to create and load (reaching the best performances) a big text file into the database supposing that the host doesn't have file transfer services from a Java JDK6 client application connecting to Oracle 11gR1 DB using JDBC-11G oci driver.I already developed a working solution by calling a procedure that stores into a file the LOB(large database object) given as input, but such a method uses too many intermediate structures that I want to avoid.So I thought about creating a ServerSocket on the DB with a first call and later connect to it and establish the data transfer with a direct and fast communication. The problem I encountered comes out because the java procedure that creates the ServerSocket can't quit and leave an executing Thread/Process listening on that Socket and the client, to be sure that the ServerSocket has been created, can't run a separate Thread to handle the rest of the job.Hope to be clear
How to execute a jax-ws soap request from a string or inputstream : I am using jax-ws ri (metro) and would like to execute a webservice call without an http container. I have an XML file containing the SOAP message (exactly the same as the HTTP POST BODY) and would like to execute in the same virtual machine a soap action. How can I do this?SOAP MESSAGE AS XML FILE - WS Endpoint or Port - SOAP MESSAGE AS XML STRING OR FILEHas anyone an idea or example?Thank you,Maciej
Java WebStart JNLP: Run Different Code in First Run : We are using WebStart JNLP file to create a shortcut on our users` desktop.The problem is that we would like the code in our jar file to be launched only when the user press the desktop shortcut.However, Java WebStart executes the jar also on the first launch (when we set the desktop icon).Is there any way we can set the icon without running the jar, but to launch the jar when the user press the desktop icon?
Restrict string input from user to alphabetic and numerical values : Basically, my situation requires me to check to see if the String that is defined by user input from the keyboard is only alphabetical characters in one case and only digits in another case. This is written in Java.my current code:switch (studentMenu) { case 1: // Change all four fields System.out.println(Please enter in a first name: ); String firstNameIntermediate = scan.next(); firstName = firstNameIntermediate.substring(0,1).toUpperCase() + firstNameIntermediate.substring(1); System.out.println(Please enter in a middle name); middleName = scan.next(); System.out.println(Please enter in a last name); lastName = scan.next(); System.out.println(Please enter in an eight digit student ID number); changeID(); break; case 2: // Change first name System.out.println(Please enter in a first name: ); firstName = scan.next(); break; case 3: // Change middle name System.out.println(Please enter in a middle name); middleName = scan.next(); break; case 4: // Change last name System.out.println(Please enter in a last name); lastName = scan.next(); case 5: // Change student ID: changeID(); break; case 6: // Exit to main menu menuExit = true; default: System.out.println(Please enter a number from 1 to 6); break; } } }public void changeID() { studentID = scan.next(); }I need to make sure the StudentID is only numerical and each of the name segments are alphabetical.
Webstat Code signing certificate for open source project : I am looking for a code signing certificate that will be accepted by Java Webstart. It is for the a href=http://arianne.sf.net rel=nofollow noreferrerArianne Project (a a href=http://sourceforge.net/blog/potm-201003/ rel=nofollow noreferrerten year old open source project hosted on a href=http://sf.net/projects/arianne rel=nofollow noreferrerSourceforge).Unfortunately being just a spare-time open source project means we cannot proof our identity by posting extracts from the register of companies. Another issue is that code signing certificates seem to be rather expensive. So if anyone has suggestions where to look, i will be very thankful.
Any ideas how I could create a network usage meter for Java SE? : I need to meter the number of bytes being used by a java application from within java (i.e. I don't have any special access to the JVM other then not having a security manager to deal with) but I need all the bytes sent/received including protocol headers and the like. Anyone have good ideas on how to do this?The obvious move is to create a new URLConnectionHandler and insert metering into the IO streams. This, however, does not provide me with the header sizes of HTTP/HTTPS messages sent to/from a Java application.
Android - Upload photo to Facebook with Facebook Android SDK : i'm new to android i'm searching for load photo to facebook by authorization,getting access_token how to do this please give me a sample code in java.its urgent please help me.Thanks,Sanjana
Effective Java item 1 applicability with TDD and dependency injection : I have been reading Effective Java and I have some concerns regarding the first Item use static factory method instead of constructor in relation to TDD and dependency injection. The item says that you should avoid having public/protected/default constructor and expose it using static factory. I agree with all the advantages related to using static factories like factories can have name, you can return subtype, you can reduce verbosity etc. But, I think in disadvantages Joshua missed TDD because having static factories in your code will lead to tight coupling and you can't mock the class using it. We will not be able to mock the class which will be having static factories. So, it hampers test driven development.Second point, I think he missed that in todays enterprise development most of the applications use one or another dependency injection container. So, when we can inject dependencies using DI so why should I use it.Please explain how it applies to today's Java enterprise development which includes DI and TDD.
Unable to do fast I/O of dynamically generated images on a IP camera : I have a image file stored at a remote server (i.e a href=http://example.com/images).The rel=nofollow noreferrerhttp://example.com/images).The images in this folder are getting updated at the rate of 1 image per 100 milliseconds Think of ip cams that transmit MJPEG images .I am using apache HTTP client api to connect to my remote server .I am getting a stream of the contentHttpClient httpClient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(http://example.com/images/screenshot.jpg); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent();I am wrapping up the input stream in BufferedInputStream for faster I/O .But since the images are getting generated at very fast rate and they are on an average 250kb in size.I would like to use the NIO features like FileChannel as well as MemoryMappedBuffers to improve the I/O performance as well access generated image files on remote server in non blocking mode.But whatever samples I have seen talk about creating FileInputStream / RandomAccessFiles which take File Object as parameter.I am getting the InputStream as response from remote server which I am unable to convert to FileInputStream to get FileChannel.I would like to know if there is any implementation in apache http client api that gives fileChannels.Or should i explore sockets to get the channel access.I have also exlored javax.imageIO , but not sure if it will meet my requirement of faster I/O
Netbeans webservice client works only when running from IDE : Using Netbeans 6.8 and metro 2.0 I have written a simple application that makes calls to a webservice and displays the results in java swing components. When I run the application in the Netbeans IDE (using F6), the application works perfectly.However, when I attempt to run the compiled application from the .jar file in the dist folder, my swing UI comes up, but when I press the button that causes my web service to be called, nothing happens.Anyone know how I can get this to work?
Using Custom Java Class file in Jruby : I am trying to execute some custom Java code through the latest version of Jruby (1.5.1), Ruby 1.8.7, with Java 1.6.0_06. I have tried both the class file and putting it in a jar method. When I try require 'java' require 'path_to_class/myClassor require 'java' require 'path_to_jar/a_jar.jar Trying both methods, I cannot access the myClass nor any other files in the jar file. Other variations on the net for importing java classes lead to the following error:`NameError: cannot load Java class com.package.myClass from C:/jruby-1.5.1/lib/ruby/site_ruby/shared/builtin/javasupport/java.rb:51:in method_missing`I have also checked the solutions on StackOverFlow and I still get the same outcome. I am wondering if this might be a problem at a deeper level.
How to read a directory from a jar file in web start : I have been trying to implement Java WebStart but the problem I'm having is that I need to get a directory from a jar file with no luck...I need to read the following directory:jar:http://localhost:8080/nadeploy/lib/NuevaAldeaFonts.jar!/net/perroazul/nafonts/resWhen I instatiate it as:new File(new URL(jar:http://...nafonts/res).toURI());it throws IllegalArgumentException.And if I try to open the jar file in order to read the directory as a jar entry with:JarFile fj = new JarFile(http://localhost:8080/nadeploy/lib/NuevaAldeaFonts.jar);It throws the following exception:java.io.FileNotFoundException: http:\localhost:8080\nadeploy\lib\NuevaAldeaFonts.jarDo I have any more options in order to read a directory from a jar obtained by Web Start?Thanks in advance
How does the java-service-wrapper decide whether to use the 32 or 64 bit VM? : We're using a vendor licensed copy of the a href=http://wrapper.tanukisoftware.org/doc/english/download.jsp rel=nofollow noreferrerTanuki Java Service Wrapper to start their platform. It ships with wrappers for every O/S flavour and architecture and the recommended profile is a 64 bit VM with a 3 gig heap.We're using 64 bit Redhat, but I've been unable to find a wrapper configuration option which forces the wrapper.sh script to use the wrapper-linux-x86-64 binary. The only way I have been able to get the wrapper to start in 64 bit mode is by deleting the wrapper-linux-x86-32 binary.Is there a way to force the wrapper into 64 bit mode? Is it simply trying to choose the fastest appropriate VM setting and choosing 32 bit mode when it can because our heap is less than 4 gig?I'd like to learn more about how the java-service-wrapper makes the 32/64 bit decision but have been unable to find anything online.
Java stored procedures as Java / .Net interop : I'm looking for a way to access a Java API from both a Java console application and an ASP.Net application.In short my Java API exposes a series of methods for dealing with invoices. All of these methods are essentially commands e.g.GenerateAllInvociesGenerateInvoiceNumberPrintAllInvoicesPrintInvoiceNumberAll methods will interact with the database. I had believed Web Services was going to be my means for interop. But I have since been made aware of Java Stored Procedures in Oracle.I believe this means I could essentially treat my stored procs as an API and have the stored procs themselves call appropriate Java to write invoices to disk and to print the invoices etc. However this feels slightly odd.Has anyone out there every used Java stored procedures to provides interop between calling Java and .Net applications before? Any suggestions? Is this a really bad idea?Thanks.
Import a class in Scripting java (javax.script) : I want to import a class that I made in my project, into my scriptI did this but it doesn't work: function doFunction(){ //Objectif Mensuel importPackage(java.lang); importClass(KPDataModel.KPData.KPItem); //ERROR HERE, this is my class that I want to import KPItem kpItem = kpItemList.get(0); System.out.println(kpItem.CellList.get(2).Value); System.out.println(-------); var proposedMediationSum = Integer.parseInt(kpItemList.get(0).CellList.get(2).Value); var refusedMediationSum = Integer.parseInt(kpItemList.get(0).CellList.get(3).Value) var totalMediation = proposedMediationSum + refusedMediationSum; kpItemList.get(0).CellList.get(4).Value = totalMediation;}
GAE Datastore Java data type for date/time values : Both java.sql.Date and java.util.Date return the following when trying to persist them in the datastore.javax.jdo.JDOUserException: Attempt to handle persistence for object using datastore-identity yet StoreManager for this datastore doesn't support that identity typeWhat data types do you use for date/time values?
Project won't update R.java? : My main class folder was named com.test, I changed it to com.myApplication, and now when I add objects to my layout my R.java won't get updated, all objects that I had before work fine, and they are in R.java, but anything new that I create won't get added to R.javaAny idea how to resolve this problem?
Any way to have Java Web Start automatically install shortcuts? : We're deploying a Web Start app that I and the other developers know how to install the shortcuts for (Control Panel - Java on Windows, /Applications/Utilities/Java Preferences on OS X), but we have no reason to believe that end users know how to do this (or even know that it can be done).Is there a way to either install the shortcuts automatically on first run, or (much preferably) ask the user if they'd like to install the shortcuts? I've been looking all over but the Sun/Oracle docs all say to go through the Java cache viewer, which I find completely ridiculous to ask of end users.
Is ImageIO.write buffered? : Should I writeBufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));ImageIO.write(im, JPEG, os);instead of ImageIO.write(im, JPEG, file);I.e. are ImageIO file operations buffered by default or not?Thanks!
Configuring permissions for JNLP: : I'm trying to run a webstart demo, which ran on my friend's Windows machine, but throws an access error on my Ubuntu Linux box. javaws http://common.l2fprod.com/jnlp/demo.jnlpAnd I get the following error on my Linux box:java.security.AccessControlException: access denied (java.util.PropertyPermission javawebstart.version read)I assume this is a configuration issue on my Ubuntu machine. What needs to be changed to allow access to the webstart version?
Java Metro Security: StreamMessage has been already consumed : I'm using metro 2.0.1 for a client application who connects to WCF Service With security. Everything works fine in my unit tests but when I call the method in my Java application I get the following exception:Exception in thread main java.lang.AssertionError: StreamMessage has been already consumed. See the nested exception for where it's consumed at com.sun.xml.ws.security.opt.impl.incoming.VerifiedStreamMessage.unconsumed(VerifiedStreamMessage.java:512) at com.sun.xml.ws.security.opt.impl.incoming.VerifiedStreamMessage.readPayloadAsJAXB(VerifiedStreamMessage.java:251) at com.sun.xml.ws.fault.SOAPFaultBuilder.create(SOAPFaultBuilder.java:536) at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:118) at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:89) at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:140) at $Proxy42.getGiftvoucherBalance(Unknown Source) at com.rs.sw.fs.service.jaxws.account.card.JaxWsGiftVoucherService.getBalance(JaxWsGiftVoucherService.java:245) at com.rs.sw.fs.application.SkyllaApplication.main(SkyllaApplication.java:119)Caused by: java.lang.Exception at com.sun.xml.ws.security.opt.impl.incoming.VerifiedStreamMessage.unconsumed(VerifiedStreamMessage.java:516) at com.sun.xml.ws.security.opt.impl.incoming.VerifiedStreamMessage.writePayloadTo(VerifiedStreamMessage.java:375) at com.sun.xml.ws.security.opt.impl.incoming.VerifiedStreamMessage.writeTo(VerifiedStreamMessage.java:493) at com.sun.xml.ws.message.AbstractMessageImpl.readAsSOAPMessage(AbstractMessageImpl.java:193) at com.sun.xml.ws.security.opt.impl.incoming.VerifiedStreamMessage.readAsSOAPMessage(VerifiedStreamMessage.java:474) at com.sun.xml.wss.jaxws.impl.PolicyResolverImpl.resolvePolicy(PolicyResolverImpl.java:151) at com.sun.xml.ws.security.opt.impl.incoming.SecurityRecipient.createMessage(SecurityRecipient.java:894) at com.sun.xml.ws.security.opt.impl.incoming.SecurityRecipient.validateMessage(SecurityRecipient.java:232) at com.sun.xml.wss.jaxws.impl.SecurityTubeBase.verifyInboundMessage(SecurityTubeBase.java:486) at com.sun.xml.wss.jaxws.impl.SecurityClientTube.processClientResponsePacket(SecurityClientTube.java:405) at com.sun.xml.wss.jaxws.impl.SecurityClientTube.processResponse(SecurityClientTube.java:338) at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:639) at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:588) at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:573) at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:470) at com.sun.xml.ws.client.Stub.process(Stub.java:319) at com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:157) at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:109) ... 5 moreI guess there's a difference between my classpath in junit and my Java application (running eclipse and maven)In case someone is interested here's our huge dependency tree:[INFO] [dependency:tree][INFO] eres.fs:fs-std:jar:3.0.0.0-SNAPSHOT[INFO] +- eres.fs:fs-core:jar:3.5.0-SNAPSHOT:compile[INFO] | +- org.beanshell:bsh-core:jar:1.2b7:compile[INFO] | +- commons-beanutils:commons-beanutils:jar:1.7.0:compile[INFO] | +- commons-collections:commons-collections:jar:3.1:compile[INFO] | +- commons-dbcp:commons-dbcp:jar:1.2.1:compile[INFO] | +- commons-lang:commons-lang:jar:2.4:compile[INFO] | +- commons-logging:commons-logging:jar:1.0.4:compile[INFO] | +- commons-pool:commons-pool:jar:1.2:compile[INFO] | +- net.sf.ehcache:ehcache-core:jar:1.7.2:compile[INFO] | | \- org.slf4j:slf4j-api:jar:1.5.8:compile[INFO] | +- jgoodies:forms:jar:1.0.5:compile[INFO] | +- jdom:jdom:jar:1.0:compile[INFO] | +- javax.transaction:jta:jar:1.0.1B:compile[INFO] | +- postgresql:postgresql:jar:8.1-407.jdbc3:compile[INFO] | +- org.springframework:spring-aop:jar:2.0.8:compile[INFO] | | \- aopalliance:aopalliance:jar:1.0:compile[INFO] | +- org.springframework:spring-beans:jar:2.0.8:compile[INFO] | +- org.springframework:spring-context:jar:2.0.8:compile[INFO] | +- org.springframework:spring-core:jar:2.0.8:compile[INFO] | +- org.springframework:spring-dao:jar:2.0.8:compile[INFO] | +- org.springframework:spring-jdbc:jar:2.0.8:compile[INFO] | +- org.springframework:spring-remoting:jar:2.0.8:compile[INFO] | +- org.springframework:spring-web:jar:2.0.8:compile[INFO] | +- wsdl4j:wsdl4j:jar:1.6.1:compile[INFO] | +- xerces:xercesImpl:jar:2.7.1:compile[INFO] | +- com.thoughtworks.xstream:xstream:jar:1.2.2:compile[INFO] | | \- xpp3:xpp3_min:jar:1.1.3.4.O:compile[INFO] | +- org.mortbay.jetty:jetty:jar:6.1.11:compile[INFO] | +- org.mortbay.jetty:jetty-util:jar:6.1.11:compile[INFO] | +- org.mortbay.jetty:servlet-api-2.5:jar:6.1.11:compile[INFO] | +- xmlbeans:xbean:jar:2.2.0:compile[INFO] | +- org.apache.xbean:xbean-spring:jar:2.8:compile[INFO] | +- org.codehaus.xfire:xfire-aegis:jar:1.2.5:compile[INFO] | | \- net.java.dev.stax-utils:stax-utils:jar:20040917:compile[INFO] | +- org.codehaus.xfire:xfire-java5:jar:1.2.5:compile[INFO] | +- org.codehaus.xfire:xfire-spring:jar:1.2.5:compile[INFO] | | \- junit:junit:jar:3.8.1:test[INFO] | +- org.codehaus.xfire:xfire-core:jar:1.2.5:compile[INFO] | | +- javax.mail:mail:jar:1.4:compile[INFO] | | +- jaxen:jaxen:jar:1.1-beta-9:compile[INFO] | | | \- xerces:xmlParserAPIs:jar:2.6.2:compile[INFO] | | +- stax:stax-api:jar:1.0.1:compile (version managed from 1.0)[INFO] | | +- commons-codec:commons-codec:jar:1.2:compile (version managed from 1.3)[INFO] | | +- org.codehaus.woodstox:wstx-asl:jar:3.2.0:compile[INFO] | | \- commons-httpclient:commons-httpclient:jar:3.0:compile[INFO] | +- org.codehaus.xfire:xfire-xmlbeans:jar:1.2.5:compile[INFO] | +- org.apache.ws.commons:XmlSchema:jar:1.1:compile[INFO] | +- javax.activation:activation:jar:1.1:compile[INFO] | +- eres.commons:barcode:jar:3.2.1:compile[INFO] | | \- com.lowagie:itext:jar:1.3.1:compile[INFO] | +- eres.commons:djester:jar:3.0.1:compile[INFO] | +- eres.commons:I18N:jar:3.0.0:compile[INFO] | +- eres.commons:log:jar:3.2.0:compile[INFO] | +- eres.commons:util:jar:3.3.0-SNAPSHOT:compile[INFO] | | \- jclark:xt:jar:20020507:compile[INFO] | | \- jclark:xp:jar:19990102:compile[INFO] | +- eres.commons:reporting:jar:3.1.0-SNAPSHOT:compile[INFO] | | \- jasperreports:jasperreports:jar:3.1.2:compile[INFO] | | +- commons-digester:commons-digester:jar:1.7:compile[INFO] | | +- jfree:jcommon:jar:1.0.12:compile[INFO] | | +- jfree:jfreechart:jar:1.0.9:compile[INFO] | | \- xml-apis:xml-apis:jar:1.3.02:compile[INFO] | +- eres.commons:set-expressions:jar:1.0.0:compile[INFO] | +- eres.fs:fs-ebo-dao:jar:3.2.2:compile[INFO] | +- eres.fs:skylla-theme:jar:3.2.0:compile[INFO] | +- eres.fs:fashion-theme:jar:3.2.0:compile[INFO] | +- eres.javapos:jpos-core:jar:3.3.0-SNAPSHOT:compile[INFO] | | +- com.linuxnet:jpcsc:jar:0.7.2:compile[INFO] | | +- gnu.io:RXTXcomm:jar:2.1.7:compile[INFO] | | +- com.serialio:Serialio:jar:6.1:compile[INFO] | | +- com.javapos:jpos:jar:1.13.0:compile[INFO] | | | \- xalan:xalan:jar:2.6.0:test (scope managed from compile)[INFO] | | +- com.javapos:jcl_editor:jar:2.2.0:runtime[INFO] | | +- com.javapos:POSTest:jar:1.7.0:runtime[INFO] | | +- com.sun.comm:comm:jar:2.0.0:compile[INFO] | | +- com.serialio:JavaTerm:jar:5.4:runtime[INFO] | | +- com.retail-logic:SolveLink:jar:1.3.0.0:compile[INFO] | | \- jp.co.nec.jpos:tw5500jpos:jar:1.0.3:compile[INFO] | +- eres.messagebus:ebo-javaobject:jar:3.2.2:compile[INFO] | | +- eres.messagebus:ebo-javaobjectAPIs:jar:3.2.2:compile[INFO] | | +- org.jibx:jibx-run:jar:1.1.6.2:compile[INFO] | | +- aspectj:aspectjrt:jar:1.5.3:compile[INFO] | | \- joda-time:joda-time:jar:1.2.1:compile[INFO] | +- eres.messagebus:gateway:jar:4.0.2.0.2:compile[INFO] | | +- sonic:sonic_Crypto:jar:6.1:runtime[INFO] | | +- sonic:sonic_Selector:jar:6.1:runtime[INFO] | | +- sonic:sonic_Client:jar:6.1:compile[INFO] | | +- sonic:sonic_SF:jar:6.1:runtime[INFO] | | +- commons-io:commons-io:jar:1.4:compile[INFO] | | \- gnu:gnu-regexp:jar:1.0.6:compile[INFO] | +- eres.messagebus:jebo-listener:jar:3.2.2:compile[INFO] | | +- eres.messagebus:ebo-marshaller:jar:3.2.2:compile[INFO] | | \- eres.messagebus:ebo-jibx-marshaller:jar:3.2.2:compile[INFO] | +- eres.services:services-client:jar:3.2.0:compile[INFO] | +- eres.services:waitticket-service:jar:3.2.1-SNAPSHOT:compile[INFO] | +- net.sourceforge.jtds:jtds:jar:1.2:compile[INFO] | +- eres.fs:remote-control:jar:3.0.0-SNAPSHOT:compile[INFO] | | \- com.sun.xml.ws:webservices-rt:jar:2.0.1:compile[INFO] | | \- javax.xml:webservices-api:jar:2.0.1:compile[INFO] | +- eres.services:customer-service-client:jar:3.3.0-SNAPSHOT:compile[INFO] | | \- eres.services:service-client-commons:jar:3.3.0-SNAPSHOT:compile[INFO] | +- eres.services:loyalty-service-client:jar:3.2.0:compile[INFO] | +- eres.services:notification-service-client:jar:3.3.0-SNAPSHOT:compile[INFO] | +- eres.fs.promopack:promopackAPIs:jar:3.2.0:compile[INFO] | +- com.rs.sw.commons:commons-util:jar:3.0.0-SNAPSHOT:compile[INFO] | +- com.rs.sw.fs.framework.domain:fs-domain-core:jar:3.0.0-SNAPSHOT:compile[INFO] | +- com.rs.sw.fs.framework.domain:fs-domain-article:jar:3.0.0-SNAPSHOT:compile[INFO] | +- com.rs.sw.fs.framework.domain:fs-domain-account:jar:3.0.0-SNAPSHOT:compile[INFO] | +- com.rs.sw.fs.framework.repository:fs-repository-core:jar:3.0.0-SNAPSHOT:compile[INFO] | | +- com.rs.sw.fs.framework.data:fs-data-api:jar:3.0.0-SNAPSHOT:compile[INFO] | | \- org.slf4j:slf4j-log4j12:jar:1.5.8:compile[INFO] | +- com.rs.sw.fs.framework.repository:fs-repository-skylla:jar:3.0.0-SNAPSHOT:compile[INFO] | | +- com.rs.sw.fs.framework.data:fs-data-jdbc:jar:3.0.0-SNAPSHOT:compile[INFO] | | +- com.rs.sw.fs.framework.data:fs-data-service:jar:3.0.0-SNAPSHOT:compile[INFO] | | +- com.rs.sw.fs.framework.domain:fs-domain-service:jar:3.0.0-SNAPSHOT:compile[INFO] | | +- com.rs.sw.fs.framework.service:fs-service-api:jar:3.0.0-SNAPSHOT:compile[INFO] | | \- com.rs.sw.fs.framework:fs-test:jar:3.0.0-SNAPSHOT:compile[INFO] | | +- dbunit:dbunit:jar:2.1:test (scope managed from compile)[INFO] | | \- com.rs.sw.commons:commons-test:jar:3.0.0-SNAPSHOT:test (scope managed from compile)[INFO] | +- com.rs.sw.fs.framework:fs-view:jar:3.0.0-SNAPSHOT:compile[INFO] | +- com.rs.sw.fs.framework.data:fs-data-gateway:jar:3.0.0-SNAPSHOT:compile[INFO] | \- com.rs.sw.fs.framework.service:fs-service-jaxws:jar:3.0.0-SNAPSHOT:compile[INFO] | +- com.rs.sw.fs.framework.service:fs-service-jaxws-giftvoucher:jar:3.0.0-SNAPSHOT:compile[INFO] | \- com.rs.sw.commons:commons-jaxws:jar:3.0.0-SNAPSHOT:compile[INFO] \- eres.commons:launcher:jar:1.0.1:compile[INFO] +- log4j:log4j:jar:1.2.13:compile[INFO] \- eres.commons:system-util-native:dll:1.0.0:compile[INFO] \- eres.commons:system-util:jar:1.0.0:compile
Java web start doesn't launch : On my Windows 7 x64 machine, I'm having problems launching my remotely deployed Web Start app (the Web Start app launches correctly on another PC as expected). In IE or FF, I click on the web start launch link, the JNLP is downloaded, it seems to get executed and nothing happens. I see javaws.exe processes running. I don't see a java.exe running. I don't know if it's related but I also can't get the java console to run. In the Control Panel Java applet settings, I have have enabled Show console and place Java icon in the system tray. I don't see the Java icon in the system tray either.I'm running Java 1.6.0_21 (32 bit). I'm able to run Netbeans so the it appears as if Java is installed correctly on my machine. Why isn't web start working?
Thread safe Hash Map? : I am writing an application which will return a HashMap to user. User will get reference to this MAP.On the backend, I will be running some threads which will update the Map.What I have done so far?I have made all the backend threads so share a common channel to update the MAP. So at backend I am sure that concurrent write operation will not be an issue.Issues I am havingIf user tries to update the MAP and simultaneously MAP is being updated at backend -- Concurrent write operation problem.If use tries to read something from MAP and simultaneously MAP is being updated at backend -- concurrent READ and WRITE Operation problem.Untill now I have not face any such issue, but i m afraid that i may face in future. Please give sugesstions.I am using ConcurrentHashMapString, String.
How to disable JUL in 3rd party jar? : In 3rd party jar logger exist this code. 'Logger.getLogger(net.java.ao).log(Level.INFO, sql.toString());'How can I disable this logger from my program?
How to give name to a callable Thread? : I am executing a Callable Object using ExecutorService thread pool. I want to give a name to this thread.To be more specific, in older version I did this -Thread thread = new Thread(runnable Task);thread.setName(My Thread Name);I use thread name in log4j logging, this helps a lot while troubleshooting. Now I am migrating my code from Java 1.4 to Java 1.6. I have written this(Given below)- but I dont know how to give name to this thread.private final ExecutorService executorPool = Executors.newCachedThreadPool();FutureString result = executorPool.submit(callable Task);Please give me some idea to give name to this thread?
Scanner in Java not working : I'm trying to write a very simple number guessing game (code is below). After 1 round is finished, the user is supposed to be able to decide whether he/she wants to play another round or not. Problem is, the program always skips the last question (never letting the user answer 'y' or otherwise. What am I missing here? Is there something about java.util.Scanner I don't know about?import java.util.Random;import java.util.Scanner;public class GuessNum {public GuessNum() { int numRandom = 0; int numGuess; int life = 5; String want = ; Random rand = new Random(); Scanner scan = new Scanner(System.in); do { int lifeLeft = 5; numRandom = rand.nextInt(9)+1; System.out.print(\nGuess the Number [1..10]\n); System.out.print(===================\n); System.out.print(You have + lifeLeft + chances.\n); do { do { System.out.print(What number do I have in mind: ); numGuess = scan.nextInt(); if (numGuess 1 || numGuess 10) System.out.println(Invalid input. Range is 1-10.); } while (numGuess 1 || numGuess 10); if (numGuess != numRandom amp;amp; lifeLeft != 0) System.out.println(Wrong! You only have + --lifeLeft + chances left.); } while (numGuess!=numRandom amp;amp; lifeLeft 0); if (numGuess == numRandom) System.out.println(Correct! -- in + (life - lifeLeft) + guess(es).); if (lifeLeft == 0) { System.out.println(You have no more lives..); System.out.println(This is the number: + numRandom); } System.out.print(\nEnter 'y' if you want to play again or any other character to exit: ); want = scan.nextLine(); } while (want.equals(y) || want.equals(Y)); } public static void main(String[] args) { new GuessNum(); }}
Assert List in Junit : How to assert list in JUnit test case? I mean not only the size of the list but also the contents of the list.
android r.java will not update : I googled a lot to find various hints what could cause this problem. Many of them on this forum, but nothing works.I installed the sdk from scratch on 3 different machines (xp, macos snow leopard, leopard) and always the same problem, that even the sample code in the android sdk doesn't compile.After hours of looking through the xml files I recognized, that when I remove ' from strings the sample code of the sdk will compile.So does a new project, as long there is no change needed in the R.java file.As soon as I try to add a button with findViewByID, I get the error that the field R.id cannot be resolved. No other changes were done to the project.As mentioned before I tried various things, including:clean project, rebuildrestart eclipseupdate sdk (even tough I installed the new sdk)no uppercase letters...Install sdk, latest eclipse classic on a clean machineI don't think it's an issue of the code itself, because even the sample code provided by the sdk doesn't compile without removing ' from the xml.Please somebody has some hints and ideas where to look next please?
Accessing XML payload of Metro 2.0 Request/Response Web Service : I am developing a web service, using Metro 2.0 and Tomcat 6, and I have a requirement to be able to log the XML payload of the request and response of a web method for development/support reasons. The payload would only be logged when in debug mode.The Web Service uses a servlet implementation (com.sun.xml.ws.transport.http.servlet.WSServlet and .WSServletContextListener classes), if that affects the answer.Is this even possible?Thanks in advance,Andy