How to Setup Dependencies Aware Ant Project for Scala
During the past days, I was patching scalac ant task and some relative issues, and now, the dependencies aware ant scalac works (post Scala 2.8.0.r19724).
Below is an example build.xml with dependencies aware setting:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project name="ScalaAntTest" default="build" basedir="."> 3 <description>Builds, tests, and runs the project ScalaAntTest.</description> 4 5 <property name="src.dir" value="${basedir}/src"/> 6 <property name="build.dir" value="${basedir}/build"/> 7 <property name="build.classes.dir" value="${build.dir}/classes"/> 8 9 <target name="init"> 10 <property environment="env"/> 11 <condition property="scala.home" value="${env.SCALA_HOME}"> 12 <isset property="env.SCALA_HOME"/> 13 </condition> 14 <fail unless="scala.home">set SCALA_HOME first</fail> 15 16 <property name="scala-library.jar" value="${scala.home}/lib/scala-library.jar"/> 17 <property name="scala-compiler.jar" value="${scala.home}/lib/scala-compiler.jar"/> 18 19 <path id="build.classpath"> 20 <pathelement location="${scala-library.jar}"/> 21 <pathelement location="${scala-compiler.jar}"/> 22 <pathelement location="${build.classes.dir}"/> 23 </path> 24 <taskdef resource="scala/tools/ant/antlib.xml"> 25 <classpath> 26 <pathelement location="${scala-compiler.jar}"/> 27 <pathelement location="${scala-library.jar}"/> 28 </classpath> 29 </taskdef> 30 </target> 31 32 <target name="build" depends="init"> 33 <mkdir dir="${build.dir}"/> 34 <mkdir dir="${build.classes.dir}"/> 35 <scalac srcdir="${src.dir}" 36 destdir="${build.classes.dir}" 37 classpathref="build.classpath" 38 force="yes" 39 addparams="-make:transitive -dependencyfile ${build.dir}/.scala_dependencies" 40 > 41 <src path="${basedir}/src1"/> 42 <!--include name="compile/**/*.scala"/--> 43 <!--exclude name="forget/**/*.scala"/--> 44 </scalac> 45 </target> 46 47 <target name="clean" depends="init"> 48 <delete dir="${build.dir}"/> 49 </target> 50 51 </project>
There are some tips here, I'll give a concise explanation:
First, there will be a file call ".scala_dependencies" which is put under "build/" directory after you first clean-build, it will record all dependencies information. Since it's put under "build/", it will be removed automatically after an "ant clean". The "-dependencyfile ${build.dir}/.scala_dependencies" parameter of scalac at line 39 enables this.
Second, you should add "-make:transitive" as scalac's parameter (line 39), which will enable scalac to evaluate the dependencies transitive.
Third, add attribute "force='yes'" (line 38), which tells scalac to check all source files for dependencies and re-compile them if files that dependents on changed.
Forth, you should include "<pathelement location='${build.dir.classes}'/>" as part of "build.classpath" (line 22), so scalac won't complain lack of already generated classes when rebuild upon parts of source files.
I've also re-write the project scheme that created by NetBeans plugin, that is, the next released NetBeans Scala plugin will automatically generate dependencies aware build.xml file for new created projects. Unfortunately, you'll have to copy/move your old project src to new created project directory if you want to benefit from it.
For some reasons, "fsc" is no longer supported as the default compiler task in NetBeans created project, which actually brought some annoyances for plugin users. Even without "fsc", the dependencies aware "scalac" should also work satisfiable in most cases.
Scala Corner Case#3: "object" or "case object" Extends Case Class? It's a Different Story
Case class in Scala is a neat feature, it automatically generates apply, extract and equals functions. But I encountered a strange "equals" behavior today, which wasted me 2 hours to find why.
Define a simple case class "Symbol", then a "VarSymbol" which extends "Symbol" with one more field "name:String". We know you can compare the equality of instances of "VarSymbol" by this "name", Scala automatically gets it right. And of course, a direct instance from "Symbol()" should not equal to any "VarSymbol", since it lacks "name" field, that's right.
case class Symbol() case class VarSymbol(name:String) extends Symbol
Then, I need a singleton object "NoSymbol", I defined it as:
object NoSymbol extends Symbol
I of course thought this "NoSymbol" should not equal any "VarSymbol" instance, or,
NoSymbol == VarSymbol("I'm var")
Should return false. But life is not so straightforward, it returns true in real life !!!
I finally got my code working, by adding a "case" before "object NoSymbol extends Symbol". This "NoSymbol" won't equal any "VarSymbol" now, I'm grad things finally go back in track.
I don't know if it's a Scala bug, or, that's what Scala thinks it should be: all "Symbol" and it's inherited instances should equal "NoSymbol" object. Anyway, here's the whole code for test:
case class Symbol()
case class VarSymbol(name:String) extends Symbol
object NoSymbol extends Symbol
case object CasedNoSymbol extends Symbol
object TestCaseObject {
def test = {
val noSym = NoSymbol
val caseNoSym = CasedNoSymbol
val varSym = VarSymbol("I'm var")
if (noSym == varSym) println("NoSym equals varSym !")
else println("NoSym doesn't equal varSym")
if (caseNoSym == varSym) println("CaseNoSym equals varSym !")
else println("CaseNoSym doesn't equal varSym")
}
}
Run TestCaseObject.test, I got:
NoSym equals varSym ! CaseNoSym doesn't equal varSym
Scala Corner Case#2: "Nothing" Can not Be Cast and Assigned to a val/var
There is a Java class which takes type parameter T, T is any type:
package dcaoyuan.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class AList<T> implements Iterator<T> {
List<T> a = new ArrayList<T>();
{
a.add((T) "string");
}
Iterator<T> itr = a.iterator();
public boolean hasNext() {
return itr.hasNext();
}
public T next() {
return itr.next();
}
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Which implemented java.util.Iterator with type parametered T next(). Notice here next() will return T
The above code simulates a case, that an existed Java lib may return an instance that has type parameter erased, on run-time.
Now let's try to call it in Scala:
package dcaoyuan.test
object Main {
def main(args: Array[String]) :Unit = {
testAList_work
testAList_unwork
}
def testAList_work :Unit = {
val a :AList[_] = new AList
// a is inferred as AList[Any]
while (a.hasNext) {
val e = a.next
println(e)
}
}
def testAList_unwork :Unit = {
val a = new AList
// a is inferred as AList[Nothing]
while (a.hasNext) {
// now a.next is Nothing, can not cast to "val e", which should at least be Any
val e = a.next // will throw java.lang.ClassCastException
println(e)
}
}
}
I wrote two functions: "testAList_work" and "testAList_unwork"
The issue is in testAList_unwork, as a simple "val a = new AList", "a" will be inferred by scalac as AList[Nothing], so, "a.next" will return an instance of type Nothing, then, "val e = a.next" will throw java.lang.ClassCastException
My question is, should this corner case be checked by scalac as an error or warning? So I do not need to dig the clause when it happens on run-time.
Scala Corner Case#1: Implement Method of Java Interface with Type Parameter Omitted by It's Sub-Class
The progress of rewriting Erlang plugin for NetBeans in Scala has reached a phase, that the Editor itself works smooth and better than ErlyBird now, the next step is to integrate an Erlang project management and index the modules/functions of OTP/project to provide smart auto-completion.
Now Scala has been proved that it can be integrated into an existed large Java based framework (NetBeans IDE here) without no much problems, I'll begin to rewrite Scala plugin in Scala soon.
Although in most cases, Scala can call existed Java code or classes smoothly, there are still some corner cases. I'll record these corner cases in blogs. Here's the first one which I also posted on scala-user mailing-list, but have not yet got final answer.
Let's begin with a detailed example:
There is a Java interface A:
public interface A<T extends String> {
void run(T t);
}
Which has a type parameter <T extends String> and abstract method run(T t)
Then a Java abstract class B extended A. But, B, as it, omitted type parameter from A. This is unsafe but valid in Java:
public abstract class B implements A {
public String me() {
return "I'm B";
}
}
Assume above classes A and B have been compiled under javac, and packed in a jar library, and I can not patch it anymore. Now I need to write a class S in Scala which should extend B:
class S extends B {
override
def run[T <: String](t:T) = {println(t)}
}
scalac will complain as:
/Users/dcaoyuan/NetBeansProjects/ScalaTestCase/src/S.scala:1: error:
class S needs to be abstract, since method run in trait A of type
(T)Unit is not defined
class S extends B {
/Users/dcaoyuan/NetBeansProjects/ScalaTestCase/src/S.scala:3: error:
method run overrides nothing
def run[T <: String](t:T) = {println(t)}
I than tried "forSome" type:
class S extends B {
override
def run(t:T forSome {type T <: String}) = {println(t)}
}
The code still did not work.
It seems that, since B omitted A's type parameter T, I have no way to get what is T, and can not successfully implement "run(T t)" method.
I also tried other forms of "forSome" usages, and always failed.
But I think Scala can always be saved with mixed Java/Scala code in such corner case, that's what I believed. So, I thought about it later when my brain was spare, and finally got a solution:
I wrote another Java abstract class B1 which extends B and pretended to have implemented "run(T t)", but actually called another new abstract method "runImpl(String t)"
public abstract class B1 extends B {
public void run(String t) {
runImpl(t);
}
public abstract void runImpl(String t);
}
Now I can let Scala S extends B1 and implement "runImpl(String t)" instead of extending B and implementing "run(T t)".
class S extends B1 {
override
def runImpl(t:String) = {println(t)}
}
Yes, scalac won't complain about "runImpl(t:String)" at all, and I got S successfully extends B by bridge class B1.
But I still hope scalac can resolve it directly, with a warning message instead of failing to compile it.
Thinking in Scala vs Erlang
Keeping Erlang in mind, I've coded two months in Scala, I'm thinking something called "Scala vs Erlang", I wrote some benchmark code to prove me (the code and result may be available someday), and I'd like to do some gradually summary on it in practical aspect. These opinions may be or not be correct currently due to lacking of deep experience and understanding, but, anyway, I need to record them now and correct myself with more experiences and understanding got on both Scala and Erlang.
Part I. Syntax
List comprehension
Erlang:
Lst = [1,2,3,4], [X + 1 || X <- Lst], lists:map(fun(X) -> X + 1 end, Lst)
Scala:
val lst = List(1,2,3,4) for (x <- lst) yield x + 1 lst.map{x => x + 1} lst.map{_ + 1} // or place holder
Pattern match
Erlang:
case X of {A, B} when is_integer(A), A > 1 -> ok; _ -> error end, {ok, [{A, B} = H|T]} = my_function(X)
Scala:
x match { case (a:Int, b:_) if a > 1 => OK // can match type case _ => ERROR } val ("ok", (h@(a, b)) :: t) = my_function(x)
List, Tuple, Array, Map, Binary, Bit
Erlang:
Lst = [1, 2, 3] %% List [0 | Lst] %% List concat {1, 2, 3} %% Tuple <<1, 2, “abc”>> %% Binary %% no Array, Map syntax
Scala:
val lst = List(1, 2, 3) // List 0 :: lst // List concat (1, 2, 3) // Tuple Array(1, 2, 3) // Array Map(“a” -> 1, “b” -> 2) // Map // no Binary, Bit syntax
Process, Actor
Erlang:
the_actor(X) -> receive ok -> io:format(“~p~n”, [X]); I -> the_actor(X + I) %% needs to explicitly continue loop end. P = spawn(mymodule, the_actor, [0]) P ! 1 P ! ok
Scala I:
class TheActor(x:Int) extends Actor { def act = loop { react { case “ok” => println(x); exit // needs to explicitly exit loop case i:Int => x += i } } } val a = new TheActor(0) a ! 1 a ! “ok”
Scala II:
val a = actor { def loop(x:Int) = { react { case "ok" => println(x) case i:Int => loop(x + i) } } loop(0) } a ! 1 a ! "ok"
Part II. Processes vs Actors
Something I
Erlang:
- Lightweight processes
- You can always (almost) create a new process for each new comer
- Scheduler treats all processes fairly
- Share nothing between processes
- Lightweight context switch between processes
- IO has been carefully delegated to independent processes
Scala:
- Active actor is delegated to JVM thread, actor /= thread
- You can create a new actor for each new comer
- But the amount of real workers (threads) is dynamically adjusted according to the processing time
- The later comers may be in wait list for further processing until a spare thread is available
- Share nothing or share something upon you decision
- Heavy context switch between working threads
- IO block is still pain unless good NIO framework (Grizzly?)
Something II
Erlang:
- Try to service everyone simultaneously
- But may loss service quality when the work is heavy, may time out (out of service)
- Ideal when processing cost is comparable to context switching cost
- Ideal for small message processing in soft real-time
- Bad for massive data processing, and cpu-heavy work
Scala:
- Try to service limited number of customers best first
- If can not service all, the later comers will be put in waiting list and may time out (out of service)
- It's difficult for soft real-time on all coming concurrent customers
- Ideal when processing cost is far more than context switching cost (context switch time is in ns on modern JVM)
- When will there be perfect NIO + Actor library?
FOR, WHILE Is Too Easy, Let's Go Looping
With several 10k code in Erlang, I'm familiar with functional style coding, and I found I can almost rewrite any functions in Erlang to Scala, in syntax meaning.
Now, I have some piece of code written in Java, which I need to translate them to Scala. Since "for", "while", or "do" statement is so easy in Java, I can find a lot of them in Java code. The problem is, should I keep them in the corresponding "for", "while", "do" in Scala, or, as what I do in Erlang, use recursive function call, or, "loop"?
I sure choose to loop, and since Scala supports recursive function call on functions defined in function body (Erlang doesn't), I choose define these functions' name as "loop", and I tried to write code let "loop" looks like a replacement of "for", "while" etc.
Here's a piece of code that is used to read number string and convert to double, only piece of them.
The Java code:
public class ReadNum {
private double readNumber(int fstChar, boolean isNeg) {
StringBuilder out = new StringBuilder(22);
out.append(fstChar);
double v = '0' - fstChar;
// the maxima length of number stirng won't exceed 22
for (int i = 0; i < 22; i++) {
int c = getChar();
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
v = v * 10 - (c - '0');
out.append(c);
continue;
case '.':
out.append('.');
return readFrac(out, 22 - i);
case 'e':
case 'E':
out.append(c);
return readExp(out, 22 - i);
default:
if (c != -1) backup(1);
if (!isNeg) return v; else return -v
}
}
return 0;
}
}
The Scala code:
class ReadNum {
private
def readNumber(fstChar:Char, isNeg:Boolean) :Double = {
val out = new StringBuilder(22)
out.append(fstChar)
val v:Double = '0' - fstChar
def loop(c:Char, v:Double, i:Int) :Double = c match {
// the maxima length of number stirng won't exceed 22
case _ if i > 21 =>
0
case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' =>
out.append(c)
val v1 = v * 10 - (c - '0')
loop(getChar, v1, i + 1)
case '.' =>
out.append('.')
readFrac(out, 22 - i)
case 'e' | 'E' =>
out.append(c)
readExp(out, 22 - i)
case _ =>
if (c != -1) backup(1)
if (isNeg) v else -v
}; loop(getChar, v, 1)
}
}
As you can see in line 25, the loop call is put at the position immediately after the "loop" definition, following "}; ", I don't put it to another new line, it makes me aware of the "loop" function is just used for this call.
And yes, I named all these embedded looping function as "loop", every where.
Things To Do in Coming Months
As the beta of Scala for NetBeans released, I found I have several things to do in the coming months.
First, I'll keep the Scala plugins going on, I'll try to re-implement the Project supporting, which, may be an extension of current NetBeans' plain Java Project, that is, you just create plain JSE or JEE project, then add Scala source files to this project, you may mix Java/Scala in one project. Another perception is, it's time to re-write whole things in Scala itself? I have a featured Scala IDE now, or, the chicken, I should make eggs via this chicken instead of duck.
Second, we get some contracts on mobile application for Banking, which, will be implemented via our current Atom/Atom Publish Protocol web service platform. The platform is written in Erlang, but, with more and more business logical requirements, maybe we should consider some Scala things?
Third, oh, it's about AIOTrade, I'v left it at corner for almost one and half year, I said it would be re-written in Scala someday, I really hope I have time. I got some requests to support drawing charts for web application, it actually can, if you understand the source code, I just wrote an example recently, I may post an article on how to do that.
Which Programming Language J. Gosling Would Use Now, Except Java?
Maybe we can get completeness of J. Gosling's opinions about Java/Scaka/JVM from here
===
According to Adam Bien's blog from JavaOne
During a meeting in the Community Corner (java.net booth) with James Gosling, a participant asked an interesting question: "Which Programming Language would you use *now* on top of JVM, except Java?". The answer was surprisingly fast and very clear: - Scala.
I think Fortress will also be a very good future choice when it gets mature.
Some Tips for Upgrading to Rails 1.2.x
Bellow are some issues that I met when upgraded from rails 1.1.6 to 1.2.x:
1.About enrivonment.rb
Make sure your application configuration behind:
Rails::Initializer.run do |config| ... end
I met this issue when I put following code:
require 'environments/localization_environment' require 'localization' Localization::load_localized_strings require 'environments/user_environment'
before that closure, which works under 1.1.6, but don't under 1.2.x
2.About ActionMailer::Base.server_settings
If you get errors like:
uninitialized constant ActiveSupport::Deprecation::RAILS_DEFAULT_LOGGER (NameError)
try to change your ActionMailer::Base.server_settings to ActionMailer::Base.smtp_settings
3.Put all "include" statements inside class definitions
You must put include statements inside class/module definitions instead of outside a class/module definition in Rails 1.2.x. Otherwise, you'll get:
Error calling Dispatcher.dispatch #<NameError: cannot remove Object::COPYRIGHT>
Functinal Style Ruby
After playing with Ruby for weeks, I found Ruby is yet interesting. I try to write my code a bit in the likeness of Erlang, where symbol vs atom, array vs list. And the most important syntax that I like are:
- everything return a value
- may return multiple values
- begin-end clause is lambda that may be directly applied
- parallel assignment
Now, let's write some code before and after (functional):
Example1:
Before
1. cond = {}
2. if par[:id]
3. feed = Feed.find(par[:id])
4. if feed
5. cond[:feed] = feed.id
6. end
7. end
8. if par[:m]
9. limit = par[:m].to_i
10. else
11. limit = 20
12. end
13. if limit >= 4096
14. limit = 4096
15. end
16. cond[:limit] = limit
17. if par[:d]
18. days = par[:d].to_f
19. if days <= 0 || days >= 365
20. days = 365
21. end
22. cond[:time] = Time.now - days*86400
23. end
After
1. cond = {
2. :feed => if par[:id]
3. feed = Feed.find(par[:id])
4. feed ? feed.id : nil
5. end,
6. :limit => begin
7. limit = par[:m] ? par[:m].to_i : 20
8. limit >= 4096 ? 4096 : limit
9. end,
10. :time => if par[:d]
11. days = par[:d].to_f
12. days = days <= 0 || days >= 365 ? 365 : days
13. Time.now - days * 86400
14. end,
15. }.delete_if { |k, v| v.nil? } # delete all nil elements of cond
Example2:
Before
1. if f[:mode] == "rss" 2. rss = f[:feed] 3. params[:feed][:channel] = rss.channel.title 4. params[:feed][:description] = rss.channel.description 5. params[:feed][:link] = rss.channel.link 6. params[:feed][:copyright] = rss.channel.copyright 7. else 8. atom = f[:feed] 9. params[:feed][:channel] = atom.title 10. params[:feed][:description] = atom.subtitle 11. params[:feed][:link] = atom.links.join 12. params[:feed][:copyright] = atom.rights 13. endAfter
1. params[:feed][:channel], 2. params[:feed][:description], 3. params[:feed][:link], 4. params[:feed][:copyright] = if f[:mode] == "rss" 5. rss = f[:feed] 6. 7. [rss.channel.title, 8. rss.channel.description, 9. rss.channel.link, 10. rss.channel.copyright] 11. else 12. atom = f[:feed] 13. 14. [atom.title, 15. atom.subtitle, 16. atom.links.join, 17. atom.rights] 18. end
Example3
1. # grp_str: p -> public(0) , u -> user(1), f -> friends(2)
2. def privilege_cond(user, grp_str)
3. grp_str ||= 'puf'
4. cond = {:pre => "", :sub => []}
5. cond = if loggedin?(user)
6. frds = grp_str.include?('f') ? user.friends.find(:all) : []
7. frd_ids = frds.collect { |frd| frd.friend_id.to_i }
8.
9. cond = if grp_str.include?('u')
10. {:pre => cond[:pre] + (cond[:pre] == "" ? "" : "OR") +
11. " user_id = ? ",
12. :sub => cond[:sub] + [user.id]}
13. else
14. cond
15. end
16.
17. cond = if grp_str.include?('f') && !frd_ids.empty?
18. {:pre => cond[:pre] + (cond[:pre] == "" ? "" : "OR") +
19. " user_id in (?) AND privilege in (?) ",
20. :sub => cond[:sub] + [frd_ids, [0, 2]]}
21. else
22. cond
23. end
24.
25. cond = if grp_str.include?('p')
26. {:pre => cond[:pre] + (cond[:pre] == "" ? "" : "OR") +
27. " user_id != ? AND privilege = ? ",
28. :sub => cond[:sub] + [user.id, 0]}
29. else
30. cond
31. end
32. else
33. {:pre => "privilege = ?",
34. :sub => [0]}
35. end
36. end
Java + Ruby + Erlang = JRE (Just Running Environment)
I'm recently doing a project under Ruby on Rail. It seems to be a reasonable programmer today, one should take at least > 3 languages.
Personally,
I like Erlang: lightweight process + message passing + functional programming + dynamic. It exactly matches my philosophy of looking the real world, and I think it's what functional programming should be.
Are there really Objects exist? I'm not sure. Instead, talking about OO, Object Oriented may be more sense. That is, an Object makes sense only when you orient it. All states look like being "in" an object, are with meaning only when you measure them. But, doesn't "measure" mean applying a "Function" on it? So, the states should always be carried only by functions rather than 'object', and the states are time streaming, they will be transfered from one function to another function, another function ..., so you catch the meaning of them when you track the functions chain, the meaning is based on the functions rather than the name of a Class as a member of. When you want to take a snapshot on them, you save them some where, such as showing on screen, stored in database, printed on paper what ever.
I like Java: tons of APIs + open source code base + Swing + NetBeans. So far, it has the best cross-platform UI tool kit to my eye. I like Swing, I can change or extend it easily to whatever I want. But things go easy because so many people have taken extremely efforts on it. It's bound too Objected, people split world to objects, then try to composite them or inherit something called super to make them together again. I feel pain when doing this, I have to split them, composite them in a way, then things change (or, the real world is still there), I split them, composite them in another way, again and again, it's called re-factor, but people may never catch the real Factor of the real world.
I, have to learn Ruby. Ruby and Rails are very good. For developers term, you should always know things are not so philosophy as yours, you will have guys thinking in different ways, of the real world. So Ruby is there, everyone can think the real world according to his understanding, yeah, in different ways, and, to make them not going too far away, you need rails.
So, I have to learn Java, as a tool make me doing many things interesting and painful; I have to learn Ruby, as a tool make my guys doing many things interesting and on rails; And I'll keep Erlang (Lisp/Scheme) as a tool make me not only doing but also thinking with interesting.
No Static Method in Interface, So I Write Code As ...
Java does not support static method in interface. But sometimes, I just want a static method to say: PersistenceManager.getDefault(), where PersistenceManager is going to be an interface. I don't like to add one more class named PersistenceManagerFactory, with a method:
public static PersistenceManager PersistenceManagerFactory.getDefault()
So I write code like:
public class PersistenceManager {
private static I i;
public static I getDefault() {
return i == null ? i = ServiceLoader.load(I.class).iterator().next() : i;
}
/** The interface I, which is actually the PersistenceManager should be: */
public static interface I {
void saveQuotes(String symbol, Frequency freq, List
Then implement the PersistenceManager.I in another package, like:
public class NetBeansPersistenceManager implements PersistenceManager.I {
...
}
And declare it under the META-INF as:
core/src/META-INF/services/org.aiotrade.math.PersistenceManager$I
which contains one line:
org.aiotrade.platform.core.netbeans.NetBeansPersistenceManager
I can call PersistenceManager.getDefault().showdown() now.
A Regress Bug in java.awt.geom.Path2D (JDK 6.0 beta 2)
I tested AIOTrade on newly downloaded JDK 6.0 beta 2, and got an exception instantly:
java.lang.ArrayIndexOutOfBoundsException: 0
at java.awt.geom.Path2D$Float.moveTo(Path2D.java:322)
at java.awt.geom.Path2D$Float.append(Path2D.java:643)
at java.awt.geom.Path2D.append(Path2D.java:1780)
The code run good in JDK 5.0, so will it be a regress bug in JDK 6.0?
I then checked the source code: 6.0 vs 5.0, and found there were likely a bit of code omited wrongly. That is, in method body of void needRoom(boolean needMove, int newCoords), should add
if (grow < 1) {
grow = 1;
}
at the next of:
int size = pointTypes.length;
if (numTypes >= size) {
int grow = size;
if (grow > EXPAND_MAX) {
grow = EXPAND_MAX;
}
The following is the proper code I've tested OK:
void needRoom(boolean needMove, int newCoords) {
if (needMove && numTypes == 0) {
throw new IllegalPathStateException("missing initial moveto "+
"in path definition");
}
int size = pointTypes.length;
if (numTypes >= size) {
int grow = size;
if (grow > EXPAND_MAX) {
grow = EXPAND_MAX;
}
/** fix bug:
* java.lang.ArrayIndexOutOfBoundsException: 0
* at java.awt.geom.Path2D$Float.moveTo(Path2D.java:322)
* at java.awt.geom.Path2D$Float.append(Path2D.java:643)
* at java.awt.geom.Path2D.append(Path2D.java:1780)
*/
if (grow < 1) {
grow = 1;
}
pointTypes = Arrays.copyOf(pointTypes, size+grow);
}
size = floatCoords.length;
if (numCoords + newCoords > size) {
int grow = size;
if (grow > EXPAND_MAX * 2) {
grow = EXPAND_MAX * 2;
}
if (grow < newCoords) {
grow = newCoords;
}
floatCoords = Arrays.copyOf(floatCoords, size+grow);
}
}
As I can not wait for it be fixed in JDK, so I wrote another org.aiotrade.util.awt.geom.Path2D and org.aiotrade.util.awt.geom.GeneralPath, and replaced the java.awt.geom.GeneralPath in my source tree. you can get the code at:
Install XWiki on Glassfish and Derby
I've upgraded blogtrade.org to glassfish b48, with XWiki and javadb (Apache Derby) integrated. Here is a short guide I posted:
http://blogtrader.org/wiki/bin/view/KnowledgeBase/XWikiGlassfishDerby
Based on Glassfish b42
The blogtrader.org and blogtrader.net are now based on the newest Glassfish Application Server b42. As Glassfish is also the default bundled J2EE server of NetBeans IDE, with a database: javadb, it's an ideal environment for the developing of BlogTrader Project. I hope to provide stock symbols updating service via a web site to BlogTrader Platform, thus I can add the information of each market, such as local time, open, close hours ect. and you'll need not to input symbol for each stock.
And, the modules updating centre could also be set.
![(please configure the [header_logo] section in trac.ini)](/chrome/!97aa87b5/site/your_project_logo.png)
rss