Commit 9b323274 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.bidi;
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.TreeBidiMap;
public class BidiMapExample {
private BidiMap countryCodes = new TreeBidiMap();
public static void main(String[] args) {
BidiMapExample example = new BidiMapExample();
example.start();
}
private void start() {
populateCountryCodes();
String countryName = (String) countryCodes.get( "tr" );
System.out.println( "Country Name for code 'tr': " + countryName );
String countryCode = (String) countryCodes.inverseBidiMap().get("Uruguay");
System.out.println( "Country Code for name 'Uruguay': " + countryCode );
countryCode = (String) countryCodes.getKey("Ukraine");
System.out.println( "Country Code for name 'Ukraine': " + countryCode );
}
private void populateCountryCodes() {
countryCodes.put("to","Tonga");
countryCodes.put("tr","Turkey");
countryCodes.put("tv","Tuvalu");
countryCodes.put("tz","Tanzania");
countryCodes.put("ua","Ukraine");
countryCodes.put("ug","Uganda");
countryCodes.put("uk","United Kingdom");
countryCodes.put("um","USA Minor Outlying Islands");
countryCodes.put("us","United States");
countryCodes.put("uy","Uruguay");
}
}
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.cache;
import java.util.Map;
import org.apache.commons.collections.map.LRUMap;
public class LRUCacheExample {
private Map cache;
public static void main(String[] args) {
LRUCacheExample example = new LRUCacheExample();
example.start();
}
private void start() {
cache = new LRUMap( 5 );
// Populate the cache with 5 stock prices
cache.put( "MSFT", new Float( 0.03 ) );
cache.put( "TSC", new Float( 0.001 ) );
cache.put( "LU", new Float( 23.30 ) );
cache.put( "CSCO", new Float( 242.20 ) );
cache.put( "P", new Float( 10.23 ) );
// Now use some of the entries in the cache
Float cscoPrice = (Float) cache.get( "CSCO" );
Float msPrice = (Float) cache.get( "MSFT" );
Float tscPrice = (Float) cache.get( "TSC" );
Float luPrice = (Float) cache.get( "LU" );
Float pPrice = (Float) cache.get( "P" );
Float msPrice2 = (Float) cache.get( "MSFT" );
// Add another price to the Map, this should kick out the LRU item.
cache.put( "AA", new Float( 203.20 ) );
// CSCO was the first price requested, it is therefor the
// least recently used.
if( !cache.containsKey("CSCO") ) {
System.out.println( "As expected CSCO was discarded" );
}
}
}
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.insensitive;
import java.util.Map;
import org.apache.commons.collections.map.CaseInsensitiveMap;
public class CaseInsensitiveExample {
Map states = new CaseInsensitiveMap();
public static void main(String[] args) {
CaseInsensitiveExample example = new CaseInsensitiveExample();
example.start();
}
private void start() {
states.put("IL", "Illinois");
states.put("PA", "Pennsylvania");
states.put("GA", "Georgia");
states.put("AZ", "Arizona");
String stateName = (String) states.get( "il" );
System.out.println( "Value retrieved for 'il': " + stateName );
stateName = (String) states.get( "IL" );
System.out.println( "Value retrieved for 'IL': " + stateName );
stateName = (String) states.get( "iL" );
System.out.println( "Value retrieved for 'iL': " + stateName );
}
}
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.lazy;
import java.net.URL;
import java.util.Map;
import org.apache.commons.collections.map.LRUMap;
import org.apache.commons.collections.map.LazyMap;
public class LazyMapExample {
Map stockQuotes;
public static void main(String[] args) throws Exception {
LazyMapExample example = new LazyMapExample();
example.start();
}
public void start() throws Exception {
StockQuoteTransformer sqTransformer = new StockQuoteTransformer();
sqTransformer.setQuoteURL( new URL("http://quotes.company.com") );
sqTransformer.setTimeout( 500 );
stockQuotes = new LRUMap( 5 );
stockQuotes = LazyMap.decorate( stockQuotes, sqTransformer );
// Now use some of the entries in the cache
Float cscoPrice = (Float) stockQuotes.get( "CSCO" );
Float msPrice = (Float) stockQuotes.get( "MSFT" );
Float tscPrice = (Float) stockQuotes.get( "TSC" );
Float luPrice = (Float) stockQuotes.get( "LU" );
Float pPrice = (Float) stockQuotes.get( "P" );
Float msPrice2 = (Float) stockQuotes.get( "MSFT" );
// Add another price to the Map, this should kick out the LRU item.
stockQuotes.put( "AA", new Float( 203.20 ) );
// CSCO was the first price requested, it is therefor the
// least recently used.
if( !stockQuotes.containsKey("CSCO") ) {
System.out.println( "As expected CSCO was discarded" );
}
}
}
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.lazy;
import java.net.URL;
import org.apache.commons.collections.Transformer;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpURL;
import org.apache.commons.httpclient.methods.GetMethod;
public class StockQuoteTransformer implements Transformer {
protected URL quoteURL;
protected long timeout;
public Object transform(Object symbol) {
QuoteRetriever retriever = new QuoteRetriever( (String) symbol );
try {
Thread retrieveThread = new Thread( retriever );
retrieveThread.start();
retrieveThread.join( timeout );
} catch( InterruptedException ie ) {
System.out.println( "Quote request timed out.");
}
return retriever.getResult();
}
public URL getQuoteURL() { return quoteURL; }
public void setQuoteURL(URL url) { quoteURL = url; }
public long getTimeout() { return timeout; }
public void setTimeout(long l) { timeout = l; }
public class QuoteRetriever implements Runnable {
private String symbol;
private Float result = new Float( Float.NaN );
public QuoteRetriever(String symbol) {
this.symbol = symbol;
}
public Float getResult() {
return result;
}
public void run() {
HttpClient client = new HttpClient();
try {
HttpURL url = new HttpURL( quoteURL.toString() );
url.setQuery( "symbol", symbol );
GetMethod getMethod = new GetMethod( url.toString() );
client.executeMethod( getMethod );
String response = getMethod.getResponseBodyAsString();
result = new Float( response );
} catch( Exception e ) {
System.out.println( "Error retrieving quote" );
}
}
}
}
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
Object[] mapArray = new Object[][] {
{ "One", new Long(2423) },
{ "Two", new Short(20s) },
{ "Three", new Integer(202) },
{ "Four", new Double(23.32) },
{ "Five", new Byte(3) }
};
Map map = ArrayUtils.toMap( mapArray );
int twoValue = MapUtils.getIntValue( map, "Two" );
int threeValue = MapUtils.getIntValue( map, "Three" );
System.out.println( "Two plus Three: " + (twoValue + threeValue) );
\ No newline at end of file
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.predicate;
public class Coach {
private String firstName;
private String lastName;
public Coach() {}
public Coach(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public void setFirstName(String string) { firstName = string; }
public void setLastName(String string) { lastName = string; }
}
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.predicate;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.functors.AllPredicate;
import org.apache.commons.collections.map.PredicatedMap;
public class ImprovedPredicatedMapExample extends ValidCoachPredicate {
Map teamMap;
public static void main(String[] args) {
ImprovedPredicatedMapExample example = new ImprovedPredicatedMapExample();
example.start();
}
public void start() {
// Create the Predicates
PropertyPredicate teamName = new PropertyPredicate( "name" );
PropertyPredicate coachFirstName = new PropertyPredicate( "coach.firstName" );
PropertyPredicate coachLastName = new PropertyPredicate( "coach.lastName" );
// Tie three Predicates together into an AllPredicate
Predicate[] predicateArray = new Predicate[] { teamName, coachFirstName, coachLastName };
AllPredicate valuePredicate = new AllPredicate( predicateArray );
// Decorate a HashMap with a predicate on the value
teamMap = PredicatedMap.decorate( new HashMap(), null, valuePredicate);
// Manufacture some teams
Team redSox = new Team( "Red Sox", new Coach( "Patrick", "Moloney") );
Team yankees= new Team( "Yankees", new Coach( "David", "McGarry") );
Team dodgers = new Team( "Dodgers", new Coach( "Nick", "Taylor") );
Team twins = new Team( null, new Coach( "Patrick", "Moloney") );
Team braves = new Team( "Braves", null );
// The follow put calls should work fine
teamMap.put( "RedSox", redSox );
teamMap.put( "Yankees", yankees );
teamMap.put( "Dodgers", dodgers );
// This put should fail because the team name is null
try {
teamMap.put( "Twins", twins);
} catch( IllegalArgumentException iae ) {
System.out.println( "Twins put failed, as expected" );
}
// This put should fail because the coach is null
try {
teamMap.put( "Braves", braves);
} catch( IllegalArgumentException iae ) {
System.out.println( "Braves put failed, as expected" );
}
}
}
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.predicate;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections.functors.AndPredicate;
import org.apache.commons.collections.map.PredicatedMap;
public class PredicatedMapExample extends ValidCoachPredicate {
Map teamMap;
public static void main(String[] args) {
PredicatedMapExample example = new PredicatedMapExample();
example.start();
}
public void start() {
// Create the Predicates
ValidTeamPredicate validTeam = new ValidTeamPredicate();
ValidCoachPredicate validCoach = new ValidCoachPredicate();
// Tie two Predicates together into an AndPredicate
AndPredicate valuePredicate = new AndPredicate( validTeam, validCoach );
// Decorate a HashMap with a predicate on the value
teamMap = PredicatedMap.decorate( new HashMap(), null, valuePredicate);
// Manufacture some teams
Team redSox = new Team( "Red Sox", new Coach( "Patrick", "Moloney") );
Team yankees= new Team( "Yankees", new Coach( "David", "McGarry") );
Team dodgers = new Team( "Dodgers", new Coach( "Nick", "Taylor") );
Team twins = new Team( null, new Coach( "Patrick", "Moloney") );
Team braves = new Team( "Braves", null );
// The follow put calls should work fine
teamMap.put( "RedSox", redSox );
teamMap.put( "Yankees", yankees );
teamMap.put( "Dodgers", dodgers );
// This put should fail because the team name is null
try {
teamMap.put( "Twins", twins);
} catch( IllegalArgumentException iae ) {
System.out.println( "Twins put failed, as expected" );
}
// This put should fail because the coach is null
try {
teamMap.put( "Braves", braves);
} catch( IllegalArgumentException iae ) {
System.out.println( "Braves put failed, as expected" );
}
}
}
/*
* ========================================================================
*
* Copyright 2005 Tim O'Brien.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================================================================
*/
package com.discursive.jccook.collections.predicate;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.Predicate;