| Tired of 100s of stupid Getter/Setter methods |
|
 |
Index ‹ java-programmer
|
- Previous
- 6
- SQL into XMLHi All;
My SQL queries return one, two, sometimes even three levels of XML
data.
So for orders in my system I would like to see in my XML:
<RESULTS>
<order>
<number>3213</number>
<date>Feb 03, 2003</date>
<product>
<name>NEC Monitor</name>
<quantity>3</quantity>
<serial_numbers>
<sn>12321312321</sn>
<sn>44314133422</sn>
<sn>43434343553</sn>
<serial_numbers>
</product>
<product>
<name>Genius Mouse</name>
<quantity>2</quantity>
<serial_numbers>
<sn>23232</sn>
<sn>44343</sn>
<serial_numbers>
</product>
</order>
<order>
<number>444</number>
<date>Mar 06, 2003</date>
<product>
<name>MS Keyboard</name>
<quantity>1</quantity>
<serial_numbers>
<sn>333333</sn>
<serial_numbers>
</product>
</order>
........
</RESULTS>
obviously my query would reutrn
order_num order_date product_name quantity
serial_number
------------------------------------------------------------------------
3231 Feb 03, 2003 NEC Monitor 3 12321312321
3231 Feb 03, 2003 NEC Monitor 3 44314133422
3231 Feb 03, 2003 NEC Monitor 3 43434343553
3231 Feb 03, 2003 Genius Mouse 2 23232
3231 Feb 03, 2003 Genius Mouse 2 44343
444 Mar 06, 2003 MS Keyboard 1 333333
You get the point. I do not want to have 3 queries, but only one that
returns something like described above.
For now I have a functioin that does this, but the algorithm is not
the best, and it only works for two levels (so XML without the s/n for
example).
This must be a common problem, I would appriciate input as to how this
is commonly done, any pointers to web sites, articles... are all
welcome. I'd try to search the groups but for what?:) I would also
like to describe my current algorithm, but for now it seems I would
just bore you.
Looking for some input,
Damjan
- 6
- Data generatorDo You know if there is any data generator for databases like TurboData,
but for free?
- 7
- [RFE] Access to Field, Method and Constructor without the use of Strings
Hi all,
I submitted the following RFE to Sun's RFE page.
As a reply I received a mail from Girish Manwani at Sun that I
should start a discussion in one of the Java newsgroups (Huh?).
To my knowledge, this is the most appropriate group. Here gos:
A DESCRIPTION OF THE REQUEST:
It should be possible to obtain references to Field, Method and
Constructor objects without the use of strings. Proposed syntax:
// Assuming the following class
public class Foo {
String bar;
public Foo(String bar) {
this.bar = bar;
}
public void fly(String to) {
bar = to;
}
}
Field fooBarField = Foo.class.bar.field;
Method fooFlyMethod = Foo.class.fly.method(new Object[]{String.class});
Constructor fooConstructor = Foo.class.constructor(new Object[]{String.class});
There are other possible options for the syntax. I would just like to see
this principally possible.
The construct is similar to the ClassName.class syntax and it can be treated
by the Compiler in the same way:
It could produce the getDeclaredField, getDeclaredMethod and getConstructor
bytecode. No modifications to the JVM would be necessary.
JUSTIFICATION :
The existance of the field/method/constructor could be checked during compile
time. Typos would no longer be possible.
A notation without strings could be very easily refactored by IDEs.
We would specifically need the feature for our typesafe querying system,
so it could work completely without strings.
http://sodaquery.sf.net/
The possibility to get Method objects without strings, would encourage many
developers to use them for more dynamic programming and would result in lots
of more flexible libraries for the Java platform.
Thanks in advance for your attention and for positive comments.
Kind regards,
Carl
Carl Rosenberger
db4o - database for objects - http://www.db4o.com
- 7
- How does Java make assignments atomic?>From what I understand, Java guarantees that all assignments to
primitive types (except non-volatile 64-bit types) will be atomic.
How does it do this? I thought that the only truly uninterruptable
processor instruction was the test-and-set, and that test-and-set was
the basis from which richer thread synchronization resources typically
provided by an underlying operating system (e.g. semaphores, mutexes,
critical sections) were built.
Does Java internally implement all of its generated assignment opcodes
inside some kind of test-and-set-based wrappers?
Thanks.
- 10
- 10
- JButton - Set font to fillHi,
I want to create the best fitting font for my jbutton, so when the user
expands the UI, the JButton expands or shrinks, so I then change the size of
the font to fill the button correctly..
I am trying something like this on component resize:
- 10
- 12
- JOptionPane.showInputDialog on JButton[][] arraySorry i have a problem.
I don't know the java language but i must create a grid Of button witch
random Values, and when i clicked on one button i must change the internal
values.
I try ti make a code but i don't know how to pass the value of botton to
mouse event, and change it with
String input = JOptionPane.showInputDialog("Insert value:");
for a single button there aren't any problems, but how can I change the
value of an array of button witch MouseEvent?
Thx!!!! please help me!!!!
QUADRATOFRAME.CLASS
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class QuadratoFrame extends JFrame {
JButton pulsante = new JButton();
int N=6;
int MAXELEM = 50;
int[][] mat=new int[N][N];
JButton[][] jb = new JButton[N][N];
private JPanel pannello2= new JPanel();
LeftButtonListener leftListener = new LeftButtonListener();
public QuadratoFrame() {
Random generator=new Random();
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
mat[i][j]=generator.nextInt(MAXELEM);
for(int i = 0; i < N; i++)
for (int j=0; j<N; j++)
{
jb[i][j] = new JButton(Integer.toString(mat[i][j]));
pulsante=jb[i][j];
pulsante.addMouseListener(leftListener);
}
pannello2.setLayout(new GridLayout(N,N));
getContentPane().add(pannello2);
pack();
for(int i = 0; i < jb.length; i++)
for (int j=0; j<N; j++)
pannello2.add(jb[i][j]);
}
private class LeftButtonListener implements MouseListener {
public void mouseClicked(MouseEvent event) { }
public void mouseEntered(MouseEvent event) { }
public void mouseExited(MouseEvent event) { }
public void mousePressed(MouseEvent event) {
String input = JOptionPane.showInputDialog("Insert new value:");
}
public void mouseReleased(MouseEvent event) { }
}
}
QUADRATOTEST.CLASS
import javax.swing.*;
/**Una classe che rende attivo il programma Frattali
*tramite la costruzione e la visualizzazione della finestra Frattali nel
main.
*/
public class QuadratoTest {
public static void main(String[] args) {
JFrame myFrame=new QuadratoFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(800,600);
myFrame.show();
}
}
- 14
- JBuilder applet, adding class to jarI have applet which uses classes like java.util.AbstractList,
java.awt.Point. Unfortunately MS VM doesnt support above(i got IO
exception, above classes not found) So i guess i have to add those
classes to my jar. No idea how to do it... Any help appreciated...
- 14
- Making and Returning Java Byte Arrays in C++ via JNI (Help! Please!)How do you make java byte arrays, fill them with values, and return
them in c++? I have no clue where to start. The JNI Tutorial a at
Java's website isn't much help because it doesn't really explain how to
make new jarrays. Any tips, how-tos and example code are welcome! (And
can anybody please explain me what's jsize? Is it just another integer?)
- 16
- IE AutomationI am working on developing a test application in java. I use java for UI
only. I use JNI to communicate with a VC MFC DLL. I launch an IE browser
instance in one JNI method (init()), which works fine.
OleInitialize(NULL);
CLSID clsid;
CLSIDFromProgID(OLESTR("InternetExplorer.Application"), &clsid);
HRESULT hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER,
IID_IWebBrowser2, (void**)&m_spBrowser);
I store the browser pointer (IWebBrowser2 *) as a C++ class instance
variable. BTW, I start a
thread on the native side (_beginthread) which in turn calls the method that
launches the browser.
Previously I was facing the problem of marshalling, the IWebBrowser2 pointer
was getting correupted, when used in different methods (even the simple
properties of IWebBrowser2 (like IWebBrowser2::fullname) were not
accessible). So now I have added the code of marshalling after the browser
is launched. In almost all the other methods, I first unmarshall the
interface and then marshall it back at the end of it. This solved my earlier
mentioned problem.
void CIECanvas::MarshallInterface()
{
HRESULT hr;
if(SUCCEEDED(hr = ::CreateStreamOnHGlobal(NULL, TRUE, &pstm)))
{
LARGE_INTEGER bZero = {0, 0};
pstm->Seek(bZero, STREAM_SEEK_SET, NULL);
if(SUCCEEDED(::CoMarshalInterface(pstm, IID_IWebBrowser2, m_spBrowser,
MSHCTX_INPROC, NULL, MSHLFLAGS_NORMAL)))
{
pstm->Seek(bZero, STREAM_SEEK_SET, NULL);
}
}
}
void CIECanvas::UnmarshallInterface()
{
LARGE_INTEGER bZero = {0, 0};
pstm->Seek(bZero, STREAM_SEEK_SET, NULL);
HRESULT hr = ::CoUnmarshalInterface(pstm, IID_IWebBrowser2,
(void**)&m_spBrowser);
if(FAILED(hr))
{
showMessageBox("CIECanvas::UnmarshallInterface()", "%s %ld", "FAILED.
ERROR CODE = ", GetLastError());
}
}
Then for recording I use AfxConnectionAdvise(), which is working fine.
The problem I am facing is in Replaying the events.
1)The VM crashes with a hotspot error, when on the first page some link
click event is present, which loads a new page. One observation here is the
VM crashes after onBeforeNavigate2 or TitleChange events are fired.
2)I also tried Yahoo's registration page (having a lot of dropdowns and
checkboxes), it works fine for the first few events, but then the VM
crashes.
My questions are
1)Does IE handle the events like page loading (tiltle change etc.) and click
on some link in different threads? How are the events handled (any useful
info on this)?
2)How should I fix the problem?
3)Is it related to marshalling of IE COM pointers?
Please replay ASAP,
Nikhil
- 16
- Using BigInteger and BigDecimal [WAS: Converting floats to Strings and back]
"Alun Harford" <email***@***.com> wrote in message
news:dlvmk8$j8e$email***@***.com...
>
> Unless you want speed (ie. the arithmetic is hard and you've analysed the
> result of using floating-point to do it), or you want to demonstrate some
> of
> the nasty things that happen with floating point, use BigDecimal.
> a) It requires significantly less use of your brain, which generally
> reduces
> the number of bugs.
> b) Your users shouldn't have to think about the limitations of floating
> point without a very good reason.
I've experimented with using BigInteger instead of int in my code with
mixed results. Code that was integer-math intensive (e.g. finding prime
numbers) typically ran 5 to 7 times slower, which is pretty bad, but not
"noticeable" for typical user applications. I'll probably continue this
practice because for most of my apps, the bottleneck is not the
integer-math, and the extra flexibility is nice.
My question is: is there a "best" way to store BigInteger and BigDecimal
values in databases (particularly in SQL)? The two most obvious solutions to
me is to store them as BLOBs or as strings. I'd probably favor the latter,
because although it uses more storage space and processing time (e.g. to
parse the string back into a BigInteger value), it'll probably be easier to
inspect the DB to make sure all the values are correct during debugging.
- Oliver
- 16
- Help choosing JSP ServerHello,
could you folks share with me your recomendations on what JSP servers are
available for a small
business with a very small budget, hopefully something that would produce
error message little
more descriptive than that of Tomcat and also with discent web-server
plugin capabilities and
administration interface.
Thanks in advance,
Ilya Bari.
- 16
- portaudit and linux-sun-jdk15>
X-XaM3-API-Version: 4.3 (R1) (B3pl17)
X-SenderIP: 82.49.197.26
I'm referring to the informations displayed on this page:
http://www.vuxml.org/freebsd/18e5428f-ae7c-11d9-837d-000e0c2e438a.html
Is the information about linux-sun-jdk15 correct?
1.5.* <= linux-sun-jdk <= 1.5.2.02,2
I think that the correct version should be 1.5.0.02,2 considering also that a 1.5 based version >=1.5.1 doesn't (yet) exist.
The last jdk versions for linux is 1.5.0.11 and the port with that version has been committed today, but portaudit is still complaining about this vulnerability.
Thank you.
P.S.
Sorry if I'm writing to too many people, but I'm not sure about who is responsible for that problem.
------------------------------------------------------
Passa a Infostrada. ADSL e Telefono senza limiti e senza canone Telecom
http://click.libero.it/infostrada25feb07
- 16
- JMS and httpsHi all,
Have JMS to use with https
It says in documentation to supply these four arguments,
javax.net.ssl.trustStore, javax.net.ssl.keyStore,
javax.net.ssl.keyStoreType and javax.net.ssl.keyStorePassword
Here's my sample below:
System.setProperty("javax.net.ssl.trustStore", "C:\\Program
Files\\Java\\j2re1.4.2_03\\lib\\security\\cacerts");
System.setProperty("javax.net.ssl.keyStore",
"D:\\Projects\\certificates\\tomcat.keystore");
System.setProperty("javax.net.ssl.keyStoreType", "jks");
System.setProperty("javax.net.ssl.keyStorePassword",
"changeit");
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"org.exolab.jms.jndi.InitialContextFactory");
properties.put(Context.PROVIDER_URL,
"https://localhost:8443/");
jndiContext = new InitialContext(properties);
For some reason after creating the new initial context, its reporting:
Default SSL context init failed: null
Did I set my trustStore path correctly?
Thanks
|
| Author |
Message |
Chris Smith

