Search in sources :

Example 26 with BiConsumer

use of java.util.function.BiConsumer in project crypto-bot by jnidzwetzki.

the class BarMegerTest method testBarMerger1.

/**
 * Test one Bar
 * @throws InterruptedException
 * @throws IOException
 */
@Test(timeout = 5000)
public void testBarMerger1() throws InterruptedException, IOException {
    final CountDownLatch latch = new CountDownLatch(1);
    final BiConsumer<BitfinexCurrencyPair, Bar> BarConsumer = (s, t) -> {
        latch.countDown();
    };
    final BarMerger BarMerger = new BarMerger(BitfinexCurrencyPair.BTC_USD, Timeframe.MINUTES_1, BarConsumer);
    BarMerger.addNewPrice(1000000, 1.0, 5.0);
    BarMerger.close();
    latch.await();
}
Also used : BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) CountDownLatch(java.util.concurrent.CountDownLatch) BarMerger(com.github.jnidzwetzki.cryptobot.util.BarMerger) BiConsumer(java.util.function.BiConsumer) SimpleDateFormat(java.text.SimpleDateFormat) IOException(java.io.IOException) Test(org.junit.Test) ParseException(java.text.ParseException) Assert(org.junit.Assert) Timeframe(com.github.jnidzwetzki.bitfinex.v2.entity.Timeframe) Bar(org.ta4j.core.Bar) Bar(org.ta4j.core.Bar) BarMerger(com.github.jnidzwetzki.cryptobot.util.BarMerger) CountDownLatch(java.util.concurrent.CountDownLatch) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) Test(org.junit.Test)

Example 27 with BiConsumer

use of java.util.function.BiConsumer in project crypto-bot by jnidzwetzki.

the class BarMegerTest method testTickMerger4.

/**
 * Test three tick merge with other timestamps
 * @throws InterruptedException
 * @throws IOException
 * @throws ParseException
 */
@Test(timeout = 6000)
public void testTickMerger4() throws InterruptedException, IOException, ParseException {
    final SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss");
    final CountDownLatch latch = new CountDownLatch(2);
    final BiConsumer<BitfinexCurrencyPair, Bar> tickConsumer = (s, t) -> {
        latch.countDown();
    };
    final BarMerger tickMerger = new BarMerger(BitfinexCurrencyPair.BTC_USD, Timeframe.MINUTES_1, tickConsumer);
    tickMerger.addNewPrice(parser.parse("01:01:23").getTime(), 1.0, 5.0);
    tickMerger.addNewPrice(parser.parse("01:01:33").getTime(), 2.0, 5.0);
    tickMerger.addNewPrice(parser.parse("02:02:53").getTime(), 2.0, 5.0);
    tickMerger.close();
    latch.await();
}
Also used : BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) CountDownLatch(java.util.concurrent.CountDownLatch) BarMerger(com.github.jnidzwetzki.cryptobot.util.BarMerger) BiConsumer(java.util.function.BiConsumer) SimpleDateFormat(java.text.SimpleDateFormat) IOException(java.io.IOException) Test(org.junit.Test) ParseException(java.text.ParseException) Assert(org.junit.Assert) Timeframe(com.github.jnidzwetzki.bitfinex.v2.entity.Timeframe) Bar(org.ta4j.core.Bar) Bar(org.ta4j.core.Bar) BarMerger(com.github.jnidzwetzki.cryptobot.util.BarMerger) CountDownLatch(java.util.concurrent.CountDownLatch) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) SimpleDateFormat(java.text.SimpleDateFormat) Test(org.junit.Test)

Example 28 with BiConsumer

use of java.util.function.BiConsumer in project crypto-bot by jnidzwetzki.

the class BarMegerTest method testTickMerger3.

/**
 * Test three tick merge
 * @throws InterruptedException
 * @throws IOException
 * @throws ParseException
 */
