| Using BigInteger and BigDecimal [WAS: Converting floats to Strings and back] |
|
 |
Index ‹ java-programmer
|
- Previous
- 1
- Static Variables and JAR FilesI am curious - does the scope of static variables carry across
different JAR files?
Here's the issue:
BaseClass is in "BaseClasses.jar"
ExtendedClassA extends BaseClass is in "AnotherPackage.jar"
ExtendedClassB extends BaseClass is in "EvenAnotherPackage.jar"
BaseClass has a static object (ObjectX). Now, normally, this static
object is static across all of the subclasses. However...
These JAR files (AnotherPackage and EvenAnotherPackage) are being read
in by a separate tool. When ExtendedClassA and ExtendedClassB are
used within the context of this tool, ObjectX is instantiated twice
and has two separate values. As far as I can tell, the tool runs
ExtendedClassA and ExtendedClassB within the same JVM, so I am unsure
of what is going on.
Does anybody have any insight into what is going on here? (Sorry for
being vague. I'm not actually working the project, but I'm curious
from an academic standpoint. Another group ran across this problem
today.)
- 2
- 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.
- 3
- 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
- 3
- [ANNOUNCE] Apache Derby 10.4.1.3 releasedThe Apache Derby project is pleased to announce a new feature release
of Derby, 10.4.1.3.
Apache Derby is a subproject of the Apache DB project.
Derby is a pure Java relational database engine which conforms to the
ISO/ANSI SQL and JDBC standards. Derby aims to be easy for developers
and end-users to work with.
Derby 10.4.1.3 can be obtained from the Derby download site:
http://db.apache.org/derby/derby_downloads.html.
Derby 10.4.1.3 introduces the following new capabilities:
* Asynchronous Replication
Allows you to maintain an up to date copy of your (master) database on
a different host (the slave). In the case of a crash on the master
database you can perform failover to the copy (slave database) and
continue serving client requests against your database.
* Security
o Shutting down the Network Server now supports user authentication,
and in fact requires credentials when authentication is enabled.
* SQL
o Table Functions. Using table functions and standard SQL, you can pose
sophisticated queries against in-memory collections, flat files, web
resources, non-relational databases, etc.. Table functions also let
you efficiently import data from web feeds, sensor logs, and other
relational databases.
o Unique constraints on nullable columns.
o SQL ROW_NUMBER() window function, (for an empty, inlined window
specification).
o Bracketed comments (/* ... */).
* Performance and Memory Usage
o New buffer manager with better concurrency.
o Statement cache in the client driver.
o Caching of isolation level and current schema in the client
driver.
* Administration
o Java Management Extensions (JMX) for Derby, allowing
local and remote monitoring and management of running Derby instances
(embedded or Network Server).
o Continuation prompt. ij adds a short "> " prompt to the next line
after a newline has been entered by the user without ending the
statement with a semicolon.
Derby 10.4.1.3 also has many bugfixes, including the fix for
DERBY-3347 which can cause unrecoverable database corruption. All
10.3 users are encouraged to upgrade to avoid potential corruption
issues.
--
Regards,
Dyre
- 5
- 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:
- 5
- 5
- 6
- Data generatorDo You know if there is any data generator for databases like TurboData,
but for free?
- 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
- 8
- 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...
- 9
- 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.
- 14
- 15
- 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
- [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
- 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
|
| Author |
Message |
Oliver Wong

|
Posted: 2005-11-23 5:03:00 |
Top |
java-programmer, 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
|
| |
|
| |
 |
Chris Uppal

|
Posted: 2005-11-23 18:59:00 |
Top |
java-programmer >> Using BigInteger and BigDecimal [WAS: Converting floats to Strings and back]
Oliver Wong wrote:
> 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 [...]
Also, other applications that read the data (not Java) will be able to work
with it. E.g. report generators.
Since one of the biggest (arguably the only) reason to keep data in SQL-style
databases is so that the data can be application-independent, it makes sense to
keep data in application-independent formats where possible.
-- chris
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- 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.
- 2
- Tired of 100s of stupid Getter/Setter methodsTor 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
- 3
- 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
- 4
- 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
- 5
- 6
- log4j questionIs log4j specifically a servlet, or is it an API that can be called from
ANY java program that wanst to do logging?
- 7
- 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 ***/
- 8
- 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
- 9
- 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 ;(
- 10
- 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)
- 11
- Executable binaryHello java experts:
Is there any tool to make java file into executable binary? thanks in
advance
- 12
- 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?)
- 13
- 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.
- 14
- 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();
}
}
- 15
- 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
|
|
|