|
Posted: 2003-12-29 23:41:00 |
Top |
java-programmer, Tired of 100s of stupid Getter/Setter methods
Tor Iver Wilhelmsen wrote:
> Dave Glasser <email***@***.com> writes:
>
> > Java does not. Methods can be overridden with less restrictive access
> > (like the common practice of overriding Object.clone() with a public
> > clone() method) but not more restrictive access.
>
> But they can be overridden with exception-throwing code to ensure
> they're not used.
Indeed. That's more of a symptom of a problem than a reasonable
solution. You're then left with a class that professes to follow an
interface, but doesn't follow it. What you really wanted was to
implement a different interface on top of existing functionality... a
task for which composition is ideal.
Of course, in a pinch, the exception-throwing kludge will work; it's
integrated into the collections API and even given a fancy name:
"optional methods". However, even its light application there is
generally acknowledged to be one of the few great failures of that API.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
|
| |
|
| |
 |
Chris Smith

|
Posted: 2003-12-29 23:41:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Tor Iver Wilhelmsen wrote:
> Dave Glasser <email***@***.com> writes:
>
> > Java does not. Methods can be overridden with less restrictive access
> > (like the common practice of overriding Object.clone() with a public
> > clone() method) but not more restrictive access.
>
> But they can be overridden with exception-throwing code to ensure
> they're not used.
Indeed. That's more of a symptom of a problem than a reasonable
solution. You're then left with a class that professes to follow an
interface, but doesn't follow it. What you really wanted was to
implement a different interface on top of existing functionality... a
task for which composition is ideal.
Of course, in a pinch, the exception-throwing kludge will work; it's
integrated into the collections API and even given a fancy name:
"optional methods". However, even its light application there is
generally acknowledged to be one of the few great failures of that API.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
|
| |
|
| |
 |
kamikaze

|
Posted: 2003-12-30 4:35:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Dimitri Maziuk <email***@***.com>
wrote on Sun, 28 Dec 2003 19:16:25 +0000 (UTC):
> Most OO courses spend a lot of time praising benefits of
> inheritance, so people tend to use it where it isn't
> entirely appropriate. Or have hard time deciding where it
> is appropriate.
I find more often that a lot of people have come to OOP from
procedural programming without any formal training, and haven't bothered
to learn the native idioms.
> E.g. Stack based on Vector -- it "is a" vector, in a sense,
> but without random access to the elements. So you either
> have to redeclare most Vector's methods as private in
> Stack to hide them (you only want isEmpty(), push(),
> and pop()) -- that's a lot of typing.
That's wrong, as anyone who's programmed in Forth knows. Very often
when using a stack, you want random access to the elements. A "minimal"
stack is only really useful in trivial computer science proofs, not in
real applications. A Vector is a pretty decent representation of a LIFO
stack, and it's an efficient representation, since it'll grow and shrink
at the top of the array.
If you were implementing swch a class and wanted to only see the
relevant methods, you could implement a restricted interface and
recommend using a reference to that. That's the correct solution,
rather than ignoring the fact that those methods are appropriate to the
subclass.
--
<a href="http://kuoi.asui.uidaho.edu/~kamikaze/"> Mark Hughes </a>
"God, I think. God. He doesn't answer, and I'd be justifiably scared--but not
in a panic!--if he did, since I would know it really was Resuna, or a tiny
brain tumor, or some boo-boo in my mix of neurotransmitters." -John Barnes
|
| |
|
| |
 |