@Test(timeout = 6000)
public void testTickMerger3() throws InterruptedException, IOException, ParseException {
    final SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss");
    final CountDownLatch latch = new CountDownLatch(2);
    final BiConsumer<BitfinexCurrencyPair, Bar> tickConsumer = (s, t) -> {
        latch.countDown();
    };
    final BarMerger tickMerger = new BarMerger(BitfinexCurrencyPair.BTC_USD, Timeframe.MINUTES_1, tickConsumer);
    tickMerger.addNewPrice(parser.parse("01:01:23").getTime(), 1.0, 5.0);
    tickMerger.addNewPrice(parser.parse("01:01:33").getTime(), 2.0, 5.0);
    tickMerger.addNewPrice(parser.parse("01:02:53").getTime(), 2.0, 5.0);
    tickMerger.close();
    latch.await();
}
Also used : BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) CountDownLatch(java.util.concurrent.CountDownLatch) BarMerger(com.github.jnidzwetzki.cryptobot.util.BarMerger) BiConsumer(java.util.function.BiConsumer) SimpleDateFormat(java.text.SimpleDateFormat) IOException(java.io.IOException) Test(org.junit.Test) ParseException(java.text.ParseException) Assert(org.junit.Assert) Timeframe(com.github.jnidzwetzki.bitfinex.v2.entity.Timeframe) Bar(org.ta4j.core.Bar) Bar(org.ta4j.core.Bar) BarMerger(com.github.jnidzwetzki.cryptobot.util.BarMerger) CountDownLatch(java.util.concurrent.CountDownLatch) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) SimpleDateFormat(java.text.SimpleDateFormat) Test(org.junit.Test)

Example 29 with BiConsumer

use of java.util.function.BiConsumer in project crypto-bot by jnidzwetzki.

the class HistoricalCandlesHelper method requestHistoricalCandles.

/**
 * Request historical candles
 *
 * @param bitfinexApiBroker
 * @param timeframe
 * @param tradedCurrencies
 * @return
 * @throws InterruptedException
 * @throws APIException
 */
public static Map<BitfinexCandlestickSymbol, TimeSeries> requestHistoricalCandles(final BitfinexApiBroker bitfinexApiBroker, final Timeframe timeframe, final List<BitfinexCurrencyPair> tradedCurrencies) throws InterruptedException, APIException {
    logger.info("Request historical candles");
    final Map<BitfinexCandlestickSymbol, TimeSeries> timeSeries = new HashMap<>();
    for (final BitfinexCurrencyPair currency : tradedCurrencies) {
        final String bitfinexString = currency.toBitfinexString();
        final BaseTimeSeries currencyTimeSeries = new BaseTimeSeries(bitfinexString);
        final BitfinexCandlestickSymbol barSymbol = new BitfinexCandlestickSymbol(currency, timeframe);
        timeSeries.put(barSymbol, currencyTimeSeries);
        final CountDownLatch tickCountdown = new CountDownLatch(100);
        // Add bars to timeseries callback
        final BiConsumer<BitfinexCandlestickSymbol, BitfinexTick> callback = (channelSymbol, tick) -> {
            final TimeSeries timeSeriesToAdd = timeSeries.get(channelSymbol);
            final Bar bar = BarConverter.convertBitfinexTick(tick);
            try {
                timeSeriesToAdd.addBar(bar);
                tickCountdown.countDown();
            } catch (IllegalArgumentException e) {
                logger.error("Unable to add tick {} to time series, last tick is {}", bar, timeSeriesToAdd.getLastBar());
            }
        };
        bitfinexApiBroker.getQuoteManager().registerCandlestickCallback(barSymbol, callback);
        bitfinexApiBroker.getQuoteManager().subscribeCandles(barSymbol);
        // Wait for 100 bars or 10 seconds. All snapshot ticks are handled in
        // a synchronized block, so we receive the full snapshot even if we
        // call removeTickCallback.
        tickCountdown.await(10, TimeUnit.SECONDS);
        bitfinexApiBroker.getQuoteManager().registerCandlestickCallback(barSymbol, callback);
        bitfinexApiBroker.getQuoteManager().unsubscribeCandles(barSymbol);
        logger.info("Loaded ticks for symbol {} {}", bitfinexString, +timeSeries.get(barSymbol).getEndIndex());
    }
    return timeSeries;
}
Also used : TimeSeries(org.ta4j.core.TimeSeries) BitfinexApiBroker(com.github.jnidzwetzki.bitfinex.v2.BitfinexApiBroker) BitfinexTick(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexTick) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Timeframe(com.github.jnidzwetzki.bitfinex.v2.entity.Timeframe) BitfinexCandlestickSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexCandlestickSymbol) Bar(org.ta4j.core.Bar) APIException(com.github.jnidzwetzki.bitfinex.v2.entity.APIException) TimeUnit(java.util.concurrent.TimeUnit) BaseTimeSeries(org.ta4j.core.BaseTimeSeries) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) BarConverter(com.github.jnidzwetzki.cryptobot.util.BarConverter) TimeSeries(org.ta4j.core.TimeSeries) BaseTimeSeries(org.ta4j.core.BaseTimeSeries) BitfinexTick(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexTick) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Bar(org.ta4j.core.Bar) BitfinexCandlestickSymbol(com.github.jnidzwetzki.bitfinex.v2.entity.symbol.BitfinexCandlestickSymbol) BaseTimeSeries(org.ta4j.core.BaseTimeSeries) BitfinexCurrencyPair(com.github.jnidzwetzki.bitfinex.v2.entity.BitfinexCurrencyPair)

