idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
37,000 | public Order placeOrder ( OrderParams orderParams , String variety ) throws KiteException , JSONException , IOException { String url = routes . get ( "orders.place" ) . replace ( ":variety" , variety ) ; Map < String , Object > params = new HashMap < > ( ) ; if ( orderParams . exchange != null ) params . put ( "exchange" , orderParams . exchange ) ; if ( orderParams . tradingsymbol != null ) params . put ( "tradingsymbol" , orderParams . tradingsymbol ) ; if ( orderParams . transactionType != null ) params . put ( "transaction_type" , orderParams . transactionType ) ; if ( orderParams . quantity != null ) params . put ( "quantity" , orderParams . quantity ) ; if ( orderParams . price != null ) params . put ( "price" , orderParams . price ) ; if ( orderParams . product != null ) params . put ( "product" , orderParams . product ) ; if ( orderParams . orderType != null ) params . put ( "order_type" , orderParams . orderType ) ; if ( orderParams . validity != null ) params . put ( "validity" , orderParams . validity ) ; if ( orderParams . disclosedQuantity != null ) params . put ( "disclosed_quantity" , orderParams . disclosedQuantity ) ; if ( orderParams . triggerPrice != null ) params . put ( "trigger_price" , orderParams . triggerPrice ) ; if ( orderParams . squareoff != null ) params . put ( "squareoff" , orderParams . squareoff ) ; if ( orderParams . stoploss != null ) params . put ( "stoploss" , orderParams . stoploss ) ; if ( orderParams . trailingStoploss != null ) params . put ( "trailing_stoploss" , orderParams . trailingStoploss ) ; if ( orderParams . tag != null ) params . put ( "tag" , orderParams . tag ) ; JSONObject jsonObject = new KiteRequestHandler ( proxy ) . postRequest ( url , params , apiKey , accessToken ) ; Order order = new Order ( ) ; order . orderId = jsonObject . getJSONObject ( "data" ) . getString ( "order_id" ) ; return order ; } | Places an order . |
37,001 | public Order cancelOrder ( String orderId , String variety ) throws KiteException , JSONException , IOException { String url = routes . get ( "orders.cancel" ) . replace ( ":variety" , variety ) . replace ( ":order_id" , orderId ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; JSONObject jsonObject = new KiteRequestHandler ( proxy ) . deleteRequest ( url , params , apiKey , accessToken ) ; Order order = new Order ( ) ; order . orderId = jsonObject . getJSONObject ( "data" ) . getString ( "order_id" ) ; return order ; } | Cancels an order . |
37,002 | public List < Order > getOrders ( ) throws KiteException , JSONException , IOException { String url = routes . get ( "orders" ) ; JSONObject response = new KiteRequestHandler ( proxy ) . getRequest ( url , apiKey , accessToken ) ; return Arrays . asList ( gson . fromJson ( String . valueOf ( response . get ( "data" ) ) , Order [ ] . class ) ) ; } | Fetches collection of orders from the orderbook . |
37,003 | public Map < String , List < Position > > getPositions ( ) throws KiteException , JSONException , IOException { Map < String , List < Position > > positionsMap = new HashMap < > ( ) ; JSONObject response = new KiteRequestHandler ( proxy ) . getRequest ( routes . get ( "portfolio.positions" ) , apiKey , accessToken ) ; JSONObject allPositions = response . getJSONObject ( "data" ) ; positionsMap . put ( "net" , Arrays . asList ( gson . fromJson ( String . valueOf ( allPositions . get ( "net" ) ) , Position [ ] . class ) ) ) ; positionsMap . put ( "day" , Arrays . asList ( gson . fromJson ( String . valueOf ( allPositions . get ( "day" ) ) , Position [ ] . class ) ) ) ; return positionsMap ; } | Retrieves the list of positions . |
37,004 | public JSONObject convertPosition ( String tradingSymbol , String exchange , String transactionType , String positionType , String oldProduct , String newProduct , int quantity ) throws KiteException , JSONException , IOException { Map < String , Object > params = new HashMap < > ( ) ; params . put ( "tradingsymbol" , tradingSymbol ) ; params . put ( "exchange" , exchange ) ; params . put ( "transaction_type" , transactionType ) ; params . put ( "position_type" , positionType ) ; params . put ( "old_product" , oldProduct ) ; params . put ( "new_product" , newProduct ) ; params . put ( "quantity" , quantity ) ; KiteRequestHandler kiteRequestHandler = new KiteRequestHandler ( proxy ) ; return kiteRequestHandler . putRequest ( routes . get ( "portfolio.positions.modify" ) , params , apiKey , accessToken ) ; } | Modifies an open position s product type . Only an MIS CNC and NRML positions can be converted . |
37,005 | public List < Instrument > getInstruments ( ) throws KiteException , IOException , JSONException { KiteRequestHandler kiteRequestHandler = new KiteRequestHandler ( proxy ) ; return readCSV ( kiteRequestHandler . getCSVRequest ( routes . get ( "market.instruments.all" ) , apiKey , accessToken ) ) ; } | Retrieves list of market instruments available to trade . |
37,006 | public Map < String , Quote > getQuote ( String [ ] instruments ) throws KiteException , JSONException , IOException { KiteRequestHandler kiteRequestHandler = new KiteRequestHandler ( proxy ) ; JSONObject jsonObject = kiteRequestHandler . getRequest ( routes . get ( "market.quote" ) , "i" , instruments , apiKey , accessToken ) ; Type type = new TypeToken < Map < String , Quote > > ( ) { } . getType ( ) ; return gson . fromJson ( String . valueOf ( jsonObject . get ( "data" ) ) , type ) ; } | Retrieves quote and market depth for an instrument |
37,007 | public Map < String , TriggerRange > getTriggerRange ( String [ ] instruments , String transactionType ) throws KiteException , JSONException , IOException { String url = routes . get ( "market.trigger_range" ) . replace ( ":transaction_type" , transactionType . toLowerCase ( ) ) ; JSONObject response = new KiteRequestHandler ( proxy ) . getRequest ( url , "i" , instruments , apiKey , accessToken ) ; Type type = new TypeToken < Map < String , TriggerRange > > ( ) { } . getType ( ) ; return gson . fromJson ( String . valueOf ( response . get ( "data" ) ) , type ) ; } | Retrieves buy or sell trigger range for Cover Orders . |
37,008 | public HistoricalData getHistoricalData ( Date from , Date to , String token , String interval , boolean continuous ) throws KiteException , IOException , JSONException { SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; Map < String , Object > params = new HashMap < > ( ) ; params . put ( "from" , format . format ( from ) ) ; params . put ( "to" , format . format ( to ) ) ; params . put ( "continuous" , continuous ? 1 : 0 ) ; String url = routes . get ( "market.historical" ) . replace ( ":instrument_token" , token ) . replace ( ":interval" , interval ) ; HistoricalData historicalData = new HistoricalData ( ) ; historicalData . parseResponse ( new KiteRequestHandler ( proxy ) . getRequest ( url , params , apiKey , accessToken ) ) ; return historicalData ; } | Retrieves historical data for an instrument . |
37,009 | public List < MFInstrument > getMFInstruments ( ) throws KiteException , IOException , JSONException { KiteRequestHandler kiteRequestHandler = new KiteRequestHandler ( proxy ) ; return readMfCSV ( kiteRequestHandler . getCSVRequest ( routes . get ( "mutualfunds.instruments" ) , apiKey , accessToken ) ) ; } | Retrieves mutualfunds instruments . |
37,010 | public MFOrder placeMFOrder ( String tradingsymbol , String transactionType , double amount , double quantity , String tag ) throws KiteException , IOException , JSONException { Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "tradingsymbol" , tradingsymbol ) ; params . put ( "transaction_type" , transactionType ) ; params . put ( "amount" , amount ) ; if ( transactionType . equals ( Constants . TRANSACTION_TYPE_SELL ) ) params . put ( "quantity" , quantity ) ; params . put ( "tag" , tag ) ; JSONObject response = new KiteRequestHandler ( proxy ) . postRequest ( routes . get ( "mutualfunds.orders.place" ) , params , apiKey , accessToken ) ; MFOrder MFOrder = new MFOrder ( ) ; MFOrder . orderId = response . getJSONObject ( "data" ) . getString ( "order_id" ) ; return MFOrder ; } | Place a mutualfunds order . |
37,011 | public boolean cancelMFOrder ( String orderId ) throws KiteException , IOException , JSONException { KiteRequestHandler kiteRequestHandler = new KiteRequestHandler ( proxy ) ; kiteRequestHandler . deleteRequest ( routes . get ( "mutualfunds.cancel_order" ) . replace ( ":order_id" , orderId ) , new HashMap < String , Object > ( ) , apiKey , accessToken ) ; return true ; } | If cancel is successful then api will respond as 200 and send back true else it will be sent back to user as KiteException . |
37,012 | public MFOrder getMFOrder ( String orderId ) throws KiteException , IOException , JSONException { JSONObject response = new KiteRequestHandler ( proxy ) . getRequest ( routes . get ( "mutualfunds.order" ) . replace ( ":order_id" , orderId ) , apiKey , accessToken ) ; return gson . fromJson ( response . get ( "data" ) . toString ( ) , MFOrder . class ) ; } | Retrieves individual mutualfunds order . |
37,013 | public MFSIP placeMFSIP ( String tradingsymbol , String frequency , int installmentDay , int instalments , int initialAmount , double amount ) throws KiteException , IOException , JSONException { Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "tradingsymbol" , tradingsymbol ) ; params . put ( "frequency" , frequency ) ; params . put ( "instalment_day" , installmentDay ) ; params . put ( "instalments" , instalments ) ; params . put ( "initial_amount" , initialAmount ) ; params . put ( "amount" , amount ) ; MFSIP MFSIP = new MFSIP ( ) ; JSONObject response = new KiteRequestHandler ( proxy ) . postRequest ( routes . get ( "mutualfunds.sips.place" ) , params , apiKey , accessToken ) ; MFSIP . orderId = response . getJSONObject ( "data" ) . getString ( "order_id" ) ; MFSIP . sipId = response . getJSONObject ( "data" ) . getString ( "sip_id" ) ; return MFSIP ; } | Place a mutualfunds sip . |
37,014 | public boolean modifyMFSIP ( String frequency , int day , int instalments , double amount , String status , String sipId ) throws KiteException , IOException , JSONException { Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "frequency" , frequency ) ; params . put ( "day" , day ) ; params . put ( "instalments" , instalments ) ; params . put ( "amount" , amount ) ; params . put ( "status" , status ) ; new KiteRequestHandler ( proxy ) . putRequest ( routes . get ( "mutualfunds.sips.modify" ) . replace ( ":sip_id" , sipId ) , params , apiKey , accessToken ) ; return true ; } | Modify a mutualfunds sip . |
37,015 | public boolean cancelMFSIP ( String sipId ) throws KiteException , IOException , JSONException { new KiteRequestHandler ( proxy ) . deleteRequest ( routes . get ( "mutualfunds.sip" ) . replace ( ":sip_id" , sipId ) , new HashMap < String , Object > ( ) , apiKey , accessToken ) ; return true ; } | Cancel a mutualfunds sip . |
37,016 | public MFSIP getMFSIP ( String sipId ) throws KiteException , IOException , JSONException { JSONObject response = new KiteRequestHandler ( proxy ) . getRequest ( routes . get ( "mutualfunds.sip" ) . replace ( ":sip_id" , sipId ) , apiKey , accessToken ) ; return gson . fromJson ( response . get ( "data" ) . toString ( ) , MFSIP . class ) ; } | Retrieve an individual sip . |
37,017 | public JSONObject invalidateAccessToken ( ) throws IOException , KiteException , JSONException { String url = routes . get ( "api.token" ) ; Map < String , Object > params = new HashMap < > ( ) ; params . put ( "api_key" , apiKey ) ; params . put ( "access_token" , accessToken ) ; return new KiteRequestHandler ( proxy ) . deleteRequest ( url , params , apiKey , accessToken ) ; } | Kills the session by invalidating the access token . |
37,018 | public JSONObject invalidateRefreshToken ( String refreshToken ) throws IOException , KiteException , JSONException { Map < String , Object > param = new HashMap < > ( ) ; param . put ( "refresh_token" , refreshToken ) ; param . put ( "api_key" , apiKey ) ; String url = routes . get ( "api.token" ) ; return new KiteRequestHandler ( proxy ) . deleteRequest ( url , param , apiKey , accessToken ) ; } | Kills the refresh token . |
37,019 | private List < Instrument > readCSV ( String input ) throws IOException { ICsvBeanReader beanReader = null ; File temp = File . createTempFile ( "tempfile" , ".tmp" ) ; BufferedWriter bw = new BufferedWriter ( new FileWriter ( temp ) ) ; bw . write ( input ) ; bw . close ( ) ; beanReader = new CsvBeanReader ( new FileReader ( temp ) , CsvPreference . STANDARD_PREFERENCE ) ; String [ ] header = beanReader . getHeader ( true ) ; CellProcessor [ ] processors = getProcessors ( ) ; Instrument instrument ; List < Instrument > instruments = new ArrayList < > ( ) ; while ( ( instrument = beanReader . read ( Instrument . class , header , processors ) ) != null ) { instruments . add ( instrument ) ; } return instruments ; } | This method parses csv and returns instrument list . |
37,020 | private CellProcessor [ ] getProcessors ( ) { CellProcessor [ ] processors = new CellProcessor [ ] { new NotNull ( new ParseLong ( ) ) , new NotNull ( new ParseLong ( ) ) , new NotNull ( ) , new org . supercsv . cellprocessor . Optional ( ) , new NotNull ( new ParseDouble ( ) ) , new org . supercsv . cellprocessor . Optional ( new ParseDate ( "yyyy-MM-dd" ) ) , new org . supercsv . cellprocessor . Optional ( ) , new NotNull ( new ParseDouble ( ) ) , new NotNull ( new ParseInt ( ) ) , new NotNull ( ) , new NotNull ( ) , new NotNull ( ) } ; return processors ; } | This method returns array of cellprocessor for parsing csv . |
37,021 | private CellProcessor [ ] getMfProcessors ( ) { CellProcessor [ ] processors = new CellProcessor [ ] { new org . supercsv . cellprocessor . Optional ( ) , new org . supercsv . cellprocessor . Optional ( ) , new org . supercsv . cellprocessor . Optional ( ) , new org . supercsv . cellprocessor . Optional ( new ParseBool ( ) ) , new org . supercsv . cellprocessor . Optional ( new ParseBool ( ) ) , new org . supercsv . cellprocessor . Optional ( new ParseDouble ( ) ) , new org . supercsv . cellprocessor . Optional ( new ParseDouble ( ) ) , new org . supercsv . cellprocessor . Optional ( new ParseDouble ( ) ) , new org . supercsv . cellprocessor . Optional ( new ParseDouble ( ) ) , new org . supercsv . cellprocessor . Optional ( new ParseDouble ( ) ) , new org . supercsv . cellprocessor . Optional ( ) , new org . supercsv . cellprocessor . Optional ( ) , new org . supercsv . cellprocessor . Optional ( ) , new org . supercsv . cellprocessor . Optional ( ) , new org . supercsv . cellprocessor . Optional ( new ParseDouble ( ) ) , new org . supercsv . cellprocessor . Optional ( new ParseDate ( "yyyy-MM-dd" ) ) } ; return processors ; } | This method returns array of cellprocessor for parsing mutual funds csv . |
37,022 | private TimerTask getTask ( ) { TimerTask checkForRestartTask = new TimerTask ( ) { public void run ( ) { if ( lastPongAt == 0 ) return ; Date currentDate = new Date ( ) ; long timeInterval = ( currentDate . getTime ( ) - lastPongAt ) ; if ( timeInterval >= 2 * pingInterval ) { doReconnect ( ) ; } } } ; return checkForRestartTask ; } | Returns task which performs check every second for reconnection . |
37,023 | public void doReconnect ( ) { if ( ! tryReconnection ) return ; if ( nextReconnectInterval == 0 ) { nextReconnectInterval = ( int ) ( 2000 * Math . pow ( 2 , count ) ) ; } else { nextReconnectInterval = ( int ) ( nextReconnectInterval * Math . pow ( 2 , count ) ) ; } if ( nextReconnectInterval > maxRetryInterval ) { nextReconnectInterval = maxRetryInterval ; } if ( count <= maxRetries ) { if ( canReconnect ) { count ++ ; reconnect ( new ArrayList < > ( subscribedTokens ) ) ; canReconnect = false ; canReconnectTimer = new Timer ( ) ; canReconnectTimer . schedule ( new TimerTask ( ) { public void run ( ) { canReconnect = true ; } } , nextReconnectInterval ) ; } } else if ( count > maxRetries ) { if ( timer != null ) { timer . cancel ( ) ; timer = null ; } } } | Performs reconnection after a particular interval if count is less than maximum retries . |
37,024 | private void createUrl ( String accessToken , String apiKey ) { wsuri = new Routes ( ) . getWsuri ( ) . replace ( ":access_token" , accessToken ) . replace ( ":api_key" , apiKey ) ; } | Creates url for websocket connection . |
37,025 | public void connect ( ) { try { ws . setPingInterval ( pingInterval ) ; ws . connect ( ) ; } catch ( WebSocketException e ) { e . printStackTrace ( ) ; if ( onErrorListener != null ) { onErrorListener . onError ( e ) ; } if ( tryReconnection ) { if ( timer == null ) { if ( lastPongAt == 0 ) { lastPongAt = 1 ; } timer = new Timer ( ) ; timer . scheduleAtFixedRate ( getTask ( ) , 0 , pongCheckInterval ) ; } } } } | Establishes a web socket connection . |
37,026 | public WebSocketAdapter getWebsocketAdapter ( ) { return new WebSocketAdapter ( ) { public void onConnected ( WebSocket websocket , Map < String , List < String > > headers ) { count = 0 ; nextReconnectInterval = 0 ; if ( onConnectedListener != null ) { onConnectedListener . onConnected ( ) ; } if ( tryReconnection ) { if ( timer != null ) { timer . cancel ( ) ; } timer = new Timer ( ) ; timer . scheduleAtFixedRate ( getTask ( ) , 0 , pongCheckInterval ) ; } } public void onTextMessage ( WebSocket websocket , String message ) { parseTextMessage ( message ) ; } public void onBinaryMessage ( WebSocket websocket , byte [ ] binary ) { try { super . onBinaryMessage ( websocket , binary ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; if ( onErrorListener != null ) { onErrorListener . onError ( e ) ; } } ArrayList < Tick > tickerData = parseBinary ( binary ) ; if ( onTickerArrivalListener != null ) { onTickerArrivalListener . onTicks ( tickerData ) ; } } public void onPongFrame ( WebSocket websocket , WebSocketFrame frame ) { try { super . onPongFrame ( websocket , frame ) ; Date date = new Date ( ) ; lastPongAt = date . getTime ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; if ( onErrorListener != null ) { onErrorListener . onError ( e ) ; } } } public void onDisconnected ( WebSocket websocket , WebSocketFrame serverCloseFrame , WebSocketFrame clientCloseFrame , boolean closedByServer ) { if ( onDisconnectedListener != null ) { onDisconnectedListener . onDisconnected ( ) ; } return ; } public void onError ( WebSocket websocket , WebSocketException cause ) { try { super . onError ( websocket , cause ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; if ( onErrorListener != null ) { onErrorListener . onError ( e ) ; } } } } ; } | Returns a WebSocketAdapter to listen to ticker related events . |
37,027 | public void disconnect ( ) { if ( timer != null ) { timer . cancel ( ) ; } if ( ws != null && ws . isOpen ( ) ) { ws . disconnect ( ) ; subscribedTokens = new HashSet < > ( ) ; modeMap . clear ( ) ; } } | Disconnects websocket connection . |
37,028 | public void setMode ( ArrayList < Long > tokens , String mode ) { JSONObject jobj = new JSONObject ( ) ; try { JSONArray list = new JSONArray ( ) ; JSONArray listMain = new JSONArray ( ) ; listMain . put ( 0 , mode ) ; for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { list . put ( i , tokens . get ( i ) ) ; } listMain . put ( 1 , list ) ; jobj . put ( "a" , mSetMode ) ; jobj . put ( "v" , listMain ) ; for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { modeMap . put ( tokens . get ( i ) , mode ) ; } } catch ( JSONException e ) { e . printStackTrace ( ) ; } if ( ws != null ) { ws . sendText ( jobj . toString ( ) ) ; } } | Setting different modes for an arraylist of tokens . |
37,029 | public void subscribe ( ArrayList < Long > tokens ) { if ( ws != null ) { if ( ws . isOpen ( ) ) { createTickerJsonObject ( tokens , mSubscribe ) ; ws . sendText ( createTickerJsonObject ( tokens , mSubscribe ) . toString ( ) ) ; subscribedTokens . addAll ( tokens ) ; for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { modeMap . put ( tokens . get ( i ) , modeQuote ) ; } } else { if ( onErrorListener != null ) { onErrorListener . onError ( new KiteException ( "ticker is not connected" , 504 ) ) ; } } } else { if ( onErrorListener != null ) { onErrorListener . onError ( new KiteException ( "ticker is null not connected" , 504 ) ) ; } } } | Subscribes for list of tokens . |
37,030 | private JSONObject createTickerJsonObject ( ArrayList < Long > tokens , String action ) { JSONObject jobj = new JSONObject ( ) ; try { JSONArray list = new JSONArray ( ) ; for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { list . put ( i , tokens . get ( i ) ) ; } jobj . put ( "v" , list ) ; jobj . put ( "a" , action ) ; } catch ( JSONException e ) { } return jobj ; } | Create a JSONObject to send message to server . |
37,031 | public void unsubscribe ( ArrayList < Long > tokens ) { if ( ws != null ) { if ( ws . isOpen ( ) ) { ws . sendText ( createTickerJsonObject ( tokens , mUnSubscribe ) . toString ( ) ) ; subscribedTokens . removeAll ( tokens ) ; for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { modeMap . remove ( tokens . get ( i ) ) ; } } } } | Unsubscribes ticks for list of tokens . |
37,032 | private Tick getIndeciesData ( byte [ ] bin , int x ) { int dec = 100 ; Tick tick = new Tick ( ) ; tick . setMode ( modeFull ) ; tick . setTradable ( false ) ; tick . setInstrumentToken ( x ) ; tick . setLastTradedPrice ( convertToDouble ( getBytes ( bin , 4 , 8 ) ) / dec ) ; tick . setHighPrice ( convertToDouble ( getBytes ( bin , 8 , 12 ) ) / dec ) ; tick . setLowPrice ( convertToDouble ( getBytes ( bin , 12 , 16 ) ) / dec ) ; tick . setOpenPrice ( convertToDouble ( getBytes ( bin , 16 , 20 ) ) / dec ) ; tick . setClosePrice ( convertToDouble ( getBytes ( bin , 20 , 24 ) ) / dec ) ; tick . setNetPriceChangeFromClosingPrice ( convertToDouble ( getBytes ( bin , 24 , 28 ) ) / dec ) ; if ( bin . length > 28 ) { long tickTimeStamp = convertToLong ( getBytes ( bin , 28 , 32 ) ) * 1000 ; if ( isValidDate ( tickTimeStamp ) ) { tick . setTickTimestamp ( new Date ( tickTimeStamp ) ) ; } else { tick . setTickTimestamp ( null ) ; } } return tick ; } | Parses NSE indices data . |
37,033 | private Tick getLtpQuote ( byte [ ] bin , int x , int dec1 ) { Tick tick1 = new Tick ( ) ; tick1 . setMode ( modeLTP ) ; tick1 . setTradable ( true ) ; tick1 . setInstrumentToken ( x ) ; tick1 . setLastTradedPrice ( convertToDouble ( getBytes ( bin , 4 , 8 ) ) / dec1 ) ; return tick1 ; } | Parses LTP data . |
37,034 | private Tick getFullData ( byte [ ] bin , int dec , Tick tick ) { long lastTradedtime = convertToLong ( getBytes ( bin , 44 , 48 ) ) * 1000 ; if ( isValidDate ( lastTradedtime ) ) { tick . setLastTradedTime ( new Date ( lastTradedtime ) ) ; } else { tick . setLastTradedTime ( null ) ; } tick . setOi ( convertToDouble ( getBytes ( bin , 48 , 52 ) ) ) ; tick . setOpenInterestDayHigh ( convertToDouble ( getBytes ( bin , 52 , 56 ) ) ) ; tick . setOpenInterestDayLow ( convertToDouble ( getBytes ( bin , 56 , 60 ) ) ) ; long tickTimeStamp = convertToLong ( getBytes ( bin , 60 , 64 ) ) * 1000 ; if ( isValidDate ( tickTimeStamp ) ) { tick . setTickTimestamp ( new Date ( tickTimeStamp ) ) ; } else { tick . setTickTimestamp ( null ) ; } tick . setMarketDepth ( getDepthData ( bin , dec , 64 , 184 ) ) ; return tick ; } | Parses full mode data . |
37,035 | private Map < String , ArrayList < Depth > > getDepthData ( byte [ ] bin , int dec , int start , int end ) { byte [ ] depthBytes = getBytes ( bin , start , end ) ; int s = 0 ; ArrayList < Depth > buy = new ArrayList < Depth > ( ) ; ArrayList < Depth > sell = new ArrayList < Depth > ( ) ; for ( int k = 0 ; k < 10 ; k ++ ) { s = k * 12 ; Depth depth = new Depth ( ) ; depth . setQuantity ( ( int ) convertToDouble ( getBytes ( depthBytes , s , s + 4 ) ) ) ; depth . setPrice ( convertToDouble ( getBytes ( depthBytes , s + 4 , s + 8 ) ) / dec ) ; depth . setOrders ( ( int ) convertToDouble ( getBytes ( depthBytes , s + 8 , s + 10 ) ) ) ; if ( k < 5 ) { buy . add ( depth ) ; } else { sell . add ( depth ) ; } } Map < String , ArrayList < Depth > > depthMap = new HashMap < String , ArrayList < Depth > > ( ) ; depthMap . put ( "buy" , buy ) ; depthMap . put ( "sell" , sell ) ; return depthMap ; } | Reads all bytes and returns map of depth values for offer and bid |
37,036 | private ArrayList < byte [ ] > splitPackets ( byte [ ] bin ) { ArrayList < byte [ ] > packets = new ArrayList < byte [ ] > ( ) ; int noOfPackets = getLengthFromByteArray ( getBytes ( bin , 0 , 2 ) ) ; int j = 2 ; for ( int i = 0 ; i < noOfPackets ; i ++ ) { int sizeOfPacket = getLengthFromByteArray ( getBytes ( bin , j , j + 2 ) ) ; byte [ ] packet = Arrays . copyOfRange ( bin , j + 2 , j + 2 + sizeOfPacket ) ; packets . add ( packet ) ; j = j + 2 + sizeOfPacket ; } return packets ; } | Each byte stream contains many packets . This method reads first two bits and calculates number of packets in the byte stream and split it . |
37,037 | private double convertToDouble ( byte [ ] bin ) { ByteBuffer bb = ByteBuffer . wrap ( bin ) ; bb . order ( ByteOrder . BIG_ENDIAN ) ; if ( bin . length < 4 ) return bb . getShort ( ) ; else if ( bin . length < 8 ) return bb . getInt ( ) ; else return bb . getDouble ( ) ; } | Convert binary data to double datatype |
37,038 | private int getLengthFromByteArray ( byte [ ] bin ) { ByteBuffer bb = ByteBuffer . wrap ( bin ) ; bb . order ( ByteOrder . BIG_ENDIAN ) ; return bb . getShort ( ) ; } | Returns length of packet by reading byte array values . |
37,039 | private void reconnect ( final ArrayList < Long > tokens ) { nonUserDisconnect ( ) ; try { ws = new WebSocketFactory ( ) . createSocket ( wsuri ) ; } catch ( IOException e ) { if ( onErrorListener != null ) { onErrorListener . onError ( e ) ; } return ; } ws . addListener ( getWebsocketAdapter ( ) ) ; connect ( ) ; final OnConnect onUsersConnectedListener = this . onConnectedListener ; setOnConnectedListener ( new OnConnect ( ) { public void onConnected ( ) { if ( subscribedTokens . size ( ) > 0 ) { Map < Long , String > backupModeMap = new HashMap < > ( ) ; backupModeMap . putAll ( modeMap ) ; ArrayList < Long > tokens = new ArrayList < > ( ) ; tokens . addAll ( subscribedTokens ) ; subscribe ( tokens ) ; Map < String , ArrayList < Long > > modes = new HashMap < > ( ) ; for ( Map . Entry < Long , String > item : backupModeMap . entrySet ( ) ) { if ( ! modes . containsKey ( item . getValue ( ) ) ) { modes . put ( item . getValue ( ) , new ArrayList < Long > ( ) ) ; } modes . get ( item . getValue ( ) ) . add ( item . getKey ( ) ) ; } for ( Map . Entry < String , ArrayList < Long > > modeArrayItem : modes . entrySet ( ) ) { setMode ( modeArrayItem . getValue ( ) , modeArrayItem . getKey ( ) ) ; } } lastPongAt = 0 ; count = 0 ; nextReconnectInterval = 0 ; onConnectedListener = onUsersConnectedListener ; } } ) ; } | Disconnects and reconnects com . zerodhatech . ticker . |
37,040 | private void parseTextMessage ( String message ) { JSONObject data ; try { data = new JSONObject ( message ) ; if ( ! data . has ( "type" ) ) { return ; } String type = data . getString ( "type" ) ; if ( type . equals ( "order" ) ) { if ( orderUpdateListener != null ) { orderUpdateListener . onOrderUpdate ( getOrder ( data ) ) ; } } } catch ( JSONException e ) { e . printStackTrace ( ) ; } } | Parses incoming text message . |
37,041 | public static ImageGalleryFragment newInstance ( Bundle extras ) { ImageGalleryFragment fragment = new ImageGalleryFragment ( ) ; fragment . setArguments ( extras ) ; return fragment ; } | region Factory Methods |
37,042 | public void onImageClick ( int position ) { Intent intent = new Intent ( ImageGalleryActivity . this , FullScreenImageGalleryActivity . class ) ; Bundle bundle = new Bundle ( ) ; bundle . putStringArrayList ( FullScreenImageGalleryActivity . KEY_IMAGES , images ) ; bundle . putInt ( FullScreenImageGalleryActivity . KEY_POSITION , position ) ; intent . putExtras ( bundle ) ; startActivity ( intent ) ; } | region ImageGalleryAdapter . OnImageClickListener Methods |
37,043 | public void loadFullScreenImage ( ImageView iv , String imageUrl , int width , LinearLayout bglinearLayout ) { fullScreenImageLoader . loadFullScreenImage ( iv , imageUrl , width , bglinearLayout ) ; } | region FullScreenImageGalleryAdapter . FullScreenImageLoader Methods |
37,044 | public RectF getZoomedRect ( ) { if ( mScaleType == ScaleType . FIT_XY ) { throw new UnsupportedOperationException ( "getZoomedRect() not supported with FIT_XY" ) ; } PointF topLeft = transformCoordTouchToBitmap ( 0 , 0 , true ) ; PointF bottomRight = transformCoordTouchToBitmap ( viewWidth , viewHeight , true ) ; float w = getDrawable ( ) . getIntrinsicWidth ( ) ; float h = getDrawable ( ) . getIntrinsicHeight ( ) ; return new RectF ( topLeft . x / w , topLeft . y / h , bottomRight . x / w , bottomRight . y / h ) ; } | Return a Rect representing the zoomed image . |
37,045 | private void savePreviousImageValues ( ) { if ( matrix != null && viewHeight != 0 && viewWidth != 0 ) { matrix . getValues ( m ) ; prevMatrix . setValues ( m ) ; prevMatchViewHeight = matchViewHeight ; prevMatchViewWidth = matchViewWidth ; prevViewHeight = viewHeight ; prevViewWidth = viewWidth ; } } | Save the current matrix and view dimensions in the prevMatrix and prevView variables . |
37,046 | public void setZoom ( TouchImageView img ) { PointF center = img . getScrollPosition ( ) ; setZoom ( img . getCurrentZoom ( ) , center . x , center . y , img . getScaleType ( ) ) ; } | Set zoom parameters equal to another TouchImageView . Including scale position and ScaleType . |
37,047 | private void fixTrans ( ) { matrix . getValues ( m ) ; float transX = m [ Matrix . MTRANS_X ] ; float transY = m [ Matrix . MTRANS_Y ] ; float fixTransX = getFixTrans ( transX , viewWidth , getImageWidth ( ) ) ; float fixTransY = getFixTrans ( transY , viewHeight , getImageHeight ( ) ) ; if ( fixTransX != 0 || fixTransY != 0 ) { matrix . postTranslate ( fixTransX , fixTransY ) ; } } | Performs boundary checking and fixes the image matrix if it is out of bounds . |
37,048 | private void fitImageToView ( ) { Drawable drawable = getDrawable ( ) ; if ( drawable == null || drawable . getIntrinsicWidth ( ) == 0 || drawable . getIntrinsicHeight ( ) == 0 ) { return ; } if ( matrix == null || prevMatrix == null ) { return ; } int drawableWidth = drawable . getIntrinsicWidth ( ) ; int drawableHeight = drawable . getIntrinsicHeight ( ) ; float scaleX = ( float ) viewWidth / drawableWidth ; float scaleY = ( float ) viewHeight / drawableHeight ; switch ( mScaleType ) { case CENTER : scaleX = scaleY = 1 ; break ; case CENTER_CROP : scaleX = scaleY = Math . max ( scaleX , scaleY ) ; break ; case CENTER_INSIDE : scaleX = scaleY = Math . min ( 1 , Math . min ( scaleX , scaleY ) ) ; case FIT_CENTER : scaleX = scaleY = Math . min ( scaleX , scaleY ) ; break ; case FIT_XY : break ; default : throw new UnsupportedOperationException ( "TouchImageView does not support FIT_START or FIT_END" ) ; } float redundantXSpace = viewWidth - ( scaleX * drawableWidth ) ; float redundantYSpace = viewHeight - ( scaleY * drawableHeight ) ; matchViewWidth = viewWidth - redundantXSpace ; matchViewHeight = viewHeight - redundantYSpace ; if ( ! isZoomed ( ) && ! imageRenderedAtLeastOnce ) { matrix . setScale ( scaleX , scaleY ) ; matrix . postTranslate ( redundantXSpace / 2 , redundantYSpace / 2 ) ; normalizedScale = 1 ; } else { if ( prevMatchViewWidth == 0 || prevMatchViewHeight == 0 ) { savePreviousImageValues ( ) ; } prevMatrix . getValues ( m ) ; m [ Matrix . MSCALE_X ] = matchViewWidth / drawableWidth * normalizedScale ; m [ Matrix . MSCALE_Y ] = matchViewHeight / drawableHeight * normalizedScale ; float transX = m [ Matrix . MTRANS_X ] ; float transY = m [ Matrix . MTRANS_Y ] ; float prevActualWidth = prevMatchViewWidth * normalizedScale ; float actualWidth = getImageWidth ( ) ; translateMatrixAfterRotate ( Matrix . MTRANS_X , transX , prevActualWidth , actualWidth , prevViewWidth , viewWidth , drawableWidth ) ; float prevActualHeight = prevMatchViewHeight * normalizedScale ; float actualHeight = getImageHeight ( ) ; translateMatrixAfterRotate ( Matrix . MTRANS_Y , transY , prevActualHeight , actualHeight , prevViewHeight , viewHeight , drawableHeight ) ; matrix . setValues ( m ) ; } fixTrans ( ) ; setImageMatrix ( matrix ) ; } | If the normalizedScale is equal to 1 then the image is made to fit the screen . Otherwise it is made to fit the screen according to the dimensions of the previous image matrix . This allows the image to maintain its zoom after rotation . |
37,049 | private int setViewSize ( int mode , int size , int drawableWidth ) { int viewSize ; switch ( mode ) { case MeasureSpec . EXACTLY : viewSize = size ; break ; case MeasureSpec . AT_MOST : viewSize = Math . min ( drawableWidth , size ) ; break ; case MeasureSpec . UNSPECIFIED : viewSize = drawableWidth ; break ; default : viewSize = size ; break ; } return viewSize ; } | Set view dimensions based on layout params |
37,050 | private void translateMatrixAfterRotate ( int axis , float trans , float prevImageSize , float imageSize , int prevViewSize , int viewSize , int drawableSize ) { if ( imageSize < viewSize ) { m [ axis ] = ( viewSize - ( drawableSize * m [ Matrix . MSCALE_X ] ) ) * 0.5f ; } else if ( trans > 0 ) { m [ axis ] = - ( ( imageSize - viewSize ) * 0.5f ) ; } else { float percentage = ( Math . abs ( trans ) + ( 0.5f * prevViewSize ) ) / prevImageSize ; m [ axis ] = - ( ( percentage * imageSize ) - ( viewSize * 0.5f ) ) ; } } | After rotating the matrix needs to be translated . This function finds the area of image which was previously centered and adjusts translations so that is again the center post - rotation . |
37,051 | private PointF transformCoordTouchToBitmap ( float x , float y , boolean clipToBitmap ) { matrix . getValues ( m ) ; float origW = getDrawable ( ) . getIntrinsicWidth ( ) ; float origH = getDrawable ( ) . getIntrinsicHeight ( ) ; float transX = m [ Matrix . MTRANS_X ] ; float transY = m [ Matrix . MTRANS_Y ] ; float finalX = ( ( x - transX ) * origW ) / getImageWidth ( ) ; float finalY = ( ( y - transY ) * origH ) / getImageHeight ( ) ; if ( clipToBitmap ) { finalX = Math . min ( Math . max ( finalX , 0 ) , origW ) ; finalY = Math . min ( Math . max ( finalY , 0 ) , origH ) ; } return new PointF ( finalX , finalY ) ; } | This function will transform the coordinates in the touch event to the coordinate system of the drawable that the imageview contain |
37,052 | private PointF transformCoordBitmapToTouch ( float bx , float by ) { matrix . getValues ( m ) ; float origW = getDrawable ( ) . getIntrinsicWidth ( ) ; float origH = getDrawable ( ) . getIntrinsicHeight ( ) ; float px = bx / origW ; float py = by / origH ; float finalX = m [ Matrix . MTRANS_X ] + getImageWidth ( ) * px ; float finalY = m [ Matrix . MTRANS_Y ] + getImageHeight ( ) * py ; return new PointF ( finalX , finalY ) ; } | Inverse of transformCoordTouchToBitmap . This function will transform the coordinates in the drawable s coordinate system to the view s coordinate system . |
37,053 | public void loadFullScreenImage ( final ImageView iv , String imageUrl , int width , final LinearLayout bgLinearLayout ) { if ( ! TextUtils . isEmpty ( imageUrl ) ) { Picasso . with ( iv . getContext ( ) ) . load ( imageUrl ) . resize ( width , 0 ) . into ( iv , new Callback ( ) { public void onSuccess ( ) { Bitmap bitmap = ( ( BitmapDrawable ) iv . getDrawable ( ) ) . getBitmap ( ) ; Palette . from ( bitmap ) . generate ( new Palette . PaletteAsyncListener ( ) { public void onGenerated ( Palette palette ) { applyPalette ( palette , bgLinearLayout ) ; } } ) ; } public void onError ( ) { } } ) ; } else { iv . setImageDrawable ( null ) ; } } | region FullScreenImageGalleryAdapter . FullScreenImageLoader |
37,054 | public void sign ( Key privateKey , List < X509Certificate > x509List , String password , HashAlgorithm hashAlgorithm ) throws XMLSignatureException , MarshalException , IOException , FormatNotUnderstoodException { if ( this . tempSignFileOS != null ) { this . tempSignFileOS . close ( ) ; } SignatureConfig sc = new SignatureConfig ( ) ; sc . addSignatureFacet ( new OOXMLSignatureFacet ( ) ) ; sc . addSignatureFacet ( new KeyInfoSignatureFacet ( ) ) ; sc . addSignatureFacet ( new XAdESSignatureFacet ( ) ) ; sc . addSignatureFacet ( new Office2010SignatureFacet ( ) ) ; sc . setKey ( ( PrivateKey ) privateKey ) ; sc . setSigningCertificateChain ( x509List ) ; sc . setDigestAlgo ( hashAlgorithm ) ; FileInputStream tempSignFileIS = null ; try { InputStream tmpFileInputStream = new FileInputStream ( this . tempSignFile ) ; if ( password == null ) { this . signUnencryptedOpcPackage ( tmpFileInputStream , sc ) ; } else { this . signEncryptedPackage ( tmpFileInputStream , sc , password ) ; } } catch ( InvalidFormatException | IOException e ) { LOG . error ( e ) ; } finally { if ( this . finalOutputStream != null ) { this . finalOutputStream . close ( ) ; } if ( tempSignFileIS != null ) { tempSignFileIS . close ( ) ; } } } | Signs the Excel OOXML file and writes it to the final outputstream |
37,055 | public void close ( ) throws IOException { try { if ( this . tempSignFileOS != null ) { this . tempSignFileOS . close ( ) ; } } finally { if ( ! this . tempSignFile . delete ( ) ) { LOG . warn ( "Could not delete temporary files used for signing" ) ; } } } | Cleans up tempfolder |
37,056 | public Key getPrivateKey ( String alias , String password ) throws UnrecoverableKeyException , KeyStoreException , NoSuchAlgorithmException { return this . keystore . getKey ( alias , password . toCharArray ( ) ) ; } | Reads a private key from keystore |
37,057 | public void setPassword ( String alias , String password , String passwordPassword ) throws NoSuchAlgorithmException , InvalidKeySpecException , KeyStoreException { SecretKeyFactory skf = SecretKeyFactory . getInstance ( "PBE" ) ; SecretKey pSecret = skf . generateSecret ( new PBEKeySpec ( password . toCharArray ( ) ) ) ; KeyStore . PasswordProtection kspp = new KeyStore . PasswordProtection ( passwordPassword . toCharArray ( ) ) ; this . keystore . setEntry ( alias , new KeyStore . SecretKeyEntry ( pSecret ) , kspp ) ; } | Sets the password in the currently openend keystore . Do not forget to store it afterwards |
37,058 | public void close ( ) throws IOException { try { prepareMetaData ( ) ; if ( this . oStream != null ) { if ( this . howc . getPassword ( ) == null ) { finalizeWriteNotEncrypted ( ) ; } else if ( this . currentWorkbook instanceof HSSFWorkbook ) { finalizeWriteEncryptedHSSF ( ) ; } else if ( this . currentWorkbook instanceof XSSFWorkbook ) { finalizeWriteEncryptedXSSF ( ) ; } else { LOG . error ( "Could not write encrypted workbook, because type of workbook is unknown" ) ; } } } finally { if ( this . ooxmlDocumentFileSystem != null ) { ooxmlDocumentFileSystem . close ( ) ; } if ( this . currentWorkbook != null ) { this . currentWorkbook . close ( ) ; } for ( Workbook currentWorkbookItem : this . listOfWorkbooks ) { if ( currentWorkbookItem != null ) { currentWorkbookItem . close ( ) ; } } } try { if ( this . signUtil != null ) { LOG . info ( "Signing document \"" + this . howc . getFileName ( ) + "\"" ) ; if ( this . howc . getSigCertificate ( ) == null ) { LOG . error ( "Cannot sign document \"" + this . howc . getFileName ( ) + "\". No certificate for key provided" ) ; } else if ( ! ( this . currentWorkbook instanceof XSSFWorkbook ) ) { LOG . warn ( "Signing of docuemnts in old Excel format not supported for \"" + this . howc . getFileName ( ) + "\"" ) ; } else { try { ArrayList < X509Certificate > certList = new ArrayList < > ( ) ; certList . add ( this . howc . getSigCertificate ( ) ) ; this . signUtil . sign ( this . howc . getSigKey ( ) , certList , this . howc . getPassword ( ) , MSExcelWriter . getHashAlgorithm ( this . howc . getSigHash ( ) ) ) ; } catch ( XMLSignatureException | MarshalException | IOException | FormatNotUnderstoodException e ) { LOG . error ( "Cannot sign document \"" + this . howc . getFileName ( ) + "\" " + e ) ; } } } } finally { if ( this . signUtil != null ) { this . signUtil . close ( ) ; } } } | Writes the document in - memory representation to the OutputStream . Afterwards it closes all related workbooks . |
37,059 | public static boolean isSupportedFormat ( String format ) { for ( int i = 0 ; i < MSExcelWriter . VALID_FORMAT . length ; i ++ ) { if ( VALID_FORMAT [ i ] . equals ( format ) ) { return true ; } } return false ; } | Checks if format is supported |
37,060 | public static CipherAlgorithm getAlgorithmCipher ( String encryptAlgorithm ) { if ( encryptAlgorithm == null ) { return null ; } switch ( encryptAlgorithm ) { case "aes128" : return CipherAlgorithm . aes128 ; case "aes192" : return CipherAlgorithm . aes192 ; case "aes256" : return CipherAlgorithm . aes256 ; case "des" : return CipherAlgorithm . des ; case "des3" : return CipherAlgorithm . des3 ; case "des3_112" : return CipherAlgorithm . des3_112 ; case "rc2" : return CipherAlgorithm . rc2 ; case "rc4" : return CipherAlgorithm . rc4 ; case "rsa" : return CipherAlgorithm . rsa ; default : LOG . error ( "Uknown encryption algorithm: \"" + encryptAlgorithm + "\"" ) ; break ; } return null ; } | Returns the CipherAlgorithm object matching the String . |
37,061 | public static HashAlgorithm getHashAlgorithm ( String hashAlgorithm ) { if ( hashAlgorithm == null ) { return null ; } switch ( hashAlgorithm ) { case "md2" : return HashAlgorithm . md2 ; case "md4" : return HashAlgorithm . md4 ; case "md5" : return HashAlgorithm . md5 ; case "none" : return HashAlgorithm . none ; case "ripemd128" : return HashAlgorithm . ripemd128 ; case "ripemd160" : return HashAlgorithm . ripemd160 ; case "sha1" : return HashAlgorithm . sha1 ; case "sha224" : return HashAlgorithm . sha224 ; case "sha256" : return HashAlgorithm . sha256 ; case "sha384" : return HashAlgorithm . sha384 ; case "sha512" : return HashAlgorithm . sha512 ; case "whirlpool" : return HashAlgorithm . whirlpool ; default : LOG . error ( "Uknown hash algorithm: \"" + hashAlgorithm + "\"" ) ; break ; } return null ; } | Returns the HashAlgorithm object matching the String . |
37,062 | public static EncryptionMode getEncryptionModeCipher ( String encryptionMode ) { if ( encryptionMode == null ) { return null ; } switch ( encryptionMode ) { case "agile" : return EncryptionMode . agile ; case "binaryRC4" : return EncryptionMode . binaryRC4 ; case "cryptoAPI" : return EncryptionMode . cryptoAPI ; case "standard" : return EncryptionMode . standard ; default : LOG . error ( "Uknown enncryption mode \"" + encryptionMode + "\"" ) ; break ; } return null ; } | Returns the EncryptionMode object matching the String . |
37,063 | public static ChainingMode getChainMode ( String chainMode ) { if ( chainMode == null ) { return null ; } switch ( chainMode ) { case "cbc" : return ChainingMode . cbc ; case "cfb" : return ChainingMode . cfb ; case "ecb" : return ChainingMode . ecb ; default : LOG . error ( "Uknown chainmode: \"" + chainMode + "\"" ) ; break ; } return null ; } | Returns the ChainMode object matching the String . |
37,064 | private String parseCellInlineStringText ( XMLEventReader xer ) throws XMLStreamException , FormatNotUnderstoodException { String result = "" ; XMLEvent xe ; while ( ( xe = xer . nextTag ( ) ) . isStartElement ( ) ) { String elementName = xe . asStartElement ( ) . getName ( ) . getLocalPart ( ) . toUpperCase ( ) ; switch ( elementName ) { case "T" : result = xer . getElementText ( ) ; break ; case "R" : result = this . parseCellInlineStringRichText ( xer ) ; break ; case "RPH" : case "PHONETICPR" : this . skipXMLElementHierarchy ( xer ) ; break ; default : LOG . error ( "Unknown inline string tag: " + elementName ) ; throw new FormatNotUnderstoodException ( "Unknown inline string tag: " + elementName ) ; } } return result ; } | Parses an inline string from cell in XML format |
37,065 | public void open ( FileInputSplit split ) throws IOException { super . open ( split ) ; if ( this . customSchema == null ) { ExcelFlinkFileInputFormat effif = new ExcelFlinkFileInputFormat ( this . shocr ) ; effif . open ( split ) ; SpreadSheetCellDAO [ ] currentRow = effif . nextRecord ( null ) ; int i = 0 ; while ( ( currentRow != null ) && ( i != this . maxInferRows ) ) { this . converter . updateSpreadSheetCellRowToInferSchemaInformation ( currentRow ) ; i ++ ; currentRow = effif . nextRecord ( null ) ; } effif . close ( ) ; this . customSchema = this . converter . getSchemaRow ( ) ; } else { this . converter . setSchemaRow ( this . customSchema ) ; } } | Open an Excel file |
37,066 | public Tuple3 < Long , Long , GenericDataType [ ] > getCurrentState ( ) throws IOException { return new Tuple3 < > ( this . getOfficeReader ( ) . getCurrentParser ( ) . getCurrentSheet ( ) , this . getOfficeReader ( ) . getCurrentParser ( ) . getCurrentRow ( ) , this . converter . getSchemaRow ( ) ) ; } | Store currently processed sheet and row as well as infered schema |
37,067 | public void readFrom ( InputStream is ) throws IOException { this . currentItem = 0 ; OutputStream tempOS = null ; if ( ( this . ca != null ) || ( this . compressTempFile ) ) { tempOS = new FileOutputStream ( this . tempFile ) ; if ( this . ca != null ) { tempOS = new CipherOutputStream ( tempOS , this . ciEncrypt ) ; } if ( this . compressTempFile ) { tempOS = new GZIPOutputStream ( tempOS , EncryptedCachedDiskStringsTable . compressBufferSize ) ; } } else { this . tempRAF = new RandomAccessFile ( this . tempFile , "rw" ) ; } XMLEventReader xer = null ; try { xer = StaxHelper . newXMLInputFactory ( ) . createXMLEventReader ( this . originalIS ) ; while ( xer . hasNext ( ) ) { XMLEvent xe = xer . nextEvent ( ) ; if ( xe . isStartElement ( ) && xe . asStartElement ( ) . getName ( ) . getLocalPart ( ) . equalsIgnoreCase ( "si" ) ) { String siText = this . parseSIText ( xer ) ; this . addString ( siText , tempOS ) ; this . count ++ ; } } } catch ( XMLStreamException e ) { LOG . error ( "Cannot read original SharedStringTable from document. Exception " + e ) ; throw new IOException ( e ) ; } catch ( FormatNotUnderstoodException e ) { LOG . error ( "Cannot read properly SharedStringTable from document. Exception " + e ) ; throw new IOException ( e ) ; } finally { if ( tempOS != null ) { tempOS . close ( ) ; } } this . accessTempFile ( 0L ) ; } | Reads from the original Excel document the string table and puts it into a compressed and encrypted file . |
37,068 | public RichTextString getItemAt ( int idx ) { try { return new XSSFRichTextString ( this . getString ( idx ) ) ; } catch ( IOException e ) { LOG . error ( "Cannot read from temporary shared String table. Exception: " + e ) ; } return new XSSFRichTextString ( "" ) ; } | Get an item from the shared string table |
37,069 | public void close ( ) throws IOException { if ( this . in != null ) { this . in . close ( ) ; } if ( ! this . tempFile . delete ( ) ) { LOG . warn ( "Cannot delete tempFile: " + this . tempFile . getAbsolutePath ( ) ) ; throw new IOException ( "Cannot delete tempFile: " + this . tempFile . getAbsolutePath ( ) ) ; } ; } | Closes the temporary inputstream and deletes the temp file |
37,070 | private void addString ( String str , OutputStream os ) throws IOException { if ( this . cacheSize >= 0 ) { byte [ ] strbytes = str . getBytes ( EncryptedCachedDiskStringsTable . encoding ) ; byte [ ] sizeOfStr = ByteBuffer . allocate ( 4 ) . putInt ( strbytes . length ) . array ( ) ; this . stringPositionInFileList . add ( this . tempFileSize ) ; if ( os != null ) { os . write ( sizeOfStr ) ; os . write ( strbytes ) ; } else { FileChannel fc = this . tempRAF . getChannel ( ) . position ( this . tempFileSize ) ; fc . write ( ByteBuffer . wrap ( sizeOfStr ) ) ; fc . write ( ByteBuffer . wrap ( strbytes ) ) ; } this . tempFileSize += sizeOfStr . length + strbytes . length ; } if ( this . cacheSize < 0 ) { this . cache . put ( this . currentItem , str ) ; this . currentItem ++ ; } else if ( ( this . cacheSize > 0 ) && ( this . currentItem < this . cacheSize ) ) { this . cache . put ( this . currentItem , str ) ; this . currentItem ++ ; } } | Adds a string to the table on disk |
37,071 | public void initialize ( Configuration conf , Properties prop ) throws SerDeException { this . initialize ( conf , prop , null ) ; } | Initializes the Serde |
37,072 | public static String getCellAddressA1Format ( int rowNum , int columnNum ) { CellAddress cellAddr = new CellAddress ( rowNum , columnNum ) ; return cellAddr . formatAsString ( ) ; } | Generate a cell address in A1 format from a row and column number |
37,073 | public boolean addLinkedWorkbook ( String name , InputStream inputStream , String password ) throws FormatNotUnderstoodException { if ( this . addedFormulaEvaluators . containsKey ( name ) ) { return false ; } LOG . debug ( "Start adding \"" + name + "\" to current workbook" ) ; HadoopOfficeReadConfiguration linkedWBHOCR = new HadoopOfficeReadConfiguration ( ) ; linkedWBHOCR . setLocale ( this . hocr . getLocale ( ) ) ; linkedWBHOCR . setSheets ( null ) ; linkedWBHOCR . setIgnoreMissingLinkedWorkbooks ( this . hocr . getIgnoreMissingLinkedWorkbooks ( ) ) ; linkedWBHOCR . setFileName ( name ) ; linkedWBHOCR . setPassword ( password ) ; linkedWBHOCR . setMetaDataFilter ( null ) ; MSExcelParser linkedWBMSExcelParser = new MSExcelParser ( linkedWBHOCR , null ) ; linkedWBMSExcelParser . parse ( inputStream ) ; this . addedWorkbooks . add ( linkedWBMSExcelParser . getCurrentWorkbook ( ) ) ; this . addedFormulaEvaluators . put ( name , linkedWBMSExcelParser . getCurrentFormulaEvaluator ( ) ) ; this . formulaEvaluator . setupReferencedWorkbooks ( addedFormulaEvaluators ) ; return true ; } | Adds a linked workbook that is referred from this workbook . If the filename is already in the list then it is not processed twice . Note that the inputStream is closed after parsing |
37,074 | public List < String > getLinkedWorkbooks ( ) { List < String > result = new ArrayList < > ( ) ; if ( this . currentWorkbook instanceof HSSFWorkbook ) { result = getLinkedWorkbooksHSSF ( ) ; } else if ( this . currentWorkbook instanceof XSSFWorkbook ) { for ( ExternalLinksTable element : ( ( XSSFWorkbook ) this . currentWorkbook ) . getExternalLinksTable ( ) ) { result . add ( element . getLinkedFileName ( ) ) ; } } else { LOG . warn ( "Cannot determine linked workbooks" ) ; } return result ; } | Provides a list of filenames that contain workbooks that are linked with the current one . Officially supported only for new Excel format . For the old Excel format this is experimental |
37,075 | public void close ( ) throws IOException { if ( this . in != null ) { in . close ( ) ; } if ( this . currentWorkbook != null ) { LOG . debug ( "Closing current Workbook \"" + this . hocr . getFileName ( ) + "\"" ) ; this . currentWorkbook . close ( ) ; } for ( Workbook addedWorkbook : this . addedWorkbooks ) { addedWorkbook . close ( ) ; } } | Close parser and linked workbooks |
37,076 | public GenericDataType [ ] getSchemaRow ( ) { GenericDataType [ ] result = new GenericDataType [ this . schemaRow . size ( ) ] ; this . schemaRow . toArray ( result ) ; return result ; } | Returns a list of objects corresponding to the schema . |
37,077 | public void create ( OutputStream oStream , Map < String , InputStream > linkedWorkbooks , Map < String , String > linkedWorkbooksPasswords , InputStream template ) throws OfficeWriterException { this . oStream = oStream ; if ( this . currentOfficeSpreadSheetWriter != null ) { this . currentOfficeSpreadSheetWriter . create ( oStream , linkedWorkbooks , linkedWorkbooksPasswords , template ) ; } else { throw new OfficeWriterException ( EX_NO_WRITER_INSTANTIATED ) ; } } | Creates a new office document |
37,078 | public void write ( Object o ) throws OfficeWriterException { if ( this . currentOfficeSpreadSheetWriter != null ) { this . currentOfficeSpreadSheetWriter . write ( o ) ; } else { throw new OfficeWriterException ( EX_NO_WRITER_INSTANTIATED ) ; } } | Writes an object to the office document . Note the type of object highly depends on the underlying writer . E . g . for SpreadSheet - based writers it is of class SpreadSheetCellDAO |
37,079 | private WebTarget withAuthToken ( final WebTarget target ) { if ( _sessionOptions . getAuthToken ( ) != null ) { return target . queryParam ( AUTH_TOKEN_PARAM_NAME , _sessionOptions . getAuthToken ( ) ) ; } else { return target ; } } | Add authorization token to the web target . |
37,080 | protected < T > T getResponse ( final WebTarget target , final ResponseProcessor < T > responseProcessor , final Request request ) { Builder requestBuilder = target . request ( ) ; Response response = requestBuilder . buildGet ( ) . invoke ( ) ; if ( response . getStatus ( ) == Response . Status . OK . getStatusCode ( ) ) { InputStream inputStream = response . readEntity ( InputStream . class ) ; try { T result = responseProcessor . process ( inputStream , request ) ; response . close ( ) ; inputStream . close ( ) ; return result ; } catch ( IOException ex ) { response . close ( ) ; throw new QuandlRuntimeException ( "Problem closing input stream" ) ; } catch ( RuntimeException t ) { response . close ( ) ; try { inputStream . close ( ) ; } catch ( IOException ioe ) { } throw t ; } } else if ( response . getStatus ( ) == UNPROCESSABLE_ENTITY ) { String msg = "Response code to " + target . getUri ( ) + " was " + response . getStatusInfo ( ) ; response . close ( ) ; throw new QuandlUnprocessableEntityException ( msg ) ; } else if ( response . getStatus ( ) == TOO_MANY_REQUESTS ) { Long retryAfter = parseOptionalHeader ( response , RETRY_AFTER ) ; Long rateLimitLimit = parseOptionalHeader ( response , X_RATELIMIT_LIMIT ) ; Long rateLimitRemaining = parseOptionalHeader ( response , X_RATELIMIT_REMAINING ) ; String msg = "Response code to " + target . getUri ( ) + " was " + response . getStatusInfo ( ) ; response . close ( ) ; throw new QuandlTooManyRequestsException ( msg , retryAfter , rateLimitLimit , rateLimitRemaining ) ; } else if ( response . getStatus ( ) == SERVICE_UNAVAILABLE ) { String msg = "Response code to " + target . getUri ( ) + " was 503 (Service Unavailable)" ; response . close ( ) ; throw new QuandlServiceUnavailableException ( msg ) ; } else { String msg = "Response code to " + target . getUri ( ) + " was " + response . getStatusInfo ( ) ; response . close ( ) ; throw new QuandlRuntimeException ( msg ) ; } } | Generic method to handle the invocation of the requests error processing and so on leaving the specialised methods to simply invoke with the appropriate ReponseProcessor to process the resulting InputStream . |
37,081 | public static void notNull ( final Object argument , final String name ) { if ( argument == null ) { s_logger . error ( "Argument {} was null" , name ) ; throw new QuandlRuntimeException ( "Value " + name + " was null" ) ; } } | Throws an exception if the argument is not null . |
37,082 | public static < E > void notNullOrEmpty ( final E [ ] argument , final String name ) { if ( argument == null ) { s_logger . error ( "Argument {} was null" , name ) ; throw new QuandlRuntimeException ( "Value " + name + " was null" ) ; } else if ( argument . length == 0 ) { s_logger . error ( "Argument {} was empty array" , name ) ; throw new QuandlRuntimeException ( "Value " + name + " was empty array" ) ; } } | Throws an exception if the array argument is not null or empty . |
37,083 | public static < E > void notNullOrEmpty ( final Collection < E > argument , final String name ) { if ( argument == null ) { s_logger . error ( "Argument {} was null" , name ) ; throw new QuandlRuntimeException ( "Value " + name + " was null" ) ; } else if ( argument . size ( ) == 0 ) { s_logger . error ( "Argument {} was empty collection" , name ) ; throw new QuandlRuntimeException ( "Value " + name + " was empty collection" ) ; } } | Throws an exception if the collection argument is not null or empty . |
37,084 | public static QuandlCodeRequest singleColumn ( final String quandlCode , final int columnNumber ) { ArgumentChecker . notNull ( quandlCode , "quandlCode" ) ; return new QuandlCodeRequest ( quandlCode , columnNumber ) ; } | Request just a single column for a given quandlCode . |
37,085 | public static QuandlCodeRequest allColumns ( final String quandlCode ) { ArgumentChecker . notNull ( quandlCode , "quandlCode" ) ; return new QuandlCodeRequest ( quandlCode , null ) ; } | Request all columns for a given quandlCode . |
37,086 | public static TabularResult of ( final HeaderDefinition headerDefinition , final List < Row > rows ) { ArgumentChecker . notNull ( headerDefinition , "headerDefinition" ) ; ArgumentChecker . notNull ( rows , "rows" ) ; return new TabularResult ( headerDefinition , rows ) ; } | Create a tabular result set from a header definition and an ordered list of rows . |
37,087 | public HeaderDefinition getHeaderDefinition ( ) { JSONArray jsonArray = null ; try { jsonArray = _jsonObject . getJSONArray ( COLUMN_NAMES_FIELD ) ; List < String > columnNames = new ArrayList < String > ( jsonArray . length ( ) ) ; for ( int i = 0 ; i < jsonArray . length ( ) ; i ++ ) { columnNames . add ( jsonArray . getString ( i ) ) ; } return HeaderDefinition . of ( columnNames ) ; } catch ( JSONException ex ) { s_logger . error ( "Metadata had unexpected structure - could not extract column_names field. Was:\n{}" , _jsonObject . toString ( ) ) ; throw new QuandlRuntimeException ( "Metadata had unexpected structure" , ex ) ; } } | Extract a HeaderDefinition from the meta data . Throws a QuandlRuntimeException if it cannot construct a valid HeaderDefinition |
37,088 | public String getQuandlCode ( ) { try { String dataSourceField = getString ( DATA_SOURCE_FIELD ) ; String codeField = getString ( CODE_FIELD ) ; return dataSourceField + "/" + codeField ; } catch ( RuntimeException ex ) { return null ; } } | Get the Quandl code associated with this metadata . |
37,089 | public String getString ( final String fieldName ) { try { return _jsonObject . getString ( fieldName ) ; } catch ( JSONException ex ) { throw new RuntimeException ( "Cannot find field" , ex ) ; } } | Get a String field . Throws a QuandlRuntimeException if it cannot find the field |
37,090 | public Double getDouble ( final String fieldName ) { try { if ( _jsonObject . isNull ( fieldName ) ) { return null ; } else { return _jsonObject . getDouble ( fieldName ) ; } } catch ( JSONException ex ) { throw new QuandlRuntimeException ( "Cannot find field" , ex ) ; } } | Get a Double field . This attempts to work around the stupid NaN is null behavior by explicitly testing for null . Throws a QuandlRuntimeException if it cannot find the field |
37,091 | public int getTotalDocuments ( ) { try { final int totalDocs = _jsonObject . getJSONObject ( META_OBJECT_FIELD ) . getInt ( "total_count" ) ; return totalDocs ; } catch ( JSONException ex ) { throw new QuandlRuntimeException ( "Could not find total_count field in results from Quandl" , ex ) ; } } | Get the total number of documents in this result set . Throws a QuandlRuntimeException if Quandl response doesn t contain this field although it should . |
37,092 | public int getDocumentsPerPage ( ) { try { final int perPage = _jsonObject . getJSONObject ( META_OBJECT_FIELD ) . getInt ( "per_page" ) ; return perPage ; } catch ( JSONException ex ) { throw new QuandlRuntimeException ( "Could not find total_count field in results from Quandl" , ex ) ; } } | Get the number of documents per page in this result set . Throws a QuandlRuntimeException if Quandl response doesn t contain this field although it should . |
37,093 | public int getCurrentPage ( ) { try { final int currentPage = _jsonObject . getJSONObject ( META_OBJECT_FIELD ) . getInt ( "current_page" ) ; return currentPage ; } catch ( JSONException ex ) { throw new QuandlRuntimeException ( "Could not find total_count field in results from Quandl" , ex ) ; } } | Get the current page of this result set . You can specify the page number in the request . Throws a QuandlRuntimeException if Quandl response doesn t contain this field although it should . |
37,094 | public List < MetaDataResult > getMetaDataResultList ( ) { JSONArray jsonArray = null ; try { jsonArray = _jsonObject . getJSONArray ( DATASETS_ARRAY_FIELD ) ; List < MetaDataResult > metaDataResults = new ArrayList < MetaDataResult > ( jsonArray . length ( ) ) ; for ( int i = 0 ; i < jsonArray . length ( ) ; i ++ ) { metaDataResults . add ( MetaDataResult . of ( jsonArray . getJSONObject ( i ) ) ) ; } return metaDataResults ; } catch ( JSONException ex ) { s_logger . error ( "Metadata had unexpected structure - could not extract datasets field, was:\n{}" , _jsonObject . toString ( ) ) ; throw new QuandlRuntimeException ( "Metadata had unexpected structure" , ex ) ; } } | Extract a list of MetaDataResult objects each one representing a match . Throws a QuandlRuntimeException if it cannot construct a valid HeaderDefinition |
37,095 | public static Row of ( final HeaderDefinition headerDefinition , final String [ ] values ) { ArgumentChecker . notNull ( headerDefinition , "headerDefinition" ) ; ArgumentChecker . notNull ( values , "values" ) ; return new Row ( headerDefinition , values ) ; } | Create a Row . Items in the values array can be null although the array cannot . If the headerDefinition has a different number of columns than the length of the values array then an IllegalArgumentException will be thrown . |
37,096 | public Row withPaddedHeader ( final HeaderDefinition headerDefinition ) { if ( _headerDefinition != headerDefinition ) { String [ ] values = new String [ headerDefinition . size ( ) ] ; System . arraycopy ( _values , 0 , values , 0 , _values . length ) ; return Row . of ( headerDefinition , values ) ; } else { return this ; } } | Create row with new header . |
37,097 | public String processMultiMetaDataRequest ( final MultiMetaDataRequest request ) { StringBuilder result = new StringBuilder ( ) ; for ( String code : request . getQuandlCodes ( ) ) { if ( result . length ( ) > 0 ) { result . append ( "," ) ; } result . append ( code ) ; } return result . toString ( ) ; } | Process a multi - metadata request into a descriptive title string . |
37,098 | public String processDataSetRequest ( final DataSetRequest request ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( request . getQuandlCode ( ) ) ; if ( request . getColumnIndex ( ) != null ) { sb . append ( " column index " ) ; sb . append ( request . getColumnIndex ( ) ) ; } if ( request . getStartDate ( ) != null ) { sb . append ( " from " ) ; sb . append ( request . getStartDate ( ) ) ; } if ( request . getEndDate ( ) != null ) { sb . append ( " until " ) ; sb . append ( request . getEndDate ( ) ) ; } if ( request . getFrequency ( ) != null ) { sb . append ( " sampled " ) ; sb . append ( request . getFrequency ( ) ) ; } if ( request . getSortOrder ( ) != null ) { sb . append ( " sorted into " ) ; sb . append ( request . getSortOrder ( ) ) ; sb . append ( " order" ) ; } if ( request . getTransform ( ) != null ) { sb . append ( " transformed by " ) ; sb . append ( request . getTransform ( ) ) ; } if ( request . getMaxRows ( ) != null ) { sb . append ( " with at most " ) ; sb . append ( request . getMaxRows ( ) ) ; sb . append ( " rows" ) ; } return sb . toString ( ) ; } | Process a data set request into a descriptive title string . |
37,099 | public String processMultiDataSetRequest ( final MultiDataSetRequest request ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Quandl codes " ) ; final Iterator < QuandlCodeRequest > iter = request . getQuandlCodeRequests ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { QuandlCodeRequest req = iter . next ( ) ; sb . append ( req . getQuandlCode ( ) ) ; if ( req . isSingleColumnRequest ( ) ) { sb . append ( "[" ) ; sb . append ( req . getColumnNumber ( ) ) ; sb . append ( "]" ) ; } if ( iter . hasNext ( ) ) { sb . append ( "," ) ; } } if ( request . getStartDate ( ) != null ) { sb . append ( " from " ) ; sb . append ( request . getStartDate ( ) ) ; } if ( request . getEndDate ( ) != null ) { sb . append ( " until " ) ; sb . append ( request . getEndDate ( ) ) ; } if ( request . getFrequency ( ) != null ) { sb . append ( " sampled " ) ; sb . append ( request . getFrequency ( ) ) ; } if ( request . getSortOrder ( ) != null ) { sb . append ( " sorted into " ) ; sb . append ( request . getSortOrder ( ) ) ; sb . append ( " order" ) ; } if ( request . getTransform ( ) != null ) { sb . append ( " transformed by " ) ; sb . append ( request . getTransform ( ) ) ; } if ( request . getMaxRows ( ) != null ) { sb . append ( " with at most " ) ; sb . append ( request . getMaxRows ( ) ) ; sb . append ( " rows" ) ; } return sb . toString ( ) ; } | Process a multi data set request into a descriptive title string . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.