flashcache.QuoteLoader Maven / Gradle / Ivy
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* 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. See accompanying
* LICENSE file.
*/
package flashcache;
import com.gemstone.gemfire.cache.CacheLoader;
import com.gemstone.gemfire.cache.LoaderHelper;
import com.gemstone.gemfire.cache.Region;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
* This class implements a CacheLoader used by the Quote program to
* search for quotes in other caches and, failing that, to pull quotes
* from the NASDAQ FlashQuote web site.
*
*
*
* When a CacheLoader
is associated with a {@link
* Region}, GemFire will use it to load requested objects when there
* is a cache-miss.
*
* @author GemStone Systems, Inc.
*
* @since 2.0
*/
public class QuoteLoader implements CacheLoader
{
/** this method is invoked by GemFire when there is a cache miss */
public Object load(LoaderHelper helper)
{
String key = helper.getKey(); // the name of the cache entry
// first check other caches but don't invoke their CacheLoaders
System.out.println("(QuoteLoader netSearching for " + key + ")");
try {
Object hit = helper.netSearch(false);
if (hit != null) {
return hit;
}
}
catch (Exception e) {
System.out.println(e.toString());
}
// now query quote.nasdaq.com
System.out.println("(QuoteLoader querying nasdaq for " + key + ")");
return loadSnapshot(key);
}
/** this method is invoked by the load() method when the requested quote
isn't in the cache system and must be loaded from the NASDAQ web site */
String loadSnapshot(String symbolToLoad) {
String page = "";
String symbol = symbolToLoad;
try {
InputStream result;
InputStreamReader reader;
char[] buffer = new char[100000];
int numchars;
if (symbol == null)
symbol = "JAVA";
// the following code queries the quotes.nasdaq.com service and
// parses out the information needed to form the quote. There is
// retry logic in case nasdaq fails to respond
boolean done = false;
int maxTries = 4;
for (int tries=0; !done && (tries < maxTries); tries++) {
// note that nasdaq may charge for quote lookup services
if (tries > 0) {
page = ""; // reset the received portion of the web page
}
URL lookupURL = new URL(
"http://quotes.nasdaq.com/quote.dll?page=quick&mode=stock&symbol="
+ symbol
);
String endTag = "