Dimitri Maziuk

|
Posted: 2003-12-30 5:11:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Mark 'Kamikaze' Hughes sez:
...
> If you were implementing swch a class and wanted to only see the
> relevant methods, you could implement a restricted interface and
> recommend using a reference to that. That's the correct solution,
> rather than ignoring the fact that those methods are appropriate to the
> subclass.
Yeah, but interface does not hide the other methods of implementing
class. Stack/Vector may not be a particularly good example of why you
would want to hide those methods, but sometimes you do want that even
IRL (in textbooks it comes under "hiding implementation details").
Besides, an interface in Java terms means you have to type in the
code, whereas inheritance lets you inherit the implementation.
With composition you can reuse the implementation and hide it, too.
Put it in the private field, and make whatever public interface you
like with least amount of trouble -- compared to hoops you have to
jump through to hide superclass' members or to writing code for all
methods specified by interface.
A typical Java example is type-safe containers: I want a vector of
strings, not Objects. But you can't override on return value. The
(arguably) easiest way out is to put Vector inside StringVector and
write a bunch of one-liner accessors with (String) casts where
appropriate. Again, composition instead of inheritance.
Dima
--
True courage comes from steadying yourself and forcing yourself to ssh into the
fscking thing yet again and not admitting that it doesn't care what it's done
to your life. -- "Hidden among the nodes" by ADB
|
| |
|
| |
 |
brougham5

|
Posted: 2003-12-30 8:01:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Tor Iver Wilhelmsen <email***@***.com> wrote:
>But they can be overridden with exception-throwing code to ensure
>they're not used.
While duct tape and bailing wire can always be used in a pinch, I'd suggest
using kludges to "fix" code is a symptom that the design should be improved.
Having a subclass throw an exception because the method doesn't make sense
in the context of the subclass seems like a violation of the liskov
substituion principle.
|
| |
|
| |
 |
Joona I Palaste

|
Posted: 2004-1-1 2:03:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Chris Smith <email***@***.com> scribbled the following:
> Tor Iver Wilhelmsen wrote:
>> Dave Glasser <email***@***.com> writes:
>>
>> > Java does not. Methods can be overridden with less restrictive access
>> > (like the common practice of overriding Object.clone() with a public
>> > clone() method) but not more restrictive access.
>>
>> But they can be overridden with exception-throwing code to ensure
>> they're not used.
> Indeed. That's more of a symptom of a problem than a reasonable
> solution. You're then left with a class that professes to follow an
> interface, but doesn't follow it. What you really wanted was to
> implement a different interface on top of existing functionality... a
> task for which composition is ideal.
> Of course, in a pinch, the exception-throwing kludge will work; it's
> integrated into the collections API and even given a fancy name:
> "optional methods". However, even its light application there is
> generally acknowledged to be one of the few great failures of that API.
I have to agree. In my Software Design: Java course, a homework problem
asked me to demonstrate a problem with the Collections framework. My
answer was "optional methods", which are a design problem.
In "real" code, I once had to make an abstract class called an
"ImmutableIterator". It's a java.util.Iterator that makes remove()
throw an UnsupportedOperationException but leaves the other methods
as abstract. This is bad OO design, but with java.util.Iterator being
what it is, how could I have avoided it?
A better solution would have been java.util.Iterator without remove()
and java.util.MutableIterator inheriting from it, adding remove().
This would have made my ImmutableIterator needless.
--
/-- Joona Palaste (email***@***.com) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"This isn't right. This isn't even wrong."
- Wolfgang Pauli
|
| |
|
| |
 |
kamikaze

|
Posted: 2004-1-1 2:48:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Dimitri Maziuk <email***@***.com>
wrote on Mon, 29 Dec 2003 21:10:50 +0000 (UTC):
> Mark 'Kamikaze' Hughes sez:
>> If you were implementing swch a class and wanted to only see the
>> relevant methods, you could implement a restricted interface and
>> recommend using a reference to that. That's the correct solution,
>> rather than ignoring the fact that those methods are appropriate to the
>> subclass.
> Yeah, but interface does not hide the other methods of implementing
> class. Stack/Vector may not be a particularly good example of why you
> would want to hide those methods, but sometimes you do want that even
> IRL (in textbooks it comes under "hiding implementation details").
It is a common academic exercise, because academics don't have any
real work to do, so they obsess about mathematical purity. In real
engineering, though, I've never seen a case where subclassing was
appropriate and yet you'd need to disable some methods. That's a code
smell, telling you that you need to refactor a new common superclass.
> Besides, an interface in Java terms means you have to type in the
> code, whereas inheritance lets you inherit the implementation.
> With composition you can reuse the implementation and hide it, too.
Well, of course you have to type in the code, because the
implementation will be totally different. If there's common code, but
they're not subclassing each other, you're almost certainly doing
something wrong. Again, that's a code smell. "Fixing" it by wrapping
some other class up is like patching on your car door with duct tape.
> A typical Java example is type-safe containers: I want a vector of
> strings, not Objects. But you can't override on return value. The
> (arguably) easiest way out is to put Vector inside StringVector and
> write a bunch of one-liner accessors with (String) casts where
> appropriate. Again, composition instead of inheritance.
That's just hiding the fact of casting from the user, but you're still
paying the performance penalty. java.util.Properties has String->String
mappings, on top of the Hashtable implementation, and that works well
enough for its purposes, because people *don't* abuse it. Prior to
generics going in the language, the "right" solution was to make a
template class (with "${TYPE}" as a placeholder) and use sed to generate
your actual classes. They're not going to have a common interface, no
matter what you do. A StringVector cannot take Integer parameters.
They have methods with the same names, but the signatures are totally
different. Inheritance, composition, and interfaces are all wrong for
that case.
Ultimately, though, "type-safe" containers are not necessary. In 6
years of Java development, I've never had problems with putting the
wrong things in a generic container, and I know this, because the act of
casting it when I withdraw it would be a valid safety check. It's just
paranoia from people who don't test their code adequately.
--
<a href="http://kuoi.asui.uidaho.edu/~kamikaze/"> Mark Hughes </a>
"God, I think. God. He doesn't answer, and I'd be justifiably scared--but not
in a panic!--if he did, since I would know it really was Resuna, or a tiny
brain tumor, or some boo-boo in my mix of neurotransmitters." -John Barnes
|
| |
|
| |
 |
Chris Smith

|
Posted: 2004-1-1 3:58:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Joona I Palaste wrote:
> Chris Smith <email***@***.com> scribbled the following:
> > Of course, in a pinch, the exception-throwing kludge will work; it's
> > integrated into the collections API and even given a fancy name:
> > "optional methods". However, even its light application there is
> > generally acknowledged to be one of the few great failures of that API.
>
> I have to agree. In my Software Design: Java course, a homework problem
> asked me to demonstrate a problem with the Collections framework. My
> answer was "optional methods", which are a design problem.
> In "real" code, I once had to make an abstract class called an
> "ImmutableIterator". It's a java.util.Iterator that makes remove()
> throw an UnsupportedOperationException but leaves the other methods
> as abstract. This is bad OO design, but with java.util.Iterator being
> what it is, how could I have avoided it?
Another real example. Part of what I maintain is a data access
framework for a particular application. Basically, it's a very simple
O/R mapper plus some utility classes. Recently, in response to some
scalability issues from a large customer, I took a method that
previously read objects from a database and populated a java.util.List,
and instead substituted (in some circumstances) my own implementation of
List that maintains a ResultSet and doesn't instantiate the data until
it's requested.
This broke some remote corner of the application. On looking into it,
it turns out that some other developer had ignored the clear
documentation stating that this list should be treated as read-only, and
had instead discovered that the method was returning an ArrayList, and
had modified that list as if it were some private working-space for an
algorithm. I fixed the client code, and added bold tags around the
appropriate warning in the API docs for the data framework... but I
doubt the developer read the documentation before doing so last time,
and I doubt the next developer will read the docs before doing so again.
It would be nice to be able to return an UnmodifiableList that simply
doesn't HAVE those methods.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
|
| |
|
| |
 |
