proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
knowm_XChange
XChange/xchange-stream-gemini/src/main/java/info/bitrich/xchangestream/gemini/GeminiStreamingMarketDataService.java
GeminiStreamingMarketDataService
filterEventsByReason
class GeminiStreamingMarketDataService implements StreamingMarketDataService { private final GeminiStreamingService service; private final Map<CurrencyPair, GeminiOrderbook> orderbooks = new HashMap<>(); private final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); public GeminiStreamingMarketDataService(GeminiStreamingService service) { this.service = service; } private boolean filterEventsByReason(JsonNode message, String type, String reason) {<FILL_FUNCTION_BODY>} @Override public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) { int maxDepth = (int) MoreObjects.firstNonNull(args.length > 0 ? args[0] : null, 1); Observable<GeminiOrderbook> subscribedOrderbookSnapshot = service .subscribeChannel(currencyPair, maxDepth, maxDepth) .filter( s -> filterEventsByReason(s, "change", "initial") || filterEventsByReason(s, "change", "place") || filterEventsByReason(s, "change", "cancel") || filterEventsByReason(s, "change", "trade")) .filter( s -> // filter out updates that arrive before initial book orderbooks.get(currencyPair) != null || filterEventsByReason(s, "change", "initial")) .map( (JsonNode s) -> { if (filterEventsByReason(s, "change", "initial")) { GeminiWebSocketTransaction transaction = mapper.treeToValue(s, GeminiWebSocketTransaction.class); GeminiOrderbook orderbook = transaction.toGeminiOrderbook(currencyPair); orderbooks.put(currencyPair, orderbook); return orderbook; } if (filterEventsByReason(s, "change", "place") || filterEventsByReason(s, "change", "cancel") || filterEventsByReason(s, "change", "trade")) { GeminiWebSocketTransaction transaction = mapper.treeToValue(s, GeminiWebSocketTransaction.class); GeminiLimitOrder[] levels = transaction.toGeminiLimitOrdersUpdate(); GeminiOrderbook orderbook = orderbooks.get(currencyPair); orderbook.updateLevels(levels); return orderbook; } throw new NotYetImplementedForExchangeException( " Unknown message type, even after filtering: " + s.toString()); }); return subscribedOrderbookSnapshot.map( geminiOrderbook -> GeminiAdaptersX.toOrderbook(geminiOrderbook, maxDepth, new Date())); } @Override public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) { return PublishSubject.create( emitter -> getOrderBook(currencyPair, args) .subscribe( orderBook -> { LimitOrder firstBid = orderBook.getBids().iterator().next(); LimitOrder firstAsk = orderBook.getAsks().iterator().next(); emitter.onNext( new Ticker.Builder() .instrument(currencyPair) .bid(firstBid.getLimitPrice()) .bidSize(firstBid.getOriginalAmount()) .ask(firstAsk.getLimitPrice()) .askSize(firstAsk.getOriginalAmount()) .timestamp( firstBid.getTimestamp().after(firstAsk.getTimestamp()) ? firstBid.getTimestamp() : firstAsk.getTimestamp()) .build()); }, emitter::onError)); } @Override public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) { Observable<GeminiTrade[]> subscribedTrades = service .subscribeChannel(currencyPair, args) .filter(s -> filterEventsByReason(s, "trade", null)) .map( (JsonNode s) -> { GeminiWebSocketTransaction transaction = mapper.treeToValue(s, GeminiWebSocketTransaction.class); return transaction.toGeminiTrades(); }); return subscribedTrades.flatMapIterable(s -> adaptTrades(s, currencyPair).getTrades()); } }
boolean hasEvents = false; if (message.has("events")) { for (JsonNode jsonEvent : message.get("events")) { boolean reasonResult = reason == null || (jsonEvent.has("reason") && jsonEvent.get("reason").asText().equals(reason)); if (jsonEvent.get("type").asText().equals(type) && reasonResult) { hasEvents = true; break; } } } return hasEvents;
1,115
125
1,240
<no_super_class>
knowm_XChange
XChange/xchange-stream-gemini/src/main/java/info/bitrich/xchangestream/gemini/dto/GeminiOrderbook.java
GeminiOrderbook
createFromLevels
class GeminiOrderbook { private final Map<BigDecimal, GeminiLimitOrder> asks; private final Map<BigDecimal, GeminiLimitOrder> bids; private final CurrencyPair currencyPair; public GeminiOrderbook(CurrencyPair currencyPair) { this.bids = new TreeMap<>(Comparator.reverseOrder()); this.asks = new TreeMap<>(); this.currencyPair = currencyPair; } public void createFromLevels(GeminiLimitOrder[] levels) {<FILL_FUNCTION_BODY>} public void updateLevel(GeminiLimitOrder level) { Map<BigDecimal, GeminiLimitOrder> orderBookSide = level.getSide() == Order.OrderType.ASK ? asks : bids; boolean shouldDelete = level.getAmount().compareTo(BigDecimal.ZERO) == 0; // BigDecimal is immutable type (thread safe naturally), // strip the trailing zeros to ensure the hashCode is same when two BigDecimal are equal but // decimal scale are different, such as "1.1200" & "1.12" BigDecimal price = level.getPrice().stripTrailingZeros(); if (shouldDelete) { orderBookSide.remove(price); } else { orderBookSide.put(price, level); } } public void updateLevels(GeminiLimitOrder[] levels) { for (GeminiLimitOrder level : levels) { updateLevel(level); } } public Collection<GeminiLimitOrder> getAsks() { return asks.values(); } public Collection<GeminiLimitOrder> getBids() { return bids.values(); } public CurrencyPair getCurrencyPair() { return currencyPair; } }
for (GeminiLimitOrder level : levels) { Map<BigDecimal, GeminiLimitOrder> orderBookSide = level.getSide() == Order.OrderType.ASK ? asks : bids; orderBookSide.put(level.getPrice(), level); }
474
73
547
<no_super_class>
knowm_XChange
XChange/xchange-stream-hitbtc/src/main/java/info/bitrich/xchangestream/hitbtc/dto/HitbtcWebSocketOrderBook.java
HitbtcWebSocketOrderBook
createFromLevels
class HitbtcWebSocketOrderBook { private Map<BigDecimal, HitbtcOrderLimit> asks; private Map<BigDecimal, HitbtcOrderLimit> bids; private long sequence = 0; public HitbtcWebSocketOrderBook(HitbtcWebSocketOrderBookTransaction orderbookTransaction) { createFromLevels(orderbookTransaction); } private void createFromLevels(HitbtcWebSocketOrderBookTransaction orderbookTransaction) {<FILL_FUNCTION_BODY>} public HitbtcOrderBook toHitbtcOrderBook() { HitbtcOrderLimit[] askLimits = asks.entrySet().stream().map(Map.Entry::getValue).toArray(HitbtcOrderLimit[]::new); HitbtcOrderLimit[] bidLimits = bids.entrySet().stream().map(Map.Entry::getValue).toArray(HitbtcOrderLimit[]::new); return new HitbtcOrderBook(askLimits, bidLimits); } public void updateOrderBook(HitbtcWebSocketOrderBookTransaction orderBookTransaction) { if (orderBookTransaction.getParams().getSequence() <= sequence) { return; } updateOrderBookItems(orderBookTransaction.getParams().getAsk(), asks); updateOrderBookItems(orderBookTransaction.getParams().getBid(), bids); sequence = orderBookTransaction.getParams().getSequence(); } private void updateOrderBookItems( HitbtcOrderLimit[] itemsToUpdate, Map<BigDecimal, HitbtcOrderLimit> localItems) { for (HitbtcOrderLimit itemToUpdate : itemsToUpdate) { localItems.remove(itemToUpdate.getPrice()); if (itemToUpdate.getSize().signum() != 0) { localItems.put(itemToUpdate.getPrice(), itemToUpdate); } } } }
this.asks = new TreeMap<>(BigDecimal::compareTo); this.bids = new TreeMap<>(reverseOrder(BigDecimal::compareTo)); for (HitbtcOrderLimit orderBookItem : orderbookTransaction.getParams().getAsk()) { if (orderBookItem.getSize().signum() != 0) { asks.put(orderBookItem.getPrice(), orderBookItem); } } for (HitbtcOrderLimit orderBookItem : orderbookTransaction.getParams().getBid()) { if (orderBookItem.getSize().signum() != 0) { bids.put(orderBookItem.getPrice(), orderBookItem); } } sequence = orderbookTransaction.getParams().getSequence();
473
196
669
<no_super_class>
knowm_XChange
XChange/xchange-stream-hitbtc/src/main/java/info/bitrich/xchangestream/hitbtc/dto/HitbtcWebSocketOrderBookTransaction.java
HitbtcWebSocketOrderBookTransaction
toHitbtcOrderBook
class HitbtcWebSocketOrderBookTransaction extends HitbtcWebSocketBaseTransaction { private static final String ORDERBOOK_METHOD_UPDATE = "updateOrderbook"; private HitbtcWebSocketOrderBookParams params; public HitbtcWebSocketOrderBookTransaction( @JsonProperty("method") String method, @JsonProperty("params") HitbtcWebSocketOrderBookParams params) { super(method); this.params = params; } public HitbtcWebSocketOrderBookParams getParams() { return params; } public HitbtcWebSocketOrderBook toHitbtcOrderBook(HitbtcWebSocketOrderBook orderbook) {<FILL_FUNCTION_BODY>} }
if (method.equals(ORDERBOOK_METHOD_UPDATE)) { orderbook.updateOrderBook(this); return orderbook; } return new HitbtcWebSocketOrderBook(this);
179
54
233
<methods>public void <init>(java.lang.String) ,public java.lang.String getMethod() <variables>protected final non-sealed java.lang.String method
knowm_XChange
XChange/xchange-stream-kraken/src/main/java/info/bitrich/xchangestream/kraken/KrakenStreamingTradeService.java
KrakenDtoUserTradeHolder
adaptKrakenOrders
class KrakenDtoUserTradeHolder extends HashMap<String, KrakenOwnTrade> {} @Override public Observable<Order> getOrderChanges(CurrencyPair currencyPair, Object... args) { try { if (!ownTradesObservableSet) { synchronized (this) { if (!ownTradesObservableSet) { String channelName = getChannelName(KrakenSubscriptionName.openOrders); ownTradesObservable = streamingService .subscribeChannel(channelName) .filter(JsonNode::isArray) .filter(Objects::nonNull) .map(jsonNode -> jsonNode.get(0)) .map( jsonNode -> StreamingObjectMapperHelper.getObjectMapper() .treeToValue(jsonNode, KrakenDtoOrderHolder[].class)) .flatMapIterable(this::adaptKrakenOrders) .share(); ownTradesObservableSet = true; } } } return Observable.create( emit -> ownTradesObservable .filter( order -> currencyPair == null || order.getCurrencyPair() == null || order.getCurrencyPair().compareTo(currencyPair) == 0) .subscribe(emit::onNext, emit::onError, emit::onComplete)); } catch (Exception e) { return Observable.error(e); } } private Iterable<Order> adaptKrakenOrders(KrakenDtoOrderHolder[] dtoList) {<FILL_FUNCTION_BODY>
List<Order> result = new ArrayList<>(); for (KrakenDtoOrderHolder dtoHolder : dtoList) { for (Map.Entry<String, KrakenOpenOrder> dtoOrderEntry : dtoHolder.entrySet()) { String orderId = dtoOrderEntry.getKey(); KrakenOpenOrder dto = dtoOrderEntry.getValue(); KrakenOpenOrder.KrakenDtoDescr descr = dto.descr; CurrencyPair pair = descr == null ? null : new CurrencyPair(descr.pair); Order.OrderType side = descr == null ? null : KrakenAdapters.adaptOrderType(KrakenType.fromString(descr.type)); String orderType = (descr == null || descr.ordertype == null) ? null : descr.ordertype; Order.Builder builder; if ("limit".equals(orderType)) builder = new LimitOrder.Builder(side, pair).limitPrice(descr.price); else if ("stop".equals(orderType)) builder = new StopOrder.Builder(side, pair).limitPrice(descr.price).stopPrice(descr.price2); else if ("market".equals(orderType)) builder = new MarketOrder.Builder(side, pair); else // this is an order update (not the full order, it may only update one field) builder = new MarketOrder.Builder(side, pair); result.add( builder .id(orderId) .originalAmount(dto.vol) .cumulativeAmount(dto.vol_exec) .averagePrice(dto.avg_price) .orderStatus( dto.status == null ? null : KrakenAdapters.adaptOrderStatus(KrakenOrderStatus.fromString(dto.status))) .timestamp(dto.opentm == null ? null : new Date((long) (dto.opentm * 1000L))) .fee(dto.fee) .flags(adaptFlags(dto.oflags)) .userReference(dto.userref == null ? null : Integer.toString(dto.userref)) .build()); } } return result;
409
572
981
<no_super_class>
knowm_XChange
XChange/xchange-stream-krakenfutures/src/main/java/info/bitrich/xchangestream/krakenfutures/KrakenFuturesStreamingMarketDataService.java
KrakenFuturesStreamingMarketDataService
getFundingRate
class KrakenFuturesStreamingMarketDataService implements StreamingMarketDataService { private final ObjectMapper objectMapper = StreamingObjectMapperHelper.getObjectMapper(); private final KrakenFuturesStreamingService service; private final Map<Instrument, OrderBook> orderBookMap = new HashMap<>(); public KrakenFuturesStreamingMarketDataService(KrakenFuturesStreamingService service) { this.service = service; } @Override public Observable<OrderBook> getOrderBook(Instrument instrument, Object... args) { String channelName = service.ORDERBOOK + KrakenFuturesAdapters.adaptKrakenFuturesSymbol(instrument); return service .subscribeChannel(channelName) .filter(message -> message.has("feed")) .map( message -> { try { if (message.get("feed").asText().contains("book_snapshot")) { orderBookMap.put( instrument, KrakenFuturesStreamingAdapters.adaptKrakenFuturesSnapshot( objectMapper.treeToValue( message, KrakenFuturesStreamingOrderBookSnapshotResponse.class))); } else if (message.get("feed").asText().equals(service.ORDERBOOK)) { KrakenFuturesStreamingOrderBookDeltaResponse delta = objectMapper.treeToValue( message, KrakenFuturesStreamingOrderBookDeltaResponse.class); orderBookMap .get(instrument) .update( new LimitOrder.Builder( (delta .getSide() .equals( KrakenFuturesStreamingOrderBookDeltaResponse .KrakenFuturesStreamingSide.sell)) ? Order.OrderType.ASK : Order.OrderType.BID, instrument) .limitPrice(delta.getPrice()) .originalAmount(delta.getQty()) .timestamp(delta.getTimestamp()) .build()); } if (orderBookMap .get(instrument) .getBids() .get(0) .getLimitPrice() .compareTo(orderBookMap.get(instrument).getAsks().get(0).getLimitPrice()) > 0) { throw new IOException("OrderBook crossed!!!"); } return orderBookMap.get(instrument); } catch (Exception e) { throw new IOException(e); } }); } @Override public Observable<Ticker> getTicker(Instrument instrument, Object... args) { String channelName = service.TICKER + KrakenFuturesAdapters.adaptKrakenFuturesSymbol(instrument); return service .subscribeChannel(channelName) .filter(message -> message.has("feed") && message.has("product_id")) .filter( message -> message .get("product_id") .asText() .equals(KrakenFuturesAdapters.adaptKrakenFuturesSymbol(instrument))) .map( message -> KrakenFuturesStreamingAdapters.adaptTicker( objectMapper.treeToValue(message, KrakenFuturesStreamingTickerResponse.class))); } @Override public Observable<Trade> getTrades(Instrument instrument, Object... args) { String channelName = service.TRADES + KrakenFuturesAdapters.adaptKrakenFuturesSymbol(instrument); return service .subscribeChannel(channelName) .filter(message -> message.has("feed") && message.has("product_id")) .filter(message -> message.get("feed").asText().equals("trade")) .map( message -> KrakenFuturesStreamingAdapters.adaptTrade( objectMapper.treeToValue(message, KrakenFuturesStreamingTradeResponse.class))); } @Override public Observable<FundingRate> getFundingRate(Instrument instrument, Object... args) {<FILL_FUNCTION_BODY>} }
String channelName = service.TICKER + KrakenFuturesAdapters.adaptKrakenFuturesSymbol(instrument); return service .subscribeChannel(channelName) .filter(message -> message.has("feed") && message.has("product_id")) .filter( message -> message .get("product_id") .asText() .equals(KrakenFuturesAdapters.adaptKrakenFuturesSymbol(instrument))) .map( message -> KrakenFuturesStreamingAdapters.adaptFundingRate( objectMapper.treeToValue(message, KrakenFuturesStreamingTickerResponse.class)));
1,048
180
1,228
<no_super_class>
knowm_XChange
XChange/xchange-stream-krakenfutures/src/main/java/info/bitrich/xchangestream/krakenfutures/KrakenFuturesStreamingService.java
KrakenFuturesStreamingService
getChannelNameFromMessage
class KrakenFuturesStreamingService extends JsonNettyStreamingService { private static final Logger LOG = LoggerFactory.getLogger(KrakenFuturesStreamingService.class); protected final String ORDERBOOK = "book"; protected final String TICKER = "ticker"; protected final String TRADES = "trade"; protected final String FILLS = "fills"; private String CHALLENGE = ""; private final ExchangeSpecification exchangeSpecification; public KrakenFuturesStreamingService(String apiUrl, ExchangeSpecification exchangeSpecification) { super(apiUrl); this.exchangeSpecification = exchangeSpecification; } @Override protected String getChannelNameFromMessage(JsonNode message) {<FILL_FUNCTION_BODY>} @Override protected void handleMessage(JsonNode message) { super.handleMessage(message); if (message.has("event") && message.get("event").asText().equals("alert") && message.has("message") && message.get("message").asText().equals("Failed to subscribe to authenticated feed")) { new Thread( () -> { try { sendMessage( objectMapper.writeValueAsString(getWebSocketMessage("subscribe", FILLS))); } catch (JsonProcessingException e) { throw new RuntimeException(e); } }) .start(); } if (message.has("event") && message.has("message")) { if (message.get("event").asText().equals("challenge")) { CHALLENGE = message.get("message").asText(); LOG.debug("New CHALLENGE has been saved."); } } } @Override public String getSubscribeMessage(String channelName, Object... args) throws IOException { return objectMapper.writeValueAsString(getWebSocketMessage("subscribe", channelName)); } @Override public String getUnsubscribeMessage(String channelName, Object... args) throws IOException { return objectMapper.writeValueAsString(getWebSocketMessage("unsubscribe", channelName)); } @Override protected Completable openConnection() { return super.openConnection() .doOnComplete( () -> { LOG.debug("Open connection, reset CHALLENGE..."); CHALLENGE = ""; sendMessage( StreamingObjectMapperHelper.getObjectMapper() .writeValueAsString( new KrakenFuturesStreamingChallengeRequest( exchangeSpecification.getApiKey()))); }) .delay(3, TimeUnit.SECONDS); } private KrakenFuturesStreamingWebsocketMessage getWebSocketMessage( String event, String channelName) { if (channelName.contains(ORDERBOOK)) { return new KrakenFuturesStreamingWebsocketMessage( event, ORDERBOOK, new String[] {channelName.replace(ORDERBOOK, "")}); } else if (channelName.contains(TICKER)) { return new KrakenFuturesStreamingWebsocketMessage( event, TICKER, new String[] {channelName.replace(TICKER, "")}); } else if (channelName.contains(TRADES)) { return new KrakenFuturesStreamingWebsocketMessage( event, TRADES, new String[] {channelName.replace(TRADES, "")}); } else if (channelName.contains(FILLS)) { return new KrakenFuturesStreamingAuthenticatedWebsocketMessage( event, FILLS, null, exchangeSpecification.getApiKey(), CHALLENGE, signChallenge()); } else { throw new NotImplementedException( "ChangeName " + channelName + " has not been implemented yet."); } } private String signChallenge() { return KrakenFuturesDigest.createInstance(exchangeSpecification.getSecretKey()) .signMessage(CHALLENGE); } }
String channelName = ""; if (message.has("feed") && message.has("product_id")) { if (message.get("feed").asText().contains(ORDERBOOK)) { channelName = ORDERBOOK + message.get("product_id").asText(); } else if (message.get("feed").asText().contains(TICKER)) { channelName = TICKER + message.get("product_id").asText(); } else if (message.get("feed").asText().contains(TRADES)) { channelName = TRADES + message.get("product_id").asText(); } } // Fills if (message.has("feed")) { if (message.get("feed").asText().equals(FILLS)) { channelName = FILLS; } } LOG.debug("ChannelName: " + channelName); return channelName;
1,027
235
1,262
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
knowm_XChange
XChange/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingMarketDataService.java
KucoinStreamingMarketDataService
createOrderBookObservable
class KucoinStreamingMarketDataService implements StreamingMarketDataService { private static final Logger logger = LoggerFactory.getLogger(KucoinStreamingMarketDataService.class); private final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); private final Map<CurrencyPair, Observable<OrderBook>> orderbookSubscriptions = new ConcurrentHashMap<>(); private final Map<CurrencyPair, Observable<KucoinOrderBookEventData>> orderBookRawUpdatesSubscriptions = new ConcurrentHashMap<>(); private final KucoinStreamingService service; private final KucoinMarketDataService marketDataService; private final Runnable onApiCall; public KucoinStreamingMarketDataService( KucoinStreamingService service, KucoinMarketDataService marketDataService, Runnable onApiCall) { this.service = service; this.marketDataService = marketDataService; this.onApiCall = onApiCall; } @Override public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) { String channelName = "/market/ticker:" + KucoinAdapters.adaptCurrencyPair(currencyPair); return service .subscribeChannel(channelName) .doOnError( ex -> logger.warn("encountered error while subscribing to channel " + channelName, ex)) .map(node -> mapper.treeToValue(node, KucoinTickerEvent.class)) .map(KucoinTickerEvent::getTicker); } @Override public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) { return orderbookSubscriptions.computeIfAbsent(currencyPair, this::initOrderBookIfAbsent); } private Observable<OrderBook> initOrderBookIfAbsent(CurrencyPair currencyPair) { orderBookRawUpdatesSubscriptions.computeIfAbsent( currencyPair, s -> triggerObservableBody(rawOrderBookUpdates(s))); return createOrderBookObservable(currencyPair); } private Observable<KucoinOrderBookEventData> rawOrderBookUpdates(CurrencyPair currencyPair) { String channelName = "/market/level2:" + KucoinAdapters.adaptCurrencyPair(currencyPair); return service .subscribeChannel(channelName) .doOnError( ex -> logger.warn("encountered error while subscribing to channel " + channelName, ex)) .map(it -> mapper.treeToValue(it, KucoinOrderBookEvent.class)) .map(e -> e.data); } private Observable<OrderBook> createOrderBookObservable(CurrencyPair currencyPair) {<FILL_FUNCTION_BODY>} private <T> Observable<T> triggerObservableBody(Observable<T> observable) { Consumer<T> NOOP = whatever -> {}; observable.subscribe(NOOP); return observable; } @Override public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) { throw new NotYetImplementedForExchangeException(); } private final class OrderbookSubscription { final Observable<KucoinOrderBookEventData> stream; final AtomicLong lastUpdateId = new AtomicLong(); final AtomicLong snapshotLastUpdateId = new AtomicLong(); OrderBook orderBook; private OrderbookSubscription(Observable<KucoinOrderBookEventData> stream) { this.stream = stream; } void invalidateSnapshot() { snapshotLastUpdateId.set(0); } void initSnapshotIfInvalid(CurrencyPair currencyPair) { if (snapshotLastUpdateId.get() != 0) return; try { logger.info("Fetching initial orderbook snapshot for {} ", currencyPair); onApiCall.run(); OrderBookResponse book = marketDataService.getKucoinOrderBookFull(currencyPair); lastUpdateId.set(Long.parseLong(book.getSequence())); snapshotLastUpdateId.set(lastUpdateId.get()); orderBook = KucoinAdapters.adaptOrderBook(currencyPair, book); } catch (Exception e) { logger.error("Failed to fetch initial order book for " + currencyPair, e); snapshotLastUpdateId.set(0); lastUpdateId.set(0); orderBook = null; } } } }
// 1. Open a stream // 2. Buffer the events you receive from the stream. OrderbookSubscription subscription = new OrderbookSubscription(orderBookRawUpdatesSubscriptions.get(currencyPair)); return subscription .stream // 3. Get a depth snapshot // (we do this if we don't already have one or we've invalidated a previous one) .doOnNext(transaction -> subscription.initSnapshotIfInvalid(currencyPair)) .doOnError(ex -> logger.warn("encountered error while processing order book event", ex)) // If we failed, don't return anything. Just keep trying until it works .filter(transaction -> subscription.snapshotLastUpdateId.get() > 0L) // 4. Drop any event where u is <= lastUpdateId in the snapshot .filter(depth -> depth.sequenceEnd > subscription.snapshotLastUpdateId.get()) // 5. The first processed should have U <= lastUpdateId+1 AND u >= lastUpdateId+1, and // subsequent events would // normally have u == lastUpdateId + 1 which is stricter version of the above - let's be // more relaxed // each update has absolute numbers so even if there's an overlap it does no harm .filter( depth -> { long lastUpdateId = subscription.lastUpdateId.get(); boolean result = lastUpdateId == 0L || (depth.sequenceStart <= lastUpdateId + 1 && depth.sequenceEnd >= lastUpdateId + 1); if (result) { subscription.lastUpdateId.set(depth.sequenceEnd); } else { // If not, we re-sync logger.info( "Orderbook snapshot for {} out of date (last={}, U={}, u={}). This is normal. Re-syncing.", currencyPair, lastUpdateId, depth.sequenceStart, depth.sequenceEnd); subscription.invalidateSnapshot(); } return result; }) // 7. The data in each event is the absolute quantity for a price level // 8. If the quantity is 0, remove the price level // 9. Receiving an event that removes a price level that is not in your local order book can // happen and is normal. .map( depth -> { depth.update(currencyPair, subscription.orderBook); return subscription.orderBook; }) .share();
1,147
615
1,762
<no_super_class>
knowm_XChange
XChange/xchange-stream-kucoin/src/main/java/info/bitrich/xchangestream/kucoin/KucoinStreamingService.java
KucoinStreamingService
handleMessage
class KucoinStreamingService extends JsonNettyStreamingService { private final AtomicLong refCount = new AtomicLong(); private final Observable<Long> pingPongSrc; private final boolean privateChannel; private Disposable pingPongSubscription; public KucoinStreamingService(String apiUrl, int pingInterval, boolean privateChannel) { super(apiUrl); this.privateChannel = privateChannel; pingPongSrc = Observable.interval(pingInterval, pingInterval, TimeUnit.MILLISECONDS); } @Override public Completable connect() { Completable conn = super.connect(); return conn.andThen( (CompletableSource) (completable) -> { try { if (pingPongSubscription != null && !pingPongSubscription.isDisposed()) { pingPongSubscription.dispose(); } pingPongSubscription = pingPongSrc.subscribe( o -> this.sendMessage( "{\"type\":\"ping\", \"id\": \"" + refCount.incrementAndGet() + "\"}")); completable.onComplete(); } catch (Exception e) { completable.onError(e); } }); } @Override protected String getChannelNameFromMessage(JsonNode message) { JsonNode topic = message.get("topic"); return topic != null ? topic.asText() : null; } @Override public String getSubscribeMessage(String channelName, Object... args) throws IOException { KucoinWebSocketSubscribeMessage message = new KucoinWebSocketSubscribeMessage( channelName, refCount.incrementAndGet(), privateChannel); return objectMapper.writeValueAsString(message); } @Override public String getUnsubscribeMessage(String channelName, Object... args) throws IOException { KucoinWebSocketUnsubscribeMessage message = new KucoinWebSocketUnsubscribeMessage(channelName, refCount.incrementAndGet()); return objectMapper.writeValueAsString(message); } @Override protected void handleMessage(JsonNode message) {<FILL_FUNCTION_BODY>} @Override protected WebSocketClientHandler getWebSocketClientHandler( WebSocketClientHandshaker handshaker, WebSocketClientHandler.WebSocketMessageHandler handler) { return new KucoinNettyWebSocketClientHandler(handshaker, handler); } private class KucoinNettyWebSocketClientHandler extends NettyWebSocketClientHandler { public KucoinNettyWebSocketClientHandler( WebSocketClientHandshaker handshaker, WebSocketMessageHandler handler) { super(handshaker, handler); } public void channelInactive(ChannelHandlerContext ctx) { if (pingPongSubscription != null && !pingPongSubscription.isDisposed()) { pingPongSubscription.dispose(); } super.channelInactive(ctx); } } }
JsonNode typeNode = message.get("type"); if (typeNode != null) { String type = typeNode.asText(); if ("message".equals(type)) super.handleMessage(message); else if ("error".equals(type)) super.handleError(message, new Exception(message.get("data").asText())); }
776
90
866
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
knowm_XChange
XChange/xchange-stream-lgo/src/main/java/info/bitrich/xchangestream/lgo/LgoStreamingService.java
LgoStreamingService
getCustomHeaders
class LgoStreamingService extends JsonNettyStreamingService { private final LgoSignatureService signatureService; private final String apiUrl; LgoStreamingService(LgoSignatureService signatureService, String apiUrl) { super(apiUrl, Integer.MAX_VALUE, Duration.ofSeconds(10), Duration.ofSeconds(15), 1); this.apiUrl = apiUrl; this.signatureService = signatureService; } @Override protected String getChannelNameFromMessage(JsonNode message) { String channel = message.get("channel").asText(); if (channel.equals("trades") || channel.equals("level2") || channel.equals("user")) { return channel + "-" + message.get("product_id").textValue(); } return channel; } @Override public String getSubscribeMessage(String channelName, Object... args) throws IOException { return getObjectMapper().writeValueAsString(LgoSubscription.subscribe(channelName)); } @Override public String getUnsubscribeMessage(String channelName, Object... args) throws IOException { return getObjectMapper().writeValueAsString(LgoSubscription.unsubscribe(channelName)); } @Override protected DefaultHttpHeaders getCustomHeaders() {<FILL_FUNCTION_BODY>} }
DefaultHttpHeaders headers = super.getCustomHeaders(); String timestamp = String.valueOf(System.currentTimeMillis()); headers.add("X-LGO-DATE", timestamp); String auth = signatureService.digestSignedUrlHeader(this.apiUrl, timestamp); headers.add("Authorization", auth); return headers;
337
86
423
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, int) ,public void <init>(java.lang.String, int, java.time.Duration, java.time.Duration, int) ,public void messageHandler(java.lang.String) ,public boolean processArrayMessageSeparately() <variables>private static final Logger LOG,protected final ObjectMapper objectMapper
knowm_XChange
XChange/xchange-stream-lgo/src/main/java/info/bitrich/xchangestream/lgo/domain/LgoMatchOrderEvent.java
LgoMatchOrderEvent
applyOnOrders
class LgoMatchOrderEvent extends LgoBatchOrderEvent { /** Trade identifier */ private final String tradeId; /** Trade price (quote currency) */ private final BigDecimal tradePrice; /** Trade quantity (base currency) */ private final BigDecimal filledQuantity; /** Remaining amount (base currency) */ private final BigDecimal remainingQuantity; /** Fees (quote currency) */ private final BigDecimal fees; /** Trade liquidity (T for taker, M for maker) */ private final String liquidity; /** Trade type (BID/ASK): taker order type */ private Order.OrderType orderType; public LgoMatchOrderEvent( @JsonProperty("type") String type, @JsonProperty("order_id") String orderId, @JsonProperty("time") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date time, @JsonProperty("trade_id") String tradeId, @JsonProperty("price") BigDecimal price, @JsonProperty("filled_quantity") BigDecimal filledQuantity, @JsonProperty("remaining_quantity") BigDecimal remainingQuantity, @JsonProperty("fees") BigDecimal fees, @JsonProperty("liquidity") String liquidity) { super(type, orderId, time); this.tradeId = tradeId; this.tradePrice = price; this.filledQuantity = filledQuantity; this.remainingQuantity = remainingQuantity; this.fees = fees; this.liquidity = liquidity; } public LgoMatchOrderEvent( Long batchId, String type, String orderId, Date time, String tradeId, BigDecimal tradePrice, BigDecimal filledQuantity, BigDecimal remainingQuantity, BigDecimal fees, String liquidity, Order.OrderType orderType) { super(batchId, type, orderId, time); this.tradeId = tradeId; this.tradePrice = tradePrice; this.filledQuantity = filledQuantity; this.remainingQuantity = remainingQuantity; this.fees = fees; this.liquidity = liquidity; this.orderType = orderType; } public String getTradeId() { return tradeId; } public BigDecimal getTradePrice() { return tradePrice; } public BigDecimal getFilledQuantity() { return filledQuantity; } public BigDecimal getRemainingQuantity() { return remainingQuantity; } public BigDecimal getFees() { return fees; } public String getLiquidity() { return liquidity; } public Order.OrderType getOrderType() { return orderType; } public void setOrderType(Order.OrderType orderType) { this.orderType = orderType; } @Override public Order applyOnOrders(CurrencyPair currencyPair, Map<String, Order> allOrders) {<FILL_FUNCTION_BODY>} }
Order matchedOrder = allOrders.get(getOrderId()); matchedOrder.setOrderStatus(Order.OrderStatus.PARTIALLY_FILLED); matchedOrder.setCumulativeAmount(matchedOrder.getOriginalAmount().subtract(remainingQuantity)); BigDecimal fee = matchedOrder.getFee() == null ? fees : matchedOrder.getFee().add(fees); matchedOrder.setFee(fee); return matchedOrder;
836
119
955
<methods>public void <init>(java.lang.Long, java.lang.String, java.lang.String, java.util.Date) ,public abstract org.knowm.xchange.dto.Order applyOnOrders(org.knowm.xchange.currency.CurrencyPair, Map<java.lang.String,org.knowm.xchange.dto.Order>) ,public java.lang.Long getBatchId() ,public void setBatchId(long) <variables>private java.lang.Long batchId
knowm_XChange
XChange/xchange-stream-lgo/src/main/java/info/bitrich/xchangestream/lgo/domain/LgoPendingOrderEvent.java
LgoPendingOrderEvent
applyOnOrders
class LgoPendingOrderEvent extends LgoBatchOrderEvent { /** Type of Order (L for LimitOrder, M for MarketOrder) when type=pending */ private final String orderType; /** Limit price (quote currency) when type=pending and orderType=L */ private final BigDecimal limitPrice; /** Side of the order: BID/ASK when type=pending */ private final Order.OrderType side; /** Initial amount (base currency) when type=pending */ private final BigDecimal initialAmount; public LgoPendingOrderEvent( @JsonProperty("type") String type, @JsonProperty("order_id") String orderId, @JsonProperty("time") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") Date time, @JsonProperty("order_type") String orderType, @JsonProperty("price") BigDecimal price, @JsonProperty("side") String side, @JsonProperty("quantity") BigDecimal quantity) { super(type, orderId, time); this.orderType = orderType; this.limitPrice = price; this.side = side.equals("B") ? Order.OrderType.BID : Order.OrderType.ASK; this.initialAmount = quantity; } public LgoPendingOrderEvent( Long batchId, String type, String orderId, Date time, String orderType, BigDecimal limitPrice, Order.OrderType side, BigDecimal initialAmount) { super(batchId, type, orderId, time); this.orderType = orderType; this.limitPrice = limitPrice; this.side = side; this.initialAmount = initialAmount; } @Override public Order applyOnOrders(CurrencyPair currencyPair, Map<String, Order> allOrders) {<FILL_FUNCTION_BODY>} public String getOrderType() { return orderType; } public BigDecimal getLimitPrice() { return limitPrice; } public Order.OrderType getSide() { return side; } public BigDecimal getInitialAmount() { return initialAmount; } }
Order order = LgoAdapter.adaptPendingOrder(this, currencyPair); allOrders.put(order.getId(), order); return order;
587
41
628
<methods>public void <init>(java.lang.Long, java.lang.String, java.lang.String, java.util.Date) ,public abstract org.knowm.xchange.dto.Order applyOnOrders(org.knowm.xchange.currency.CurrencyPair, Map<java.lang.String,org.knowm.xchange.dto.Order>) ,public java.lang.Long getBatchId() ,public void setBatchId(long) <variables>private java.lang.Long batchId
knowm_XChange
XChange/xchange-stream-okcoin/src/main/java/info/bitrich/xchangestream/okcoin/dto/OkCoinOrderbook.java
OkCoinOrderbook
createFromDepthLevels
class OkCoinOrderbook { private final BigDecimal zero = new BigDecimal(0); private final SortedMap<BigDecimal, BigDecimal[]> asks; private final SortedMap<BigDecimal, BigDecimal[]> bids; public OkCoinOrderbook() { asks = new TreeMap<>( java.util.Collections .reverseOrder()); // Because okcoin adapter uses reverse sort for asks!!! bids = new TreeMap<>(); } public OkCoinOrderbook(OkCoinDepth depth) { this(); createFromDepth(depth); } public void createFromDepth(OkCoinDepth depth) { BigDecimal[][] depthAsks = depth.getAsks(); BigDecimal[][] depthBids = depth.getBids(); createFromDepthLevels(depthAsks, Order.OrderType.ASK); createFromDepthLevels(depthBids, Order.OrderType.BID); } public void createFromDepthLevels(BigDecimal[][] depthLevels, Order.OrderType side) {<FILL_FUNCTION_BODY>} public void updateLevels(BigDecimal[][] depthLevels, Order.OrderType side) { for (BigDecimal[] level : depthLevels) { updateLevel(level, side); } } public void updateLevel(BigDecimal[] level, Order.OrderType side) { SortedMap<BigDecimal, BigDecimal[]> orderBookSide = side == Order.OrderType.ASK ? asks : bids; boolean shouldDelete = level[1].compareTo(zero) == 0; BigDecimal price = level[0]; orderBookSide.remove(price); if (!shouldDelete) { orderBookSide.put(price, level); } } public BigDecimal[][] getSide(Order.OrderType side) { SortedMap<BigDecimal, BigDecimal[]> orderbookLevels = side == Order.OrderType.ASK ? asks : bids; Collection<BigDecimal[]> levels = orderbookLevels.values(); return levels.toArray(new BigDecimal[orderbookLevels.size()][]); } public BigDecimal[][] getAsks() { return getSide(Order.OrderType.ASK); } public BigDecimal[][] getBids() { return getSide(Order.OrderType.BID); } public OkCoinDepth toOkCoinDepth(long epoch) { Date timestamp = new java.util.Date(epoch); return new OkCoinDepth(getAsks(), getBids(), timestamp); } }
SortedMap<BigDecimal, BigDecimal[]> orderbookLevels = side == Order.OrderType.ASK ? asks : bids; for (BigDecimal[] level : depthLevels) { orderbookLevels.put(level[0], level); }
677
70
747
<no_super_class>
knowm_XChange
XChange/xchange-stream-okex/src/main/java/info/bitrich/xchangestream/okex/OkexStreamingTradeService.java
OkexStreamingTradeService
getUserTrades
class OkexStreamingTradeService implements StreamingTradeService { private final OkexStreamingService service; private final ExchangeMetaData exchangeMetaData; private final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); public OkexStreamingTradeService( OkexStreamingService service, ExchangeMetaData exchangeMetaData) { this.service = service; this.exchangeMetaData = exchangeMetaData; } @Override public Observable<UserTrade> getUserTrades(Instrument instrument, Object... args) {<FILL_FUNCTION_BODY>} }
String channelUniqueId = USERTRADES + OkexAdapters.adaptInstrument(instrument); return service .subscribeChannel(channelUniqueId) .filter(message -> message.has("data")) .flatMap( jsonNode -> { List<OkexOrderDetails> okexOrderDetails = mapper.treeToValue( jsonNode.get("data"), mapper .getTypeFactory() .constructCollectionType(List.class, OkexOrderDetails.class)); return Observable.fromIterable( OkexAdapters.adaptUserTrades(okexOrderDetails, exchangeMetaData).getUserTrades()); });
158
180
338
<no_super_class>
knowm_XChange
XChange/xchange-stream-poloniex2/src/main/java/info/bitrich/xchangestream/poloniex2/PoloniexStreamingMarketDataService.java
PoloniexStreamingMarketDataService
getTrades
class PoloniexStreamingMarketDataService implements StreamingMarketDataService { private static final Logger LOG = LoggerFactory.getLogger(PoloniexStreamingMarketDataService.class); private static final String TICKER_CHANNEL_ID = "1002"; private final PoloniexStreamingService service; private final Supplier<Observable<Ticker>> streamingTickers; public PoloniexStreamingMarketDataService( PoloniexStreamingService service, Map<Integer, CurrencyPair> currencyIdMap) { this.service = service; final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); streamingTickers = Suppliers.memoize( () -> service .subscribeChannel(TICKER_CHANNEL_ID) .map( s -> { PoloniexWebSocketTickerTransaction ticker = mapper.treeToValue(s, PoloniexWebSocketTickerTransaction.class); CurrencyPair currencyPair = currencyIdMap.get(ticker.getPairId()); return adaptPoloniexTicker( ticker.toPoloniexTicker(currencyPair), currencyPair); }) .share()); } @Override public Observable<OrderBook> getOrderBook(CurrencyPair currencyPair, Object... args) { Observable<PoloniexOrderbook> subscribedOrderbook = service .subscribeCurrencyPairChannel(currencyPair) .scan( Optional.empty(), (Optional<PoloniexOrderbook> orderbook, List<PoloniexWebSocketEvent> poloniexWebSocketEvents) -> poloniexWebSocketEvents.stream() .filter( s -> s instanceof PoloniexWebSocketOrderbookInsertEvent || s instanceof PoloniexWebSocketOrderbookModifiedEvent) .reduce( orderbook, (poloniexOrderbook, s) -> getPoloniexOrderbook(orderbook, s), (o1, o2) -> { throw new UnsupportedOperationException("No parallel execution"); })) .filter(Optional::isPresent) .map(Optional::get); return subscribedOrderbook.map(s -> adaptPoloniexDepth(s.toPoloniexDepth(), currencyPair)); } @Override public Observable<Ticker> getTicker(CurrencyPair currencyPair, Object... args) { return streamingTickers.get().filter(ticker -> ticker.getCurrencyPair().equals(currencyPair)); } @Override public Observable<Trade> getTrades(CurrencyPair currencyPair, Object... args) {<FILL_FUNCTION_BODY>} private Optional<PoloniexOrderbook> getPoloniexOrderbook( final Optional<PoloniexOrderbook> orderbook, final PoloniexWebSocketEvent s) { if (s.getEventType().equals("i")) { OrderbookInsertEvent insertEvent = ((PoloniexWebSocketOrderbookInsertEvent) s).getInsert(); SortedMap<BigDecimal, BigDecimal> asks = insertEvent.toDepthLevels(OrderbookInsertEvent.ASK_SIDE); SortedMap<BigDecimal, BigDecimal> bids = insertEvent.toDepthLevels(OrderbookInsertEvent.BID_SIDE); return Optional.of(new PoloniexOrderbook(asks, bids)); } else { OrderbookModifiedEvent modifiedEvent = ((PoloniexWebSocketOrderbookModifiedEvent) s).getModifiedEvent(); orderbook .orElseThrow( () -> new IllegalStateException("Orderbook update received before initial snapshot")) .modify(modifiedEvent); return orderbook; } } }
Observable<PoloniexWebSocketTradeEvent> subscribedTrades = service .subscribeCurrencyPairChannel(currencyPair) .flatMapIterable(poloniexWebSocketEvents -> poloniexWebSocketEvents) .filter(PoloniexWebSocketTradeEvent.class::isInstance) .map(PoloniexWebSocketTradeEvent.class::cast) .share(); return subscribedTrades.map( s -> PoloniexWebSocketAdapter.convertPoloniexWebSocketTradeEventToTrade(s, currencyPair));
983
150
1,133
<no_super_class>
knowm_XChange
XChange/xchange-stream-poloniex2/src/main/java/info/bitrich/xchangestream/poloniex2/dto/PoloniexWebSocketEventsTransaction.java
PoloniexWebSocketEventsTransaction
createEvents
class PoloniexWebSocketEventsTransaction { private Long channelId; private Long seqId; private List<PoloniexWebSocketEvent> events; @JsonCreator public PoloniexWebSocketEventsTransaction( @JsonProperty("channelId") final Long channelId, @JsonProperty("seqId") final Long seqId, @JsonProperty("jsonEvents") final List<JsonNode> jsonEvents) { this.channelId = channelId; this.seqId = seqId; this.events = createEvents(jsonEvents); } public Long getChannelId() { return channelId; } public Long getSeqId() { return seqId; } public List<PoloniexWebSocketEvent> getEvents() { return events; } private List<PoloniexWebSocketEvent> createEvents(final List<JsonNode> jsonEvents) {<FILL_FUNCTION_BODY>} private static Order.OrderType sideFromString(String side) { if (side.equals("1")) { return Order.OrderType.BID; } else if (side.equals("0")) { return Order.OrderType.ASK; } throw new IllegalArgumentException("Unknown side: " + side); } }
final ObjectMapper mapper = StreamingObjectMapperHelper.getObjectMapper(); List<PoloniexWebSocketEvent> events = new ArrayList<>(jsonEvents.size()); for (JsonNode jsonNode : jsonEvents) { String eventType = jsonNode.get(0).asText(); switch (eventType) { case "i": { OrderbookInsertEvent orderbookInsertEvent = mapper.convertValue(jsonNode.get(1), OrderbookInsertEvent.class); PoloniexWebSocketOrderbookInsertEvent insertEvent = new PoloniexWebSocketOrderbookInsertEvent(orderbookInsertEvent); events.add(insertEvent); break; } case "o": { OrderbookModifiedEvent orderbookModifiedEvent = new OrderbookModifiedEvent( jsonNode.get(1).asText(), new BigDecimal(jsonNode.get(2).asText()), new BigDecimal(jsonNode.get(3).asText())); PoloniexWebSocketOrderbookModifiedEvent insertEvent = new PoloniexWebSocketOrderbookModifiedEvent(orderbookModifiedEvent); events.add(insertEvent); break; } case "t": { /* * ["t", "<trade id>", <1 for buy 0 for sell>, "<price>", "<size>", <timestamp>] */ String tradeId = jsonNode.get(1).asText(); Order.OrderType side = sideFromString(jsonNode.get(2).asText()); BigDecimal price = new BigDecimal(jsonNode.get(3).asText()); BigDecimal size = new BigDecimal(jsonNode.get(4).asText()); int timestampSeconds = jsonNode.get(5).asInt(); TradeEvent tradeEvent = new TradeEvent(tradeId, side, price, size, timestampSeconds); PoloniexWebSocketTradeEvent insertEvent = new PoloniexWebSocketTradeEvent(tradeEvent); events.add(insertEvent); break; } default: // Ignore } } return events;
333
544
877
<no_super_class>
knowm_XChange
XChange/xchange-stream-poloniex2/src/main/java/info/bitrich/xchangestream/poloniex2/dto/PoloniexWebSocketTickerTransaction.java
PoloniexWebSocketTickerTransaction
toPoloniexTicker
class PoloniexWebSocketTickerTransaction { public String channelId; public String timestamp; public String[] ticker; public PoloniexTicker toPoloniexTicker(CurrencyPair currencyPair) {<FILL_FUNCTION_BODY>} public int getPairId() { return Integer.parseInt(ticker[0]); } }
PoloniexMarketData poloniexMarketData = new PoloniexMarketData(); BigDecimal last = new BigDecimal(ticker[1]); BigDecimal lowestAsk = new BigDecimal(ticker[2]); BigDecimal highestBid = new BigDecimal(ticker[3]); BigDecimal percentChange = new BigDecimal(ticker[4]); BigDecimal baseVolume = new BigDecimal(ticker[5]); BigDecimal quoteVolume = new BigDecimal(ticker[6]); BigDecimal isFrozen = new BigDecimal(ticker[7]); BigDecimal high24hr = new BigDecimal(ticker[8]); BigDecimal low24hr = new BigDecimal(ticker[9]); poloniexMarketData.setLast(last); poloniexMarketData.setLowestAsk(lowestAsk); poloniexMarketData.setHighestBid(highestBid); poloniexMarketData.setPercentChange(percentChange); poloniexMarketData.setBaseVolume(baseVolume); poloniexMarketData.setQuoteVolume(quoteVolume); poloniexMarketData.setHigh24hr(high24hr); poloniexMarketData.setLow24hr(low24hr); return new PoloniexTicker(poloniexMarketData, currencyPair);
98
373
471
<no_super_class>
knowm_XChange
XChange/xchange-stream-serum/src/main/java/info/bitrich/xchangestream/serum/SerumStreamingExchange.java
SerumStreamingExchange
getDefaultExchangeSpecification
class SerumStreamingExchange extends SerumExchange implements StreamingExchange { private SerumStreamingService streamingService; @Override public Completable connect(ProductSubscription... args) { final String url = Solana.valueOf( String.valueOf(getExchangeSpecification().getExchangeSpecificParametersItem("Env"))) .wsUrl(); this.streamingService = new SerumStreamingService(url); applyStreamingSpecification(getExchangeSpecification(), this.streamingService); return this.streamingService.connect(); } @Override public Completable disconnect() { final SerumStreamingService service = streamingService; streamingService = null; return service.disconnect(); } @Override public Observable<Throwable> reconnectFailure() { return streamingService.subscribeReconnectFailure(); } @Override public Observable<Object> connectionSuccess() { return streamingService.subscribeConnectionSuccess(); } @Override public Observable<ConnectionStateModel.State> connectionStateObservable() { return streamingService.subscribeConnectionState(); } @Override public boolean isAlive() { return streamingService != null && streamingService.isSocketOpen(); } @Override public StreamingMarketDataService getStreamingMarketDataService() { return null; } @Override public void useCompressedMessages(boolean compressedMessages) { streamingService.useCompressedMessages(compressedMessages); } @Override public ExchangeSpecification getDefaultExchangeSpecification() {<FILL_FUNCTION_BODY>} }
final ExchangeSpecification exchangeSpec = new ExchangeSpecification(this.getClass()); exchangeSpec.setSslUri(Solana.MAINNET.restUrl()); exchangeSpec.setHost("projectserum.com"); exchangeSpec.setPort(80); exchangeSpec.setExchangeName("Serum"); exchangeSpec.setExchangeDescription( "Serum is a decentralized cryptocurrency exchange built on Solana."); exchangeSpec.setExchangeSpecificParametersItem("Env", "MAINNET"); return exchangeSpec;
422
136
558
<methods>public non-sealed void <init>() ,public org.knowm.xchange.ExchangeSpecification getDefaultExchangeSpecification() ,public void remoteInit() <variables>protected final Logger logger
knowm_XChange
XChange/xchange-stream-serum/src/main/java/info/bitrich/xchangestream/serum/SerumSubscriptionManager.java
SerumSubscriptionManager
removedSubscription
class SerumSubscriptionManager { private static final Logger LOG = LoggerFactory.getLogger(SerumSubscriptionManager.class); /** * Map tracks in-flight requests for subscriptions * * <p>reqID -> channelName 246 -> accountSubscribe_BTC-USD */ private final Map<Integer, String> inflightSubscriptionMap = new ConcurrentHashMap<>(); /** * Map tracks request ids of a subscription to the internal channelName that is used to refer to * that channel * * <p>reqID -> subID 246 -> 11024 */ private final Map<Integer, String> requestIdToChannelName = new ConcurrentHashMap<>(); /** * Map tracks request ids of a subscription to the subscription id that Solana responds with * * <p>reqID -> subID 246 -> 11024 */ private final Map<Integer, Integer> requestIdToSubscriptionId = new ConcurrentHashMap<>(); /** * Map tracks inverse of `subscriptionIdToRequestId * * <p>subID -> reqID 11024 -> 246 */ private final Map<Integer, Integer> subscriptionIdToRequestId = new ConcurrentHashMap<>(); /** * Modifies maps to add a new subscription confirmed by Solana * * @param reqID used in subscription * @param subID assigned by Solana to track the channel */ public void newSubscription(int reqID, int subID) { final String channelName = inflightSubscriptionMap.remove(reqID); requestIdToSubscriptionId.put(reqID, subID); requestIdToChannelName.put(reqID, channelName); subscriptionIdToRequestId.put(subID, reqID); LOG.info("Channel={} has been subscribed on subscription={}", channelName, subID); } /** * Modifies maps to remove subscriptions we have unsubscribed from * * @param reqID used in subscription * @param status of unsubscription */ public void removedSubscription(int reqID, boolean status) {<FILL_FUNCTION_BODY>} public String getChannelName(int subID) { final int reqId = subscriptionIdToRequestId.get(subID); return requestIdToChannelName.get(reqId); } public int generateNewInflightRequest(final String channelName) { int reqID = Math.abs(UUID.randomUUID().hashCode()); inflightSubscriptionMap.put(reqID, channelName); return reqID; } }
final int subID1 = requestIdToSubscriptionId.remove(reqID); final String channelName1 = requestIdToChannelName.remove(reqID); subscriptionIdToRequestId.remove(subID1); LOG.info( "Channel={} has been unsubscribed for subscription={} status={}", channelName1, subID1, status);
686
99
785
<no_super_class>
knowm_XChange
XChange/xchange-therock/src/main/java/org/knowm/xchange/therock/dto/account/TheRockWithdrawal.java
TheRockWithdrawal
toString
class TheRockWithdrawal { private String currency; /** Should be null for the default method (ie. not Ripple) */ private Method withdrawMethod; private String destinationAddress; private Long destinationTag = null; private BigDecimal amount; private TheRockWithdrawal(String currency, BigDecimal amount, String destinationAddress) { this(currency, amount, destinationAddress, null, null); } private TheRockWithdrawal( String currency, BigDecimal amount, String destinationAddress, Method withdrawMethod, Long destinationTag) { this.currency = currency; this.amount = amount; this.destinationAddress = destinationAddress; this.withdrawMethod = withdrawMethod; this.destinationTag = destinationTag; } public static TheRockWithdrawal createRippleWithdrawal( String currency, BigDecimal amount, String destinationAddress, Long destinationTag) { return new TheRockWithdrawal( currency, amount, destinationAddress, Method.RIPPLE, destinationTag); } public static TheRockWithdrawal createDefaultWithdrawal( String currency, BigDecimal amount, String destinationAddress) { return new TheRockWithdrawal(currency, amount, destinationAddress); } public String getCurrency() { return currency; } public Method getWithdrawMethod() { return withdrawMethod; } public String getDestinationAddress() { return destinationAddress; } public Long getDestinationTag() { return destinationTag; } public BigDecimal getAmount() { return amount; } @Override public String toString() {<FILL_FUNCTION_BODY>} public enum Method { RIPPLE } }
return String.format( "TheRockWithdrawal{currency='%s', withdrawMethod='%s', destinationAddress='%s', amount=%s}", currency, withdrawMethod == null ? "<default>" : withdrawMethod, destinationAddress, amount);
469
75
544
<no_super_class>
knowm_XChange
XChange/xchange-therock/src/main/java/org/knowm/xchange/therock/dto/marketdata/TheRockTicker.java
TheRockTicker
toString
class TheRockTicker { @JsonDeserialize(using = CurrencyPairDeserializer.class) private CurrencyPair fundId; private Date date; private BigDecimal bid, ask, last, volume, volumeTraded, open, high, low, close; public CurrencyPair getFundId() { return fundId; } public Date getDate() { return date; } public BigDecimal getBid() { return bid; } public BigDecimal getAsk() { return ask; } public BigDecimal getLast() { return last; } public BigDecimal getVolume() { return volume; } public BigDecimal getVolumeTraded() { return volumeTraded; } public BigDecimal getOpen() { return open; } public BigDecimal getHigh() { return high; } public BigDecimal getLow() { return low; } public BigDecimal getClose() { return close; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return String.format( "TheRockTicker{currencyPair=%s, date=%s, bid=%s, ask=%s, last=%s, volume=%s, volumeTraed=%s, open=%s, high=%s, low=%s, close=%s}", fundId, date, bid, ask, last, volume, volumeTraded, open, high, low, close);
314
105
419
<no_super_class>
knowm_XChange
XChange/xchange-therock/src/main/java/org/knowm/xchange/therock/dto/marketdata/TheRockTrade.java
TheRockTrade
toString
class TheRockTrade { private final BigDecimal amount; private final Date date; private final BigDecimal price; private final long id; private final Side side; public TheRockTrade( @JsonProperty("amount") BigDecimal amount, @JsonProperty("date") Date date, @JsonProperty("price") BigDecimal price, @JsonProperty("id") long id, @JsonProperty("side") Side tradeSide) { this.amount = amount; this.date = date; this.price = price; this.id = id; this.side = tradeSide; } public BigDecimal getAmount() { return amount; } public Date getDate() { return date; } public BigDecimal getPrice() { return price; } public long getId() { return id; } public Side getSide() { return side; } @Override public String toString() {<FILL_FUNCTION_BODY>} public enum Side { sell, buy, close_long, close_short } }
return "TheRockTrade [amount=" + amount + ", date=" + date + ", price=" + price + ", id=" + id + ", side=" + side + "]";
308
70
378
<no_super_class>
knowm_XChange
XChange/xchange-therock/src/main/java/org/knowm/xchange/therock/dto/trade/TheRockOrder.java
TheRockOrder
toString
class TheRockOrder { private Long id; private TheRock.Pair fundId; private Side side; private Type type; private String status; private BigDecimal amount; private BigDecimal amountUnfilled; private BigDecimal price; private String conditionalType; private BigDecimal conditionalPrice; private String date; private String closeOn; private boolean dark; private BigDecimal leverage; private long positionId; protected TheRockOrder() {} public TheRockOrder( TheRock.Pair fundId, Side side, Type type, BigDecimal amount, BigDecimal price) { this.fundId = fundId; this.side = side; this.type = type; this.amount = amount; this.price = price; } public Long getId() { return id; } public TheRock.Pair getFundId() { return fundId; } public Side getSide() { return side; } public Type getType() { return type; } public String getStatus() { return status; } public BigDecimal getAmount() { return amount; } public BigDecimal getAmountUnfilled() { return amountUnfilled; } public BigDecimal getPrice() { return price; } public String getConditionalType() { return conditionalType; } public BigDecimal getConditionalPrice() { return conditionalPrice; } public String getDate() { return date; } public String getCloseOn() { return closeOn; } public boolean isDark() { return dark; } public BigDecimal getLeverage() { return leverage; } public long getPositionId() { return positionId; } @Override public String toString() {<FILL_FUNCTION_BODY>} public enum Side { buy, sell } public enum Type { market, limit } }
return String.format( "TheRockOrder{id=%d, side=%s, type=%s, amount=%s, amountUnfilled=%s, price=%s, fundId=%s, status='%s'}", id, side, type, amount, amountUnfilled, price, fundId, status);
560
84
644
<no_super_class>
knowm_XChange
XChange/xchange-therock/src/main/java/org/knowm/xchange/therock/service/TheRockDigest.java
TheRockDigest
digestParams
class TheRockDigest implements ParamsDigest { public static final String HMAC_SHA_512 = "HmacSHA512"; private final Mac mac; public TheRockDigest(String secretKeyStr) { try { final SecretKey secretKey = new SecretKeySpec(secretKeyStr.getBytes(), HMAC_SHA_512); mac = Mac.getInstance(HMAC_SHA_512); mac.init(secretKey); } catch (Exception e) { throw new RuntimeException("Error initializing The Rock Signer", e); } } @Override public String digestParams(RestInvocation restInvocation) {<FILL_FUNCTION_BODY>} }
final String nonce = restInvocation .getParamValue(HeaderParam.class, TheRockAuthenticated.X_TRT_NONCE) .toString(); mac.update(nonce.getBytes()); mac.update(restInvocation.getInvocationUrl().getBytes()); return String.format("%0128x", new BigInteger(1, mac.doFinal()));
190
103
293
<no_super_class>
knowm_XChange
XChange/xchange-therock/src/main/java/org/knowm/xchange/therock/service/TheRockTradeService.java
TheRockTradeService
placeMarketOrder
class TheRockTradeService extends TheRockTradeServiceRaw implements TradeService { public TheRockTradeService(Exchange exchange) { super(exchange); } @Override public String placeMarketOrder(MarketOrder order) throws IOException, ExchangeException {<FILL_FUNCTION_BODY>} @Override public String placeLimitOrder(LimitOrder order) throws IOException, ExchangeException { final TheRockOrder placedOrder = placeTheRockOrder( order.getCurrencyPair(), order.getOriginalAmount(), order.getLimitPrice(), TheRockAdapters.adaptSide(order.getType()), TheRockOrder.Type.limit); return placedOrder.getId().toString(); } /** * Not available from exchange since TheRock needs currency pair in order to return open orders */ @Override public OpenOrders getOpenOrders() throws IOException { return getOpenOrders(createOpenOrdersParams()); } @Override public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { CurrencyPair currencyPair = null; if (params instanceof OpenOrdersParamCurrencyPair) { currencyPair = ((OpenOrdersParamCurrencyPair) params).getCurrencyPair(); } if (currencyPair == null) { throw new ExchangeException("CurrencyPair parameter must not be null."); } return TheRockAdapters.adaptOrders(getTheRockOrders(currencyPair)); } /** Not available from exchange since TheRock needs currency pair in order to cancel an order */ @Override public boolean cancelOrder(String orderId) throws IOException { CurrencyPair cp = (CurrencyPair) exchange .getExchangeSpecification() .getExchangeSpecificParameters() .get(TheRockExchange.CURRENCY_PAIR); if (cp == null) { throw new ExchangeException("Provide TheRockCancelOrderParams with orderId and currencyPair"); } return cancelOrder(cp, orderId); } @Override public boolean cancelOrder(CancelOrderParams params) throws IOException { if (!(params instanceof CancelOrderByIdParams)) { return false; } CancelOrderByIdParams paramId = (CancelOrderByIdParams) params; CurrencyPair currencyPair; if (params instanceof CancelOrderByCurrencyPair) { CancelOrderByCurrencyPair paramCurrencyPair = (CancelOrderByCurrencyPair) params; currencyPair = paramCurrencyPair.getCurrencyPair(); } else { currencyPair = null; } return cancelOrder(currencyPair, paramId.getOrderId()); } @Override public Class[] getRequiredCancelOrderParamClasses() { return new Class[] {CancelOrderByIdParams.class, CancelOrderByCurrencyPair.class}; } private boolean cancelOrder(CurrencyPair currencyPair, String orderId) throws TheRockException, NumberFormatException, IOException { TheRockOrder cancelledOrder = cancelTheRockOrder(currencyPair, Long.parseLong(orderId)); return "deleted".equals(cancelledOrder.getStatus()); } /** * Not available from exchange since TheRock needs currency pair in order to return/show the order */ @Override public Collection<Order> getOrder(String... orderIds) throws IOException { throw new NotAvailableFromExchangeException(); } @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { if (!(params instanceof TradeHistoryParamCurrencyPair)) { throw new ExchangeException("TheRock API recquires " + TradeHistoryParamCurrencyPair.class); } TradeHistoryParamCurrencyPair pairParams = (TradeHistoryParamCurrencyPair) params; Long sinceTradeId = null; // get all trades starting from a specific trade_id if (params instanceof TradeHistoryParamsIdSpan) { TradeHistoryParamsIdSpan trId = (TradeHistoryParamsIdSpan) params; try { sinceTradeId = Long.valueOf(trId.getStartId()); } catch (Throwable ignored) { } } Date after = null; Date before = null; if (params instanceof TradeHistoryParamsTimeSpan) { TradeHistoryParamsTimeSpan time = (TradeHistoryParamsTimeSpan) params; after = time.getStartTime(); before = time.getEndTime(); } int pageLength = 200; int page = 0; if (params instanceof TradeHistoryParamPaging) { TradeHistoryParamPaging tradeHistoryParamPaging = (TradeHistoryParamPaging) params; pageLength = tradeHistoryParamPaging.getPageLength(); page = tradeHistoryParamPaging.getPageNumber(); } return TheRockAdapters.adaptUserTrades( getTheRockUserTrades( pairParams.getCurrencyPair(), sinceTradeId, after, before, pageLength, page), pairParams.getCurrencyPair()); } @Override public OpenOrdersParams createOpenOrdersParams() { return new TheRockOpenOrdersParams(); } }
final TheRockOrder placedOrder = placeTheRockOrder( order.getCurrencyPair(), order.getOriginalAmount(), BigDecimal.ZERO, TheRockAdapters.adaptSide(order.getType()), TheRockOrder.Type.market); return placedOrder.getId().toString();
1,315
86
1,401
<methods>public void <init>(org.knowm.xchange.Exchange) ,public org.knowm.xchange.therock.dto.trade.TheRockOrder cancelTheRockOrder(org.knowm.xchange.currency.CurrencyPair, java.lang.Long) throws java.io.IOException,public org.knowm.xchange.therock.dto.trade.TheRockOrders getTheRockOrders(org.knowm.xchange.currency.CurrencyPair) throws java.io.IOException,public org.knowm.xchange.therock.dto.trade.TheRockOrders getTheRockOrders(org.knowm.xchange.currency.CurrencyPair, java.util.Date, java.util.Date, java.lang.String, org.knowm.xchange.therock.dto.trade.TheRockOrder.Side, java.lang.Long, int) throws java.io.IOException,public org.knowm.xchange.therock.dto.trade.TheRockTransaction[] getTheRockTransactions(java.lang.String, java.util.Date, java.util.Date) throws java.io.IOException,public org.knowm.xchange.therock.dto.trade.TheRockUserTrades getTheRockUserTrades(org.knowm.xchange.currency.CurrencyPair, java.lang.Long, java.util.Date, java.util.Date, int, int) throws java.io.IOException,public org.knowm.xchange.therock.dto.trade.TheRockOrder placeTheRockOrder(org.knowm.xchange.currency.CurrencyPair, java.math.BigDecimal, java.math.BigDecimal, org.knowm.xchange.therock.dto.trade.TheRockOrder.Side, org.knowm.xchange.therock.dto.trade.TheRockOrder.Type) throws org.knowm.xchange.exceptions.ExchangeException, java.io.IOException,public org.knowm.xchange.therock.dto.trade.TheRockOrder placeTheRockOrder(org.knowm.xchange.currency.CurrencyPair, org.knowm.xchange.therock.dto.trade.TheRockOrder) throws org.knowm.xchange.exceptions.ExchangeException, java.io.IOException,public org.knowm.xchange.therock.dto.trade.TheRockOrder showTheRockOrder(org.knowm.xchange.currency.CurrencyPair, java.lang.Long) throws java.io.IOException<variables>private final non-sealed org.knowm.xchange.therock.service.TheRockDigest signatureCreator,private final non-sealed org.knowm.xchange.therock.TheRockAuthenticated theRockAuthenticated
knowm_XChange
XChange/xchange-therock/src/main/java/org/knowm/xchange/therock/service/TheRockTradeServiceRaw.java
TheRockTradeServiceRaw
placeTheRockOrder
class TheRockTradeServiceRaw extends TheRockBaseService { private final TheRockAuthenticated theRockAuthenticated; private final TheRockDigest signatureCreator; public TheRockTradeServiceRaw(Exchange exchange) { super(exchange); final ExchangeSpecification spec = exchange.getExchangeSpecification(); this.theRockAuthenticated = ExchangeRestProxyBuilder.forInterface(TheRockAuthenticated.class, spec).build(); this.signatureCreator = new TheRockDigest(spec.getSecretKey()); } public TheRockOrder placeTheRockOrder( CurrencyPair currencyPair, BigDecimal amount, BigDecimal price, TheRockOrder.Side side, TheRockOrder.Type type) throws ExchangeException, IOException { return placeTheRockOrder( currencyPair, new TheRockOrder(new TheRock.Pair(currencyPair), side, type, amount, price)); } public TheRockOrder placeTheRockOrder(CurrencyPair currencyPair, TheRockOrder order) throws ExchangeException, IOException {<FILL_FUNCTION_BODY>} public TheRockOrder cancelTheRockOrder(CurrencyPair currencyPair, Long orderId) throws TheRockException, IOException { try { return theRockAuthenticated.cancelOrder( new TheRock.Pair(currencyPair), orderId, exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory()); } catch (TheRockException e) { throw new ExchangeException(e); } } public TheRockOrders getTheRockOrders(CurrencyPair currencyPair) throws TheRockException, IOException { try { return theRockAuthenticated.orders( new TheRock.Pair(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory()); } catch (TheRockException e) { throw new ExchangeException(e); } } public TheRockOrders getTheRockOrders( CurrencyPair currencyPair, Date after, Date before, String status, TheRockOrder.Side side, Long positionId, int page) throws TheRockException, IOException { try { return theRockAuthenticated.orders( new TheRock.Pair(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), after, before, status, side, positionId, page); } catch (TheRockException e) { throw new ExchangeException(e); } } public TheRockOrder showTheRockOrder(CurrencyPair currencyPair, Long orderId) throws TheRockException, IOException { try { return theRockAuthenticated.showOrder( new TheRock.Pair(currencyPair), orderId, exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory()); } catch (TheRockException e) { throw new ExchangeException(e); } } public TheRockUserTrades getTheRockUserTrades( CurrencyPair currencyPair, Long sinceTradeId, Date after, Date before, int pageSize, int page) throws IOException { try { return theRockAuthenticated.trades( new TheRock.Pair(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), sinceTradeId, after, before, pageSize, page); } catch (Throwable e) { throw new ExchangeException(e); } } public TheRockTransaction[] getTheRockTransactions(String type, Date after, Date before) throws IOException { try { return theRockAuthenticated .transactions( exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), type, after, before, null, 0) .getTransactions(); } catch (Throwable e) { throw new ExchangeException(e); } } }
try { return theRockAuthenticated.placeOrder( new TheRock.Pair(currencyPair), exchange.getExchangeSpecification().getApiKey(), signatureCreator, exchange.getNonceFactory(), order); } catch (TheRockException e) { throw new ExchangeException(e); }
1,129
89
1,218
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>
knowm_XChange
XChange/xchange-tradeogre/src/main/java/org/knowm/xchange/tradeogre/service/TradeOgreAccountServiceRaw.java
TradeOgreAccountServiceRaw
getTradeOgreBalances
class TradeOgreAccountServiceRaw extends TradeOgreBaseService { protected TradeOgreAccountServiceRaw(TradeOgreExchange exchange) { super(exchange); } public List<Balance> getTradeOgreBalances() throws IOException {<FILL_FUNCTION_BODY>} public TradeOgreBalance getTradeOgreBalance(Currency currency) throws IOException { return tradeOgre.getBalance(base64UserPwd, currency.toString().toUpperCase()); } }
return tradeOgre.getBalances(base64UserPwd).getBalances().entrySet().stream() .map( entry -> new Balance.Builder() .total(entry.getValue()) .currency(new Currency(entry.getKey())) .build()) .collect(Collectors.toList());
133
88
221
<methods><variables>protected final non-sealed java.lang.String base64UserPwd,protected final non-sealed org.knowm.xchange.tradeogre.TradeOgreAuthenticated tradeOgre
knowm_XChange
XChange/xchange-tradeogre/src/main/java/org/knowm/xchange/tradeogre/service/TradeOgreBaseService.java
TradeOgreBaseService
calculateBase64UserPwd
class TradeOgreBaseService extends BaseExchangeService<TradeOgreExchange> implements BaseService { protected final TradeOgreAuthenticated tradeOgre; protected final String base64UserPwd; protected TradeOgreBaseService(TradeOgreExchange exchange) { super(exchange); String apiKey = exchange.getExchangeSpecification().getApiKey(); String secretKey = exchange.getExchangeSpecification().getSecretKey(); base64UserPwd = calculateBase64UserPwd(exchange); ClientConfigCustomizer clientConfigCustomizer = config -> { ClientConfigUtil.addBasicAuthCredentials(config, apiKey, secretKey); config.setJacksonObjectMapperFactory( new DefaultJacksonObjectMapperFactory() { @Override public void configureObjectMapper(ObjectMapper objectMapper) { super.configureObjectMapper(objectMapper); objectMapper.configure( DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true); } }); }; tradeOgre = ExchangeRestProxyBuilder.forInterface( TradeOgreAuthenticated.class, exchange.getExchangeSpecification()) .clientConfigCustomizer(clientConfigCustomizer) .build(); } private String calculateBase64UserPwd(TradeOgreExchange exchange) {<FILL_FUNCTION_BODY>} }
String userPwd = exchange.getExchangeSpecification().getApiKey() + ":" + exchange.getExchangeSpecification().getSecretKey(); return "Basic " + new String(Base64.getEncoder().encode(userPwd.getBytes()));
361
71
432
<methods>public void verifyOrder(org.knowm.xchange.dto.trade.LimitOrder) ,public void verifyOrder(org.knowm.xchange.dto.trade.MarketOrder) <variables>protected final non-sealed org.knowm.xchange.tradeogre.TradeOgreExchange exchange
knowm_XChange
XChange/xchange-tradeogre/src/main/java/org/knowm/xchange/tradeogre/service/TradeOgreMarketDataServiceRaw.java
TradeOgreMarketDataServiceRaw
getTradeOgreTickers
class TradeOgreMarketDataServiceRaw extends TradeOgreBaseService { /** * Constructor * * @param exchange */ public TradeOgreMarketDataServiceRaw(TradeOgreExchange exchange) { super(exchange); } public TradeOgreTicker getTradeOgreTicker(CurrencyPair market) throws IOException { return tradeOgre.getTicker(TradeOgreAdapters.adaptCurrencyPair(market)); } public Stream<Ticker> getTradeOgreTickers() throws IOException {<FILL_FUNCTION_BODY>} public TradeOgreOrderBook getTradeOgreOrderBook(CurrencyPair currencyPair) throws IOException { String market = TradeOgreAdapters.adaptCurrencyPair(currencyPair); return tradeOgre.getOrderBook(market); } }
return tradeOgre.getTickers().stream() .map(Map::entrySet) .flatMap(Collection::stream) .map( entry -> TradeOgreAdapters.adaptTicker( TradeOgreAdapters.adaptTradeOgreCurrencyPair(entry.getKey()), entry.getValue()));
220
89
309
<methods><variables>protected final non-sealed java.lang.String base64UserPwd,protected final non-sealed org.knowm.xchange.tradeogre.TradeOgreAuthenticated tradeOgre
knowm_XChange
XChange/xchange-truefx/src/main/java/org/knowm/xchange/truefx/dto/marketdata/TrueFxTicker.java
TrueFxTickerDeserializer
deserialize
class TrueFxTickerDeserializer extends JsonDeserializer<TrueFxTicker> { private final CsvMapper mapper = new CsvMapper(); private final CsvSchema schema = mapper.schemaFor(TrueFxTicker.class); @Override public TrueFxTicker deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {<FILL_FUNCTION_BODY>} }
ArrayNode array = mapper.readerFor(TrueFxTicker.class).with(schema).readTree(parser); String pair = array.get(0).asText(); long timestamp = array.get(1).asLong(); BigDecimal bid = new BigDecimal(array.get(2).asText()); BigDecimal bidBP = new BigDecimal(array.get(3).asText()); BigDecimal ask = new BigDecimal(array.get(4).asText()); BigDecimal askBP = new BigDecimal(array.get(5).asText()); BigDecimal low = new BigDecimal(array.get(6).asText()); BigDecimal high = new BigDecimal(array.get(7).asText()); BigDecimal open = new BigDecimal(array.get(8).asText()); return new TrueFxTicker(pair, timestamp, bid, bidBP, ask, askBP, low, high, open);
113
241
354
<no_super_class>
knowm_XChange
XChange/xchange-vaultoro/src/main/java/org/knowm/xchange/vaultoro/VaultoroUtils.java
VaultoroUtils
parseDate
class VaultoroUtils { private static DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); public static Date parseDate(String dateString) {<FILL_FUNCTION_BODY>} }
// 2015-04-13T07:56:36.185Z format.setTimeZone(TimeZone.getTimeZone("GMT")); try { return format.parse(dateString); } catch (ParseException e) { return null; }
70
84
154
<no_super_class>
knowm_XChange
XChange/xchange-vaultoro/src/main/java/org/knowm/xchange/vaultoro/service/VaultoroDigest.java
VaultoroDigest
digestParams
class VaultoroDigest extends BaseParamsDigest { private VaultoroDigest(String secretKeyBase64) { super(secretKeyBase64, HMAC_SHA_256); } public static VaultoroDigest createInstance(String secretKeyBase64) { return secretKeyBase64 == null ? null : new VaultoroDigest(secretKeyBase64); } @Override public String digestParams(RestInvocation restInvocation) {<FILL_FUNCTION_BODY>} }
String invocationUrl = restInvocation.getInvocationUrl(); Mac mac = getMac(); mac.update(invocationUrl.getBytes()); return String.format("%040x", new BigInteger(1, mac.doFinal()));
140
65
205
<methods>public javax.crypto.Mac getMac() <variables>public static final java.lang.String HMAC_MD5,public static final java.lang.String HMAC_SHA_1,public static final java.lang.String HMAC_SHA_256,public static final java.lang.String HMAC_SHA_384,public static final java.lang.String HMAC_SHA_512,private final non-sealed javax.crypto.Mac mac
knowm_XChange
XChange/xchange-vaultoro/src/main/java/org/knowm/xchange/vaultoro/service/VaultoroMarketDataService.java
VaultoroMarketDataService
getOrderBook
class VaultoroMarketDataService extends VaultoroMarketDataServiceRaw implements MarketDataService { /** * Constructor * * @param exchange */ public VaultoroMarketDataService(Exchange exchange) { super(exchange); } @Override public List<CurrencyPair> getExchangeSymbols() throws IOException { return super.getExchangeSymbols(); } @Override public OrderBook getOrderBook(CurrencyPair arg0, Object... arg1) throws IOException {<FILL_FUNCTION_BODY>} @Override public Ticker getTicker(CurrencyPair arg0, Object... arg1) throws IOException { BigDecimal latest = super.getLast(arg0); return VaultoroAdapters.adaptVaultoroLatest(latest); } @Override public Trades getTrades(CurrencyPair arg0, Object... arg1) throws IOException { List<VaultoroTrade> vaultoroTrades = super.getVaultoroTrades(arg0); return VaultoroAdapters.adaptVaultoroTransactions(vaultoroTrades, arg0); } }
List<VaultoroOrderBook> vaultoroOrderBooks = super.getVaultoroOrderBook(arg0); List<VaultoroOrder> asks = new ArrayList<>(); List<VaultoroOrder> bids = new ArrayList<>(); for (VaultoroOrderBook vaultoroOrderBook : vaultoroOrderBooks) { asks.addAll(vaultoroOrderBook.getSells()); bids.addAll(vaultoroOrderBook.getBuys()); } VaultoroOrderBook vaultoroOrderBook = new VaultoroOrderBook(); vaultoroOrderBook.setB(bids); vaultoroOrderBook.setS(asks); return VaultoroAdapters.adaptVaultoroOrderBook(vaultoroOrderBook, arg0);
304
196
500
<methods>public void <init>(org.knowm.xchange.Exchange) ,public List<org.knowm.xchange.currency.CurrencyPair> getExchangeSymbols() throws java.io.IOException,public java.math.BigDecimal getLast(org.knowm.xchange.currency.CurrencyPair) throws org.knowm.xchange.vaultoro.VaultoroException, java.io.IOException,public List<org.knowm.xchange.vaultoro.dto.marketdata.VaultoroOrderBook> getVaultoroOrderBook(org.knowm.xchange.currency.CurrencyPair) throws org.knowm.xchange.vaultoro.VaultoroException, java.io.IOException,public List<org.knowm.xchange.vaultoro.dto.marketdata.VaultoroTrade> getVaultoroTrades(org.knowm.xchange.currency.CurrencyPair) throws org.knowm.xchange.vaultoro.VaultoroException, java.io.IOException<variables>
knowm_XChange
XChange/xchange-vaultoro/src/main/java/org/knowm/xchange/vaultoro/service/VaultoroTradeServiceRaw.java
VaultoroTradeServiceRaw
getVaultoroOrders
class VaultoroTradeServiceRaw extends VaultoroBaseService { /** * Constructor * * @param exchange */ public VaultoroTradeServiceRaw(Exchange exchange) { super(exchange); } public VaultoroCancelOrderResponse cancelVaultoroOrder(String orderId) throws IOException { try { VaultoroCancelOrderResponse response = vaultoro.cancel(orderId, exchange.getNonceFactory(), apiKey, signatureCreator); return response; } catch (VaultoroException e) { throw new ExchangeException(e); } } public Map<String, List<VaultoroOpenOrder>> getVaultoroOrders() throws IOException {<FILL_FUNCTION_BODY>} public VaultoroNewOrderResponse placeLimitOrder( CurrencyPair currencyPair, OrderType orderType, BigDecimal amount, BigDecimal price) throws IOException { return placeOrder("limit", currencyPair, orderType, amount, price); } public VaultoroNewOrderResponse placeMarketOrder( CurrencyPair currencyPair, OrderType orderType, BigDecimal amount) throws IOException { return placeOrder("market", currencyPair, orderType, amount, null); } private VaultoroNewOrderResponse placeOrder( String type, CurrencyPair currencyPair, OrderType orderType, BigDecimal amount, BigDecimal price) throws IOException { String baseSymbol = currencyPair.base.getCurrencyCode().toLowerCase(); if (orderType == OrderType.BID) { if (price == null) { VaultoroMarketDataService ds = new VaultoroMarketDataService(exchange); OrderBook orderBook = ds.getOrderBook(currencyPair); List<LimitOrder> asks = orderBook.getAsks(); if (!asks.isEmpty()) { LimitOrder lowestAsk = orderBook.getAsks().get(0); price = lowestAsk.getLimitPrice(); } else { price = ds.getLast(currencyPair); } } else { amount = price.multiply(amount, new MathContext(8, RoundingMode.HALF_DOWN)); } try { return vaultoro.buy( baseSymbol, type, exchange.getNonceFactory(), apiKey, amount, price, signatureCreator); } catch (VaultoroException e) { throw new ExchangeException(e); } } else { try { return vaultoro.sell( baseSymbol, type, exchange.getNonceFactory(), apiKey, amount, price, signatureCreator); } catch (VaultoroException e) { throw new ExchangeException(e); } } } }
try { VaultoroOrdersResponse response = vaultoro.getOrders(exchange.getNonceFactory(), apiKey, signatureCreator); return response.getData().get(0); } catch (VaultoroException e) { throw new ExchangeException(e); }
708
78
786
<methods>public void <init>(org.knowm.xchange.Exchange) <variables>protected final non-sealed java.lang.String apiKey,protected final non-sealed ParamsDigest signatureCreator,protected final non-sealed org.knowm.xchange.vaultoro.VaultoroAuthenticated vaultoro
knowm_XChange
XChange/xchange-yobit/src/main/java/org/knowm/xchange/yobit/dto/marketdata/YoBitInfo.java
YoBitInfo
toString
class YoBitInfo { private Long server_time; private YoBitPairs pairs; public YoBitInfo( @JsonProperty("server_time") Long server_time, @JsonProperty("pairs") YoBitPairs pairs) { super(); this.server_time = server_time; this.pairs = pairs; } public Long getServer_time() { return server_time; } public YoBitPairs getPairs() { return pairs; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "YoBitInfo [server_time=" + server_time + ", pairs=" + pairs + "]";
162
32
194
<no_super_class>
knowm_XChange
XChange/xchange-yobit/src/main/java/org/knowm/xchange/yobit/dto/marketdata/YoBitPair.java
YoBitPairDeserializer
deserializeFromNode
class YoBitPairDeserializer extends JsonDeserializer<YoBitPair> { private static BigDecimal getNumberIfPresent(JsonNode numberNode) { final String numberString = numberNode.asText(); return numberString.isEmpty() ? null : new BigDecimal(numberString); } public static YoBitPair deserializeFromNode(JsonNode tickerNode) {<FILL_FUNCTION_BODY>} @Override public YoBitPair deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectCodec oc = jp.getCodec(); final JsonNode tickerNode = oc.readTree(jp); return deserializeFromNode(tickerNode); } }
final Integer decimal_places = tickerNode.path("decimal_places").asInt(); final BigDecimal min_price = getNumberIfPresent(tickerNode.path("min_price")); final BigDecimal max_price = getNumberIfPresent(tickerNode.path("max_price")); final BigDecimal min_amount = getNumberIfPresent(tickerNode.path("min_amount")); final BigDecimal min_total = getNumberIfPresent(tickerNode.path("min_total")); final Integer hidden = tickerNode.path("hidden").asInt(); final BigDecimal fee = getNumberIfPresent(tickerNode.path("fee")); final BigDecimal fee_buyer = getNumberIfPresent(tickerNode.path("fee_buyer")); final BigDecimal fee_seller = getNumberIfPresent(tickerNode.path("fee_seller")); return new YoBitPair( decimal_places, min_price, max_price, min_amount, min_total, hidden, fee, fee_buyer, fee_seller);
201
283
484
<no_super_class>
knowm_XChange
XChange/xchange-yobit/src/main/java/org/knowm/xchange/yobit/dto/marketdata/YoBitPairs.java
YoBitPricesDeserializer
deserialize
class YoBitPricesDeserializer extends JsonDeserializer<YoBitPairs> { @Override public YoBitPairs deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {<FILL_FUNCTION_BODY>} }
Map<CurrencyPair, YoBitPair> priceMap = new HashMap<>(); ObjectCodec oc = jp.getCodec(); JsonNode node = oc.readTree(jp); if (node.isObject()) { Iterator<Entry<String, JsonNode>> priceEntryIter = node.fields(); while (priceEntryIter.hasNext()) { Entry<String, JsonNode> priceEntryNode = priceEntryIter.next(); String pairString = priceEntryNode.getKey(); CurrencyPair pair = YoBitAdapters.adaptCurrencyPair(pairString); JsonNode priceNode = priceEntryNode.getValue(); YoBitPair price = YoBitPairDeserializer.deserializeFromNode(priceNode); priceMap.put(pair, price); } } return new YoBitPairs(priceMap);
77
221
298
<no_super_class>
knowm_XChange
XChange/xchange-yobit/src/main/java/org/knowm/xchange/yobit/dto/marketdata/YoBitTicker.java
YoBitTicker
toString
class YoBitTicker { private final BigDecimal high; private final BigDecimal low; private final BigDecimal avg; private final BigDecimal vol; private final BigDecimal volCur; private final BigDecimal last; private final BigDecimal buy; private final BigDecimal sell; private final long updated; public YoBitTicker( @JsonProperty("high") BigDecimal high, @JsonProperty("low") BigDecimal low, @JsonProperty("avg") BigDecimal avg, @JsonProperty("vol") BigDecimal vol, @JsonProperty("vol_cur") BigDecimal volCur, @JsonProperty("last") BigDecimal last, @JsonProperty("buy") BigDecimal buy, @JsonProperty("sell") BigDecimal sell, @JsonProperty("updated") long updated) { this.high = high; this.low = low; this.avg = avg; this.vol = vol; this.volCur = volCur; this.last = last; this.buy = buy; this.sell = sell; this.updated = updated; } public BigDecimal getBuy() { return buy; } public BigDecimal getHigh() { return high; } public BigDecimal getLow() { return low; } public BigDecimal getAvg() { return avg; } public BigDecimal getVol() { return vol; } public BigDecimal getVolCur() { return volCur; } public BigDecimal getLast() { return last; } public BigDecimal getSell() { return sell; } public long getUpdated() { return updated; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "YoBitTickker [buy=" + buy + ", high=" + high + ", low=" + low + ", avg=" + avg + ", vol=" + vol + ", volCur=" + volCur + ", last=" + last + ", sell=" + sell + ", updated=" + updated + "]";
504
120
624
<no_super_class>
knowm_XChange
XChange/xchange-yobit/src/main/java/org/knowm/xchange/yobit/dto/marketdata/YoBitTickersDeserializer.java
YoBitTickersDeserializer
deserialize
class YoBitTickersDeserializer extends JsonDeserializer<YoBitTickersReturn> { @Override public YoBitTickersReturn deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {<FILL_FUNCTION_BODY>} }
JsonNode node = p.readValueAsTree(); Map<String, YoBitTicker> tickers = new HashMap<>(); if (node.isObject()) { Iterator<Map.Entry<String, JsonNode>> priceEntryIter = node.fields(); while (priceEntryIter.hasNext()) { Map.Entry<String, JsonNode> priceEntryNode = priceEntryIter.next(); JsonNode jsonNode = priceEntryNode.getValue(); ObjectReader jsonObjectReader = new ObjectMapper().readerFor(YoBitTicker.class); YoBitTicker ticker = jsonObjectReader.readValue(jsonNode); String ccy = priceEntryNode.getKey(); tickers.put(ccy, ticker); } } return new YoBitTickersReturn(tickers);
75
211
286
<no_super_class>
knowm_XChange
XChange/xchange-yobit/src/main/java/org/knowm/xchange/yobit/service/YoBitMarketDataServiceRaw.java
YoBitMarketDataServiceRaw
getPairListAsString
class YoBitMarketDataServiceRaw extends YoBitBaseService<YoBit> { // Not specified in the API doc but real private static final int MAX_PAIR_LIST_SIZE = 512; protected YoBitMarketDataServiceRaw(Exchange exchange) { super(YoBit.class, exchange); } public YoBitInfo getProducts() throws IOException { return service.getProducts(); } public YoBitTickersReturn getYoBitTickers(Iterable<CurrencyPair> currencyPairs) throws IOException { return service.getTickers(getPairListAsString(currencyPairs)); } public YoBitOrderBooksReturn getOrderBooks(Iterable<CurrencyPair> currencyPairs, Integer limit) throws IOException { return service.getOrderBooks(getPairListAsString(currencyPairs), limit); } public YoBitTrades getPublicTrades(Iterable<CurrencyPair> currencyPairs) throws IOException { return service.getTrades(getPairListAsString(currencyPairs)); } private String getPairListAsString(Iterable<CurrencyPair> currencyPairs) {<FILL_FUNCTION_BODY>} }
String markets = YoBitAdapters.adaptCcyPairsToUrlFormat(currencyPairs); if (markets.length() > MAX_PAIR_LIST_SIZE) { throw new ExchangeException( "URL too long: YoBit allows a maximum of " + MAX_PAIR_LIST_SIZE + " characters for total pair lists size. Provided string is " + markets.length() + " characters long."); } return markets;
318
119
437
<methods><variables>protected final non-sealed org.knowm.xchange.yobit.YoBit service,protected final non-sealed org.knowm.xchange.yobit.YoBitDigest signatureCreator
knowm_XChange
XChange/xchange-yobit/src/main/java/org/knowm/xchange/yobit/service/YoBitTradeServiceRaw.java
YoBitTradeServiceRaw
trade
class YoBitTradeServiceRaw extends YoBitBaseService<YoBit> implements TradeService { public YoBitTradeServiceRaw(YoBitExchange exchange) { super(YoBit.class, exchange); } @Override public OpenOrders getOpenOrders() throws IOException { throw new NotYetImplementedForExchangeException("Need to specify OpenOrdersParams"); } public BaseYoBitResponse activeOrders(OpenOrdersParamCurrencyPair params) throws IOException { CurrencyPair currencyPair = params.getCurrencyPair(); String market = YoBitAdapters.adaptCcyPairToUrlFormat(currencyPair); BaseYoBitResponse response = service.activeOrders( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "ActiveOrders", exchange.getNonceFactory(), market); if (!response.success) throw new ExchangeException("failed to get open orders"); return response; } public BaseYoBitResponse trade(LimitOrder limitOrder) throws IOException {<FILL_FUNCTION_BODY>} public BaseYoBitResponse cancelOrder(CancelOrderByIdParams params) throws IOException { return cancelOrderById(params.getOrderId()); } protected BaseYoBitResponse cancelOrderById(String orderId) throws IOException { return service.cancelOrder( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "CancelOrder", exchange.getNonceFactory(), Long.valueOf(orderId)); } public BaseYoBitResponse tradeHistory( Integer count, Long offset, String market, Long fromTransactionId, Long endTransactionId, String order, Long fromTimestamp, Long toTimestamp) throws IOException { return service.tradeHistory( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "TradeHistory", exchange.getNonceFactory(), offset, count, fromTransactionId, endTransactionId, order, fromTimestamp, toTimestamp, market); } public Collection<Order> getOrderImpl(String... orderIds) throws IOException { List<Order> orders = new ArrayList<>(); for (String orderId : orderIds) { Long id = Long.valueOf(orderId); BaseYoBitResponse response = service.orderInfo( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "OrderInfo", exchange.getNonceFactory(), id); if (response.returnData != null) { Map map = (Map) response.returnData.get(orderId); Order order = YoBitAdapters.adaptOrder(orderId, map); orders.add(order); } } return orders; } @Override public Collection<Order> getOrder(OrderQueryParams... orderQueryParams) throws IOException { return getOrderImpl(TradeService.toOrderIds(orderQueryParams)); } }
String market = YoBitAdapters.adaptCcyPairToUrlFormat(limitOrder.getCurrencyPair()); String direction = limitOrder.getType().equals(Order.OrderType.BID) ? "buy" : "sell"; BaseYoBitResponse response = service.trade( exchange.getExchangeSpecification().getApiKey(), signatureCreator, "Trade", exchange.getNonceFactory(), market, direction, limitOrder.getLimitPrice(), limitOrder.getOriginalAmount()); if (!response.success) throw new ExchangeException("failed to get place order"); return response;
791
167
958
<methods><variables>protected final non-sealed org.knowm.xchange.yobit.YoBit service,protected final non-sealed org.knowm.xchange.yobit.YoBitDigest signatureCreator
knowm_XChange
XChange/xchange-zaif/src/main/java/org/knowm/xchange/zaif/ZaifAdapters.java
ZaifAdapters
toLimitOrderList
class ZaifAdapters { private static Logger logger = LoggerFactory.getLogger(ZaifAdapters.class); public ZaifAdapters() {} public static OrderBook adaptOrderBook(ZaifFullBook book, CurrencyPair currencyPair) { List<LimitOrder> asks = toLimitOrderList(book.getAsks(), Order.OrderType.ASK, currencyPair); List<LimitOrder> bids = toLimitOrderList(book.getBids(), Order.OrderType.BID, currencyPair); return new OrderBook(null, asks, bids); } private static List<LimitOrder> toLimitOrderList( ZaifFullBookTier[] levels, Order.OrderType orderType, CurrencyPair currencyPair) {<FILL_FUNCTION_BODY>} public static ExchangeMetaData adaptMetadata(List<ZaifMarket> markets) { Map<Instrument, InstrumentMetaData> pairMeta = new HashMap<>(); for (ZaifMarket zaifMarket : markets) { pairMeta.put(zaifMarket.getName(), new InstrumentMetaData.Builder().build()); } return new ExchangeMetaData(pairMeta, null, null, null, null); } }
List<LimitOrder> allLevels = new ArrayList<>(); if (levels != null) { for (ZaifFullBookTier tier : levels) { allLevels.add( new LimitOrder(orderType, tier.getVolume(), currencyPair, "", null, tier.getPrice())); } } return allLevels;
315
98
413
<no_super_class>
knowm_XChange
XChange/xchange-zaif/src/main/java/org/knowm/xchange/zaif/dto/marketdata/ZaifFullBookTier.java
ZaifFullBookTier
toString
class ZaifFullBookTier { private final BigDecimal price; private final BigDecimal volume; public ZaifFullBookTier(Object[] tier) { if (tier != null && tier.length == 2) { this.price = new BigDecimal(tier[0].toString()); this.volume = new BigDecimal(tier[1].toString()); } else throw new ZaifException("Invalid Tier"); } public BigDecimal getPrice() { return this.price; } public BigDecimal getVolume() { return this.volume; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ZaifFullBookTier [price=" + price + ", volume=" + volume + "]";
188
31
219
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/GlobalSystemConfigLoader.java
GlobalSystemConfigLoader
loadSystemConfig
class GlobalSystemConfigLoader { /** * 只读,无需同步 */ private static final Map<String, String> RMIConfig = new HashMap<>(); private static final List<Entry<String, Integer>> addresses = new ArrayList<>(); private static final List<Predicate<String>> filters; static { filters = new ArrayList<>(); filters.add(x -> x == null || x.trim().contains("##") || x.length() == 0); filters.add(x -> { if (x.contains("master_req_ip")) { String[] kv = x.split("=")[1].split(":"); String address = kv[0].trim(); Integer port = Integer.parseInt(kv[1].trim()); addresses.add(new Entry<>(address, port)); return true; } else return false; }); } /** * 避免多线程情况重复加载 */ private static volatile boolean loaded = false; public static void loadConfig() { if(loaded) return; loaded = true; loadSystemConfig(); loadRMIConfig(); } public static Entry<String, Integer> getAddress(int index) { if(index < 0 || index >= addresses.size()) throw new ArrayIndexOutOfBoundsException(); return addresses.get(index); } public static int getAddressSize() { return addresses.size(); } /** * 加载系统配置 */ private static void loadSystemConfig() {<FILL_FUNCTION_BODY>} /** * 加载RMI配置 */ private static void loadRMIConfig() { File file = FileLoader.loadFile("config.rmi"); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { final String[] text = new String[1]; while ((text[0] = reader.readLine()) != null) { if (filters.stream().noneMatch(x -> x.test(text[0]))) { String[] kv = text[0].split("="); String key = kv[0]; String value = kv[1]; RMIConfig.put(key.trim(), value.trim()); } } } catch (IOException e) { System.out.println("GlobalSystemConfigLoader -> 配置文件 -- config.rmi 格式错误!"); } } /** * * @param key RMI 属性名字 * @return RMI 对应配置 */ public static String getRMIConfig(String key) { return RMIConfig.get(key); } }
File file = FileLoader.loadFile("config.sys"); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { final String[] text = new String[1]; while ((text[0] = reader.readLine()) != null) { if (filters.stream().noneMatch(x -> x.test(text[0]))) { int index = text[0].indexOf("="); String key = text[0].substring(0, index); String value = text[0].substring(index + 1); System.setProperty(key.trim(), value.trim()); } } } catch (IOException e) { System.out.println("GlobalSystemConfigLoader -> 配置文件 -- config.sys 格式错误!"); }
702
202
904
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/acceptor/AbstractAcceptor.java
AbstractAcceptor
accept
class AbstractAcceptor<T> extends AbstractRequester implements Consumer<T>, Function<T, T>, CookieProcessor { public AbstractAcceptor() { this(null); } public AbstractAcceptor(TimeWaitingStrategy strategy) { this(strategy, URLMapper.MAIN_PAGE.toString()); } public AbstractAcceptor(TimeWaitingStrategy strategy, String webSite) { super(strategy, webSite); } protected abstract void consumLogic(T t) throws Exception; @Override public void accept(T t) {<FILL_FUNCTION_BODY>} @Override public T apply(T t) { accept(t); return t; } }
System.out.println(getClass().getSimpleName() + " accepting..."); int retryTime = this.strategy.retryTimes(); try { int loopTime = 1; while (retryTime > loopTime) { try { consumLogic(t); break; } catch (Exception e) { if(!(e instanceof IOException)) throw e; System.out.println("Acceptor: Network busy Retrying -> " + loopTime + " times"); updateCookie(webSite); this.strategy.waiting(loopTime++); } } } catch (Exception e) { e.printStackTrace(); }
198
180
378
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) <variables>protected ObjectMapper mapper,protected org.decaywood.timeWaitingStrategy.TimeWaitingStrategy strategy,protected java.lang.String webSite
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/AbstractCollector.java
AbstractCollector
get
class AbstractCollector<T> extends AbstractRequester implements Supplier<T>, CookieProcessor { /** * 收集器收集逻辑,由子类实现 */ protected abstract T collectLogic() throws Exception; public AbstractCollector(TimeWaitingStrategy strategy) { this(strategy, URLMapper.MAIN_PAGE.toString()); } /** * @param strategy 超时等待策略(null则设置为默认等待策略) * @param webSite 站点(默认为雪球网首页,可拓展其他财经网站--作用为获取cookie) */ public AbstractCollector(TimeWaitingStrategy strategy, String webSite) { super(strategy, webSite); } @Override public T get() {<FILL_FUNCTION_BODY>} }
System.out.println(getClass().getSimpleName() + " collecting..."); T res = null; int retryTime = this.strategy.retryTimes(); try { int loopTime = 1; while (retryTime > loopTime) { try { res = collectLogic(); break; } catch (Exception e) { if(!(e instanceof IOException)) throw e; System.out.println("Collector: Network busy Retrying -> " + loopTime + " times"); updateCookie(webSite); this.strategy.waiting(loopTime++); } } } catch (Exception e) { e.printStackTrace(); } return res;
222
186
408
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) <variables>protected ObjectMapper mapper,protected org.decaywood.timeWaitingStrategy.TimeWaitingStrategy strategy,protected java.lang.String webSite
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/CommentCollector.java
CommentCollector
collectLogic
class CommentCollector extends AbstractCollector<List<Comment>> { private String postId; public CommentCollector(String postId) { super(null); this.postId = postId; } @Override protected List<Comment> collectLogic() throws Exception {<FILL_FUNCTION_BODY>} }
String target = URLMapper.COMMENTS_INFO_JSON.toString(); int page = 1; List<Comment> res = new ArrayList<>(); while (true) { int cnt = 20; RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("id", postId) .addParameter("count", cnt) .addParameter("page", page) .addParameter("reply", true) .addParameter("split", true); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); List<Comment> comments = JsonParser.parseArray(Comment::new, (t, n) -> { User user = JsonParser.parse(User::new, n.get("user")); JsonNode replyComment = n.get("reply_comment"); if (!(replyComment instanceof NullNode)) { Comment reply_comment = JsonParser.parse(Comment::new, replyComment); User replyUser = JsonParser.parse(User::new, replyComment.get("user")); reply_comment.setUser(replyUser); t.setReply_comment(reply_comment); } t.setUser(user); }, node.get("comments")); if (CollectionUtils.isEmpty(comments)) { break; } res.addAll(comments); page++; } return res;
88
363
451
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.Comment> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/CommissionIndustryCollector.java
CommissionIndustryCollector
collectLogic
class CommissionIndustryCollector extends AbstractCollector<List<Industry>> { public CommissionIndustryCollector() { this(null); } /** *@param strategy 超时等待策略(null则设置为默认等待策略) */ public CommissionIndustryCollector(TimeWaitingStrategy strategy) { super(strategy); } @Override public List<Industry> collectLogic() throws Exception {<FILL_FUNCTION_BODY>} }
List<Industry> res = new ArrayList<>(); String target = URLMapper.COMPREHENSIVE_PAGE.toString(); String content = request(new URL(target)); Document doc = Jsoup.parse(content); Elements element = doc.getElementsByClass("second-nav") .get(1).children() .get(2).children() .get(3).children() .select("a"); StringBuilder builder = new StringBuilder(); for (Element ele : element) { if (!ele.hasAttr("title") || !ele.hasAttr("href")) continue; builder.append(ele.attr("href")); res.add(new Industry(ele.attr("title"), builder.toString())); builder.delete(0, builder.length()); } return res;
136
210
346
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.Industry> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/DateRangeCollector.java
DateRangeCollector
collectLogic
class DateRangeCollector extends AbstractCollector <List<Date>> { private final Date from; private final Date to; public DateRangeCollector(Date from, Date to) { this(null, from, to); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param from 起始时间 * @param to 结束时间 */ public DateRangeCollector(TimeWaitingStrategy strategy, Date from, Date to) { super(strategy); if(from == null || to == null || from.after(to)) throw new IllegalArgumentException(); this.from = from; this.to = to; } @Override public List<Date> collectLogic() throws Exception {<FILL_FUNCTION_BODY>} }
List<Date> dates = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); StringBuilder builder = new StringBuilder(); for (Date i = from; i.before(to) || i.equals(to); ) { dates.add(i); calendar.setTime(i); builder.delete(0, builder.length()); calendar.add(Calendar.DATE, 1); i = calendar.getTime(); } return dates;
217
124
341
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<java.util.Date> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/HuShenNewsRefCollector.java
HuShenNewsRefCollector
processNode
class HuShenNewsRefCollector extends AbstractCollector<List<URL>> { //新闻内容阈值 private static final int MAX_PAGE_SIZE = 5; //新闻主题 public enum Topic { TOTAL("5"),//全部新闻 MARKET("6"),//市场动态 ANALISIS("7"),//投资分析 IDEA("8");//投资理念 private String topic; Topic(String str) { this.topic = str; } public String getVal() { return this.topic; } } private Topic topicType = Topic.TOTAL; private int pageEndTo = 1; public HuShenNewsRefCollector() { this(Topic.TOTAL, 1); } public HuShenNewsRefCollector(Topic topicType, int pageEndTo) { this(null, topicType, pageEndTo); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param topicType 主题类型 * @param pageEndTo 搜索页面数 从1到pageEndTo */ public HuShenNewsRefCollector(TimeWaitingStrategy strategy, Topic topicType, int pageEndTo) { super(strategy); if(pageEndTo < 1) throw new IllegalArgumentException(); this.pageEndTo = Math.min(pageEndTo, MAX_PAGE_SIZE); this.topicType = topicType; } @Override public List<URL> collectLogic() throws Exception { String target = URLMapper.HU_SHEN_NEWS_REF_JSON.toString(); List<JsonNode> nodeList = new ArrayList<>(); for (int i = 1; i <= pageEndTo; i++) { JsonNode node; try { int loopTime = 1; while (strategy.retryTimes() > loopTime) { try { RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("simple_user", "1") .addParameter("topicType", topicType.getVal()) .addParameter("page", i); URL url = new URL(builder.build()); String json = request(url); node = mapper.readTree(json); nodeList.add(node); break; } catch (Exception e) { if(!(e instanceof IOException)) throw e; System.out.println("Collector: Network busy Retrying -> " + loopTime + " times"); updateCookie(webSite); this.strategy.waiting(loopTime++); } } } catch (Exception e) { e.printStackTrace(); } } return processNode(nodeList); } private List<URL> processNode(List<JsonNode> nodeList) {<FILL_FUNCTION_BODY>} }
List<URL> res = new ArrayList<>(); for (JsonNode node : nodeList) { try { for (JsonNode jsonNode : node) { String suffix = jsonNode.get("target").asText(); String path = URLMapper.MAIN_PAGE.toString() + suffix; res.add(new URL(path)); } } catch (MalformedURLException e) { e.printStackTrace(); } } return res;
760
126
886
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<java.net.URL> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/MarketQuotationsRankCollector.java
MarketQuotationsRankCollector
processNode
class MarketQuotationsRankCollector extends AbstractCollector<List<Stock>> { // 排序规则,待更多拓展.... public static final String ORDER_BY_PERCENT = "percent";//按涨幅排序 public static final String ORDER_BY_VOLUME = "volume";//按成交量排序 public static final String ORDER_BY_AMOUNT = "amount";//成交额 public static final String ORDER_BY_TURNOVER_RATE = "turnover_rate";//按换手排序 public static final int TOPK_MAX_SHRESHOLD = 500; /** * 股票类型 */ public enum StockType { SH_A("sha"),//沪市A SH_B("shb"),//沪市B SZ_A("sza"),//深市A SZ_B("szb"),//深市B GROWTH_ENTERPRISE_BOARD("cyb"),//创业板 SMALL_MEDIUM_ENTERPRISE_BOARD("zxb"),//中小板 HK("hk"),//港股 US("us");//美股 private String val; StockType(String val) { this.val = val; } } private final StockType stockType; private final String orderPattern; private boolean asc; private final int topK; public MarketQuotationsRankCollector(StockType stockType, String orderPattern) { this(stockType, orderPattern, 10); } public MarketQuotationsRankCollector(StockType stockType, String orderPattern, int topK) { this(null, stockType, orderPattern, topK); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param stockType 股票类型 * @param orderPattern 排序规则 * @param topK 取排名前K */ public MarketQuotationsRankCollector( TimeWaitingStrategy strategy, StockType stockType, String orderPattern, int topK ) { super(strategy); orderPattern = orderPattern == null ? "" : orderPattern; if(!isLegal(orderPattern) || topK <= 0) throw new IllegalArgumentException("Not legal or not support yet exception"); this.stockType = stockType == null ? StockType.SH_A : stockType; this.orderPattern = orderPattern; this.topK = Math.min(topK, TOPK_MAX_SHRESHOLD); } private boolean isLegal(String orderPattern) { return orderPattern.equals(ORDER_BY_AMOUNT) || orderPattern.equals(ORDER_BY_PERCENT) || orderPattern.equals(ORDER_BY_TURNOVER_RATE) || orderPattern.equals(ORDER_BY_VOLUME); } public MarketQuotationsRankCollector ascend() { this.asc = true; return this; } public MarketQuotationsRankCollector descend() { this.asc = false; return this; } @Override public List<Stock> collectLogic() throws Exception { String target = URLMapper.MARKET_QUOTATIONS_RANK_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("stockType", stockType.val) .addParameter("order", asc ? "asc" : "desc") .addParameter("orderBy", orderPattern) .addParameter("size", topK) .addParameter("page", 1) .addParameter("column", "symbol%2Cname"); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); return processNode(node); } private List<Stock> processNode(JsonNode node) {<FILL_FUNCTION_BODY>} public StockType getStockType() { return stockType; } public String getOrderPattern() { return orderPattern; } }
List<Stock> stocks = new ArrayList<>(); JsonNode data = node.get("data"); for (JsonNode jsonNode : data) { String symbol = jsonNode.get(0).asText(); String name = jsonNode.get(1).asText(); Stock stock = new Stock(name, symbol); stocks.add(stock); } return stocks;
1,080
100
1,180
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.Stock> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/MostProfitableCubeCollector.java
MostProfitableCubeCollector
collectLogic
class MostProfitableCubeCollector extends AbstractCollector<List<Cube>> { /** * 组合所在股市 */ public enum Market { CN("cn"),//沪深组合 US("us"),//美股组合 HK("hk");//港股组合 private String val; Market(String val) { this.val = val; } @Override public String toString() { return val; } } /** * 收益排序规则 */ public enum ORDER_BY { DAILY("daily_gain"),//按日收益排序 MONTHLY("monthly_gain"),//按月收益排序 YEARLY("annualized_gain_rate");//按年收益 private String val; ORDER_BY(String val) { this.val = val; } @Override public String toString() { return val; } } public static final int CUBE_SIZE_SHRESHOLD = 400; //topK阈值 private Market market; private ORDER_BY order_by; private int topK; public MostProfitableCubeCollector() { this(Market.CN); } public MostProfitableCubeCollector(Market market) { this(market, ORDER_BY.MONTHLY); } public MostProfitableCubeCollector(Market market, ORDER_BY order_by) { this(null, market, order_by, 10); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param market 组合所在市场 * @param order_by 收益排序规则 * @param topK 排名前K的组合 */ public MostProfitableCubeCollector(TimeWaitingStrategy strategy, Market market, ORDER_BY order_by, int topK) { super(strategy); this.market = market == null ? Market.CN : market; this.order_by = order_by == null ? ORDER_BY.MONTHLY : order_by; if(topK <= 0) throw new IllegalArgumentException(); this.topK = Math.min(topK, CUBE_SIZE_SHRESHOLD); } @Override public List<Cube> collectLogic() throws Exception {<FILL_FUNCTION_BODY>} private List<Cube> processNode(JsonNode node) { JsonNode list = node.get("list"); List<Cube> cubes = new ArrayList<>(); for (JsonNode jsonNode : list) { String id = jsonNode.get("id").asText(); String name = jsonNode.get("name").asText(); String symbol = jsonNode.get("symbol").asText(); String daily_gain = jsonNode.get("daily_gain").asText(); String monthly_gain = jsonNode.get("monthly_gain").asText(); String annualized_gain_rate = jsonNode.get("annualized_gain_rate").asText(); String total_gain = jsonNode.get("total_gain").asText(); Cube cube = new Cube(id, name, symbol); cube.setDaily_gain(daily_gain); cube.setMonthly_gain(monthly_gain); cube.setAnnualized_gain_rate(annualized_gain_rate); cube.setTotal_gain(total_gain); cubes.add(cube); } return cubes; } public Market getMarket() { return market; } public ORDER_BY getOrder_by() { return order_by; } }
String target = URLMapper.CUBES_RANK_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("category", 12) .addParameter("count", topK) .addParameter("market", market.toString()) .addParameter("profit", order_by.toString()); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); return processNode(node);
1,003
130
1,133
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.Cube> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/StockCommentCollector.java
StockCommentCollector
collectLogic
class StockCommentCollector extends AbstractCollector<List<PostInfo>> { public enum SortType { // 最新时间 time, // 热度排名 alpha } private String symbol; private int pageSize; private int page; private String sort; public StockCommentCollector(String symbol, SortType type, int page, int pageSize) { super(null); this.symbol = symbol; this.page = page; this.pageSize = pageSize; this.sort = type.toString(); } @Override protected List<PostInfo> collectLogic() throws Exception {<FILL_FUNCTION_BODY>} }
if (StringUtils.isNull(symbol) || page < 1 || pageSize <= 0) { throw new IllegalArgumentException("symbol is null or page size is zero"); } String target = URLMapper.STOCK_MAIN_PAGE.toString(); RequestParaBuilder builder = new RequestParaBuilder(target); builder.addParameter("count", pageSize); builder.addParameter("symbol", symbol); builder.addParameter("sort", sort); builder.addParameter("page", page); URL url = new URL(builder.build()); String json = requestWithoutGzip(url); JsonNode node = mapper.readTree(json); List<PostInfo> postInfos = new ArrayList<>(); for (JsonNode jsonNode : node.get("list")) { PostInfo postInfo = JsonParser.parse(PostInfo::new, jsonNode); postInfos.add(postInfo); } return postInfos;
181
234
415
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.PostInfo> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/StockScopeHotRankCollector.java
StockScopeHotRankCollector
processNode
class StockScopeHotRankCollector extends AbstractCollector<List<Stock>> { /** * 热股关注范围 */ public enum Scope { GLOBAL_WITHIN_1_HOUR("10", "10"),//全球1小时内 GLOBAL_WITHIN_24_HOUR("10", "20"),//全球24小时内 US_WITHIN_1_HOUR("11", "11"),//美股1小时内 US_WITHIN_24_HOUR("11", "21"),//美股24小时内 SH_SZ_WITHIN_1_HOUR("12", "12"),//沪深1小时内 SH_SZ_WITHIN_24_HOUR("12", "22"),//沪深24小时内 HK_WITHIN_1_HOUR("13", "13"),//港股1小时内 HK_WITHIN_24_HOUR("13", "23");//港股24小时内 private String scope; private String time; Scope(String scope, String time) { this.scope = scope; this.time = time; } public String getScope() { return scope; } public String getTime() { return time; } } //排名前K阈值 public static final int PAGE_SIZE_SHRESHOLD = 20; private Scope scope; private int topK; public StockScopeHotRankCollector() { this(PAGE_SIZE_SHRESHOLD); } public StockScopeHotRankCollector(Scope scope) { this(null, scope, PAGE_SIZE_SHRESHOLD); } public StockScopeHotRankCollector(int topK) { this(null, Scope.SH_SZ_WITHIN_1_HOUR, topK); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param scope 热股关注范围 * @param topK 排名前K个股 */ public StockScopeHotRankCollector(TimeWaitingStrategy strategy, Scope scope, int topK) { super(strategy); if(topK <= 0) throw new IllegalArgumentException(); this.topK = Math.min(topK, PAGE_SIZE_SHRESHOLD); this.scope = scope == null ? Scope.SH_SZ_WITHIN_24_HOUR : scope; } @Override public List<Stock> collectLogic() throws Exception { String target = URLMapper.SCOPE_STOCK_RANK_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("size", topK) .addParameter("_type", scope.getScope()) .addParameter("type", scope.getTime()); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); return processNode(node); } private List<Stock> processNode(JsonNode node) {<FILL_FUNCTION_BODY>} public Scope getScope() { return scope; } }
List<Stock> stocks = new ArrayList<>(); JsonNode rankNode = node.get("ranks"); for (JsonNode jsonNode : rankNode) { String symbol = jsonNode.get("symbol").asText(); String name = jsonNode.get("name").asText(); Stock stock = new Stock(name, symbol); stocks.add(stock); } return stocks;
855
101
956
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.Stock> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/StockSlectorBaseCollector.java
StockSlectorBaseCollector
processNode
class StockSlectorBaseCollector extends AbstractCollector<List<Stock>> { /** * 指标链,指标分多种类型,不同类型可挂靠在指标链头节点上 * 收集器会根据指标链的指标进行统计并收集符合指标链所有指标的个股 */ QuotaChainNode head; public StockSlectorBaseCollector() { this(null); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) */ public StockSlectorBaseCollector(TimeWaitingStrategy strategy) { super(strategy); head = new QuotaHead(); } /** * @param node 需要添加到指标链上的股票指标 */ public void addQuotaChainNode(QuotaChainNode node) { head.setNext(node); } @Override public List<Stock> collectLogic() throws Exception { String target = URLMapper.STOCK_SELECTOR_JSON.toString(); URL url = new URL(target + head.generateQuotaRequest()); String json = request(url); JsonNode node = mapper.readTree(json); return processNode(node); } private List<Stock> processNode(JsonNode node) {<FILL_FUNCTION_BODY>} }
JsonNode jsonNode = node.get("list"); List<Stock> stocks = new ArrayList<>(); for (JsonNode n : jsonNode) { String symbol = n.get("symbol").asText(); String name = n.get("name").asText(); Stock stock = new Stock(name, symbol); stocks.add(stock); } return stocks;
352
97
449
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.Stock> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/collector/UserCommentCollector.java
UserCommentCollector
collectLogic
class UserCommentCollector extends AbstractCollector<List<PostInfo>> { private String userId; /** 评论页码 */ private int fromPage; /** 评论页码 */ private int toPage; private int pageSize; public UserCommentCollector(String userId, int fromPage, int toPage, int pageSize) { super(null); this.userId = userId; this.fromPage = fromPage; this.toPage = toPage; this.pageSize = pageSize; } @Override protected List<PostInfo> collectLogic() throws Exception {<FILL_FUNCTION_BODY>} }
if (StringUtils.isEmpty(userId) || fromPage < 1 || fromPage > toPage) { throw new IllegalArgumentException("userId is null or page size illegal"); } String target = URLMapper.USER_COMMENT_JSON.toString(); List<PostInfo> postInfos = new ArrayList<>(); for (int i = fromPage; i <= toPage; i++) { RequestParaBuilder builder = new RequestParaBuilder(target); builder.addParameter("page", i); builder.addParameter("user_id", userId); builder.addParameter("count", pageSize); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); toPage = Math.min(toPage, Integer.parseInt(node.get("maxPage").asText())); for (JsonNode jsonNode : node.get("statuses")) { PostInfo postInfo = JsonParser.parse(PostInfo::new, jsonNode); postInfos.add(postInfo); } } return postInfos;
175
272
447
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.PostInfo> get() <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/CapitalFlow.java
CapitalFlow
copy
class CapitalFlow implements DeepCopy<CapitalFlow> { private final String capitalInflow;//资金流向(万) private final String largeQuantity;//大单(万) private final String midQuantity;//中单(万) private final String smallQuantity;//小单(万) private final String largeQuantBuy;//大单主动买入(手) private final String largeQuantSell;//大单主动卖出(手) private final String largeQuantDealProp;//大单成交占比(%) private final String fiveDayInflow;//五天净流入总量 private final List<Double> fiveDayInflows;//五天净流入详情 /** * * @param capitalInflow 资金流向 * @param largeQuantity 大单 * @param midQuantity 中单 * @param smallQuantity 小单 * @param largeQuantBuy 大单主动买入 * @param largeQuantSell 大单主动卖出 * @param largeQuantDealProp 大单成交占比 * @param fiveDayInflow 五天净流入总量 * @param fiveDayInflows 五天净流入详情 */ public CapitalFlow(String capitalInflow, String largeQuantity, String midQuantity, String smallQuantity, String largeQuantBuy, String largeQuantSell, String largeQuantDealProp, String fiveDayInflow, List<Double> fiveDayInflows) { this.capitalInflow = capitalInflow; this.largeQuantity = largeQuantity; this.midQuantity = midQuantity; this.smallQuantity = smallQuantity; this.largeQuantBuy = largeQuantBuy; this.largeQuantSell = largeQuantSell; this.largeQuantDealProp = largeQuantDealProp; this.fiveDayInflow = fiveDayInflow; this.fiveDayInflows = fiveDayInflows; } public String getCapitalInflow() { return capitalInflow; } public String getLargeQuantity() { return largeQuantity; } public String getMidQuantity() { return midQuantity; } public String getSmallQuantity() { return smallQuantity; } public String getLargeQuantBuy() { return largeQuantBuy; } public String getLargeQuantSell() { return largeQuantSell; } public String getLargeQuantDealProp() { return largeQuantDealProp; } public String getFiveDayInflow() { return fiveDayInflow; } public List<Double> getFiveDayInflows() { return fiveDayInflows; } @Override public CapitalFlow copy() {<FILL_FUNCTION_BODY>} }
return new CapitalFlow( capitalInflow, largeQuantity, midQuantity, smallQuantity, largeQuantBuy, largeQuantSell, largeQuantDealProp, fiveDayInflow, new ArrayList<>(fiveDayInflows));
762
74
836
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/Comment.java
Comment
equals
class Comment implements User.UserSetter { public interface CommentSetter { void addComments(List<Comment> comments); String getPostId(); int getReplyCnt(); } /** 评论id */ private String id; /** 用户信息 */ private User user; /** 引用 */ private Comment reply_comment; /** 评论内容 */ private String text; /** 用户id */ private String user_id; public String getId() { return id; } public void setId(String id) { this.id = id; } public User getUser() { return user; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public Comment getReply_comment() { return reply_comment; } public void setReply_comment(Comment reply_comment) { this.reply_comment = reply_comment; } @Override public void setUser(User user) { this.user = user; } @Override public String getUserId() { return user_id; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(id); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Comment comment = (Comment) o; return id.equals(comment.id);
435
56
491
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/CompanyInfo.java
CompanyInfo
copy
class CompanyInfo implements DeepCopy<CompanyInfo> { private final String compsname;//公司名称 private final String orgtype;//组织形式 private final String founddate;//成立日期 private final String bizscope;//经营范围 private final String majorbiz;//主营业务 private final String region;//地区代码 private final List<Industry> tqCompIndustryList;//所属板块 /** * * @param compsname 公司名称 * @param orgtype 组织形式 * @param founddate 成立日期 * @param bizscope 经营范围 * @param majorbiz 主营业务 * @param region 地区代码 * @param tqCompIndustryList 所属板块 */ public CompanyInfo(String compsname, String orgtype, String founddate, String bizscope, String majorbiz, String region, List<Industry> tqCompIndustryList) { this.compsname = compsname; this.orgtype = orgtype; this.founddate = founddate; this.bizscope = bizscope; this.majorbiz = majorbiz; this.region = region; this.tqCompIndustryList = tqCompIndustryList; } public String getCompsname() { return compsname; } public String getOrgtype() { return orgtype; } public String getFounddate() { return founddate; } public String getBizscope() { return bizscope; } public String getMajorbiz() { return majorbiz; } public String getRegion() { return region; } public List<Industry> getTqCompIndustryList() { return tqCompIndustryList; } @Override public CompanyInfo copy() {<FILL_FUNCTION_BODY>} }
return new CompanyInfo( compsname, orgtype, founddate, bizscope, majorbiz, region, new ArrayList<>(tqCompIndustryList));
529
56
585
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/Cube.java
Cube
copy
class Cube implements DeepCopy<Cube> { private final String cubeID; private final String name; private final String symbol; private String daily_gain = EmptyObject.emptyString; //日收益 private String monthly_gain = EmptyObject.emptyString;//月收益 private String annualized_gain_rate = EmptyObject.emptyString;//年收益 private String total_gain = EmptyObject.emptyString;//总收益 private CubeTrend cubeTrend = EmptyObject.emptyCubeTrend;//组合收益历史走线 private MarketIndexTrend marketIndexTrend = EmptyObject.emptyMarketIndexTrend;//大盘历史走线 private Rebalancing rebalancing = EmptyObject.emptyRebalancing;//调仓记录 /** * * @param cubeID 组合代码 * @param name 组合名称 * @param symbol 组合代码 */ public Cube(String cubeID, String name, String symbol) { this.cubeID = cubeID; this.name = name; this.symbol = symbol; } @Override public Cube copy() {<FILL_FUNCTION_BODY>} //日收益 public void setDaily_gain(String daily_gain) { this.daily_gain = daily_gain; } //月收益 public void setMonthly_gain(String monthly_gain) { this.monthly_gain = monthly_gain; } //总收益 public void setTotal_gain(String total_gain) { this.total_gain = total_gain; } //组合收益历史走线 public void setCubeTrend(CubeTrend cubeTrend) { this.cubeTrend = cubeTrend; } //大盘历史走线 public void setMarketIndexTrend(MarketIndexTrend marketIndexTrend) { this.marketIndexTrend = marketIndexTrend; } //调仓记录 public void setRebalancing(Rebalancing rebalancing) { this.rebalancing = rebalancing; } //年收益 public void setAnnualized_gain_rate(String annualized_gain_rate) { this.annualized_gain_rate = annualized_gain_rate; } public String getDaily_gain() { return daily_gain; } public String getMonthly_gain() { return monthly_gain; } public String getAnnualized_gain_rate() { return annualized_gain_rate; } public String getTotal_gain() { return total_gain; } public String getCubeID() { return cubeID; } public String getName() { return name; } public String getSymbol() { return symbol; } public Rebalancing getRebalancing() { return rebalancing; } public CubeTrend getCubeTrend() { return cubeTrend; } public MarketIndexTrend getMarketIndexTrend() { return marketIndexTrend; } }
Cube cube = new Cube(cubeID, name, symbol); cube.setDaily_gain(daily_gain); cube.setMonthly_gain(monthly_gain); cube.setAnnualized_gain_rate(annualized_gain_rate); cube.setTotal_gain(total_gain); cube.setCubeTrend(cubeTrend.copy()); cube.setMarketIndexTrend(marketIndexTrend.copy()); cube.setRebalancing(rebalancing); return cube;
858
158
1,016
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/Industry.java
Industry
hashCode
class Industry implements DeepCopy<Industry> { private final String industryName;//板块名字 private final String industryInfo;//板块代码 public Industry(final String industryName, final String industrySiteURL) { this.industryName = industryName; this.industryInfo = industrySiteURL; } public String getIndustryName() { return industryName; } public String getIndustryInfo() { return industryInfo; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Industry industry = (Industry) o; return industryName.equals(industry.industryName) && industryInfo.equals(industry.industryInfo); } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { return "industryName = " + industryName + " " + "industryInfo = " + industryInfo; } @Override public Industry copy() { return new Industry(industryName, industryInfo); } }
int result = industryName.hashCode(); result = 31 * result + industryInfo.hashCode(); return result;
326
34
360
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/LongHuBangInfo.java
BizsunitInfo
equals
class BizsunitInfo implements Serializable { private final String bizsunitcode; //营业部编号 private final String bizsunitname; //营业部名称 private final String buyamt; // 买入额度 private final String saleamt; // 卖出额度 private final String tradedate; //交易日期 yyyymmdd public BizsunitInfo(String bizsunitcode, String bizsunitname, String buyamt, String saleamt, String tradedate) { if(StringUtils.nullOrEmpty(bizsunitcode, bizsunitname, buyamt, saleamt, tradedate)) throw new IllegalArgumentException(); this.bizsunitcode = bizsunitcode; this.bizsunitname = bizsunitname; this.buyamt = buyamt; this.saleamt = saleamt; this.tradedate = tradedate; } public String getBizsunitcode() { return bizsunitcode; } public String getBizsunitname() { return bizsunitname; } public String getBuyamt() { return buyamt; } public String getSaleamt() { return saleamt; } public String getTradedate() { return tradedate; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return bizsunitname.hashCode(); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BizsunitInfo info = (BizsunitInfo) o; return bizsunitname.equals(info.bizsunitname);
420
75
495
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/PostInfo.java
PostInfo
addComments
class PostInfo implements User.UserSetter, Comment.CommentSetter { /** 描述 */ private String description; /** 正文 */ private String text; /** 帖子id */ private String id; /** userId/commentId */ private String target; /** 标题 */ private String title; /** 用户id */ private String user_id; /** 用户信息 填充次信息需要用到 UserSetMapper */ private User user; /** 点赞数 */ private String like_count; /** 已阅读次数 */ private String view_count; /** 回复数量 */ private String reply_count; private Set<Comment> comments = new HashSet<>(); public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLike_count() { return like_count; } public void setLike_count(String like_count) { this.like_count = like_count; } public String getView_count() { return view_count; } public void setView_count(String view_count) { this.view_count = view_count; } public String getReply_count() { return reply_count; } public void setReply_count(String reply_count) { this.reply_count = reply_count; } public User getUser() { return user; } public Set<Comment> getComments() { return comments; } public void setComments(Set<Comment> comments) { this.comments = comments; } @Override public void addComments(List<Comment> comments) {<FILL_FUNCTION_BODY>} @Override public String getPostId() { return getId(); } @Override public int getReplyCnt() { return Integer.parseInt(reply_count); } @Override public void setUser(User user) { this.user = user; } @Override public String getUserId() { return this.user_id; } }
if (CollectionUtils.isEmpty(comments)) { return; } this.comments = new HashSet<>(this.comments); this.comments.addAll(comments);
807
48
855
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/selectorQuota/AbstractQuotaNode.java
AbstractQuotaNode
generateQuotaRequest
class AbstractQuotaNode implements QuotaChainNode { private QuotaChainNode next = EmptyObject.emptyQuotaChainNode; @Override public QuotaChainNode getNext() { return next; } @Override public void setNext(QuotaChainNode next) { if(next == null) return; if(!end()) getNext().setNext(next); else this.next = next; } @Override public String generateQuotaRequest() {<FILL_FUNCTION_BODY>} abstract StringBuilder builderSelf(); }
StringBuilder builder = builderSelf(); if(!this.end()) builder.append(this.getNext().generateQuotaRequest()); builder.deleteCharAt(builder.length() - 1); return builder.toString();
149
59
208
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/selectorQuota/BasicQuota.java
BasicQuota
builderSelf
class BasicQuota extends AbstractQuotaNode { private String mc = "ALL";//总市值(亿) private String fmc = "ALL";//流通市值(亿) private String pettm = "ALL";//动态市盈率(倍) private String pelyr = "ALL";//静态市盈率(倍) private String eps = "ALL";//每股收益 private String bps = "ALL";//每股净资产 private String roediluted = "ALL";//净资产收益率 private String netprofit = "ALL";//净利润(万) private String dy = "ALL";//股息率(%) private String pb = "ALL";//市净率(倍) //设置总市值范围 public void setMc(double from, double to) { mc = from + "_" + to; } //设置流通市值范围 public void setFmc(double from, double to) { fmc = from + "_" + to; } //设置动态市盈率范围 public void setPettm(double from, double to) { pettm = from + "_" + to; } //设置静态市盈率范围 public void setPelyr(double from, double to) { pelyr = from + "_" + to; } //设置每股收益范围 public void setEps(double from, double to) { eps = from + "_" + to; } //设置每股净资产范围 public void setBps(double from, double to) { bps = from + "_" + to; } //设置净资产收益率范围 public void setRoediluted(double from, double to) { roediluted = from + "_" + to; } //设置净利润范围 public void setNetprofit(double from, double to) { netprofit = from + "_" + to; } //设置股息率范围 public void setDy(double from, double to) { dy = from + "_" + to; } //设置市净率范围 public void setPb(double from, double to) { pb = from + "_" + to; } @Override StringBuilder builderSelf() {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder(); append(builder, "mc", mc); append(builder, "fmc", fmc); append(builder, "pettm", pettm); append(builder, "pelyr", pelyr); appendWithTimePrefix(builder, "eps", eps); appendWithTimePrefix(builder, "bps", bps); appendWithTimePrefix(builder, "roediluted", roediluted); appendWithTimePrefix(builder, "netprofit", netprofit); append(builder, "dy", dy); append(builder, "pb", pb); return builder;
601
161
762
<methods>public non-sealed void <init>() ,public java.lang.String generateQuotaRequest() ,public org.decaywood.entity.selectorQuota.QuotaChainNode getNext() ,public void setNext(org.decaywood.entity.selectorQuota.QuotaChainNode) <variables>private org.decaywood.entity.selectorQuota.QuotaChainNode next
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/selectorQuota/MarketQuotationsQuota.java
MarketQuotationsQuota
builderSelf
class MarketQuotationsQuota extends AbstractQuotaNode { private String current = "ALL"; //当前价 private String pct = "ALL"; //本日涨跌幅(%) private String pct5 = "ALL"; //前5日涨跌幅(%) private String pct10 = "ALL"; //前10日涨跌幅(%) private String pct20 = "ALL"; //前20日涨跌幅(%) private String pct1m = "ALL"; //近1月涨跌幅(%) private String chgpct = "ALL"; //本日振幅(%) private String chgpct5 = "ALL"; //前5日振幅(%) private String chgpct10 = "ALL"; //前10日振幅(%) private String chgpct20 = "ALL"; //前20日振幅(%) private String chgpct1m = "ALL"; //近1月振幅(%) private String volume = "ALL"; //本日成交量(万) private String volavg30 = "ALL"; //30日均量(万) private String amount = "ALL"; //成交额(万) private String tr = "ALL"; // 本日换手率(%) private String tr5 = "ALL"; //前5日换手率(%) private String tr10 = "ALL"; // 前10日换手率(%) private String tr20 = "ALL"; //前20日换手率(%) private String tr1m = "ALL"; //近1月换手率(%) //设置当前价范围 public void setCurrent(double from, double to) { this.current = from + "_" + to; } //设置本日涨跌幅范围 public void setPct(double from, double to) { this.pct = from + "_" + to; } //设置前5日涨跌幅范围 public void setPct5(double from, double to) { this.pct5 = from + "_" + to; } //设置前10日涨跌幅范围 public void setPct10(double from, double to) { this.pct10 = from + "_" + to; } //设置前20日涨跌幅范围 public void setPct20(double from, double to) { this.pct20 = from + "_" + to; } //设置近1月涨跌幅范围 public void setPct1m(double from, double to) { this.pct1m = from + "_" + to; } //设置本日振幅范围 public void setChgpct(double from, double to) { this.chgpct = from + "_" + to; } //设置前5日振幅范围 public void setChgpct5(double from, double to) { this.chgpct5 = from + "_" + to; } //设置前10日振幅范围 public void setChgpct10(double from, double to) { this.chgpct10 = from + "_" + to; } //设置前20日振幅范围 public void setChgpct20(double from, double to) { this.chgpct20 = from + "_" + to; } //设置前1月振幅范围 public void setChgpct1m(double from, double to) { this.chgpct1m = from + "_" + to; } //设置本日成交量范围 public void setVolume(double from, double to) { this.volume = from + "_" + to; } //设置前30日均量范围 public void setVolavg30(double from, double to) { this.volavg30 = from + "_" + to; } //设置成交额范围 public void setAmount(double from, double to) { this.amount = from + "_" + to; } //设置本日换手率范围 public void setTr(double from, double to) { this.tr = from + "_" + to; } //设置前5日换手率范围 public void setTr5(double from, double to) { this.tr5 = from + "_" + to; } //设置前10日换手率范围 public void setTr10(double from, double to) { this.tr10 = from + "_" + to; } //设置前20日换手率范围 public void setTr20(double from, double to) { this.tr20 = from + "_" + to; } //设置前1月换手率范围 public void setTr1m(double from, double to) { this.tr1m = from + "_" + to; } @Override StringBuilder builderSelf() {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder(); append(builder, "current", current); append(builder, "pct", pct); append(builder, "pct5", pct5); append(builder, "pct10", pct10); append(builder, "pct20", pct20); append(builder, "pct1m", pct1m); append(builder, "chgpct", chgpct); append(builder, "chgpct5", chgpct5); append(builder, "chgpct10", chgpct10); append(builder, "chgpct20", chgpct20); append(builder, "chgpct1m", chgpct1m); append(builder, "volume", volume); append(builder, "volavg30", volavg30); append(builder, "amount", amount); append(builder, "tr", tr); append(builder, "tr5", tr5); append(builder, "tr10", tr10); append(builder, "tr20", tr20); append(builder, "tr1m", tr1m); return builder;
1,282
307
1,589
<methods>public non-sealed void <init>() ,public java.lang.String generateQuotaRequest() ,public org.decaywood.entity.selectorQuota.QuotaChainNode getNext() ,public void setNext(org.decaywood.entity.selectorQuota.QuotaChainNode) <variables>private org.decaywood.entity.selectorQuota.QuotaChainNode next
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/selectorQuota/QuotaHead.java
QuotaHead
builderSelf
class QuotaHead extends AbstractQuotaNode { private String category = "SH"; private String exchange = ""; //市场 private String areacode = ""; //地域 private String indcode = ""; //板块代码 private String orderby = "symbol"; //排序方式 private String order = "desc"; private String page = "1"; @Override StringBuilder builderSelf() {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder("?"); append(builder, "category", category); append(builder, "exchange", exchange); append(builder, "areacode", areacode); append(builder, "indcode", indcode); append(builder, "orderby", orderby); append(builder, "order", order); append(builder, "page", page); return builder;
118
107
225
<methods>public non-sealed void <init>() ,public java.lang.String generateQuotaRequest() ,public org.decaywood.entity.selectorQuota.QuotaChainNode getNext() ,public void setNext(org.decaywood.entity.selectorQuota.QuotaChainNode) <variables>private org.decaywood.entity.selectorQuota.QuotaChainNode next
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/selectorQuota/XueQiuQuota.java
XueQiuQuota
builderSelf
class XueQiuQuota extends AbstractQuotaNode { private String follow = "ALL"; //累计关注人数 private String tweet = "ALL"; //累计讨论次数 private String deal = "ALL"; //累计交易分享数 private String follow7d = "ALL"; //一周新增关注 private String tweet7d = "ALL"; //一周新增讨论数 private String deal7d = "ALL"; //一周新增交易分享数 private String follow7dpct = "ALL"; //一周关注增长率(%) private String tweet7dpct = "ALL"; //一周讨论增长率(%) private String deal7dpct = "ALL"; //一周交易分享增长率(%) private QuotaChainNode next; //设置累计关注人数范围 public void setFollow(double from, double to) { this.follow = from + "_" + to; } //设置累计讨论次数范围 public void setTweet(double from, double to) { this.tweet = from + "_" + to; } //设置累计交易分享数范围 public void setDeal(double from, double to) { this.deal = from + "_" + to; } //设置一周新增关注范围 public void setFollow7d(double from, double to) { this.follow7d = from + "_" + to; } //设置一周新增讨论数范围 public void setTweet7d(double from, double to) { this.tweet7d = from + "_" + to; } //设置一周新增交易分享数范围 public void setDeal7d(double from, double to) { this.deal7d = from + "_" + to; } //设置一周关注增长率范围 public void setFollow7dpct(double from, double to) { this.follow7dpct = from + "_" + to; } //设置一周讨论增长率范围 public void setTweet7dpct(double from, double to) { this.tweet7dpct = from + "_" + to; } //设置一周交易分享增长率范围 public void setDeal7dpct(double from, double to) { this.deal7dpct = from + "_" + to; } @Override StringBuilder builderSelf() {<FILL_FUNCTION_BODY>} }
StringBuilder builder = new StringBuilder(); append(builder, "follow", follow); append(builder, "tweet", tweet); append(builder, "deal", deal); append(builder, "follow7d", follow7d); append(builder, "tweet7d", tweet7d); append(builder, "deal7d", deal7d); append(builder, "follow7dpct", follow7dpct); append(builder, "tweet7dpct", tweet7dpct); append(builder, "deal7dpct", deal7dpct); return builder;
613
154
767
<methods>public non-sealed void <init>() ,public java.lang.String generateQuotaRequest() ,public org.decaywood.entity.selectorQuota.QuotaChainNode getNext() ,public void setNext(org.decaywood.entity.selectorQuota.QuotaChainNode) <variables>private org.decaywood.entity.selectorQuota.QuotaChainNode next
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/entity/trend/Rebalancing.java
TrendBlock
toString
class TrendBlock implements ITrendBlock { private final String stock_name; private final String stock_symbol; private final String created_at;//time private final String prev_price; private final String price; private final String prev_weight; private final String target_weight; private final String weight; private final String rebalancing_id; /** * * @param stock_name 股票名称 * @param stock_symbol 股票代码 * @param created_at 调仓时间 * @param prev_price 上一次调仓价格 * @param price 当前价格 * @param prev_weight 上一次持仓比例 * @param target_weight 期望持仓比例 * @param weight 实际持仓比例 * @param rebalancing_id 调仓节点ID */ public TrendBlock(String stock_name, String stock_symbol, String created_at, String prev_price, String price, String prev_weight, String target_weight, String weight, String rebalancing_id ) { if(StringUtils.nullOrEmpty(stock_name, stock_symbol, created_at , prev_price, price, prev_weight, target_weight, weight, rebalancing_id)) throw new IllegalArgumentException(); this.stock_name = stock_name; this.stock_symbol = stock_symbol; this.created_at = created_at; this.prev_price = prev_price; this.price = price; this.prev_weight = prev_weight; this.target_weight = target_weight; this.weight = weight; this.rebalancing_id = rebalancing_id; } public String getStock_name() { return stock_name; } public String getStock_symbol() { return stock_symbol; } public String getCreated_at() { return created_at; } public String getPrev_price() { return prev_price; } public String getPrice() { return price; } public String getPrev_weight() { return prev_weight; } public String getTarget_weight() { return target_weight; } public String getWeight() { return weight; } public String getRebalancing_id() { return rebalancing_id; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "TrendBlock{" + "stock_name='" + stock_name + '\'' + ", stock_symbol='" + stock_symbol + '\'' + ", created_at='" + created_at + '\'' + ", prev_price='" + prev_price + '\'' + ", price='" + price + '\'' + ", prev_weight='" + prev_weight + '\'' + ", target_weight='" + target_weight + '\'' + ", weight='" + weight + '\'' + ", rebalancing_id='" + rebalancing_id + '\'' + '}';
663
157
820
<methods>public void <init>(List<org.decaywood.entity.trend.Rebalancing.TrendBlock>) ,public List<org.decaywood.entity.trend.Rebalancing.TrendBlock> getHistory() <variables>protected final non-sealed List<org.decaywood.entity.trend.Rebalancing.TrendBlock> history
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/filter/AbstractFilter.java
AbstractFilter
test
class AbstractFilter<T> extends AbstractRequester implements Predicate<T>, CookieProcessor { protected abstract boolean filterLogic(T t) throws Exception; public AbstractFilter(TimeWaitingStrategy strategy) { this(strategy, URLMapper.MAIN_PAGE.toString()); } public AbstractFilter(TimeWaitingStrategy strategy, String webSite) { super(strategy, webSite); } @Override public boolean test(T t) {<FILL_FUNCTION_BODY>} }
System.out.println(getClass().getSimpleName() + " filtering..."); boolean res = false; int retryTime = this.strategy.retryTimes(); try { int loopTime = 1; boolean needRMI = true; while (retryTime > loopTime) { try { res = filterLogic(t); break; } catch (Exception e) { if(!(e instanceof IOException)) throw e; System.out.println("Filter: Network busy Retrying -> " + loopTime + " times"); updateCookie(webSite); this.strategy.waiting(loopTime++); } } } catch (Exception e) { e.printStackTrace(); } return res;
141
203
344
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) <variables>protected ObjectMapper mapper,protected org.decaywood.timeWaitingStrategy.TimeWaitingStrategy strategy,protected java.lang.String webSite
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/filter/PageKeyFilter.java
PageKeyFilter
filterLogic
class PageKeyFilter extends AbstractFilter<URL> { private String key; private boolean regex; public PageKeyFilter(String key, boolean regex) { this(null, key, regex); } /** * @param strategy 超时等待策略(null则设置为默认等待策略) * @param key 关键字 * @param regex 是否启用正则表达式 */ public PageKeyFilter(TimeWaitingStrategy strategy, String key, boolean regex) { super(strategy); this.key = key; this.regex = regex; } @Override protected boolean filterLogic(URL url) throws Exception {<FILL_FUNCTION_BODY>} }
if (url == null) return false; String pageContent = request(url); boolean res; if(regex) { Pattern pattern = Pattern.compile(key); Matcher matcher = pattern.matcher(pageContent); res = matcher.find(); } else res = pageContent.contains(key); return res;
188
94
282
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public boolean test(java.net.URL) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/AbstractMapper.java
AbstractMapper
apply
class AbstractMapper <T, R> extends AbstractRequester implements Function<T, R>, CookieProcessor { protected abstract R mapLogic(T t) throws Exception; public AbstractMapper(TimeWaitingStrategy strategy) { this(strategy, URLMapper.MAIN_PAGE.toString()); } public AbstractMapper(TimeWaitingStrategy strategy, String webSite) { super(strategy, webSite); } @Override public R apply(T t) {<FILL_FUNCTION_BODY>} }
if (t != null) System.out.println(getClass().getSimpleName() + " mapping -> " + t.getClass().getSimpleName()); R res = null; int retryTime = this.strategy.retryTimes(); try { int loopTime = 1; boolean needRMI = true; if(t != null) //noinspection unchecked t = t instanceof DeepCopy ? ((DeepCopy<T>) t).copy() : t; while (retryTime > loopTime) { try { res = mapLogic(t); needRMI = false; break; } catch (Exception e) { if (!(e instanceof IOException)) throw e; System.out.println("Mapper: Network busy Retrying -> " + loopTime + " times" + " " + this.getClass().getSimpleName()); updateCookie(webSite); this.strategy.waiting(loopTime++); } } } catch (Exception e) { e.printStackTrace(); } return res;
144
285
429
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) <variables>protected ObjectMapper mapper,protected org.decaywood.timeWaitingStrategy.TimeWaitingStrategy strategy,protected java.lang.String webSite
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/comment/CommentSetMapper.java
CommentSetMapper
mapLogic
class CommentSetMapper <T extends Comment.CommentSetter> extends AbstractMapper<T, T> { private int pageSize; public CommentSetMapper() { this(Integer.MAX_VALUE); } public CommentSetMapper(int pageSize) { super(null); this.pageSize = pageSize; } @Override protected T mapLogic(T commentSetter) throws Exception {<FILL_FUNCTION_BODY>} }
String postId = commentSetter.getPostId(); String target = URLMapper.COMMENTS_INFO_JSON.toString(); int replyCnt = commentSetter.getReplyCnt(); int page = 1; while (replyCnt > 0) { int cnt = Math.min(replyCnt, pageSize); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("id", postId) .addParameter("count", cnt) .addParameter("page", page) .addParameter("reply", true) .addParameter("split", true); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); List<Comment> comments = JsonParser.parseArray(Comment::new, (t, n) -> { User user = JsonParser.parse(User::new, n.get("user")); JsonNode replyComment = n.get("reply_comment"); if (!(replyComment instanceof NullNode)) { Comment reply_comment = JsonParser.parse(Comment::new, replyComment); User replyUser = JsonParser.parse(User::new, replyComment.get("user")); reply_comment.setUser(replyUser); t.setReply_comment(reply_comment); } t.setUser(user); }, node.get("comments")); commentSetter.addComments(comments); page++; replyCnt -= cnt; } return commentSetter;
121
392
513
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public T apply(T) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/cubeFirst/CubeToCubeWithLastBalancingMapper.java
CubeToCubeWithLastBalancingMapper
processCube
class CubeToCubeWithLastBalancingMapper extends AbstractMapper<Cube, Cube> { private static final int COUNT_THRESHOLD = 50; private final int count; public CubeToCubeWithLastBalancingMapper() { this(null, 10); } public CubeToCubeWithLastBalancingMapper(int i) { this(null, i); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param count 调仓记录数 */ public CubeToCubeWithLastBalancingMapper(TimeWaitingStrategy strategy, int count) { super(strategy); if(count <= 0) throw new IllegalArgumentException(); this.count = Math.min(COUNT_THRESHOLD, count); } @Override public Cube mapLogic(Cube cube) throws Exception { if(cube == null || cube == EmptyObject.emptyCube) return EmptyObject.emptyCube; String target = URLMapper.CUBE_REBALANCING_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("cube_symbol", cube.getSymbol()) .addParameter("count", count) .addParameter("page", 1); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); processCube(cube, node); return cube; } private void processCube(Cube cube, JsonNode node) {<FILL_FUNCTION_BODY>} }
JsonNode list = node.get("list"); List<Rebalancing.TrendBlock> history = new ArrayList<>(); for (JsonNode jsonNode : list) { for (JsonNode jn : jsonNode.get("rebalancing_histories")) { String stock_name = jn.get("stock_name").asText(); String stock_symbol = jn.get("stock_symbol").asText(); String created_at = jn.get("created_at").asText(); String prev_price = jn.get("prev_price").asText(); String price = jn.get("price").asText(); String prev_weight = jn.get("prev_weight").asText(); String target_weight = jn.get("target_weight").asText(); String weight = jn.get("weight").asText(); String rebalancing_id = jn.get("rebalancing_id").asText(); Rebalancing.TrendBlock trendBlock = new Rebalancing.TrendBlock( stock_name, stock_symbol, created_at, prev_price, price, prev_weight, target_weight, weight, rebalancing_id); history.add(trendBlock); } } Rebalancing rebalancing = new Rebalancing(history); cube.setRebalancing(rebalancing);
437
355
792
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public org.decaywood.entity.Cube apply(org.decaywood.entity.Cube) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/cubeFirst/CubeToCubeWithTrendMapper.java
CubeToCubeWithTrendMapper
mapLogic
class CubeToCubeWithTrendMapper extends AbstractMapper<Cube, Cube> { private final long since; private final long until; public CubeToCubeWithTrendMapper(Date since, Date until) { this(null, since, until); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param since 走线计算起始时间 * @param until 走线计算结束时间 */ public CubeToCubeWithTrendMapper( TimeWaitingStrategy strategy, Date since, Date until) { super(strategy); if(since == null || until == null || since.after(until)) throw new IllegalArgumentException("Null Pointer"); this.since = since.getTime(); this.until = until.getTime(); } @Override public Cube mapLogic(Cube cube) throws Exception {<FILL_FUNCTION_BODY>} private void processCube(Cube cube, JsonNode node) { JsonNode cubeNode = node.get(0); JsonNode SH300Node = node.get(1); CubeTrend cubeTrend = processCubeNode(cubeNode); MarketIndexTrend marketIndexTrend = processSH00Node(SH300Node); cube.setCubeTrend(cubeTrend); cube.setMarketIndexTrend(marketIndexTrend); } private CubeTrend processCubeNode(JsonNode node) { JsonNode trendNode = node.get("list"); List<CubeTrend.TrendBlock> blocks = new ArrayList<>(); for (JsonNode jsonNode : trendNode) { String time = jsonNode.get("time").asText(); String date = jsonNode.get("date").asText(); String value = jsonNode.get("value").asText(); String percent = jsonNode.get("percent").asText(); CubeTrend.TrendBlock trendBlock = new CubeTrend.TrendBlock( time, date, value, percent); blocks.add(trendBlock); } if(blocks.isEmpty()) return EmptyObject.emptyCubeTrend; return new CubeTrend( node.get("symbol").asText(), node.get("name").asText(), blocks.get(0).getTime(), blocks.get(blocks.size() - 1).getTime(), blocks); } private MarketIndexTrend processSH00Node(JsonNode node) { JsonNode trendNode = node.get("list"); List<MarketIndexTrend.TrendBlock> blocks = new ArrayList<>(); for (JsonNode jsonNode : trendNode) { String time = jsonNode.get("time").asText(); String date = jsonNode.get("date").asText(); String value = jsonNode.get("value").asText(); String percent = jsonNode.get("percent").asText(); MarketIndexTrend.TrendBlock trendBlock = new MarketIndexTrend.TrendBlock( time, date, value, percent); blocks.add(trendBlock); } if(blocks.isEmpty()) return EmptyObject.emptyMarketIndexTrend; return new MarketIndexTrend( node.get("symbol").asText(), node.get("name").asText(), blocks.get(0).getTime(), blocks.get(blocks.size() - 1).getTime(), blocks); } }
if(cube == null || cube == EmptyObject.emptyCube) return EmptyObject.emptyCube; String target = URLMapper.CUBE_TREND_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("cube_symbol", cube.getSymbol()) .addParameter("since", since) .addParameter("until", until); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); processCube(cube, node); return cube;
929
160
1,089
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public org.decaywood.entity.Cube apply(org.decaywood.entity.Cube) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/dateFirst/DateToLongHuBangStockMapper.java
DateToLongHuBangStockMapper
mapLogic
class DateToLongHuBangStockMapper extends AbstractMapper<Date, List<Stock>> { public DateToLongHuBangStockMapper() { this(null); } /** * @param strategy 超时等待策略(null则设置为默认等待策略) */ public DateToLongHuBangStockMapper(TimeWaitingStrategy strategy) { super(strategy); } @Override public List<Stock> mapLogic(Date date) throws Exception {<FILL_FUNCTION_BODY>} private List<Stock> processNode(JsonNode node, Date date) { List<Stock> stocks = new ArrayList<>(); for (JsonNode jsonNode : node.get("list")) { String name = jsonNode.get("name").asText(); String symbol = jsonNode.get("symbol").asText(); Stock stock = new Stock(name, symbol); stock.setStockQueryDate(date); stocks.add(stock); } return stocks; } }
String dateParam = DateParser.getTimePrefix(date, false); String target = URLMapper.LONGHUBANG_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("date", dateParam); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); return processNode(node, date);
274
111
385
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.Stock> apply(java.util.Date) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/industryFirst/IndustryToStocksMapper.java
IndustryToStocksMapper
mapLogic
class IndustryToStocksMapper extends AbstractMapper<Industry, List<Stock>> { /** * @param strategy 超时等待策略(null则设置为默认等待策略) */ public IndustryToStocksMapper(TimeWaitingStrategy strategy) { super(strategy); } public IndustryToStocksMapper() { this(null); } @Override public List<Stock> mapLogic(Industry industry) throws Exception {<FILL_FUNCTION_BODY>} private List<Stock> parserJson(JsonNode node) { List<Stock> stocks = new ArrayList<>(); JsonNode data = node.get("data"); for (JsonNode jsonNode : data.get("list")) { Stock stock = new Stock(jsonNode.get("name").asText(), jsonNode.get("symbol").asText()); stocks.add(stock); } return stocks; } }
if(industry == null || industry == EmptyObject.emptyIndustry) return new ArrayList<>(); String target = URLMapper.INDUSTRY_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target); builder.addParameter("page", 1) .addParameter("size", 500) .addParameter("order", "desc") .addParameter("order_by", "percent") .addParameter("exchange", "CN") .addParameter("market", "CN"); String info = industry.getIndustryInfo(); if (info.startsWith("#")) info = info.substring(1); for (String s : info.split("&")) { String[] keyAndVal = s.split("="); if ("level2code".equalsIgnoreCase(keyAndVal[0])) { builder.addParameter("ind_code", keyAndVal[1]); } } builder.addParameter("_", System.currentTimeMillis()); URL url = new URL(builder.build()); String json = request(url); JsonNode jsonNode = mapper.readTree(json); return parserJson(jsonNode);
247
301
548
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public List<org.decaywood.entity.Stock> apply(org.decaywood.entity.Industry) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/stockFirst/StockToCapitalFlowEntryMapper.java
StockToCapitalFlowEntryMapper
processNode
class StockToCapitalFlowEntryMapper extends AbstractMapper<Stock, Entry<Stock, CapitalFlow>> { public StockToCapitalFlowEntryMapper() { this(null); } /** * @param strategy 超时等待策略(null则设置为默认等待策略) */ public StockToCapitalFlowEntryMapper(TimeWaitingStrategy strategy) { super(strategy, URLMapper.NETEASE_MAIN_PAGE.toString()); } @Override public Entry<Stock, CapitalFlow> mapLogic(Stock stock) throws Exception { if(stock == null || stock == EmptyObject.emptyStock) return new Entry<>(EmptyObject.emptyStock, EmptyObject.emptyCapitalFlow); String no = stock.getStockNo().substring(2); String target = URLMapper.STOCK_CAPITAL_FLOW.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("symbol", no); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); return processNode(stock, node); } private Entry<Stock, CapitalFlow> processNode(Stock stock, JsonNode node) {<FILL_FUNCTION_BODY>} }
String capitalInflow = node.get("jlr_shishi").asText(); JsonNode subNode = node.get("jlr_json"); String largeQuantity = subNode.get(0).get("value").asText(); String midQuantity = subNode.get(1).get("value").asText(); String smallQuantity = subNode.get(2).get("value").asText(); String largeQuantBuy = node.get("dd_buy").asText(); String largeQuantSell = node.get("dd_sell").asText(); String largeQuantDealProp = node.get("percent").asText().replace("%", ""); String fiveDayInflow = node.get("jlr_5day_total").asText(); JsonNode fiveDayInflow_json = node.get("jlr_5day_json"); List<Double> fiveDayInflows = new ArrayList<>(); for (JsonNode jsonNode : fiveDayInflow_json) { Double val = jsonNode.get("value").asDouble(); fiveDayInflows.add(val); } CapitalFlow capitalFlow = new CapitalFlow( capitalInflow, largeQuantity, midQuantity, smallQuantity, largeQuantBuy, largeQuantSell, largeQuantDealProp, fiveDayInflow, fiveDayInflows ); return new Entry<>(stock, capitalFlow);
345
350
695
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public Entry<org.decaywood.entity.Stock,org.decaywood.entity.CapitalFlow> apply(org.decaywood.entity.Stock) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/stockFirst/StockToLongHuBangMapper.java
StockToLongHuBangMapper
composeInfo
class StockToLongHuBangMapper extends AbstractMapper <Stock, LongHuBangInfo> { public StockToLongHuBangMapper() { this(null); } /** * @param strategy 超时等待策略(null则设置为默认等待策略) */ public StockToLongHuBangMapper(TimeWaitingStrategy strategy) { super(strategy); } @Override public LongHuBangInfo mapLogic(Stock stock) throws Exception { if(stock == null || stock == EmptyObject.emptyStock) return EmptyObject.emptyLongHuBangInfo; Date date = stock.getStockQueryDate(); if (date == EmptyObject.emptyDate) throw new IllegalArgumentException("lost parameter: stockQueryDate"); String dateParam = DateParser.getTimePrefix(date, false); String target = URLMapper.LONGHUBANG_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("date", dateParam) .addParameter("symbol", stock.getStockNo()); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); return processNode(stock, node); } private LongHuBangInfo processNode(Stock stock, JsonNode node) { JsonNode detail = node.get("detail"); JsonNode buyListNode = detail.get("tqQtBizunittrdinfoBuyList"); JsonNode saleListNode = detail.get("tqQtBizunittrdinfoSaleList"); Set<LongHuBangInfo.BizsunitInfo> buyList = new HashSet<>(); Set<LongHuBangInfo.BizsunitInfo> saleList = new HashSet<>(); for (JsonNode jsonNode : buyListNode) { LongHuBangInfo.BizsunitInfo info = composeInfo(jsonNode); buyList.add(info); } for (JsonNode jsonNode : saleListNode) { LongHuBangInfo.BizsunitInfo info = composeInfo(jsonNode); saleList.add(info); } return new LongHuBangInfo(stock, stock.getStockQueryDate(), buyList, saleList); } private LongHuBangInfo.BizsunitInfo composeInfo(JsonNode jsonNode) {<FILL_FUNCTION_BODY>} }
String bizsunitcode = jsonNode.get("bizsunitcode").asText(); String bizsunitname = jsonNode.get("bizsunitname").asText(); String buyamt = jsonNode.get("buyamt").asText(); String saleamt = jsonNode.get("saleamt").asText(); String tradedate = jsonNode.get("tradedate").asText(); return new LongHuBangInfo.BizsunitInfo(bizsunitcode, bizsunitname, buyamt, saleamt, tradedate);
643
151
794
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public org.decaywood.entity.LongHuBangInfo apply(org.decaywood.entity.Stock) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/stockFirst/StockToStockWithAttributeMapper.java
StockToStockWithAttributeMapper
mapLogic
class StockToStockWithAttributeMapper extends AbstractMapper<Stock, Stock> { /** * @param strategy 超时等待策略(null则设置为默认等待策略) */ public StockToStockWithAttributeMapper(TimeWaitingStrategy strategy) { super(strategy); } public StockToStockWithAttributeMapper() { this(null); } @Override public Stock mapLogic(Stock stock) throws Exception {<FILL_FUNCTION_BODY>} }
if(stock == null || stock == EmptyObject.emptyStock) return EmptyObject.emptyStock; String target = URLMapper.STOCK_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("code", stock.getStockNo()); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); node = node.get(stock.getStockNo()); stock.setTime(node.get("time").asText()); stock.setCurrency_unit(node.get("currency_unit").asText()); stock.setCurrent(node.get("current").asText()); stock.setVolume(node.get("volume").asText()); stock.setPercentage(node.get("percentage").asText()); stock.setChange(node.get("change").asText()); stock.setOpen(node.get("open").asText()); stock.setHigh(node.get("high").asText()); stock.setLow(node.get("low").asText()); stock.setAmplitude(node.get("amplitude").asText()); stock.setFall_stop(node.get("fall_stop").asText()); stock.setRise_stop(node.get("rise_stop").asText()); stock.setClose(node.get("close").asText()); stock.setLast_close(node.get("last_close").asText()); stock.setHigh52Week(node.get("high52week").asText()); stock.setLow52week(node.get("low52week").asText()); stock.setMarketCapital(node.get("marketCapital").asText()); stock.setFloat_market_capital(node.get("float_market_capital").asText()); stock.setFloat_shares(node.get("float_shares").asText()); stock.setTotalShares(node.get("totalShares").asText()); stock.setEps(node.get("eps").asText()); stock.setNet_assets(node.get("net_assets").asText()); stock.setPe_ttm(node.get("pe_ttm").asText()); stock.setPe_lyr(node.get("pe_lyr").asText()); stock.setDividend(node.get("dividend").asText()); stock.setPsr(node.get("psr").asText()); stock.setTurnover_rate(node.get("turnover_rate").asText()); stock.setAmount(node.get("amount").asText()); return stock;
139
673
812
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public org.decaywood.entity.Stock apply(org.decaywood.entity.Stock) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/stockFirst/StockToStockWithCompanyInfoMapper.java
StockToStockWithCompanyInfoMapper
processStock
class StockToStockWithCompanyInfoMapper extends AbstractMapper <Stock, Stock> { private Map<String, Industry> industryMap; private volatile boolean initializing; public StockToStockWithCompanyInfoMapper() { this(null); } /** * @param strategy 超时等待策略(null则设置为默认等待策略) */ public StockToStockWithCompanyInfoMapper(TimeWaitingStrategy strategy) { super(strategy); } private void initMap() throws Exception { industryMap = new HashMap<>(); String target = URLMapper.COMPREHENSIVE_PAGE.toString(); String content = request(new URL(target)); Document doc = Jsoup.parse(content); Elements element = doc.getElementsByClass("second-nav") .get(1).children() .get(3).children() .get(3).children() .select("a"); StringBuilder builder = new StringBuilder(); for (Element ele : element) { if (!ele.hasAttr("title") || !ele.hasAttr("href")) continue; builder.append(ele.attr("href")); industryMap.put(ele.attr("title"), new Industry(ele.attr("title"), builder.toString())); builder.delete(0, builder.length()); } } @Override public Stock mapLogic(Stock stock) throws Exception { if(stock == null || stock == EmptyObject.emptyStock) return EmptyObject.emptyStock; if(industryMap == null && !initializing) { initializing = true; initMap(); } else while (industryMap == null) { Thread.sleep(50); } String target = URLMapper.STOCK_INDUSTRY_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("symbol", stock.getStockNo()); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json).get("tqCompInfo"); processStock(stock, node); return stock; } private void processStock(Stock stock, JsonNode node) {<FILL_FUNCTION_BODY>} }
String compsname = node.get("compsname").asText(); String orgtype = node.get("orgtype").asText(); String founddate = node.get("founddate").asText(); String bizscope = node.get("bizscope").asText(); String majorbiz = node.get("majorbiz").asText(); String region = node.get("region").asText(); List<Industry> industries = new ArrayList<>(); JsonNode subNode = node.get("tqCompIndustryList"); for (JsonNode jsonNode : subNode) { String industryName = jsonNode.get("level2name").asText(); industries.add(industryMap.get(industryName).copy()); } CompanyInfo companyInfo = new CompanyInfo( compsname, orgtype, founddate, bizscope, majorbiz, region, industries); stock.setCompanyInfo(companyInfo);
592
241
833
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public org.decaywood.entity.Stock apply(org.decaywood.entity.Stock) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/stockFirst/StockToStockWithShareHolderTrendMapper.java
StockToStockWithShareHolderTrendMapper
processStock
class StockToStockWithShareHolderTrendMapper extends AbstractMapper<Stock, Stock> { private Date from; private Date to; public StockToStockWithShareHolderTrendMapper() { this(new Date(0), new Date()); } public StockToStockWithShareHolderTrendMapper(Date from, Date to) { this(null, from, to); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param from 查询起始时间 * @param to 查询结束时间 */ public StockToStockWithShareHolderTrendMapper(TimeWaitingStrategy strategy, Date from, Date to) { super(strategy); if(from.after(to)) throw new IllegalArgumentException(); this.from = from; this.to = to; } @Override public Stock mapLogic(Stock stock) throws Exception { if(stock == null || stock == EmptyObject.emptyStock) return EmptyObject.emptyStock; String target = URLMapper.STOCK_SHAREHOLDERS_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("symbol", stock.getStockNo()) .addParameter("page", 1) .addParameter("size", 500); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json).get("list"); processStock(stock, node); return stock; } private void processStock(Stock stock, JsonNode node) {<FILL_FUNCTION_BODY>} }
List<ShareHoldersTrend.TrendBlock> history = new ArrayList<>(); for (JsonNode jsonNode : node) { String enddate = jsonNode.get("enddate").asText(); Date date = DateParser.parseDate(enddate); if(from.after(date) || date.after(to)) continue; String totalshamt = jsonNode.get("totalshamt").asText(); String holdproportionpacc = jsonNode.get("holdproportionpacc").asText(); String totalshrto = jsonNode.get("totalshrto").asText(); String proportionchg = jsonNode.get("proportionchg").asText(); String proportiongrhalfyear = jsonNode.get("proportiongrhalfyear").asText(); String proportiongrq = jsonNode.get("proportiongrq").asText(); String avgholdsumgrhalfyear = jsonNode.get("avgholdsumgrhalfyear").asText(); String avgholdsumgrq = jsonNode.get("avgholdsumgrq").asText(); ShareHoldersTrend.TrendBlock block = new ShareHoldersTrend.TrendBlock(enddate, totalshamt, holdproportionpacc, totalshrto, proportionchg, proportiongrhalfyear, proportiongrq, avgholdsumgrhalfyear, avgholdsumgrq ); history.add(block); } ShareHoldersTrend trend = history.isEmpty() ? EmptyObject.emptyShareHoldersTrend : new ShareHoldersTrend(history); stock.setShareHoldersTrend(trend);
445
419
864
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public org.decaywood.entity.Stock apply(org.decaywood.entity.Stock) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/stockFirst/StockToStockWithStockTrendMapper.java
StockToStockWithStockTrendMapper
processStock
class StockToStockWithStockTrendMapper extends AbstractMapper<Stock, Stock> { private Period period; private Date from; private Date to; public StockToStockWithStockTrendMapper() { this(Period.DAY, null, null); } public StockToStockWithStockTrendMapper(Date from, Date to) { this(Period.DAY, from, to); } public StockToStockWithStockTrendMapper(Period period, Date from, Date to) { this(null, period, from, to); } public StockToStockWithStockTrendMapper(TimeWaitingStrategy strategy, Period period, Date from, Date to) { super(strategy); if (from == null || to == null) { Calendar calendar = Calendar.getInstance(); this.to = new Date(); calendar.setTime(this.to); calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 5); this.from = calendar.getTime(); } else { this.from = from; this.to = to; } if(this.to.before(this.from)) throw new IllegalArgumentException(); this.period = period; } @Override public Stock mapLogic(Stock stock) throws Exception { if(stock == null || stock == EmptyObject.emptyStock) return EmptyObject.emptyStock; String target = URLMapper.STOCK_TREND_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("symbol", stock.getStockNo()) .addParameter("period", period.toString()) .addParameter("type", "normal") .addParameter("begin", from.getTime()) .addParameter("end", to.getTime()); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json).get("chartlist"); processStock(stock, node); return stock; } private void processStock(Stock stock, JsonNode node) {<FILL_FUNCTION_BODY>} }
List<TrendBlock> history = new ArrayList<>(); for (JsonNode jsonNode : node) { String volume = jsonNode.get("volume").asText(); String open = jsonNode.get("open").asText(); String high = jsonNode.get("high").asText(); String close = jsonNode.get("close").asText(); String low = jsonNode.get("low").asText(); String chg = jsonNode.get("chg").asText(); String percent = jsonNode.get("percent").asText(); String turnrate = jsonNode.get("turnrate").asText(); String ma5 = jsonNode.get("ma5").asText(); String ma10 = jsonNode.get("ma10").asText(); String ma20 = jsonNode.get("ma20").asText(); String ma30 = jsonNode.get("ma30").asText(); String dif = jsonNode.get("dif").asText(); String dea = jsonNode.get("dea").asText(); String macd = jsonNode.get("macd").asText(); String time = jsonNode.get("time").asText(); TrendBlock block = new TrendBlock( volume, open, high, close, low, chg, percent, turnrate, ma5, ma10, ma20, ma30, dif, dea, macd, time); history.add(block); } StockTrend trend = history.isEmpty() ? EmptyObject.emptyStockTrend : new StockTrend(stock.getStockNo(), period, history); stock.setStockTrend(trend);
570
421
991
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public org.decaywood.entity.Stock apply(org.decaywood.entity.Stock) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/stockFirst/StockToVIPFollowerCountEntryMapper.java
StockToVIPFollowerCountEntryMapper
parseHtmlToJsonNode
class StockToVIPFollowerCountEntryMapper extends AbstractMapper <Stock, Entry<Stock, Integer>> { private static final String REQUEST_PREFIX = URLMapper.MAIN_PAGE + "/S/"; private static final String REQUEST_SUFFIX = "/follows?page="; private int VIPFriendsCountShreshold; private int latestK_NewFollowers; public StockToVIPFollowerCountEntryMapper() { this(10000, 5); } public StockToVIPFollowerCountEntryMapper(int VIPFriendsCountShreshold, int latestK_NewFollowers) { this(null, VIPFriendsCountShreshold, latestK_NewFollowers); } /** * * @param strategy 超时等待策略(null则设置为默认等待策略) * @param VIPFriendsCountShreshold 是否为大V的粉丝阈值(超过这个阈值视为大V) * @param latestK_NewFollowers 只将最近K个新增用户纳入计算范围 */ public StockToVIPFollowerCountEntryMapper(TimeWaitingStrategy strategy, int VIPFriendsCountShreshold, int latestK_NewFollowers) { super(strategy); if(VIPFriendsCountShreshold < 0 || latestK_NewFollowers < 0) throw new IllegalArgumentException(); this.VIPFriendsCountShreshold = VIPFriendsCountShreshold; this.latestK_NewFollowers = latestK_NewFollowers; } @Override public Entry<Stock, Integer> mapLogic(Stock stock) throws Exception { if(stock == null || stock == EmptyObject.emptyStock) return new Entry<>(EmptyObject.emptyStock, 0); String stockNo = stock.getStockNo(); int count = 0; for (int i = 1; i < latestK_NewFollowers; i++) { String reqUrl = REQUEST_PREFIX + stockNo + REQUEST_SUFFIX + i; URL url = new URL(reqUrl); String content; while (true) { try { content = request(url); break; } catch (Exception e) { System.out.println("Mapper: Network busy Retrying"); } } JsonNode node = parseHtmlToJsonNode(content).get("followers"); if(node.size() == 0) break; for (JsonNode jsonNode : node) { int followersCount = jsonNode.get("followers_count").asInt(); if(followersCount > VIPFriendsCountShreshold) count++; } } return new Entry<>(stock, count); } private JsonNode parseHtmlToJsonNode(String content) throws IOException {<FILL_FUNCTION_BODY>} }
Document doc = Jsoup.parse(content); String indexer1 = "follows="; String indexer2 = ";seajs.use"; StringBuilder builder = new StringBuilder( doc.getElementsByTag("script") .get(15) .dataNodes() .get(0) .attr("data")); int index = builder.indexOf(indexer1); builder.delete(0, index + indexer1.length()); index = builder.indexOf(indexer2); builder.delete(index, builder.length()); return mapper.readTree(builder.toString());
739
160
899
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public Entry<org.decaywood.entity.Stock,java.lang.Integer> apply(org.decaywood.entity.Stock) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/mapper/user/UserSetMapper.java
UserSetMapper
mapLogic
class UserSetMapper extends AbstractMapper<User.UserSetter, User.UserSetter> { public UserSetMapper() { super(null); } @Override protected User.UserSetter mapLogic(User.UserSetter obj) throws Exception {<FILL_FUNCTION_BODY>} }
String userId = obj.getUserId(); if (StringUtils.isEmpty(userId)) { return obj; } String target = URLMapper.USER_INFO_JSON.toString(); RequestParaBuilder builder = new RequestParaBuilder(target) .addParameter("id", userId); URL url = new URL(builder.build()); String json = request(url); JsonNode node = mapper.readTree(json); User user = JsonParser.parse(User::new, node); obj.setUser(user); return obj;
82
142
224
<methods>public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy) ,public void <init>(org.decaywood.timeWaitingStrategy.TimeWaitingStrategy, java.lang.String) ,public org.decaywood.entity.User.UserSetter apply(org.decaywood.entity.User.UserSetter) <variables>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/timeWaitingStrategy/DefaultTimeWaitingStrategy.java
DefaultTimeWaitingStrategy
waiting
class DefaultTimeWaitingStrategy implements TimeWaitingStrategy { private final long timeWaitingThreshold; private final long timeWaiting; private final int retryTime; public DefaultTimeWaitingStrategy() { this(10000, 500, 10); } /** * * @param timeWaitingThreshold 超时等待阈值(最多等待阈值指定时间然后进入下一次请求尝试) * @param timeWaiting 起始等待时间 * @param retryTime 重试次数(超过次数抛出超时异常) */ public DefaultTimeWaitingStrategy(final long timeWaitingThreshold, long timeWaiting, int retryTime) { this.timeWaitingThreshold = timeWaitingThreshold; this.timeWaiting = timeWaiting; this.retryTime = retryTime; } @Override public void waiting(int loopTime) {<FILL_FUNCTION_BODY>} @Override public int retryTimes() { return retryTime; } }
try { long sleepTime = this.timeWaiting * (2 << loopTime); sleepTime = Math.min(sleepTime, timeWaitingThreshold); Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); }
287
76
363
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/utils/DatabaseAccessor.java
Holder
refreshConnections
class Holder { public static final DatabaseAccessor ACCESSOR = new DatabaseAccessor(); } private String jdbcDriver = ""; // 数据库驱动 private String dbUrl = ""; // 数据库 URL private String dbUsername = ""; // 数据库用户名 private String dbPassword = ""; // 数据库用户密码 private int initialConnections = 10; // 连接池的初始大小 private int autoIncreaseStep = 5;// 连接池自增步进 private int maxConnections = 50; // 连接池最大的大小 private List<PooledConnection> connections = null; // 存放连接池中数据库连接的向量 , 初始时为 null public DatabaseAccessor() { this( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/XueQiuSpider", "root", "123456" ); } public DatabaseAccessor(String jdbcDriver, String dbUrl, String dbUsername, String dbPassword) { this.jdbcDriver = jdbcDriver; this.dbUrl = dbUrl; this.dbUsername = dbUsername; this.dbPassword = dbPassword; try { createPool(); } catch (Exception e) { e.printStackTrace(); } } public synchronized void createPool() throws Exception { if (connections != null) return; Class.forName(this.jdbcDriver); connections = new CopyOnWriteArrayList<>(); createConnections(this.initialConnections); System.out.println(" 数据库连接池创建成功! "); } public synchronized Connection getConnection() { if (connections == null) return null; Connection conn; // if no available connection retry while (true) { wait(250); try { conn = getFreeConnection(); break; } catch (Exception e) { System.out.println("线程池忙,等待空闲线程"); } } return conn;// 返回获得的可用的连接 } public void returnConnection(Connection conn) { if (connections == null) { System.out.println(" 连接池不存在,无法返回此连接到连接池中 !"); return; } PooledConnection connection = this.connections.stream() .filter(x -> x.getConnection() == conn) .findAny() .orElse(emptyPooledConn); connection.setBusy(false); } public synchronized void refreshConnections() throws SQLException {<FILL_FUNCTION_BODY>
if (connections == null) { System.out.println(" 连接池不存在,无法刷新 !"); return; } for (PooledConnection connection : connections) { if (connection.isBusy()) wait(5000); // 关闭此连接,用一个新的连接代替它。 closeConnection(connection.getConnection()); connection.setConnection(newConnection()); connection.setBusy(false); }
710
121
831
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/utils/DateParser.java
DateParser
getTimePrefix
class DateParser { private static final Date quarter1; private static final Date quarter2; private static final Date quarter3; private static final Date quarter4; static { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); calendar.set(year, Calendar.MARCH, 31, 23, 59, 59); quarter1 = calendar.getTime(); calendar.set(year, Calendar.JUNE, 30, 23, 59, 59); quarter2 = calendar.getTime(); calendar.set(year, Calendar.SEPTEMBER, 30, 23, 59, 59); quarter3 = calendar.getTime(); calendar.set(year, Calendar.DECEMBER, 31, 23, 59, 59); quarter4 = calendar.getTime(); } public static Date parseToDate(String time) { DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy", Locale.ENGLISH); try { return dateFormat.parse(time); } catch (Exception e) { e.printStackTrace(); } return null; } public static String getTimePrefix(boolean quarterScope) { return getTimePrefix(new Date(), quarterScope); } public static String getTimePrefix(Date date, boolean quarterScope) {<FILL_FUNCTION_BODY>} public static Date parseDate(String yyyymmdd) { if(yyyymmdd == null || yyyymmdd.length() != 8 || !isdigit(yyyymmdd)) throw new IllegalArgumentException(); Calendar calendar = Calendar.getInstance(); int diff = Calendar.JANUARY - 1; int year = Integer.parseInt(yyyymmdd.substring(0, 4)); int month = Integer.parseInt(yyyymmdd.substring(4, 6)); int day = Integer.parseInt(yyyymmdd.substring(6, 8)); calendar.set(year, month + diff, day); return calendar.getTime(); } private static boolean isdigit(String str) { for (char c : str.toCharArray()) if(!Character.isDigit(c)) return false; return true; } }
String time_prefix; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int diff = 1 - Calendar.JANUARY; int month = calendar.get(Calendar.MONTH) + diff; int day = calendar.get(Calendar.DATE); if(quarterScope) { year = calendar.get(Calendar.YEAR); if (date.after(quarter3)) calendar.setTime(quarter3); else if(date.after(quarter2)) calendar.setTime(quarter2); else if(date.after(quarter1)) calendar.setTime(quarter1); else { year--; calendar.setTime(quarter4); } month = calendar.get(Calendar.MONTH) + diff; day = calendar.get(Calendar.DATE); } time_prefix = String.valueOf(year) + String.format("%02d", month) + String.format("%02d", day); return time_prefix;
629
274
903
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/utils/FileLoader.java
FileLoader
loadFileContent
class FileLoader { private static final String COOKIE_FLUSH_PATH = "cookie/index.txt"; private static final String ROOT_PATH = FileLoader.class.getResource("").getPath(); private static final Map<String, String> cookie = new ConcurrentHashMap<>();//多线程写状态,存在并发 /** * 加载最新cookie * @param key 关键字 * @return cookie */ public static String loadCookie(String key) { String cookies = System.getProperty("cookies"); if (StringUtils.isNotNull(cookies)) { return cookies; } if(cookie.containsKey(key)) return cookie.get(key); return EmptyObject.emptyString; } /** * 更新cookie * @param cookie cookie内容 * @param key 关键字 */ public static void updateCookie(String cookie, String key) { FileLoader.cookie.put(key, cookie); String replacedKey = key.contains(".com") ? key.substring(7, key.indexOf(".com")) : key; updateCookie(COOKIE_FLUSH_PATH, cookie, replacedKey); } public static void updateCookie(String rawPath, String text, String key) { updateCookie(rawPath, text, key, new StringBuilder(), true); } /** * 若文件不存在则创建文件 * @param rawPath 文件相对路径 * @param text 更新内容 * @param key 文件名字 * @param append 是否追加 */ public static void updateCookie(String rawPath, String text, String key, StringBuilder builder, boolean append) { String path = ROOT_PATH + rawPath; File cookie = new File(path); String p; if(!cookie.exists()) updateCookie(builder.append("../").toString() + rawPath, text, key, builder, append); else { try { p = path.replace("index", key); File file = new File(p); boolean success = true; if(!file.exists()) success = file.createNewFile(); if(!success) throw new Exception(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(p, append))) { writer.write(text); } } catch (Exception e) { System.out.println("FileLoader -> 写入失败!"); } } } /** * 加载文件内容(文件必须存在) * @param rawPath 文件相对位置 * @return File */ private static File loadFile(String rawPath, StringBuilder builder) { String path = ROOT_PATH + rawPath; File file = new File(path); if(!file.exists()) return loadFile(builder.append("../").toString() + rawPath, builder); else return file; } /** * 加载文件内容(文件必须存在) * @param rawPath 文件相对位置 * @return 文件内容 */ private static String loadFileContent(String rawPath, StringBuilder builder) {<FILL_FUNCTION_BODY>} public static File loadFile(String rawPath) { return loadFile(rawPath, new StringBuilder()); } public static String loadFileContent(String rawPath) { return loadFileContent(rawPath, new StringBuilder()); } }
File file = loadFile(rawPath, builder); StringBuilder content = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String text; while ((text = reader.readLine()) != null) { content.append(text); } } catch (IOException e) { System.out.println("FileLoader -> 读取失败!"); } return content.toString();
893
116
1,009
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/utils/HttpRequestHelper.java
HttpRequestHelper
request
class HttpRequestHelper { private Map<String, String> config; private boolean post; private boolean gzip; public HttpRequestHelper(String webSite) { this(webSite, true); } public HttpRequestHelper(String webSite, boolean gzip) { this.config = new HashMap<>(); if (gzip) { this.gzipDecode() .addToHeader("Accept-Encoding", "gzip,deflate,sdch"); } else { this.addToHeader("Accept-Encoding", "utf-8"); } this.addToHeader("Referer", webSite) .addToHeader("Cookie", FileLoader.loadCookie(webSite)) .addToHeader("Host", "xueqiu.com"); } public HttpRequestHelper post() { this.post = true; return this; } public HttpRequestHelper gzipDecode() { this.gzip = true; return this; } public HttpRequestHelper addToHeader(String key, String val) { this.config.put(key, val); return this; } public HttpRequestHelper addToHeader(String key, int val) { this.config.put(key, String.valueOf(val)); return this; } public String request(URL url) throws IOException { return request(url, this.config); } public String request(URL url, Map<String, String> config) throws IOException {<FILL_FUNCTION_BODY>} }
HttpURLConnection httpURLConn = null; try { httpURLConn = (HttpURLConnection) url.openConnection(); if (post) httpURLConn.setRequestMethod("POST"); httpURLConn.setDoOutput(true); for (Map.Entry<String, String> entry : config.entrySet()) httpURLConn.setRequestProperty(entry.getKey(), entry.getValue()); httpURLConn.connect(); InputStream in = httpURLConn.getInputStream(); if (gzip) in = new GZIPInputStream(in); BufferedReader bd = new BufferedReader(new InputStreamReader(in)); StringBuilder builder = new StringBuilder(); String text; while ((text = bd.readLine()) != null) builder.append(text); return builder.toString(); } finally { if (httpURLConn != null) httpURLConn.disconnect(); }
403
237
640
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/utils/JsonParser.java
JsonParser
parse
class JsonParser { public static <T> List<T> parseArray(Supplier<T> supplier, BiConsumer<T, JsonNode> consumer, JsonNode jsonNode) { List<T> res = new ArrayList<>(); for (JsonNode node : jsonNode) { T parse = parse(supplier, node); consumer.accept(parse, node); res.add(parse); } return res; } public static <T> T parse(Supplier<T> supplier, JsonNode jsonNode) {<FILL_FUNCTION_BODY>} }
T t = supplier.get(); ReflectionUtils.doWithFields(t.getClass(), field -> { ReflectionUtils.makeAccessible(field); String v = Optional.ofNullable(jsonNode.get(field.getName())).map(JsonNode::asText).orElse(null); field.set(t, v); }, f -> f.getType() == String.class); return t;
146
108
254
<no_super_class>
decaywood_XueQiuSuperSpider
XueQiuSuperSpider/src/main/java/org/decaywood/utils/StringUtils.java
StringUtils
unicode2String
class StringUtils { public static boolean isNull(String string) { return !isNotNull(string); } public static boolean isNotNull(String string) { return string != null; } public static boolean isNumeric(String test) { return test != null && test.length() > 0 && test.chars().allMatch(Character::isDigit); } public static boolean nullOrEmpty(String... args) { return Arrays.stream(args) .anyMatch(x -> x == null || x.length() == 0 || EmptyObject.emptyString.equals(x)); } public static String string2Unicode(String string) { StringBuilder unicode = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); unicode.append("\\u").append(Integer.toHexString(c)); } return unicode.toString(); } public static String unicode2String(String unicode) {<FILL_FUNCTION_BODY>} }
StringBuilder string = new StringBuilder(); String[] hex = unicode.split("\\\\u"); for (int i = 1; i < hex.length; i++) { int data = Integer.parseInt(hex[i], 16); string.append((char) data); } return string.toString();
287
86
373
<no_super_class>
brianfrankcooper_YCSB
YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java
AerospikeClient
init
class AerospikeClient extends site.ycsb.DB { private static final String DEFAULT_HOST = "localhost"; private static final String DEFAULT_PORT = "3000"; private static final String DEFAULT_TIMEOUT = "10000"; private static final String DEFAULT_NAMESPACE = "ycsb"; private String namespace = null; private com.aerospike.client.AerospikeClient client = null; private Policy readPolicy = new Policy(); private WritePolicy insertPolicy = new WritePolicy(); private WritePolicy updatePolicy = new WritePolicy(); private WritePolicy deletePolicy = new WritePolicy(); @Override public void init() throws DBException {<FILL_FUNCTION_BODY>} @Override public void cleanup() throws DBException { client.close(); } @Override public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { try { Record record; if (fields != null) { record = client.get(readPolicy, new Key(namespace, table, key), fields.toArray(new String[fields.size()])); } else { record = client.get(readPolicy, new Key(namespace, table, key)); } if (record == null) { System.err.println("Record key " + key + " not found (read)"); return Status.ERROR; } for (Map.Entry<String, Object> entry: record.bins.entrySet()) { result.put(entry.getKey(), new ByteArrayByteIterator((byte[])entry.getValue())); } return Status.OK; } catch (AerospikeException e) { System.err.println("Error while reading key " + key + ": " + e); return Status.ERROR; } } @Override public Status scan(String table, String start, int count, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { System.err.println("Scan not implemented"); return Status.ERROR; } private Status write(String table, String key, WritePolicy writePolicy, Map<String, ByteIterator> values) { Bin[] bins = new Bin[values.size()]; int index = 0; for (Map.Entry<String, ByteIterator> entry: values.entrySet()) { bins[index] = new Bin(entry.getKey(), entry.getValue().toArray()); ++index; } Key keyObj = new Key(namespace, table, key); try { client.put(writePolicy, keyObj, bins); return Status.OK; } catch (AerospikeException e) { System.err.println("Error while writing key " + key + ": " + e); return Status.ERROR; } } @Override public Status update(String table, String key, Map<String, ByteIterator> values) { return write(table, key, updatePolicy, values); } @Override public Status insert(String table, String key, Map<String, ByteIterator> values) { return write(table, key, insertPolicy, values); } @Override public Status delete(String table, String key) { try { if (!client.delete(deletePolicy, new Key(namespace, table, key))) { System.err.println("Record key " + key + " not found (delete)"); return Status.ERROR; } return Status.OK; } catch (AerospikeException e) { System.err.println("Error while deleting key " + key + ": " + e); return Status.ERROR; } } }
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY; updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY; Properties props = getProperties(); namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE); String host = props.getProperty("as.host", DEFAULT_HOST); String user = props.getProperty("as.user"); String password = props.getProperty("as.password"); int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT)); int timeout = Integer.parseInt(props.getProperty("as.timeout", DEFAULT_TIMEOUT)); readPolicy.timeout = timeout; insertPolicy.timeout = timeout; updatePolicy.timeout = timeout; deletePolicy.timeout = timeout; ClientPolicy clientPolicy = new ClientPolicy(); if (user != null && password != null) { clientPolicy.user = user; clientPolicy.password = password; } try { client = new com.aerospike.client.AerospikeClient(clientPolicy, host, port); } catch (AerospikeException e) { throw new DBException(String.format("Error while creating Aerospike " + "client for %s:%d.", host, port), e); }
964
341
1,305
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
brianfrankcooper_YCSB
YCSB/cloudspanner/src/main/java/site/ycsb/db/cloudspanner/CloudSpannerClient.java
CloudSpannerProperties
init
class CloudSpannerProperties { private CloudSpannerProperties() {} /** * The Cloud Spanner database name to use when running the YCSB benchmark, e.g. 'ycsb-database'. */ static final String DATABASE = "cloudspanner.database"; /** * The Cloud Spanner instance ID to use when running the YCSB benchmark, e.g. 'ycsb-instance'. */ static final String INSTANCE = "cloudspanner.instance"; /** * Choose between 'read' and 'query'. Affects both read() and scan() operations. */ static final String READ_MODE = "cloudspanner.readmode"; /** * The number of inserts to batch during the bulk loading phase. The default value is 1, which means no batching * is done. Recommended value during data load is 1000. */ static final String BATCH_INSERTS = "cloudspanner.batchinserts"; /** * Number of seconds we allow reads to be stale for. Set to 0 for strong reads (default). * For performance gains, this should be set to 10 seconds. */ static final String BOUNDED_STALENESS = "cloudspanner.boundedstaleness"; // The properties below usually do not need to be set explicitly. /** * The Cloud Spanner project ID to use when running the YCSB benchmark, e.g. 'myproject'. This is not strictly * necessary and can often be inferred from the environment. */ static final String PROJECT = "cloudspanner.project"; /** * The Cloud Spanner host name to use in the YCSB run. */ static final String HOST = "cloudspanner.host"; /** * Number of Cloud Spanner client channels to use. It's recommended to leave this to be the default value. */ static final String NUM_CHANNELS = "cloudspanner.channels"; } private static int fieldCount; private static boolean queriesForReads; private static int batchInserts; private static TimestampBound timestampBound; private static String standardQuery; private static String standardScan; private static final ArrayList<String> STANDARD_FIELDS = new ArrayList<>(); private static final String PRIMARY_KEY_COLUMN = "id"; private static final Logger LOGGER = Logger.getLogger(CloudSpannerClient.class.getName()); // Static lock for the class. private static final Object CLASS_LOCK = new Object(); // Single Spanner client per process. private static Spanner spanner = null; // Single database client per process. private static DatabaseClient dbClient = null; // Buffered mutations on a per object/thread basis for batch inserts. // Note that we have a separate CloudSpannerClient object per thread. private final ArrayList<Mutation> bufferedMutations = new ArrayList<>(); private static void constructStandardQueriesAndFields(Properties properties) { String table = properties.getProperty(CoreWorkload.TABLENAME_PROPERTY, CoreWorkload.TABLENAME_PROPERTY_DEFAULT); final String fieldprefix = properties.getProperty(CoreWorkload.FIELD_NAME_PREFIX, CoreWorkload.FIELD_NAME_PREFIX_DEFAULT); standardQuery = new StringBuilder() .append("SELECT * FROM ").append(table).append(" WHERE id=@key").toString(); standardScan = new StringBuilder() .append("SELECT * FROM ").append(table).append(" WHERE id>=@startKey LIMIT @count").toString(); for (int i = 0; i < fieldCount; i++) { STANDARD_FIELDS.add(fieldprefix + i); } } private static Spanner getSpanner(Properties properties, String host, String project) { if (spanner != null) { return spanner; } String numChannels = properties.getProperty(CloudSpannerProperties.NUM_CHANNELS); int numThreads = Integer.parseInt(properties.getProperty(Client.THREAD_COUNT_PROPERTY, "1")); SpannerOptions.Builder optionsBuilder = SpannerOptions.newBuilder() .setSessionPoolOption(SessionPoolOptions.newBuilder() .setMinSessions(numThreads) // Since we have no read-write transactions, we can set the write session fraction to 0. .setWriteSessionsFraction(0) .build()); if (host != null) { optionsBuilder.setHost(host); } if (project != null) { optionsBuilder.setProjectId(project); } if (numChannels != null) { optionsBuilder.setNumChannels(Integer.parseInt(numChannels)); } spanner = optionsBuilder.build().getService(); Runtime.getRuntime().addShutdownHook(new Thread("spannerShutdown") { @Override public void run() { spanner.close(); } }); return spanner; } @Override public void init() throws DBException {<FILL_FUNCTION_BODY>
synchronized (CLASS_LOCK) { if (dbClient != null) { return; } Properties properties = getProperties(); String host = properties.getProperty(CloudSpannerProperties.HOST); String project = properties.getProperty(CloudSpannerProperties.PROJECT); String instance = properties.getProperty(CloudSpannerProperties.INSTANCE, "ycsb-instance"); String database = properties.getProperty(CloudSpannerProperties.DATABASE, "ycsb-database"); fieldCount = Integer.parseInt(properties.getProperty( CoreWorkload.FIELD_COUNT_PROPERTY, CoreWorkload.FIELD_COUNT_PROPERTY_DEFAULT)); queriesForReads = properties.getProperty(CloudSpannerProperties.READ_MODE, "query").equals("query"); batchInserts = Integer.parseInt(properties.getProperty(CloudSpannerProperties.BATCH_INSERTS, "1")); constructStandardQueriesAndFields(properties); int boundedStalenessSeconds = Integer.parseInt(properties.getProperty( CloudSpannerProperties.BOUNDED_STALENESS, "0")); timestampBound = (boundedStalenessSeconds <= 0) ? TimestampBound.strong() : TimestampBound.ofMaxStaleness(boundedStalenessSeconds, TimeUnit.SECONDS); try { spanner = getSpanner(properties, host, project); if (project == null) { project = spanner.getOptions().getProjectId(); } dbClient = spanner.getDatabaseClient(DatabaseId.of(project, instance, database)); } catch (Exception e) { LOGGER.log(Level.SEVERE, "init()", e); throw new DBException(e); } LOGGER.log(Level.INFO, new StringBuilder() .append("\nHost: ").append(spanner.getOptions().getHost()) .append("\nProject: ").append(project) .append("\nInstance: ").append(instance) .append("\nDatabase: ").append(database) .append("\nUsing queries for reads: ").append(queriesForReads) .append("\nBatching inserts: ").append(batchInserts) .append("\nBounded staleness seconds: ").append(boundedStalenessSeconds) .toString()); }
1,306
589
1,895
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/ByteArrayByteIterator.java
ByteArrayByteIterator
toArray
class ByteArrayByteIterator extends ByteIterator { private final int originalOffset; private final byte[] str; private int off; private final int len; public ByteArrayByteIterator(byte[] s) { this.str = s; this.off = 0; this.len = s.length; originalOffset = 0; } public ByteArrayByteIterator(byte[] s, int off, int len) { this.str = s; this.off = off; this.len = off + len; originalOffset = off; } @Override public boolean hasNext() { return off < len; } @Override public byte nextByte() { byte ret = str[off]; off++; return ret; } @Override public long bytesLeft() { return len - off; } @Override public void reset() { off = originalOffset; } @Override public byte[] toArray() {<FILL_FUNCTION_BODY>} }
int size = (int) bytesLeft(); byte[] bytes = new byte[size]; System.arraycopy(str, off, bytes, 0, size); off = len; return bytes;
277
54
331
<methods>public non-sealed void <init>() ,public abstract long bytesLeft() ,public abstract boolean hasNext() ,public java.lang.Byte next() ,public int nextBuf(byte[], int) ,public abstract byte nextByte() ,public void remove() ,public void reset() ,public byte[] toArray() ,public java.lang.String toString() <variables>
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/ByteIterator.java
ByteIterator
nextBuf
class ByteIterator implements Iterator<Byte> { @Override public abstract boolean hasNext(); @Override public Byte next() { throw new UnsupportedOperationException(); } public abstract byte nextByte(); /** @return byte offset immediately after the last valid byte */ public int nextBuf(byte[] buf, int bufOff) {<FILL_FUNCTION_BODY>} public abstract long bytesLeft(); @Override public void remove() { throw new UnsupportedOperationException(); } /** Resets the iterator so that it can be consumed again. Not all * implementations support this call. * @throws UnsupportedOperationException if the implementation hasn't implemented * the method. */ public void reset() { throw new UnsupportedOperationException(); } /** Consumes remaining contents of this object, and returns them as a string. */ public String toString() { Charset cset = Charset.forName("UTF-8"); CharBuffer cb = cset.decode(ByteBuffer.wrap(this.toArray())); return cb.toString(); } /** Consumes remaining contents of this object, and returns them as a byte array. */ public byte[] toArray() { long left = bytesLeft(); if (left != (int) left) { throw new ArrayIndexOutOfBoundsException("Too much data to fit in one array!"); } byte[] ret = new byte[(int) left]; for (int i = 0; i < ret.length; i++) { ret[i] = nextByte(); } return ret; } }
int sz = bufOff; while (sz < buf.length && hasNext()) { buf[sz] = nextByte(); sz++; } return sz;
414
53
467
<no_super_class>
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/ClientThread.java
ClientThread
run
class ClientThread implements Runnable { // Counts down each of the clients completing. private final CountDownLatch completeLatch; private static boolean spinSleep; private DB db; private boolean dotransactions; private Workload workload; private int opcount; private double targetOpsPerMs; private int opsdone; private int threadid; private int threadcount; private Object workloadstate; private Properties props; private long targetOpsTickNs; private final Measurements measurements; /** * Constructor. * * @param db the DB implementation to use * @param dotransactions true to do transactions, false to insert data * @param workload the workload to use * @param props the properties defining the experiment * @param opcount the number of operations (transactions or inserts) to do * @param targetperthreadperms target number of operations per thread per ms * @param completeLatch The latch tracking the completion of all clients. */ public ClientThread(DB db, boolean dotransactions, Workload workload, Properties props, int opcount, double targetperthreadperms, CountDownLatch completeLatch) { this.db = db; this.dotransactions = dotransactions; this.workload = workload; this.opcount = opcount; opsdone = 0; if (targetperthreadperms > 0) { targetOpsPerMs = targetperthreadperms; targetOpsTickNs = (long) (1000000 / targetOpsPerMs); } this.props = props; measurements = Measurements.getMeasurements(); spinSleep = Boolean.valueOf(this.props.getProperty("spin.sleep", "false")); this.completeLatch = completeLatch; } public void setThreadId(final int threadId) { threadid = threadId; } public void setThreadCount(final int threadCount) { threadcount = threadCount; } public int getOpsDone() { return opsdone; } @Override public void run() {<FILL_FUNCTION_BODY>} private static void sleepUntil(long deadline) { while (System.nanoTime() < deadline) { if (!spinSleep) { LockSupport.parkNanos(deadline - System.nanoTime()); } } } private void throttleNanos(long startTimeNanos) { //throttle the operations if (targetOpsPerMs > 0) { // delay until next tick long deadline = startTimeNanos + opsdone * targetOpsTickNs; sleepUntil(deadline); measurements.setIntendedStartTimeNs(deadline); } } /** * The total amount of work this thread is still expected to do. */ int getOpsTodo() { int todo = opcount - opsdone; return todo < 0 ? 0 : todo; } }
try { db.init(); } catch (DBException e) { e.printStackTrace(); e.printStackTrace(System.out); return; } try { workloadstate = workload.initThread(props, threadid, threadcount); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); return; } //NOTE: Switching to using nanoTime and parkNanos for time management here such that the measurements // and the client thread have the same view on time. //spread the thread operations out so they don't all hit the DB at the same time // GH issue 4 - throws exception if _target>1 because random.nextInt argument must be >0 // and the sleep() doesn't make sense for granularities < 1 ms anyway if ((targetOpsPerMs > 0) && (targetOpsPerMs <= 1.0)) { long randomMinorDelay = ThreadLocalRandom.current().nextInt((int) targetOpsTickNs); sleepUntil(System.nanoTime() + randomMinorDelay); } try { if (dotransactions) { long startTimeNanos = System.nanoTime(); while (((opcount == 0) || (opsdone < opcount)) && !workload.isStopRequested()) { if (!workload.doTransaction(db, workloadstate)) { break; } opsdone++; throttleNanos(startTimeNanos); } } else { long startTimeNanos = System.nanoTime(); while (((opcount == 0) || (opsdone < opcount)) && !workload.isStopRequested()) { if (!workload.doInsert(db, workloadstate)) { break; } opsdone++; throttleNanos(startTimeNanos); } } } catch (Exception e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { measurements.setIntendedStartTimeNs(0); db.cleanup(); } catch (DBException e) { e.printStackTrace(); e.printStackTrace(System.out); } finally { completeLatch.countDown(); }
804
622
1,426
<no_super_class>
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/DBFactory.java
DBFactory
newDB
class DBFactory { private DBFactory() { // not used } public static DB newDB(String dbname, Properties properties, final Tracer tracer) throws UnknownDBException {<FILL_FUNCTION_BODY>} }
ClassLoader classLoader = DBFactory.class.getClassLoader(); DB ret; try { Class dbclass = classLoader.loadClass(dbname); ret = (DB) dbclass.newInstance(); } catch (Exception e) { e.printStackTrace(); return null; } ret.setProperties(properties); return new DBWrapper(ret, tracer);
62
107
169
<no_super_class>
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/GoodBadUglyDB.java
GoodBadUglyDB
delay
class GoodBadUglyDB extends DB { public static final String SIMULATE_DELAY = "gbudb.delays"; public static final String SIMULATE_DELAY_DEFAULT = "200,1000,10000,50000,100000"; private static final ReadWriteLock DB_ACCESS = new ReentrantReadWriteLock(); private long[] delays; public GoodBadUglyDB() { delays = new long[]{200, 1000, 10000, 50000, 200000}; } private void delay() {<FILL_FUNCTION_BODY>} /** * Initialize any state for this DB. Called once per DB instance; there is one DB instance per client thread. */ public void init() { int i = 0; for (String delay : getProperties().getProperty(SIMULATE_DELAY, SIMULATE_DELAY_DEFAULT).split(",")) { delays[i++] = Long.parseLong(delay); } } /** * Read a record from the database. Each field/value pair from the result will be stored in a HashMap. * * @param table The name of the table * @param key The record key of the record to read. * @param fields The list of fields to read, or null for all of them * @param result A HashMap of field/value pairs for the result * @return Zero on success, a non-zero error code on error */ public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { delay(); return Status.OK; } /** * Perform a range scan for a set of records in the database. Each field/value pair from the result will be stored * in a HashMap. * * @param table The name of the table * @param startkey The record key of the first record to read. * @param recordcount The number of records to read * @param fields The list of fields to read, or null for all of them * @param result A Vector of HashMaps, where each HashMap is a set field/value pairs for one record * @return Zero on success, a non-zero error code on error */ public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { delay(); return Status.OK; } /** * Update a record in the database. Any field/value pairs in the specified values HashMap will be written into the * record with the specified record key, overwriting any existing values with the same field name. * * @param table The name of the table * @param key The record key of the record to write. * @param values A HashMap of field/value pairs to update in the record * @return Zero on success, a non-zero error code on error */ public Status update(String table, String key, Map<String, ByteIterator> values) { delay(); return Status.OK; } /** * Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the * record with the specified record key. * * @param table The name of the table * @param key The record key of the record to insert. * @param values A HashMap of field/value pairs to insert in the record * @return Zero on success, a non-zero error code on error */ public Status insert(String table, String key, Map<String, ByteIterator> values) { delay(); return Status.OK; } /** * Delete a record from the database. * * @param table The name of the table * @param key The record key of the record to delete. * @return Zero on success, a non-zero error code on error */ public Status delete(String table, String key) { delay(); return Status.OK; } }
final Random random = ThreadLocalRandom.current(); double p = random.nextDouble(); int mod; if (p < 0.9) { mod = 0; } else if (p < 0.99) { mod = 1; } else if (p < 0.9999) { mod = 2; } else { mod = 3; } // this will make mod 3 pauses global Lock lock = mod == 3 ? DB_ACCESS.writeLock() : DB_ACCESS.readLock(); if (mod == 3) { System.out.println("OUCH"); } lock.lock(); try { final long baseDelayNs = MICROSECONDS.toNanos(delays[mod]); final int delayRangeNs = (int) (MICROSECONDS.toNanos(delays[mod + 1]) - baseDelayNs); final long delayNs = baseDelayNs + random.nextInt(delayRangeNs); final long deadline = System.nanoTime() + delayNs; do { LockSupport.parkNanos(deadline - System.nanoTime()); } while (System.nanoTime() < deadline && !Thread.interrupted()); } finally { lock.unlock(); }
1,043
337
1,380
<methods>public non-sealed void <init>() ,public void cleanup() throws site.ycsb.DBException,public abstract site.ycsb.Status delete(java.lang.String, java.lang.String) ,public java.util.Properties getProperties() ,public void init() throws site.ycsb.DBException,public abstract site.ycsb.Status insert(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status read(java.lang.String, java.lang.String, Set<java.lang.String>, Map<java.lang.String,site.ycsb.ByteIterator>) ,public abstract site.ycsb.Status scan(java.lang.String, java.lang.String, int, Set<java.lang.String>, Vector<HashMap<java.lang.String,site.ycsb.ByteIterator>>) ,public void setProperties(java.util.Properties) ,public abstract site.ycsb.Status update(java.lang.String, java.lang.String, Map<java.lang.String,site.ycsb.ByteIterator>) <variables>private java.util.Properties properties
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/InputStreamByteIterator.java
InputStreamByteIterator
toArray
class InputStreamByteIterator extends ByteIterator { private final long len; private final InputStream ins; private long off; private final boolean resetable; public InputStreamByteIterator(InputStream ins, long len) { this.len = len; this.ins = ins; off = 0; resetable = ins.markSupported(); if (resetable) { ins.mark((int) len); } } @Override public boolean hasNext() { return off < len; } @Override public byte nextByte() { int ret; try { ret = ins.read(); } catch (Exception e) { throw new IllegalStateException(e); } if (ret == -1) { throw new IllegalStateException("Past EOF!"); } off++; return (byte) ret; } @Override public long bytesLeft() { return len - off; } @Override public byte[] toArray() {<FILL_FUNCTION_BODY>} @Override public void reset() { if (resetable) { try { ins.reset(); ins.mark((int) len); off = 0; } catch (IOException e) { throw new IllegalStateException("Failed to reset the input stream", e); } } else { throw new UnsupportedOperationException(); } } }
int size = (int) bytesLeft(); byte[] bytes = new byte[size]; try { if (ins.read(bytes) < size) { throw new IllegalStateException("Past EOF!"); } } catch (IOException e) { throw new IllegalStateException(e); } off = len; return bytes;
379
93
472
<methods>public non-sealed void <init>() ,public abstract long bytesLeft() ,public abstract boolean hasNext() ,public java.lang.Byte next() ,public int nextBuf(byte[], int) ,public abstract byte nextByte() ,public void remove() ,public void reset() ,public byte[] toArray() ,public java.lang.String toString() <variables>