Example 30 with BiConsumer

use of java.util.function.BiConsumer in project raml-module-builder by folio-org.

the class AnnotationGrabber method generateMappings.

// ^http.*?//.*?/apis/patrons/.*?/fines/.*
// ^http.*?\/\/.*?\/apis\/patrons\/?(.+?)*
// ^http.*?\/\/.*?\/apis\/([^\/]+)\/([^\/]+)(\?.*)
public static JsonObject generateMappings() throws Exception {
    /* this class is one of the drivers for the client generation
     * check if the plugin set the system property in the pom and only if
     * so generate */
    String clientGen = System.getProperty("client.generate");
    String modDescr = System.getProperty("modDescrptor.generate");
    if (clientGen != null) {
        generateClient = true;
    }
    if ("true".equals(modDescr)) {
        generateModDescrptor = true;
    }
    JsonObject globalClassMapping = new JsonObject();
    // get classes in generated package
    ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClasses(RTFConsts.INTERFACE_PACKAGE);
    Collection<Object> classNames = Collections2.transform(classes, new Function<ClassPath.ClassInfo, Object>() {

        @Override
        public Object apply(ClassPath.ClassInfo input) {
            log.info("Mapping functions in " + input.getName() + " class to appropriate urls");
            // not needed - dont need transform function,
            return input.getName();
        // remove
        }
    });
    // loop over all the classes from the package
    classNames.forEach(val -> {
        try {
            ClientGenerator cGen = new ClientGenerator();
            // ----------------- class level annotations -----------------------//
            // -----------------------------------------------------------------//
            // will contain all mappings for a specific class in the package
            JsonObject classSpecificMapping = new JsonObject();
            // get annotations via reflection for a class
            Annotation[] annotations = Class.forName(val.toString()).getAnnotations();
            // create an entry for the class name = ex. "class":"com.sling.rest.jaxrs.resource.BibResource"
            classSpecificMapping.put(CLASS_NAME, val.toString());
            classSpecificMapping.put(INTERFACE_NAME, val.toString());
            // needed info - these are class level annotation - not method level
            for (int i = 0; i < annotations.length; i++) {
                // get the annotation type - example in jersey would we javax.ws.rs.Path
                Class<? extends Annotation> type = annotations[i].annotationType();
                // function
                for (Method method : type.getDeclaredMethods()) {
                    Object value = method.invoke(annotations[i], (Object[]) null);
                    if (type.isAssignableFrom(Path.class)) {
                        classSpecificMapping.put(CLASS_URL, "^/" + value);
                        if (generateClient) {
                            cGen.generateClassMeta(val.toString(), value);
                        }
                        if (generateModDescrptor && classSpecificMapping.getString(CLASS_URL) != null) {
                            String url = classSpecificMapping.getString(CLASS_URL).substring(2);
                            if (!url.contains("rmbtests")) {
                                MDGenerator.ProvidesEntry pe = MDGenerator.INSTANCE.new ProvidesEntry();
                                if (url.contains("_/tenant")) {
                                    url = "_tenant";
                                }
                                pe.setId(url);
                                MDGenerator.INSTANCE.addProvidesEntry(pe);
                            }
                        }
                    }
                }
            }
            // ----------------- method level annotations ------------ //
            // ------------------------------------------------------- //
            /**
             * will be used only if ModuleDescriptor generation is turned on
             * maps all http verbs to a single url
             */
            mdUrl2Verbs = new HashMap<>();
            JsonArray methodsInAPath;
            // iterate over all functions in the class
            Method[] methods = Class.forName(val.toString()).getMethods();
            for (int i = 0; i < methods.length; i++) {
                JsonObject methodObj = new JsonObject();
                JsonObject params = getParameterNames(methods[i]);
                // get annotations on the method and add all info per method to its
                // own methodObj
                Annotation[] methodAn = methods[i].getAnnotations();
                // System.out.println(methods[i].getName());
                // put the name of the function
                methodObj.put(FUNCTION_NAME, methods[i].getName());
                methodObj.put(METHOD_PARAMS, params);
                for (int j = 0; j < methodAn.length; j++) {
                    Class<? extends Annotation> type = methodAn[j].annotationType();
                    // System.out.println("Values of " + type.getName());
                    if (RTFConsts.POSSIBLE_HTTP_METHOD.contains(type.getName())) {
                        // put the method - get or post, etc..
                        methodObj.put(HTTP_METHOD, type.getName());
                    }
                    boolean replaceAccept = false;
                    if (type.isAssignableFrom(Produces.class)) {
                        // this is the accept header, right now can not send */*
                        // so if accept header equals any/ - change this to */*
                        replaceAccept = true;
                    }
                    for (Method method : type.getDeclaredMethods()) {
                        Object value = method.invoke(methodAn[j], (Object[]) null);
                        if (value.getClass().isArray()) {
                            List<Object> retList = new ArrayList<>();
                            for (int k = 0; k < Array.getLength(value); k++) {
                                if (replaceAccept) {
                                    // replace any/any with */* to allow declaring accpet */* which causes compilation issues
                                    // when declared in raml. so declare any/any in raml instead and replaced here
                                    retList.add(((String) Array.get(value, k)).replaceAll("any/any", ""));
                                } else {
                                    retList.add(Array.get(value, k));
                                }
                            }
                            // put generically things like consumes, produces as arrays
                            // since they can have multi values
                            methodObj.put(type.getName(), retList);
                        } else {
                            if (type.isAssignableFrom(Path.class)) {
                                String path = classSpecificMapping.getString(CLASS_URL) + URL_PATH_DELIMITER + value;
                                String regexPath = getRegexForPath(path);
                                // put path to function
                                methodObj.put(METHOD_URL, path);
                                // put regex path to function
                                methodObj.put(REGEX_URL, regexPath);
                            }
                        // System.out.println(" " + method.getName() + ": " + value.toString());
                        }
                    }
                }
                if (generateClient) {
                    cGen.generateMethodMeta(methodObj.getString(FUNCTION_NAME), methodObj.getJsonObject(METHOD_PARAMS), methodObj.getString(METHOD_URL), methodObj.getString(HTTP_METHOD), methodObj.getJsonArray(CONSUMES), methodObj.getJsonArray(PRODUCES));
                }
                // class
                if (methodObj.getString(METHOD_URL) == null) {
                    methodObj.put(METHOD_URL, classSpecificMapping.getString(CLASS_URL));
                    methodObj.put(REGEX_URL, getRegexForPath(classSpecificMapping.getString(CLASS_URL)));
                }
                if (generateModDescrptor) {
                    String verb = methodObj.getString(HTTP_METHOD);
                    verb = verb.substring(verb.lastIndexOf(".") + 1);
                    String rootURL4Service = classSpecificMapping.getString(CLASS_URL).substring(1);
                    /*if(mdUrl2Verbs.get(path.substring(1)) != null){
              mdUrl2Verbs.get(path.substring(1)).add(verb);
            } else {
              mdUrl2Verbs.put(path.substring(1), new JsonArray());
              mdUrl2Verbs.get(path.substring(1)).add(verb);
            }*/
                    if (mdUrl2Verbs.get(rootURL4Service) != null) {
                        mdUrl2Verbs.get(rootURL4Service).add(verb);
                    } else {
                        mdUrl2Verbs.put(rootURL4Service, new HashSet<String>());
                        mdUrl2Verbs.get(rootURL4Service).add(verb);
                    }
                }
                // this is the key - the regex path is the key to the functions
                // represented by this url
                // an array of functions which answer to this url (with get, delete,
                // post, etc... methods)
                methodsInAPath = classSpecificMapping.getJsonArray(methodObj.getString(REGEX_URL));
                if (methodsInAPath == null) {
                    methodsInAPath = new JsonArray();
                    classSpecificMapping.put(methodObj.getString(REGEX_URL), methodsInAPath);
                }
                methodsInAPath.add(methodObj);
            }
            // System.out.println( val.toString() );
            globalClassMapping.put(classSpecificMapping.getString(CLASS_URL), classSpecificMapping);
            if (generateClient) {
                cGen.generateClass(classSpecificMapping);
            }
            if (generateModDescrptor) {
                BiConsumer<String, Set<String>> biConsumer = (key, value) -> {
                    if (!key.contains("_/tenant") && !key.contains("rmbtests")) {
                        MDGenerator.RoutingEntry re = MDGenerator.INSTANCE.new RoutingEntry();
                        JsonArray ja = new JsonArray();
                        value.forEach(verb -> {
                            ja.add(verb);
                        });
                        re.setMethods(ja);
                        re.setEntryPath(key);
                        re.setLevel("30");
                        re.setType("request-response");
                        MDGenerator.INSTANCE.addRoutingEntry(re);
                    }
                };
                mdUrl2Verbs.forEach(biConsumer);
                MDGenerator.INSTANCE.generateMD();
                // this is needed when the MDGenerator is used to generate
                // partial MDs in submodules. the system variable is maintained
                // across the sub module builds and if not reset will generate a
                // partial MD for all sub modules
                System.setProperty("modDescrptor.generate", "false");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    });
    // writeMappings(globalClassMapping);
    return globalClassMapping;
}
Also used : PathParam(javax.ws.rs.PathParam) Array(java.lang.reflect.Array) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) HashMap(java.util.HashMap) Collections2(com.google.common.collect.Collections2) LoggerFactory(io.vertx.core.logging.LoggerFactory) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) QueryParam(javax.ws.rs.QueryParam) Parameter(java.lang.reflect.Parameter) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) JsonObject(io.vertx.core.json.JsonObject) ClassPath(com.google.common.reflect.ClassPath) Logger(io.vertx.core.logging.Logger) Method(java.lang.reflect.Method) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Annotation(java.lang.annotation.Annotation) ClassPath(com.google.common.reflect.ClassPath) HashSet(java.util.HashSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject)

Aggregations

BiConsumer (java.util.function.BiConsumer)264 Test (org.junit.Test)111 List (java.util.List)109 Map (java.util.Map)79 IOException (java.io.IOException)78 ArrayList (java.util.ArrayList)74 Consumer (java.util.function.Consumer)71 HashMap (java.util.HashMap)66 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)54 Collectors (java.util.stream.Collectors)53 CountDownLatch (java.util.concurrent.CountDownLatch)52 Collections (java.util.Collections)46 Set (java.util.Set)46 Collection (java.util.Collection)45 Arrays (java.util.Arrays)44 TimeUnit (java.util.concurrent.TimeUnit)43 Function (java.util.function.Function)43 Assert (org.junit.Assert)43 Optional (java.util.Optional)41 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)35