Dimitri Maziuk

|
Posted: 2004-1-2 8:39:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Mark 'Kamikaze' Hughes sez:
> Dimitri Maziuk <email***@***.com>
> wrote on Mon, 29 Dec 2003 21:10:50 +0000 (UTC):
>> ... (in textbooks it comes under "hiding implementation details").
>
> It is a common academic exercise, because academics don't have any
> real work to do, so they obsess about mathematical purity.
There are a couple of posts in this thread that seem to disagree.
> Ultimately, though, "type-safe" containers are not necessary.
Sure, and everything can be written in assembly and without
all those new-fangled "subroutine" things. Still, in a modern
OO language I'd like containers where at least if I put in a
String, I get a String back out.
...In 6
> years of Java development, I've never had problems with putting the
> wrong things in a generic container, and I know this, because the act of
> casting it when I withdraw it would be a valid safety check. It's just
> paranoia from people who don't test their code adequately.
All that means is you don't write class libraries for other people
to use.
Dima
--
Q276304 - Error Message: Your Password Must Be at Least 18770 Characters
and Cannot Repeat Any of Your Previous 30689 Passwords -- RISKS 21.37
|
| |
|
| |
 |
kamikaze

|
Posted: 2004-1-2 13:10:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Dimitri Maziuk <email***@***.com>
wrote on Fri, 2 Jan 2004 00:38:35 +0000 (UTC):
> Mark 'Kamikaze' Hughes sez:
>> Dimitri Maziuk <email***@***.com>
>> wrote on Mon, 29 Dec 2003 21:10:50 +0000 (UTC):
>>> ... (in textbooks it comes under "hiding implementation details").
>> It is a common academic exercise, because academics don't have any
>> real work to do, so they obsess about mathematical purity.
> There are a couple of posts in this thread that seem to disagree.
Nobody else posted on that subject at all. There are others who've
picked up procedural-programmer memes about using classes as structs
instead of using inheritance, but at least nobody else has been infected
with Ada-isms (for lack of a better term).
>> Ultimately, though, "type-safe" containers are not necessary.
> Sure, and everything can be written in assembly and without
> all those new-fangled "subroutine" things. Still, in a modern
> OO language I'd like containers where at least if I put in a
> String, I get a String back out.
You do get a String back out. The reference is not typecast to
String, but the object has never stopped being a String. A cast doesn't
change data in Java, it's just a run-time assertion that assures the
compiler that the type of the object is X, so the reference can be
assigned to a variable. Maybe you understand that already, but your way
of phrasing that suggests that you do not.
Python is a modern OO language--far more modern, more pleasant, and
more OO than Java--and it has no typed references. It has tuples,
lists, and dicts as built-in types, and their contents are not
"type-safe". It's like programming in Java with only Object references,
except the language is designed intelligently so doing that does not
suck. And the result of that choice is not that it's harder, not
lower-level, and not more dangerous, but faster, higher-level, and safer
to develop in; it's also somewhat slower at run-time, but less than
you'd think. Python's just one example, there are many others. Ask a
Lisper whether type-safe lists are necessary.
Type-safe containers are a C++-ism. C++ doesn't have a single-root
inheritance tree, so generic containers were much more difficult to do
right. Those C++-ers came to Java, and demanded templates, because
that's how they'd always done it. Sun, being the spineless jellyfish
they are, buckled. That doesn't make it holy writ.
>> ...In 6
>> years of Java development, I've never had problems with putting the
>> wrong things in a generic container, and I know this, because the act of
>> casting it when I withdraw it would be a valid safety check. It's just
>> paranoia from people who don't test their code adequately.
> All that means is you don't write class libraries for other people
> to use.
BZZT! It would be hard to get a more wrong answer. I have, many
times, for rather good pay. I just don't normally assume that other
programmers are morons or actively malicious (I reserve that attitude
for the end-users), and I don't write code that's so fragile that using
the declared interface will make it blow up. Either behaviour would be
a career-limiting move in my experience.
--
<a href="http://kuoi.asui.uidaho.edu/~kamikaze/"> Mark Hughes </a>
"God, I think. God. He doesn't answer, and I'd be justifiably scared--but not
in a panic!--if he did, since I would know it really was Resuna, or a tiny
brain tumor, or some boo-boo in my mix of neurotransmitters." -John Barnes
|
| |
|
| |
 |
brougham5

|
Posted: 2004-1-2 21:56:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Chris Smith <email***@***.com> wrote:
>This broke some remote corner of the application. On looking into it,
>it turns out that some other developer had ignored the clear
>documentation stating that this list should be treated as read-only, and
>had instead discovered that the method was returning an ArrayList, and
>had modified that list as if it were some private working-space for an
>algorithm. I fixed the client code, and added bold tags around the
>appropriate warning in the API docs for the data framework... but I
>doubt the developer read the documentation before doing so last time,
>and I doubt the next developer will read the docs before doing so again.
>It would be nice to be able to return an UnmodifiableList that simply
>doesn't HAVE those methods.
Instead of adding more docs, make it so that client code abuses don't affect
anything else.
Don't return an ArrayList that can be modified. At the very least, return a
new, deep copy of the list so that if it is modified, the rest of the
program doesn't care. Even better, return a wrapper of sorts that doesn't
allow its data to be changed if changing the data will cause problems.
If you have to rely on other developers following documentation to keep your
code from breaking, you are writing bad code.
|
| |
|
| |
 |
Chris Smith

