| String comparision efficency |
|
 |
Index ‹ java-programmer
|
- Previous
- 1
- Future of 3Djava
Why comp.lang.java.3d doesn't exist ? If is not dead, for what purpose is
using: games or some engineering tools ? Does java have a future in a
gaming industry?
- 2
- help:hibernateit drive me crazy!
where is the error?
when i use hibernate to connect to the mySQL,some error happens,just
like:
net.sf.hibernate.PropertyNotFoundException: no appropriate constructor
in class:
but i have defined a constructor without parameters!
it really block me,help!
- 3
- create a bean on webapp startupHi,
Unsuccessfully web browsing makes me come here.
I wonder if it's possible to create a bean (used by <jsp:use-bean>) on
startup, also through web.xml. I've seen it is possible to launch a
servlet with <load-on-startup> xml element, but, as I believe I've
understood, it is NOT a persistent object.
So, i'm asking if :
- is this possible to create a persistent object through a servlet
lauched at startup ?
- is there a different way ?
Regards,
--
Mounir
- 3
- JTextArea SizeHello, I'm writing a java app for a pda and as the screen size is tiny I
want to write a MiniDialog class. I only want a JTextArea and an OK button
on it and I want the JTextArea to fit the size of the modal dialog.
If I pass in a long line of text then the JTextArea appears to get wider and
I have to scroll across the screen to see the text. I want it to wrap onto
the second line etc.
I must be doing something stupid!
Thanks, Kevin.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MiniDialog {
JDialog dialog=new JDialog(new JFrame(),"Info",true);
public MiniDialog() { }
public void show(String label) {
Container c=dialog.getContentPane();
JButton ok=new JButton("OK");
dialog.getRootPane().setDefaultButton(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
JTextArea txt=new JTextArea(5,20);
txt.setEditable(false);
txt.append(label);
JScrollPane scroll=new JScrollPane(txt);
scroll.setSize(1,1);
dialog.setSize(200,200);
dialog.setLocation(20,40);
c.add(scroll,BorderLayout.CENTER);
c.add(ok,BorderLayout.SOUTH);
dialog.show();
}
}
- 5
- 7
- java/berkeley-db self-test hangHello!
The newly updated port of java/berkeley-db hangs during self-tests on one of
my machines:
dual FreeBSD/i386 6.1-stable - no hang
single FreeBSD/amd64 6.1-stable - no hang
dual FreeBSD/amd64 6.2-prerelease - hangs
There is little CPU use and all the process is doing, according to ktrace is
the repeated:
[...]
13089 java CALL clock_gettime(0,0x7ffffeff3d00)
13089 java RET clock_gettime 0
13089 java CALL kse_release(0x654f20)
13089 java RET kse_release 0
13089 java CALL kse_release(0x511f20)
13089 java RET kse_release 0
13089 java CALL clock_gettime(0,0x7ffffeff3d00)
13089 java RET clock_gettime 0
13089 java CALL kse_release(0x654f20)
13089 java RET kse_release 0
13089 java CALL kse_release(0x511f20)
[...]
Rebuilding Java did not help... Would any Java and/or thread expert, please,
try to build the port with self-testing enabled and analyze any hang? Thanks
a lot!
-mi
- 7
- I can not get data from Table cellHi every one
I try to get String from cell in jTable
every time I try to get data from cell I only get null
and this is my code
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Class.forName("com.mysql.jdbc.Driver");
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost/
uni","root","java");
Statement stat = con.createStatement();
ResultSet result;
result = stat.executeQuery("select max(no) from student_info_table");
result.next();
int mx, c;
mx = result.getInt(1);
mx = mx +1;
String inserting_Data = "insert into fee_part_table (feeNO, feeParts,
fee_1st_part) values(?, ?, ?)";
PreparedStatement ps = null;
ps = con.prepareStatement(inserting_Data);
ps.setInt(1, mx);
ps.setInt(2, c);
String st;
st = String.valueOf(jTable2.getValueAt(0, 0));
JOptionPane.showMessageDialog(this, st);
ps.setString(3, String.valueOf(jTable2.getValueAt(0, 0)));
ps.executeUpdate();
///////////////////////////////////////////////
- 8
- Load default web browserHello,
I want to load a default web browser from my swing application [using
JApplet].
Using Runtime.getRuntime.exec("RunDLL 32.exe
shell32.dll,shellExec.RunDLL"+url);[for windows]
default browser can be called.But it is working in normal class & with
frames only.
with Applet or in swing-JApplet
it is showing error as :- java.security.AccessControlException:access
denied(java.io.FilePermission<<All FILES>>)execute>.
I want a plateform independent solution which will work in swing-JApplet.
--
Message posted via JavaKB.com
http://www.javakb.com/Uwe/Forums.aspx/java-jvm/200505/1
- 8
- tomcat's classpathsHi all.
I have downloaded Tomcat 4.1.27 and I would like to create some JSPs. I took
an earlier JSP app and put it on Tomcat, and I got a class not found
exception. How do I set the classpaths for Tomcat?
One more question, how do I change the web document root? For example, I
want to change it to c:\testing.
Thanks in advance.
- 8
- code conventions - validationAnyone know of a code validator that follows this:
http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
TIA
--
Mike W
- 8
- Where have all the wintrolls gone...
"Phil Earnhardt" <email***@***.com> wrote in message
news:email***@***.com...
> >> >> No, Luke. Why don't *you* tell *us*: What would be the point of
> >having
> >> >> the language in 1441 and then doing *nothing* when Iraq was not
in
> >> >> compliance?
> >> >
> >> >There wouldn't be any point. You just beat the UN in doing
something.
> >>
> >> The question is actually the opposite, Luke: given the French never
> >> ever had any intent of enforcing the consequences spelled out in UN
> >> 1441, why did they ever bother approving it in the first place? Why
> >> not just be straight with the UN: "We will veto any measure to
approve
> >> UN military action against Iraq."
> >
> >Actually the sentence doesn't end here. If we put it into context (at
> >the time) it should read:
> >
> >We will veto any measure to approve UN military action against Iraq
if
> >the potential approval is to be based on US intelligence (read:
lies).
>
> But UN 1441 wasn't based on US intelligence.
We're not talking about 1441. France didn't vote against 1441. We're
talking about the invasion "warrant" US wanted to squeeze out of UNSC.
France felt somewhat reluctant to sign that warrant because the
evidence US intelligence (sic!) produced was not so very convincing. At
the time. Later it turned out it was total bullshit. Dubya's setting up
an investigation right now. In 50 years we might get to know the...
conclusions.
> The question remains: Iraq failed to comply with the terms of UN 1441.
> What should have been the consequences of that?
Again? Well, let's hope this time you get it: the terms should have been
enforced. But not under US flag. Maybe (more than likely) under US boot.
But the flag should have been the blue UN.
- 11
- HashMap with primitive int keyDear All,
I have a class like this:
class CustomerOrder {
int globalID;
...
}
I have an array of these.
I'd like to store an index of globalIDs, so I can do:
CustomerOrder o = index.get(123)
I could modify my class to be:
class CustomerOrder {
Integer globalID;
...
}
Perhaps it is my C++ background, but the idea of allocating an object for every
ID when I can just use an int bothers me.
I figure a HashMap is the right tool of choice, e.g.:
HashMap<Integer, CustomerOrder> index = new ...
Has anyone out there already written a modified hashmap class that uses int as
the key?
Thanks for any tips :)
Andrew
- 11
- Curb Your Spam RageRoedy Green wrote:
Leave it to good ol' Roeds to feel the spammers' pain.
[snippysnipsnip]
- 14
- JTable emulate a HTML Table?Hi,
I want to display a table of user inputted information as a table but I am
having problems formatting the layout as I want it. I have a fixed cell
width and want the cell height to adjust to fit the text entered by the
user.
I can set the widths but can only set a fixed height for a cell and am
unable to get text to wrap within it,
for example. Also with the fixed height, the single line cells would float
to the vertical center of the cell, not stay at the top. Can alignments be
set?
[date textfield][item textfield][description textarea][idenifier
textfield][cost textfield]
[submit button]
Date Item Description
Identifier Cost
12/12/03 Big Pan This is a description field that BPI420
$60
15:30 spans multiple lines an needs
to wrap. The cell height
should dynamically alter to
accomodate the text.
1/1/04 Aspirin This is a much shorter
AS123 $20
description
Am I able to do this and if so how?
Is there a better way to do this than with using a JTable? I tried doing it
with a gridbag layout but the consecutive items wouldn't stay aligned.
Please help!
Cheers
Xav
- 14
- reading values from JTableI am looking for a working example of a JTable that is constructed
with initial values in the cells, allows the user to change those values,
and reads the values out.
I've got three books on Swing, none of them show a write/read table.
I have no problem creating tables with nothing in some cells, and
reading the values out that the user entered.
Here is how I construct the tables:
DefaultTableModel model01= new DefaultTableModel(rowData,colNames);
JTable table01= new JTable(model01);
Any help greatly appreciated.
--
Robert Metzger
Hewlett-Packard Company
High Performance Computing Division
|
| Author |
Message |
Daniel

|
Posted: 2005-2-14 17:04:00 |
Top |
java-programmer, String comparision efficency
HI!
I have an appliation that will need to parse a text of unkown length.
I get the data as an array of strings (and thus I know then how much
data it is)
I want to do several things on each "row" (that is each element in the
array) I want to
1. look for a specific word (start) and count how many of them there
are in total.
2. Highlight the word alarm and append a short description to the end
of the line
my first thought was to use
for(int i=0;i<data.length++){
if(data[i].endsWith("start"){
// do the work..
}else if(data[i].startsWith("Alarm")){
//do different work
}
}
this seems to be rather inefficent as I get two (and possibly more, my
employer did not seem think these few features were enough..)
Is there a better way to do this.
As the alarm line also contains an alarm code, I do not know what it
looks like. Any suggestions?
regards
/daniel
|
| |
|
| |
 |
Thomas Weidenfeller

|
Posted: 2005-2-14 17:17:00 |
Top |
java-programmer >> String comparision efficency
Daniel wrote:
> this seems to be rather inefficent as I get two (and possibly more, my
> employer did not seem think these few features were enough..)
> Is there a better way to do this.
> As the alarm line also contains an alarm code, I do not know what it
> looks like. Any suggestions?
http://groups.google.com/groups?selm=cnhmt6%24eg8%241%40newstree.wise.edt.ericsson.se
/Thomas
--
The comp.lang.java.gui FAQ:
ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq
|
| |
|
| |
 |
asb

|
Posted: 2005-2-14 17:59:00 |
Top |
java-programmer >> String comparision efficency
email***@***.com wrote in comp.lang.java.programmer:
> my first thought was to use
>
> for(int i=0;i<data.length++){
> if(data[i].endsWith("start"){
> // do the work..
> }else if(data[i].startsWith("Alarm")){
> //do different work
> }
> }
>
> this seems to be rather inefficent as I get two (and possibly more, my
> employer did not seem think these few features were enough..)
You get two what? The worst case scenario in the above example is
that you will do two 4 character string matches (string ends with
"tart" and starts with "Alar". Do you have any idea about how
much processing power that takes?
"Premature optimization is the root of all evil".
First run your code and see if it really is inefficient.
> As the alarm line also contains an alarm code, I do not know what it
> looks like. Any suggestions?
If you don't know it, how the hell are we supposed to?
--
Antti S. Brax Rullalautailu pitæ»— lapset poissa ladulta
http://www.iki.fi/asb/ http://www.cs.helsinki.fi/u/abrax/hlb/
"Disconnect this cable to shorten, re-connect to lengthen."
-- Instructions on Logitech's USB mouse extension cord.
|
| |
|
| |
 |
Daniel

|
Posted: 2005-2-14 18:44:00 |
Top |
java-programmer >> String comparision efficency
> First run your code and see if it really is inefficient.
I have.. it takes along with getting the data (I will run a test on
only the processing soon) 5 seconds on the test machine, which
contains almost a third of the ammount of data a "real" machine
contains. I estimate that between 3 and 4 seconds of that is time to
transfear the data to my app. (I did a testrun now, and yes,
approximately 1 second is for processing the text)
While this does not seem much, the users did think it took very long
when I did show the the application. I guess I will end up with
writing some code that shows progress rather than optemize this,
maybe..
>
>> As the alarm line also contains an alarm code, I do not know what it
>> looks like. Any suggestions?
>
> If you don't know it, how the hell are we supposed to?
You mean you are not an all-powerful all-knowing divine being? ;)
I realize after reading your reply I did express myself a bit
unclear. What I mean is that the line looks like this "-103 ALARM=E03"
and that the "-103" is dependent on when it occured, and thus I do not
know which number it will be. and the "E03" is the alarm number, and
of course is unknown until runtime.
I saw that I thus can not use the endsWith or startsWith but am using
lastIndexOf()
My question for suggestions was to the problem of matching this. if
there were some relativiley simple way of doing this that I was
missing.
I will look into the links posted in the other reply.
regards
Daniel
|
| |
|
| |
 |
bugbear

|
Posted: 2005-2-14 19:02:00 |
Top |
java-programmer >> String comparision efficency
Daniel wrote:
> look for a specific word (start) and count how many of them there
> are in total.
I hate to sully an object oriented langugage with anything
so banal and old fashoinedas an algorithm, but...
http://www.cs.rpi.edu/~musser/gp/algorithms.html
BugBear
|
| |
|
| |
 |
Sebastian Millies

|
Posted: 2005-2-14 19:43:00 |
Top |
java-programmer >> String comparision efficency
Am Mon, 14 Feb 2005 11:01:52 +0000 schrieb bugbear:
> I hate to sully an object oriented langugage with anything
> so banal and old fashoinedas an algorithm, but...
>
> http://www.cs.rpi.edu/~musser/gp/algorithms.html
>
> BugBear
which brings up the question: Are there any Java libraries
for sorting and searching thst incorporate these
algorithms (Introsort, or Knuth-Morris-Pratt, Boyer-Moore
and their hybrids, resp.)? The Java Collections Framework
for one, does not document the underlying algorithms in
detail, and neither does Jakarta ORO.
-- Sebastian
|
| |
|
| |
 |
asb

|
Posted: 2005-2-14 20:07:00 |
Top |
java-programmer >> String comparision efficency
REPLACE-OBVIOUSsDOTmilliesATidsMINUSscheerDOTde wrote in comp.lang.java.program$
> The Java Collections Framework
> for one, does not document the underlying algorithms in
> detail, and neither does Jakarta ORO.
In what detail do you need the documentation?
From java.util.Arrays: The sorting algorithm is a tuned quicksort,
adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering
a Sort Function", Software-Practice and Experience, Vol. 23(11) P.
1249-1265 (November 1993). This algorithm offers n*log(n)
performance on many data sets that cause other quicksorts to
degrade to quadratic performance.
From java.util.Collections: The sorting algorithm is a modified
mergesort (in which the merge is omitted if the highest element
in the low sublist is less than the lowest element in the high
sublist). This algorithm offers guaranteed n log(n) performance.
I'd say that is quite well defined.
As a sidenote: does anyone know why Arrays.sort(Object[]) uses
a different algorithm than Arrays.sort(byte[])?
--
Antti S. Brax Rullalautailu pitæ»— lapset poissa ladulta
http://www.iki.fi/asb/ http://www.cs.helsinki.fi/u/abrax/hlb/
"Disconnect this cable to shorten, re-connect to lengthen."
-- Instructions on Logitech's USB mouse extension cord.
|
| |
|
| |
 |
Patricia Shanahan

|
Posted: 2005-2-14 22:31:00 |
Top |
java-programmer >> String comparision efficency
Antti S. Brax wrote:
> REPLACE-OBVIOUSsDOTmilliesATidsMINUSscheerDOTde wrote in comp.lang.java.program$
...
> As a sidenote: does anyone know why Arrays.sort(Object[]) uses
> a different algorithm than Arrays.sort(byte[])?
>
The issue may be stability.
In a byte array, elements that compare equal are totally and
indistinguishably identical, so there is no need to preserve
their original order.
In an Object array two elements can compare equal but be
distinguishable, so keeping them in order may matter. The
Javadocs claim that the Object[] sort is stable.
Patricia
|
| |
|
| |
 |
John C. Bollinger

|
Posted: 2005-2-14 23:13:00 |
Top |
java-programmer >> String comparision efficency
Antti S. Brax wrote:
> As a sidenote: does anyone know why Arrays.sort(Object[]) uses
> a different algorithm than Arrays.sort(byte[])?
The algorithm for sort(Object[]) has to be stable (specified in the
class-level docs for Arrays), which makes the order resulting from
Arrays.sort(Object[]) the same as that from Collections.sort(List).
Using a stable sort makes a reasonably good sense anyway. The
distinction between a stable and an unstable sort is lost when you sort
primitives, however. For those cases an algorithm was chosen that
exhibits better average performance (but the same asymptotic complexity).
--
John Bollinger
email***@***.com
|
| |
|
| |
 |
Joona I Palaste

|
Posted: 2005-2-14 23:34:00 |
Top |
java-programmer >> String comparision efficency
bugbear <email***@***.com> scribbled the following:
> Daniel wrote:
>> look for a specific word (start) and count how many of them there
>> are in total.
> I hate to sully an object oriented langugage with anything
> so banal and old fashoinedas an algorithm, but...
> http://www.cs.rpi.edu/~musser/gp/algorithms.html
Surely you meant that "banal and old fashioned" jokingly? Even in object
oriented languages, methods must eventually be implemented with
algorithms. It's all ones and zeroes in the processor, after all. There
must be *some* layer that translates the high-flying ideas into
something the processor understands.
--
/-- Joona Palaste (email***@***.com) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"O pointy birds, O pointy-pointy. Anoint my head, anointy-nointy."
- Dr. Michael Hfuhruhurr
|
| |
|
| |
 |
John C. Bollinger

|
Posted: 2005-2-14 23:35:00 |
Top |
java-programmer >> String comparision efficency
Daniel wrote:
> I have an appliation that will need to parse
[...]
> an array of strings
[...]
> I want to do several things on each
[...]
> element in the array
[...]
> 1. look for a specific word (start) and count how many of them there
> are in total.
Count how many lines contain this word? How many total occurrences of
the word there are?
> 2. Highlight the word alarm and append a short description to the end
> of the line
What does it mean to "highlight" the word?
> my first thought was to use
>
> for(int i=0;i<data.length++){
> if(data[i].endsWith("start"){
> // do the work..
> }else if(data[i].startsWith("Alarm")){
> //do different work
> }
> }
This is not "doing several things" on each element of the array. In
particular, if you see "start" and the end of one element, you do not
check for "Alarm". Also, you are doing case-sensitive tests. That may
be fine for your application, but you should be sure. Furthermore, have
you considered what happens if any of the strings contains "restart" but
not "start"? Do you need to recognize multiple occurrences of "start"
in any one string?
> this seems to be rather inefficent as I get two (and possibly more, my
> employer did not seem think these few features were enough..)
Two *what*? If you need to check multiple unrelated conditions on a
string then you need to perform a separate check for each. If you are
permitted to use relationships among the conditions (e.g. a line
containing "start" will not be an "Alarm" line) then you can structure
the code to reduce the total number of tests, as indeed your example
appears to do.
Do you have specific requirements that you are supposed to meet? If so,
then we could be more helpful if we knew what those were.
> Is there a better way to do this.
> As the alarm line also contains an alarm code, I do not know what it
> looks like. Any suggestions?
You might consider the Java regex machinery. It is unlikely to be as
fast as a simple String.startsWith(), but it sounds like your real
matching criteria are rather more complicated anyway. If you go this
route then DO compile the Pattern(s) once and reuse it, rather than
compiling it anew for each string.
--
John Bollinger
email***@***.com
|
| |
|
| |
 |
John C. Bollinger

|
Posted: 2005-2-15 0:03:00 |
Top |
java-programmer >> String comparision efficency
Daniel wrote:
>> First run your code and see if it really is inefficient.
>
> I have.. it takes along with getting the data (I will run a test on
> only the processing soon) 5 seconds on the test machine, which
> contains almost a third of the ammount of data a "real" machine
> contains. I estimate that between 3 and 4 seconds of that is time to
> transfear the data to my app. (I did a testrun now, and yes,
> approximately 1 second is for processing the text)
> While this does not seem much, the users did think it took very long
> when I did show the the application. I guess I will end up with
> writing some code that shows progress rather than optemize this,
> maybe..
You must have a large number of strings to work on. How are they
getting into your app? Do you have control of the representation? If
your app is creating the String array (as opposed to receiving it whole
over RMI, or something like that) then constructing a String[] to hold
them is inefficient.
Unless you actually need to hold everything in memory at the same time
(unlikely), it is much better to process the Strings one-by-one as you
receive them. Also, if you have not done so already then ensure that
whatever Reader or InputStream the data are coming in on is buffered.
If that doesn't improve performance enough then consider putting the
reading and processing into different threads. Since one will be doing
I/O, there is good potential to get some additional performance
improvement with this.
It is pointless to try to improve the parsing without touching the I/O,
as your tests show that about a 20% speedup is the absolute maximum you
can expect that way. If users complain that the application is too
slow, then the smaller improvement that you can reasonably hope for
(without reworking the I/O) is not going to satisfy them.
> I realize after reading your reply I did express myself a bit
> unclear. What I mean is that the line looks like this "-103 ALARM=E03"
> and that the "-103" is dependent on when it occured, and thus I do not
> know which number it will be. and the "E03" is the alarm number, and
> of course is unknown until runtime.
>
> I saw that I thus can not use the endsWith or startsWith but am using
> lastIndexOf()
>
> My question for suggestions was to the problem of matching this. if
> there were some relatively simple way of doing this that I was
> missing.
Back to the case-sensitivity question, then: you have now presented
three different possible capitalizations of the "ALARM" keyword you need
to recognize. Which is right? Do you need to parse out the other parts
of this line as well? In that case you may have crossed the threshold
where a suitable regex will be useful to you. Something like:
Pattern.compile("(-\\d+)\\s+ALARM=(.+)");
would get you a pattern that can match the example string you provided.
From the Matcher object you could then also separately extract the
"-103" and the "E03" without any additional parsing. The matching would
be fairly efficient because it can start at the beginning of the string
and reject many non-matches early.
A well-written pattern for the other test may also solve the problem of
distinguishing "start" from "restart", "starting", and "Astarte".
--
John Bollinger
email***@***.com
|
| |
|
| |
 |
bugbear

|
Posted: 2005-2-15 18:20:00 |
Top |
java-programmer >> String comparision efficency
Joona I Palaste wrote:
> bugbear <email***@***.com> scribbled the following:
>
>>Daniel wrote:
>>
>>> look for a specific word (start) and count how many of them there
>>> are in total.
>
>
>>I hate to sully an object oriented langugage with anything
>>so banal and old fashoinedas an algorithm, but...
>
>
>>http://www.cs.rpi.edu/~musser/gp/algorithms.html
>
>
> Surely you meant that "banal and old fashioned" jokingly?
Yep :-)
BugBear
|
| |
|
| |
 |
Daniel

|
Posted: 2005-2-16 16:39:00 |
Top |
java-programmer >> String comparision efficency
>You must have a large number of strings to work on. How are they
>getting into your app? Do you have control of the representation? If
>your app is creating the String array (as opposed to receiving it whole
>over RMI, or something like that) then constructing a String[] to hold
>them is inefficient.
I have a range from 0 to 1000 strings (or rows).
They get into my app via a bufferInputStream(Connected to a serialport
via the javax.comm package), so I get them as a single byte array.
As I want to display all the data in a JTextPane I assumed I had to
convert it to string. Perhaps that was a too quick conclusion?
I also did the split on "\r\n" to make it easier to distignuish
individual lines, as some lines require special treatment (as
discussed in this and previous postings)
>Unless you actually need to hold everything in memory at the same time
>(unlikely), it is much better to process the Strings one-by-one as you
>receive them. Also, if you have not done so already then ensure that
>whatever Reader or InputStream the data are coming in on is buffered.
>If that doesn't improve performance enough then consider putting the
>reading and processing into different threads. Since one will be doing
>I/O, there is good potential to get some additional performance
>improvement with this.
the thing is that I get them all in one go. As soon as I request the
data I get it all as one big chunk. I have already put it in it's own
thread so I wouldn't freeze the GUI in the process.
>It is pointless to try to improve the parsing without touching the I/O,
>as your tests show that about a 20% speedup is the absolute maximum you
>can expect that way. If users complain that the application is too
>slow, then the smaller improvement that you can reasonably hope for
>(without reworking the I/O) is not going to satisfy them.
true, my thought now is that I would make the GUI more "alive" so
instead of a "Getting data from machine" perhaps something along the
lines "Getting data from machine (XX% done)" or similar, thus
informing the user of the progress. That of course means I would have
to measure how long I have gone, but I guess that I can fake some of
this, updating the procentage even though I don't really know how
much is really done, and then put real values there as soon as I have
them...
>Back to the case-sensitivity question, then: you have now presented
>three different possible capitalizations of the "ALARM" keyword you need
>to recognize. Which is right? Do you need to parse out the other parts
I will check with the guys who wrote the software I am communicating
with, but from what I've seen so far "-103 ALARM=E04" is the correct
one.
>of this line as well? In that case you may have crossed the threshold
not of this line, this line I must find which alarm number I have,
look it up and display the whole thing as "-103 ALARM=E04 (Temperature
sensor in boiler defect)"
So a regular expresion seems like the way to go.
Thank you for your ideas and suggestions!
regards
Daniel
|
| |
|
| |
 |
Daniel

|
Posted: 2005-2-16 17:02:00 |
Top |
java-programmer >> String comparision efficency
>> 1. look for a specific word (start) and count how many of them there
>> are in total.
>
>Count how many lines contain this word? How many total occurrences of
>the word there are?
yes :) in this case it would yield the same result, as a line may not
contain the word more than once. To answer your question more
properly, I need to count the number of total occrences of the word.
>> 2. Highlight the word alarm and append a short description to the end
>> of the line
>
>What does it mean to "highlight" the word?
in this case I mark it with bold font.
like this:
SimpleAttributeSet attr = new SimpleAttributeSet();
if (bold) {
StyleConstants.setBold(attr, true);
}
try {
doc.insertString(doc.getLength(), s + "\n", attr);
} catch (BadLocationException e) {
System.out.println("Error trying to add string: " + s);
}
}
>This is not "doing several things" on each element of the array. In
>particular, if you see "start" and the end of one element, you do not
>check for "Alarm". Also, you are doing case-sensitive tests. That may
>be fine for your application, but you should be sure. Furthermore, have
>you considered what happens if any of the strings contains "restart" but
>not "start"? Do you need to recognize multiple occurrences of "start"
>in any one string?
I guess again I expressed myself a bit clumsy. since most of the
strings will not contain any of the words I'm looking for I would have
to do all the comparisions on them, which seems like a bit uneccesery
work, but I guess there is no real way to get out of that.
Not more than one occurancesy of "start" in any one string.
>containing "start" will not be an "Alarm" line) then you can structure
>the code to reduce the total number of tests, as indeed your example
>appears to do.
yes, a line containing "start" will not contain alarm and vice versa.
So I can structure my code as I tried to already, meaning when I've
found one of the speical cases I'm looking for I do not have to check
the others.
>Do you have specific requirements that you are supposed to meet? If so,
>then we could be more helpful if we knew what those were.
no, The requrement so far is that I
1. count the number of occrances of the word "START"
2. Append the meaning of an alarm number at the end of the string
containg "ALARM"
>You might consider the Java regex machinery. It is unlikely to be as
>fast as a simple String.startsWith(), but it sounds like your real
>matching criteria are rather more complicated anyway. If you go this
>route then DO compile the Pattern(s) once and reuse it, rather than
>compiling it anew for each string.
yeah, I will look into it. I have limited experience with regex and
none with the java version of it. but I guess I should be able to
figure something out.
A thought that struck me just now.
since each alarm line looks like this
"-XXX ALARM=EYY"
would it make sense (provided that no other line looks like this)
to do
if(data.getCharAt(10)=='='){
String s=data+ map.get(data.split("=")[1]); // provided I store the
definitions
//in a map.. but you get the idea.
textpane.addRow(s);
}
or is this a rather clumsy and inefficent way of achiving my goal?
/daniel
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- message Driven bean problemhi,
i am trying to design an EJB application using session , entity and
message beans
it's a messaging board , a user can add a message , reply to a
message , and delete the message
when glasfish is running more than one application,
the board client side keeps calling the wrong jms\
// the addTopic class
package web;
import ejb.Topic;
import java.io.*;
import java.util.Date;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddTopic extends HttpServlet {
@Resource(mappedName = "jms/BoardTopicFactory")
private ConnectionFactory connectionFactorys = null;
@Resource(mappedName = "jms/BoardTopic")
private Queue queue = null;
private Connection connection = null;
private Session session = null;
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
try {
try {
// creating a connection
connection = connectionFactorys.createConnection();
session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer =
session.createProducer(queue);
ObjectMessage message = session.createObjectMessage();
Topic topic = new Topic();
// getting and setting all attributes required for the
topic
topic.setTopicDate(new Date());
// topic name validation , if empty , do not add it to
the database
if (request.getParameter("topicName").equals("")) {
} else {
topic.setTopicName(request.getParameter("topicName"));
message.setObject(topic);
messageProducer.send(message);
messageProducer.close();
// connection.close();
}
} finally {
if (session != null) {
session.close();
}
if (connection != null) {
connection.close();
}
}
} catch (JMSException ex) {
ex.printStackTrace();
}
getServletConfig().getServletContext().getRequestDispatcher("/
index.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Returns a short description of the servlet.
*/
@Override
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
----------------------------------------------------------------------------------------------------
///the jms class
package ejb;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@MessageDriven(mappedName = "jms/BoardTopic", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode",
propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType",
propertyValue = "javax.jms.Queue")
})
public class BoardTopicBean implements MessageListener {
@PersistenceContext
private EntityManager em;
@Resource
MessageDrivenContext mdc;
public BoardTopicBean() {
}
public void onMessage(Message message) {
ObjectMessage msg = null;
try {
msg = (ObjectMessage) message;
persist(msg.getObject());
} catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
} catch (Throwable te) {
te.printStackTrace();
}
}
public void persist(Object object) {
// save the object (MessageTable or Topic)
em.persist(object);
// if the object is a MessageTable then add this newly created/
persisted object to the list of messages in the topic
if (object instanceof MessageTable) {
MessageTable msg = (MessageTable) object;
Topic topic = msg.getTopic();
if (topic == null) {
em.remove(msg);
} else {
topic = em.find(Topic.class, topic.getId());
topic.getMessages().add(msg);
em.merge(topic);
}
} else {
System.out.println("Wrong type in
merge..................");
}
}
}
----------------------------------------------------------------------------------------------------------------------
some of the exceptions thrown to the console
DirectConsumer:Caught Exception delivering
messagecom.sun.messaging.jmq.io.Packet cannot be cast to
com.sun.messaging.jms.ra.DirectPacket
MQJMSRA_DM4001: :Exception:ObjectMessage.getObject()DeSerializing
object::message=ejb.Topic
javax.jms.MessageFormatException:
MQJMSRA_DM4001: :Exception:ObjectMessage.getObject()DeSerializing
object::message=ejb.Topic
at
com.sun.messaging.jms.ra.DirectObjectPacket.getObject(DirectObjectPacket.java:
169)
at ejb.HockeyMessagesBean.onMessage(HockeyMessagesBean.java:
34)
at sun.reflect.GeneratedMethodAccessor140.invoke(Unknown
Source)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:
25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
com.sun.enterprise.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:
1067)
at
com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:176)
at
com.sun.ejb.containers.BaseContainer.invokeTargetBeanMethod(BaseContainer.java:
2895)
at
com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:
3986)
at
com.sun.ejb.containers.MessageBeanContainer.deliverMessage(MessageBeanContainer.java:
1111)
at
com.sun.ejb.containers.MessageBeanListenerImpl.deliverMessage(MessageBeanListenerImpl.java:
74)
at
com.sun.enterprise.connectors.inflow.MessageEndpointInvocationHandler.invoke(MessageEndpointInvocationHandler.java:
179)
at $Proxy52.onMessage(Unknown Source)
at
com.sun.messaging.jms.ra.OnMessageRunner.run(OnMessageRunner.java:258)
at
com.sun.enterprise.connectors.work.OneWork.doWork(OneWork.java:76)
at com.sun.corba.ee.impl.orbutil.threadpool.ThreadPoolImpl
$WorkerThread.run(ThreadPoolImpl.java:555)
Caused by: java.lang.ClassNotFoundException: ejb.Topic
at
com.sun.enterprise.loader.EJBClassLoader.findClassData(EJBClassLoader.java:
718)
at
com.sun.enterprise.loader.EJBClassLoader.findClass(EJBClassLoader.java:
631)
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.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at com.sun.messaging.jms.ra.DirectObjectPacket
$ObjectInputStreamWithContextLoader.resolveClass(DirectObjectPacket.java:
301)
at
java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:
1575)
at
java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:
1732)
at
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:
351)
at
com.sun.messaging.jms.ra.DirectObjectPacket.getObject(DirectObjectPacket.java:
155)
... 15 more
DirectConsumer:Caught Exception delivering
messagecom.sun.messaging.jmq.io.Packet cannot be cast to
com.sun.messaging.jms.ra.DirectPacket
MQJMSRA_DM4001: :Exception:ObjectMessage.getObject()DeSerializing
object::message=ejb.HockeyEntity
javax.jms.MessageFormatException:
MQJMSRA_DM4001: :Exception:ObjectMessage.getObject()DeSerializing
object::message=ejb.HockeyEntity
at
com.sun.messaging.jms.ra.DirectObjectPacket.getObject(DirectObjectPacket.java:
169)
at ejb.BoardTopicBean.onMessage(BoardTopicBean.java:33)
at sun.reflect.GeneratedMethodAccessor146.invoke(Unknown
Source)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:
25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
com.sun.enterprise.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:
1067)
at
com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:176)
at
com.sun.ejb.containers.BaseContainer.invokeTargetBeanMethod(BaseContainer.java:
2895)
at
com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:
3986)
at
com.sun.ejb.containers.MessageBeanContainer.deliverMessage(MessageBeanContainer.java:
1111)
at
com.sun.ejb.containers.MessageBeanListenerImpl.deliverMessage(MessageBeanListenerImpl.java:
74)
at
com.sun.enterprise.connectors.inflow.MessageEndpointInvocationHandler.invoke(MessageEndpointInvocationHandler.java:
179)
at $Proxy56.onMessage(Unknown Source)
at
com.sun.messaging.jms.ra.OnMessageRunner.run(OnMessageRunner.java:258)
at
com.sun.enterprise.connectors.work.OneWork.doWork(OneWork.java:76)
at com.sun.corba.ee.impl.orbutil.threadpool.ThreadPoolImpl
$WorkerThread.run(ThreadPoolImpl.java:555)
Caused by: java.lang.ClassNotFoundException: ejb.HockeyEntity
at
com.sun.enterprise.loader.EJBClassLoader.findClassData(EJBClassLoader.java:
718)
at
com.sun.enterprise.loader.EJBClassLoader.findClass(EJBClassLoader.java:
631)
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.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at com.sun.messaging.jms.ra.DirectObjectPacket
$ObjectInputStreamWithContextLoader.resolveClass(DirectObjectPacket.java:
301)
at
java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:
1575)
at
java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:
1732)
at
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:
351)
at
com.sun.messaging.jms.ra.DirectObjectPacket.getObject(DirectObjectPacket.java:
155)
... 15 more
DirectConsumer:Caught Exception delivering
messagecom.sun.messaging.jmq.io.Packet cannot be cast to
com.sun.messaging.jms.ra.DirectPacket
MQJMSRA_DM4001: :Exception:ObjectMessage.getObject()DeSerializing
object::message=ejb.HockeyEntity
-----------------------
any idea guys???
- 2
- BZip2-Files & JavaOk two things:
I'm trying to get the Apache BZip2 Library to work, but I always get a
NullPointerException. My code looks like this:
[CODE]
void load(String filename) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream(filename);
CBZip2InputStream = new CBZip2InputStream(fis);
}
[/CODE]
As soon as the creation of the CBZip2InputStream is reached, a
NullpointerException is thrown. Why?
Secondly: if the library is corrupted (e.g. doesn't work stable) is
there an alternative to it (Googleing did not help me very much)?
Snyke
- 3
- Bug#438188: RFP: schemaspy -- Graphical Database Schema Metadata BrowserPackage: wnpp
Severity: wishlist
* Package name : schemaspy
Version : 3.1.1
Upstream Author : John Currier <email***@***.com>
* URL : http://schemaspy.sourceforge.net/
* License : LGPL
Programming Lang: Java
Description : Graphical Database Schema Metadata Browser
SchemaSpy is a Java-based tool (requires Java 1.4 or higher) that
analyzes the metadata of a schema in a database and generates a visual
representation of it in a browser-displayable format. It lets you click
through the hierarchy of database tables via child and parent table
relationships. The browsing through relationships can occur though HTML
links and/or though the graphical representation of the relationships.
It's also designed to help resolve the obtuse errors that a database
sometimes gives related to failures due to constraints.
--
To UNSUBSCRIBE, email to email***@***.com
with a subject of "unsubscribe". Trouble? Contact email***@***.com
- 4
- 5
- 6
- FYI: A new open source/free O/R mapping tool and server page frameworkAnnounce:
A new open-source O/R mapping tool has just been released. There
are many such programs out there...but this one is very
special because it's simple (no xml configuration ! yay) and has
been tested extensively with postgres (and a bit with mysql).
This tool has been used in production enviroments so the
generated code has most bugs squeezed out by now.
If you have a minute, you can check it out at:
http://www.mollypages.org/dbo/
There's also a server-side page type thingy (like JSP) but with
much cleaner syntax (and easy typing).
Enjoy !
- 7
- JPEG manipulationHi all,
I was just wondering if there is a way of changing a JPEG image in
Java, what i mean is, can i edit a JPEG (manipulate pixels in the
image) ?
Thanks in advance
- 8
- Software Development Kit 1.5Im starting with learning Java, and a book i got about it says i need
Software Development Kit 1.4. If i download and install it, i build a
java program and i try running it with command prompt.
But, commandprompt says i need version 1.5... :( Does some1 know where
i can download this or does some1 know another program to build Java
programs with and where can i download it...
- 9
- Eclipse bug?Eclipse bug? Using most recent version (as of a couple weeks ago,
anyway), if it sits idle for a day or two in the taskbar, it stops
responding -- or at least it is really sluggish if you try to use it
again, and not just for a short time, but until you quit and restart it.
- 10
- Dynamic resizing of JPanelDear experts,
I have the a JDesktopPane and a JPanel added to the CENTER and SOUTH
position of a JFrame respectively.
I would like to dynamically resize the JPanel upon mouseExited like the
Windows TaskBar.
On mouseExited of the JPanel i set the bounds of the JPanel to a new
size. However, the sizes do not reflect visually. I have called
invalidate(), validate(), repaint() and none seems to work.
Other than using JSplitPane to create a resizable JPanel, how can I make
this work?
Others have suggested using LayoutManagers but which one and how?
Thank you in advance.
- 11
- wats the cluefrnds wen we connect with Oracle server from java,we use
getConnection(oracledriver,IPadress of
server,servername,username ,password);
forgive me if they r not in the same order.now my question is wat is
the server name if we use same system for server as well as
client.Ofcourse the IP address is loop back address.
Thanks in Advance.
Srinivas Reddy Thatiparthy.
- 12
- GUI locking up, but code running fine.I'm using Netbeans 5.0 beta for an IDE, with swing components. The
situation is something like this:
The program is a board game - the user chooses a building from a panel,
and then is supposed to get a message to choose what resource to pay
for it with. Here's a trace of the code:
Game (main object):
....
board[i].activate():
Game.game.setPlayer(worker);
Game.game.playerMessage("Choose a wooden building
from the building panel.");
Game.game.waitForBuild(type) :
built = false;
state = type + Game.BuildWood -
1;
mainPanel.buildings.getBP().setSelectedIndex(type-1);
while(!built)
{ Thread.yield(); }
No problems yet. This works fine, unless a building that needs to call
chooseResource is selected.
So, the user clicks one of these buildings, which activates the
following code, which is where the freeze occurs:
String r = Game.game.chooseResource():
state = Game.chooseResource;
resource = "";
while(resource.length()==0)
Thread.yield();
return resource;
Now chooseResource does work in any other context - resource gets set
by a mouseClicked event handler in a panel out there. But at this
point, the GUI stops responding. The playerMessage never gets printed,
and the click event never gets triggered. I did some investigating,
printing out numbers inside the two inmost loops, and the
chooseResource loop is continually running. I know the code's ugly,
but even so, the cause of this behavior is beyond me. Any suggestions
would be greatly appreciated!
- 13
- richtext componentIsn't there a richtext component available within java sdk? I know I don't
see any in the pallette, is there a class where i can initiate one? or 3rd
party?
- 14
- JCheckBox problem Please helpHi All
My question is how to remove the border from inner rectangle of a
JCheckBox.
A JCheckBox has 2 rectangles,it is possible to remove the boder from the
outside one ,but what about the rectangle where the user clicks.(I am
referring this rectangle as inner rectangle)
Hoping a quick reply
Praveen
--
Message posted via http://www.javakb.com
- 15
- How to get the path of remotly run application by knowing the port numberHi,
I am new to this group, and i request you all to help in solving the
issues i have.
Thank you for having this group.
I need to know the path or install directory of an application,
I am able to access the the application by port number.
but i need to wright a java programe thr which i need to get the path
or install directory of the application.
Eg
http://servername:2000/
I request you all to help in the same.
|
|
|