|
Posted: 2004-1-2 22:16:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Mark 'Kamikaze' Hughes wrote:
> Python is a modern OO language--far more modern, more pleasant, and
> more OO than Java--and it has no typed references. It has tuples,
> lists, and dicts as built-in types, and their contents are not
> "type-safe". It's like programming in Java with only Object references,
> except the language is designed intelligently so doing that does not
> suck. And the result of that choice is not that it's harder, not
> lower-level, and not more dangerous, but faster, higher-level, and safer
> to develop in; it's also somewhat slower at run-time, but less than
> you'd think.
Sounds like you'd rather be developing in Python. If that's the case,
fine.
Nevertheless, Java provides a specific advantage in terms of typing of
references by the compiler. That is a very reasonable advantage to
want. Among other things, it:
a. Increases performance (though that's hardly its main objective).
b. Decreases the very real possibility of bugs due to confusion
about available types. Sorry, but this possibility doesn't go
away because you assert so.
c. Gives more information to smart development tools such as code
editors, so that they can be more helpful.
That all being the case, and whether you prefer a less typed language or
not, making choices that make it easier and less painful to work within
the typed environment makes sense for Java.
> Type-safe containers are a C++-ism. C++ doesn't have a single-root
> inheritance tree, so generic containers were much more difficult to do
> right. Those C++-ers came to Java, and demanded templates, because
> that's how they'd always done it. Sun, being the spineless jellyfish
> they are, buckled. That doesn't make it holy writ.
I certainly don't think so. In fact, seems to me that in a language
where types are so important, it'd be good to do anything possible to
let the compiler find out more about types. That eliminates kludgy
syntax like casting (which is uniquely not checked by the compiler,
among all type constructs), and increases most of the advantages listed
above.
If nothing else, it would be *so* nice to finally be able to declare a
method to return a "List of Strings" -- instead of declaring it to
return a List and adding in human-only documentation that the List
contains Strings -- that generics are worth it for that alone.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
|
| |
|
| |
 |
Chris Smith

|
Posted: 2004-1-2 23:14:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
email***@***.com wrote:
> Instead of adding more docs, make it so that client code abuses don't affect
> anything else.
>
> Don't return an ArrayList that can be modified. At the very least, return a
> new, deep copy of the list so that if it is modified, the rest of the
> program doesn't care.
Perhaps you weren't paying attention. The whole point of the
modification was to prevent instantiating millions of objects from the
database when I possibly only care about the first 25. Doing a deep
copy into an ArrayList would turn an optimization into a less efficient
way of accomplishing nothing.
> If you have to rely on other developers following documentation to keep your
> code from breaking, you are writing bad code.
That wasn't the issue. I was relying on another developer following
documentation to keep that other developer's code from breaking.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
|
| |
|
| |
 |
Michael Borgwardt

|
Posted: 2004-1-2 23:41:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Chris Smith wrote:
>>Don't return an ArrayList that can be modified. At the very least, return a
>>new, deep copy of the list so that if it is modified, the rest of the
>>program doesn't care.
>
>
> Perhaps you weren't paying attention. The whole point of the
> modification was to prevent instantiating millions of objects from the
> database when I possibly only care about the first 25. Doing a deep
> copy into an ArrayList would turn an optimization into a less efficient
> way of accomplishing nothing.
I suspect he meant "shallow copy".
>>If you have to rely on other developers following documentation to keep your
>>code from breaking, you are writing bad code.
>
> That wasn't the issue. I was relying on another developer following
> documentation to keep that other developer's code from breaking.
Still, you were practically *asking* for trouble. When returning a List
that must not be modified, at least use Collections.unmodifiableList(),
that's exactly what it's for!
|
| |
|
| |
 |
Dimitri Maziuk

|
Posted: 2004-1-3 14:13:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Mark 'Kamikaze' Hughes sez:
> Type-safe containers are a C++-ism. C++ doesn't have a single-root
> inheritance tree, so generic containers were much more difficult to do
> right. Those C++-ers came to Java, and demanded templates, because
> that's how they'd always done it. Sun, being the spineless jellyfish
> they are, buckled. That doesn't make it holy writ.
May I point out that when you try to insert an orange into
vector<apple>, compiler barfs on or around the offending line?
Whereas List of Airplanes will happily accept a Pig, and when
you call fly() for each element later on... don't stand
directly under them as they fly past.
(Of course, anyone who's seen a typical g++ error message may
well argue that pigs flying overhead are a much lesser evil.
And I'll probably agree.)
Dima
--
"Mirrors and copulation are abominable because they increase the number of
entities." -- corollary to Occam's Razor
|
| |
|
| |
 |
Chris Smith

|
Posted: 2004-1-3 20:35:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Michael Borgwardt wrote:
> > Perhaps you weren't paying attention. The whole point of the
> > modification was to prevent instantiating millions of objects from the
> > database when I possibly only care about the first 25. Doing a deep
> > copy into an ArrayList would turn an optimization into a less efficient
> > way of accomplishing nothing.
>
> I suspect he meant "shallow copy".
Mmm? Any copy of the list defeats the point.
> Still, you were practically *asking* for trouble. When returning a List
> that must not be modified, at least use Collections.unmodifiableList(),
> that's exactly what it's for!
Yes, I could have done so. Since I wrote the original code years ago, I
don't recall my exact thought processes... but I probably just didn't
think about it. Nevertheless, I can emphatically claim that I would
have returned a read-only List if the interface had existed as a
superinterface of List.
Anyway, I don't recall any longer how this fit into anything in the
first place...
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
|
| |
|
| |
 |
Thomas Gagn

|
Posted: 2004-1-5 21:55:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Doesn't someone inserting pigs into their airplane list have larger
problems than the (in)ability to insert the pig? Their problem is a
faulty algorithm, not the insert. How the heck did a pig end-up being
processed as an airplane?
Dimitri Maziuk wrote:
>Mark 'Kamikaze' Hughes sez:
>
>
>
>> Type-safe containers are a C++-ism. C++ doesn't have a single-root
>>inheritance tree, so generic containers were much more difficult to do
>>right. Those C++-ers came to Java, and demanded templates, because
>>that's how they'd always done it. Sun, being the spineless jellyfish
>>they are, buckled. That doesn't make it holy writ.
>>
>>
>
>May I point out that when you try to insert an orange into
>vector<apple>, compiler barfs on or around the offending line?
>Whereas List of Airplanes will happily accept a Pig, and when
>you call fly() for each element later on... don't stand
>directly under them as they fly past.
>
>(Of course, anyone who's seen a typical g++ error message may
>well argue that pigs flying overhead are a much lesser evil.
>And I'll probably agree.)
>
>Dima
>
>
--
.tom
remove email address' dashes for replies
opensource middleware at <http://isectd.sourceforge.net>
http://gagne.homedns.org
|
| |
|
| |
 |
Michael Borgwardt

|
Posted: 2004-1-5 22:56:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Thomas Gagn?wrote:
> Doesn't someone inserting pigs into their airplane list have larger
> problems than the (in)ability to insert the pig? Their problem is a
> faulty algorithm, not the insert. How the heck did a pig end-up being
> processed as an airplane?
That's exactly the question. And it may be difficult to answer once things
have progressed to the stage where one tries to make it fly. It may have
spent a long time in that List and it may be very difficult or impossible
to reconstruct the circumstances under which it was put in there.
And that's exactly what makes type-safe containers (and type-safety in general)
are a big improvement: They make errors manifest earlier and thus speed up
debugging.
|
| |
|
| |
 |
Thomas Gagn

|
Posted: 2004-1-5 23:31:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
In that case what we have isn't of List of Airplanes, but an
AirplaneList which should have its own methods requiring Airplanes, and
perhaps some relevant methods for dealing with airplanes in the
aggregate (if applicable to the domain).
Michael Borgwardt wrote:
> Thomas Gagn?wrote:
>
>> Doesn't someone inserting pigs into their airplane list have larger
>> problems than the (in)ability to insert the pig? Their problem is a
>> faulty algorithm, not the insert. How the heck did a pig end-up
>> being processed as an airplane?
>
>
> That's exactly the question. And it may be difficult to answer once
> things
> have progressed to the stage where one tries to make it fly. It may have
> spent a long time in that List and it may be very difficult or impossible
> to reconstruct the circumstances under which it was put in there.
>
> And that's exactly what makes type-safe containers (and type-safety in
> general)
> are a big improvement: They make errors manifest earlier and thus
> speed up
> debugging.
>
>
--
.tom
remove email address' dashes for replies
opensource middleware at <http://isectd.sourceforge.net>
http://gagne.homedns.org
|
| |
|
| |
 |
Michael Borgwardt

|
Posted: 2004-1-5 23:42:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Thomas Gagn?wrote:
> In that case what we have isn't of List of Airplanes, but an
> AirplaneList which should have its own methods requiring Airplanes,
You've just described a typesafe container. Aren'you glad that they're
finally here with 1.5?
> and
> perhaps some relevant methods for dealing with airplanes in the
> aggregate (if applicable to the domain).
class AirplaneList extends List<Airplane>
{
public void doSomethingWithThePlanes(){
...
}
...
}
|
| |
|
| |
 |
Thomas Gagn

|
Posted: 2004-1-6 0:27:00 |
Top |
java-programmer >> Tired of 100s of stupid Getter/Setter methods
Michael Borgwardt wrote:
> Thomas Gagn?wrote:
>
>> In that case what we have isn't of List of Airplanes, but an
>> AirplaneList which should have its own methods requiring Airplanes,
>
>
> You've just described a typesafe container. Aren'you glad that they're
> finally here with 1.5?
Not really. Java has added more syntax for something easily implemented
with the language as it already existed.
> <snip>
>
> class AirplaneList extends List<Airplane>
> {
> public void doSomethingWithThePlanes(){
> ...
> }
> ...
> }
class AirplaneList {
private List airplanes;
...
add(Airplane anAirplane) { airplanes.add(anAirplane); }
...
}
>
>
--
.tom
remove email address' dashes for replies
opensource middleware at <http://isectd.sourceforge.net>
http://gagne.homedns.org
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- Thread and ListenerHi,
I'm doing some experiences with JOESNMP. It's very good. Guided by the
examples I was able to build a listener that receives snmp traps. It's
working fine (when running through console).
So I decided to start it automatically, together with my web
application (that is running under tomcat).
I have a servlet that is executed when tomcat starts (using
<load-on-startup>). So I did a call to my new class.
The problem is that this class is actually a listener. When it starts,
it hangs the other procedures, including tomcat initilization.
I tryed to put it under a thread, but it also hangs as soon it starts
to listen for snmp traps.
How do I ran a listner without blocking other processes? I am looking
for a solution that should work both on linux and windows.
I don't know if I made myself understood. Sorry my poor english.
TIA,
Bob
- 2
- Executable binaryHello java experts:
Is there any tool to make java file into executable binary? thanks in
advance
- 3
- When 56K was widebandHere is a movie made in the early days of Arpanet about the coming
networking technology.
http://www.vortex.com/bv/arpanet-72.wmv
It is fun to look back to see how much has changed, and by
extrapolation imagine what is to come.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
- 4
- Help - Any browser crashes with Java plug in when using parametersWhen ever I try to load java applet I, the plug in works fine unless I
specify any runtime parameters. Then as soon as I try to start up an
applet the browser will shut down right away with no warning or error
messages.
I've tried both 1.3.1_13 and 1.4.2_06 with both Internet Explorer 6 and
Firefox.
I thought maybe it was a Windows patch or something but can't find any
info on that. This happens both on a Windows 2000 and XP SP1 machine.
- 5
- Style Sheet inside GUIIs there any open source out there that will allow me to use Style
Sheets inside of a GUI window, preferably a JEditorPane? I need to be
able to open Style Sheet formatted html that is inputted into a
database through an ASP client, and then retrieved in a JAVA client.
- 6
- multi track audio card accessinghallo
I am programming in java for multi track sound card ( 4 - stereo track
-- 8 speakers). I need to output 8 mono wav audio file in eight
different speakers
for this work I have suceeded by playing two mono files in first 2
speakers ( first stereo track ) I am now searching to output other
6 mono files in other 3 different stereo tracks
how to get the port or details for the other 3 stereo tracks
I have attached 3 java files which i have used
<<<<MultiAudioStreamPlayer.java
<<<<BaseAudioStream.java
<<<<SimpleAudioStream.java
for running the below java samples there is no need to have a special
sound card but make sure to change the WAV file name in
SimpleAudioStream.java
program
I am eagerly waiting for your valuable ideas
Yours friendly
vijay
/*
* MultiAudioStreamPlayer.java
*
* This file is part of the Java Sound Examples.
*/
/*
* Copyright (c) 1999 by Matthias Pfisterer
<email***@***.com>
*
*
* This program is free software; you can redistribute it and/or
modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.SourceDataLine;
// import AudioStream;
/* +DocBookXML
<title>Playing multiple audio files concurrently</title>
<formalpara><title>Purpose</title>
<para>This program plays multiple audio files
concurrently.
It opens each file given on the command line and starts it.
The program uses the class <classname>AudioStream</classname>.</para>
</formalpara>
<formalpara><title>Level</title>
<para>experienced</para></formalpara>
<formalpara><title>Usage</title>
<para>
<cmdsynopsis>
<command>java MultiAudioStreamPlayer</command>
<arg choice="plain"
rep="repeat"><replaceable>audiofile</replaceable></arg>
</cmdsynopsis>
</para></formalpara>
<formalpara><title>Parameters</title>
<variablelist>
<varlistentry>
<term><replaceable>audiofile</replaceable></term>
<listitem><para>the name(s) of the audio file(s) to
play</para></listitem>
</varlistentry>
</variablelist>
</formalpara>
<formalpara><title>Bugs, limitations</title>
<para>Not well-tested</para></formalpara>
<formalpara><title>Source code</title>
<para>
<ulink url="MultiAudioStreamPlayer.java.html">MultiAudioStreamPlayer.java</ulink>,
<ulink url="SimpleAudioStream.java.html">SimpleAudioStream.java</ulink>,
<ulink url="BaseAudioStream.java.html">BaseAudioStream.java</ulink>
</para>
</formalpara>
-DocBookXML
*/
public class MultiAudioStreamPlayer
{
public static void main(String[] args)
{
File soundFile_L = new File("77.wav");
File soundFile_R = new File("88.wav");
SimpleAudioStream audioStream_L = null;
SimpleAudioStream audioStream_R = null;
try
{
audioStream_L = new SimpleAudioStream(soundFile_L);
audioStream_R = new SimpleAudioStream(soundFile_R);
audioStream_L.setPan(1.0f);
audioStream_R.setPan(0.0f);
audioStream_R.start();
audioStream_L.start();
}
catch (LineUnavailableException e)
{
/*
* In case of an exception, we dump the
* exception including the stack trace
* to the console output. Then, we exit
* the program.
*/
e.printStackTrace();
System.exit(1);
}
catch (UnsupportedAudioFileException e)
{
e.printStackTrace();
System.exit(1);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
System.exit(1);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
/*
if (args.length < 1)
{
System.out.println("MultiAudioStreamPlayer: usage:");
System.out.println("\tjava MultiAudioStreamPlayer <soundfile1>
<soundfile2> ...");
System.exit(1);
}
for (int i = 0; i < args.length; i++)
{
String strFilename = args[i];
File soundFile = new File(strFilename);
SimpleAudioStream audioStream = null;
try
{
audioStream = new SimpleAudioStream(soundFile);
if(i==0)
audioStream.setPan(1.0f);
else
audioStream.setPan(0.0f);
}
catch (LineUnavailableException e)
{
e.printStackTrace();
System.exit(1);
}
catch (UnsupportedAudioFileException e)
{
e.printStackTrace();
System.exit(1);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
System.exit(1);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
audioStream.start();
}
*/
/* closing the sound file after playing */
}
}
/*** MultiAudioStreamPlayer.java ***/
//_________________________________________________________________________________________________
/*
* BaseAudioStream.java
*
* This file is part of the Java Sound Examples.
*/
/*
* Copyright (c) 1999, 2000 by Matthias Pfisterer
<email***@***.com>
*
*
* This program is free software; you can redistribute it and/or
modify
* it under the terms of the GNU Library General Public License as
published
* by the Free Software Foundation; either version 2 of the License,
or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.FloatControl;
public class BaseAudioStream
implements Runnable
{
/** Flag for debugging messages.
* If true, some messages are dumped to the console
* during operation.
*/
private static boolean DEBUG = true;
/**
* means that the stream has reached EOF or was not started.
* This value is returned in property change callbacks that
* report the current media position.
*/
public static final long MEDIA_POSITION_EOF = -1L;
public static final String MEDIA_POSITION_PROPERTY =
"BaseAudioStream_media_position";
// TODO: better size
private static final int EXTERNAL_BUFFER_SIZE = 4000 * 4;
private Thread m_thread = null;
private Object m_dataSource;
private AudioInputStream m_audioInputStream;
private SourceDataLine m_line;
private FloatControl m_gainControl;
private FloatControl m_panControl;
/**
* This variable is used to distinguish stopped state from
* paused state. In case of paused state, m_bRunning is still
* true. In case of stopped state, it is set to false. Doing so
* will terminate the thread.
*/
private boolean m_bRunning;
protected BaseAudioStream()
{
m_dataSource = null;
m_audioInputStream = null;
m_line = null;
m_gainControl = null;
m_panControl = null;
}
protected void setDataSource(File file)
throws UnsupportedAudioFileException, LineUnavailableException,
IOException
{
m_dataSource = file;
initAudioInputStream();
}
protected void setDataSource(URL url)
throws UnsupportedAudioFileException, LineUnavailableException,
IOException
{
m_dataSource = url;
initAudioInputStream();
}
private void initAudioInputStream()
throws UnsupportedAudioFileException, LineUnavailableException,
IOException
{
if (m_dataSource instanceof URL)
{
initAudioInputStream((URL) m_dataSource);
}
else if (m_dataSource instanceof File)
{
initAudioInputStream((File) m_dataSource);
}
}
private void initAudioInputStream(File file)
throws UnsupportedAudioFileException, IOException
{
/*
try
{
*/
m_audioInputStream = AudioSystem.getAudioInputStream(file);
/*
}
catch (IOException e)
{
throw new IllegalArgumentException("cannot create AudioInputStream
for " + file);
}
if (m_audioInputStream == null)
{
throw new IllegalArgumentException("cannot create AudioInputStream
for " + file);
}
*/
}
private void initAudioInputStream(URL url)
throws UnsupportedAudioFileException, IOException
{
/*
try
{
*/
m_audioInputStream = AudioSystem.getAudioInputStream(url);
/*
}
catch (IOException e)
{
throw new IllegalArgumentException("cannot create AudioInputStream
for " + url);
}
if (m_audioInputStream == null)
{
throw new IllegalArgumentException("cannot create AudioInputStream
for " + url);
}
*/
}
// from AudioPlayer.java
/*
* Compressed audio data cannot be fed directely to
* Java Sound. It has to be converted explicitely.
* To do this, we create a new AudioFormat that
* says to which format we want to convert to. Then,
* we try to get a converted AudioInputStream.
* Furthermore, we use the new format and the converted
* stream.
*
* Note that the technique shown here is partly non-
* portable. It is used here to keep the example
* simple. A more advanced, more portable technique
* will (hopefully) show up in BaseAudioStream.java soon.
*
* Thanks to Christoph Hecker for finding out that this
* was missing.
*/
/*
if ((audioFormat.getEncoding() == AudioFormat.Encoding.ULAW) ||
(audioFormat.getEncoding() == AudioFormat.Encoding.ALAW))
{
if (DEBUG)
{
System.out.println("AudioPlayer.main(): converting");
}
AudioFormat newFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
audioFormat.getSampleRate(),
audioFormat.getSampleSizeInBits() * 2,
audioFormat.getChannels(),
audioFormat.getFrameSize() * 2,
audioFormat.getFrameRate(),
true);
AudioInputStream newStream =
AudioSystem.getAudioInputStream(newFormat, audioInputStream);
audioFormat = newFormat;
audioInputStream = newStream;
}
*/
protected void initLine()
throws LineUnavailableException
{
if (m_line == null)
{
createLine();
openLine();
}
else
{
AudioFormat lineAudioFormat = m_line.getFormat();
AudioFormat audioInputStreamFormat = m_audioInputStream == null ?
null : m_audioInputStream.getFormat();
if (!lineAudioFormat.equals(audioInputStreamFormat))
{
m_line.close();
openLine();
}
}
}
private void createLine()
throws LineUnavailableException
{
if (m_line != null)
{
return;
}
/*
* From the AudioInputStream, i.e. from the sound file, we
* fetch information about the format of the audio data. These
* information include the sampling frequency, the number of
* channels and the size of the samples. There information
* are needed to ask Java Sound for a suitable output line
* for this audio file.
*/
AudioFormat audioFormat = m_audioInputStream.getFormat();
if (DEBUG)
{
System.out.println("BaseAudioStream.initLine(): audio format: " +
audioFormat);
}
/*
* Asking for a line is a rather tricky thing.
* ...
* Furthermore, we have to give Java Sound a hint about how
* big the internal buffer for the line should be. Here,
* we say AudioSystem.NOT_SPECIFIED, signaling that we don't
* care about the exact size. Java Sound will use some default
* value for the buffer size.
*/
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat, AudioSystem.NOT_SPECIFIED);
m_line = (SourceDataLine) AudioSystem.getLine(info);
if (m_line.isControlSupported(FloatControl.Type.MASTER_GAIN/*VOLUME*/))
{
m_gainControl = (FloatControl)
m_line.getControl(FloatControl.Type.MASTER_GAIN);
if (DEBUG)
{
System.out.println("max gain: " + m_gainControl.getMaximum());
System.out.println("min gain: " + m_gainControl.getMinimum());
System.out.println("gain precision: " +
m_gainControl.getPrecision());
}
}
else
{
if (DEBUG)
{
System.out.println("FloatControl.Type.MASTER_GAIN is not
supported");
}
}
if (m_line.isControlSupported(FloatControl.Type.PAN/*BALANCE*/))
{
m_panControl = (FloatControl)
m_line.getControl(FloatControl.Type.PAN);
if (DEBUG)
{
System.out.println("max balance: " + m_panControl.getMaximum());
System.out.println("min balance: " + m_panControl.getMinimum());
System.out.println("balance precision: " +
m_panControl.getPrecision());
}
}
else
{
if (DEBUG)
{
System.out.println("FloatControl.Type.PAN is not supported");
}
}
}
private void openLine()
throws LineUnavailableException
{
if (m_line == null)
{
return;
}
AudioFormat audioFormat = m_audioInputStream.getFormat();
m_line.open(audioFormat, m_line.getBufferSize());
}
// TODO: if class can be instatiated without file or url,
m_audioInputStream may
// be null
protected AudioFormat getFormat()
{
return m_audioInputStream.getFormat();
}
public void start()
{
if (DEBUG)
{
System.out.println("start() called");
}
if (!(m_thread == null || !m_thread.isAlive()))
{
if (DEBUG)
{
System.out.println("WARNING: old thread still running!!");
}
}
if (DEBUG)
{
System.out.println("creating new thread");
}
m_thread = new Thread(this);
m_thread.start();
if (DEBUG)
{
System.out.println("additional thread started");
}
if (DEBUG)
{
System.out.println("starting line");
}
m_line.start();
}
protected void stop()
{
if (m_bRunning)
{
if (m_line != null)
{
m_line.stop();
m_line.flush();
}
m_bRunning = false;
/*
* We re-initialize the AudioInputStream. Since doing
* a stop on the stream implies that there has been
* a successful creation of an AudioInputStream before,
* we can almost safely ignore this exception.
* The LineUnavailableException can be ignored because
* in case of reinitializing the same AudioInputStream,
* no new line is created or opened.
*/
try
{
initAudioInputStream();
}
catch (UnsupportedAudioFileException e)
{
}
catch (LineUnavailableException e)
{
}
catch (IOException e)
{
}
}
}
public void pause()
{
m_line.stop();
}
public void resume()
{
m_line.start();
}
public void run()
{
if (DEBUG)
{
System.out.println("thread start");
}
int nBytesRead = 0;
m_bRunning = true;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
// int nFrameSize = m_line.getFormat().getFrameSize();
while (nBytesRead != -1 && m_bRunning)
{
try
{
nBytesRead = m_audioInputStream.read(abData, 0, abData.length);
}
catch (IOException e)
{
e.printStackTrace();
}
if (nBytesRead >= 0)
{
//int nFramesToWrite = nBytesRead / nFrameSize;
if (DEBUG)
{
System.out.println("Trying to write: " + nBytesRead);
}
int nBytesWritten = m_line.write(abData, 0, nBytesRead);
if (DEBUG)
{
System.out.println("Written: " + nBytesWritten);
}
}
}
/*
* Wait until all data are played.
* This is only necessary because of the bug noted below.
* (If we do not wait, we would interrupt the playback by
* prematurely closing the line and exiting the VM.)
*/
// TODO: check how this interferes with stop()
m_line.drain();
if (DEBUG)
{
System.out.println("after drain()");
}
/*
* Stop the line and reinitialize the AudioInputStream.
* This should be done before reporting end-of-media to be
* prepared if the EOM message triggers a new start().
*/
stop();
if (DEBUG)
{
System.out.println("after this.stop()");
}
}
public boolean hasGainControl()
{
return m_gainControl != null;
}
/*
public void setMute(boolean bMute)
{
if (hasGainControl())
{
m_gainControl.setMute(bMute);
}
}
public boolean getMute()
{
if (hasGainControl())
{
return m_gainControl.getMute();
}
else
{
return false;
}
}
*/
public void setGain(float fGain)
{
if (hasGainControl())
{
m_gainControl.setValue(fGain);
}
}
public float getGain()
{
if (hasGainControl())
{
return m_gainControl.getValue();
}
else
{
return 0.0F;
}
}
public float getMaximum()
{
if (hasGainControl())
{
return m_gainControl.getMaximum();
}
else
{
return 0.0F;
}
}
public float getMinimum()
{
if (hasGainControl())
{
return m_gainControl.getMinimum();
}
else
{
return 0.0F;
}
}
public boolean hasPanControl()
{
return m_panControl != null;
}
public float getPrecision()
{
if (hasPanControl())
{
return m_panControl.getPrecision();
}
else
{
return 0.0F;
}
}
public float getPan()
{
if (hasPanControl())
{
return m_panControl.getValue();
}
else
{
return 0.0F;
}
}
public void setPan(float fPan)
{
if (hasPanControl())
{
m_panControl.setValue(fPan);
}
}
}
/*** BaseAudioStream.java ***/
//----------------------------------------------------------------------------------------
/*
* SimpleAudioStream.java
*
* This file is part of the Java Sound Examples.
*/
/*
* Copyright (c) 1999, 2000 by Matthias Pfisterer
<email***@***.com>
*
*
* This program is free software; you can redistribute it and/or
modify
* it under the terms of the GNU Library General Public License as
published
* by the Free Software Foundation; either version 2 of the License,
or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free
Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.FloatControl;
public class SimpleAudioStream
extends BaseAudioStream
{
/** Flag for debugging messages.
* If true, some messages are dumped to the console
* during operation.
*/
private static boolean DEBUG = true;
// private static final int EXTERNAL_BUFFER_SIZE = 16384;
/**
* This variable is used to distinguish stopped state from
* paused state. In case of paused state, m_bRunning is still
* true. In case of stopped state, it is set to false. Doing so
* will terminate the thread.
*/
private boolean m_bRunning;
public SimpleAudioStream()
{
super();
// m_dataSource = null;
}
public SimpleAudioStream(File file)
throws UnsupportedAudioFileException, LineUnavailableException,
IOException
{
this();
setDataSource(file);
initLine();
}
public SimpleAudioStream(URL url)
throws UnsupportedAudioFileException, LineUnavailableException,
IOException
{
this();
setDataSource(url);
initLine();
}
public AudioFormat getFormat()
{
// TODO: have to check that AudioInputStream (or Line?) is
initialized
return super.getFormat();
}
/*
public void start()
{
if (DEBUG)
{
System.out.println("start() called");
}
m_thread = new Thread(this);
m_thread.start();
if (DEBUG)
{
System.out.println("additional thread started");
}
m_line.start();
if (DEBUG)
{
System.out.println("started line");
}
}
public void stop()
{
m_line.stop();
m_line.flush();
m_bRunning = false;
}
public void pause()
{
m_line.stop();
}
public void resume()
{
m_line.start();
}
*/
/*
public void run()
{
if (DEBUG)
{
System.out.println("thread start");
}
int nBytesRead = 0;
m_bRunning = true;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
int nFrameSize = m_line.getFormat().getFrameSize();
while (nBytesRead != -1 && m_bRunning)
{
try
{
nBytesRead = m_audioInputStream.read(abData, 0, abData.length);
}
catch (IOException e)
{
e.printStackTrace();
}
if (nBytesRead >= 0)
{
int nRemainingBytes = nBytesRead;
// while (nRemainingBytes > 0)
//{
if (DEBUG)
{
System.out.println("Line status (active): " +
m_line.isActive());
System.out.println("Line status (running): " +
m_line.isRunning());
System.out.println("Trying to write (bytes): " + nBytesRead);
}
int nBytesWritten = m_line.write(abData, 0, nBytesRead);
if (DEBUG)
{
System.out.println("Written (bytes): " + nBytesWritten);
}
nRemainingBytes -= nBytesWritten;
//}
}
}
if (DEBUG)
{
System.out.println("after main loop");
}
}
*/
}
/*** SimpleAudioStream.java ***/
- 7
- MI5 Persecution: ?0,000 Reward (3097)
20,000 Reward Offered to Expose the Conspiracy
I am making a pledge for information directly leading to the exposing of the "BBC Newscaster
Conspiracy". The exposing would specifically need to lead to a legally binding admission from Martyn Lewis
or Michael Buerk of the BBC they they were watching me through the TV set.
I would be happy (delighted, in fact) to pay GBP 20,000 sterling in reward for the above admission.
--------------------------------------------------------------------------------
3097
--
Posted via a free Usenet account from http://www.teranews.com
- 8
- Can't detect double-click mouse events in MustangThe following relates to Mustang b89 on Windows Server 2003. It may well
relate to earlier Java versions as well but I haven't tested it.
I think my understanding of mouse clicked events is wrong because I don't
get the behaviour I expect. When I implement the following code:
table.getTableHeader().addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent event)
{
System.out.println("Mouse event, clickCount = " +
event.getClickCount());
}
}
I get the following output for every double-click:
Mouse event, clickCount = 1
Mouse event, clickCount = 2
Shouldn't it be just one event with a clickCount of 2? How can I tell the
difference between the first event and a normal single-click?
Thanks,
Wes
- 9
- log4j questionIs log4j specifically a servlet, or is it an API that can be called from
ANY java program that wanst to do logging?
- 10
- PreferencesHello!
I've just read about Preferences in JDK1.4 and wonder where java store data
between sessions???? I've found no related files with suitable contant..
Sorry for lammer question ;(
- 11
- 12
- does IntelliJ do any of these thingsI am taking IntelliJ out for its first spin. See
http://mindprod.com/jgloss/intellij.html
You can see my first program at:
http://mindprod.com/jgloss/arraylist.html#GROWINGARRAYLIST
Everything is going smoothly. I wondered if the following features
exist somewhere and I just can't find them.
1. Reorder methods and declarations in canonical order. I make heavy
use of this in Eclipse to save finding the right spot to insert. I put
methods and declarations I am working temporarily adjacent then
reorder.
2. tidy javadoc.
3. summarise syntax errors, like the Eclipse "problems" panel.
4. quickly ensure Javadoc are complete. I have found the lint which
requires opening a zillion tree elements to find nit picks rather than
true errors.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
- 13
- www.rakeback.gr
This week opportunity
FREE $50
If you're new to SunPoker, we'll match your first deposit up to $50 with
a 100% deposit bonus. See details at:
www.rakeback.gr
If you are interesting about how to play and how to win, please
contact us on e-mail: email***@***.com and we will send you book with
tip and tricks.
Sincerely yours
www.rakeback.gr
- 14
- corba-J2EE-EJB-WebSphere?Some help for a newbee?
I've been a c/C++ programmer in VMS, OS/400, and most recently, Windows
and Dot Net. However, I have recently signed on as Q/A manager at a
predominantly Java shop. We have some consultants coming in to assess our
scaleability and architecture, and I'd like to be in a position to at least
make some intelligable noises. I have gotten the sense that there is at
least some compatability between these, but I'm not picking up the extent,
if any, to which any are essentially competing technologies. Is some subset
of these an obvious choice for a medium volume site with lots of active
content, with scaleability, performance, and maintainability being our top
three criteria? Thanks.
Joe
email***@***.com
(please remove "nospam." to reply)
- 15
- Second URL.openstream in second thread causes ProtocolExceptionI have a multi-threaded Java http image proxy service application that
runs fine on Windows 2000. The app retrieves multiple, distinct images
from a webserver with one image retrieval process per thread. The
webserver images change every so often, but each distinct URL used in
my proxy service remains the same. Each thread repeats its image
download every few seconds to retrieve updated images. It all works
great.
I am trying to move this app to a Red Hat Fedora core 4 machine.
Almost everything works except I am getting a protocol exception when
I try to open a second URL stream in a second thread. Within seconds,
one of the threads will throw a ProtocolException error with error
text of '1.1/ 200 OK'. Any one stream/thread combo will work fine.
Trying to start another causes problems.
If I comment out the URL.openStream() call, I can start a dozen
threads, run them for as long as I want and stop them all quite
nicely. Again, all of the code works beautifully on Windows 2000. I'm
not sure if this is a Java problem or, perhaps, a Linux server
configuration problem.
It just seems that the Red Hat server/Java environment is having a
hard time having two http protocol discussions in two threads at the
same time. Occasionally, the threads will both succeed for a few
image revolutions, so there is a little inconsistency in when the
failure occurs.
gdhurst
|
|
|