Example usage for org.apache.commons.lang3.tuple Pair getLeft

List of usage examples for org.apache.commons.lang3.tuple Pair getLeft

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getLeft.

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this pair.

When treated as a key-value pair, this is the key.

Usage

From source file:de.tuberlin.uebb.jbop.optimizer.var.LocalVarInliner.java

private AbstractInsnNode handleNode(final InsnList original, final AbstractInsnNode currentNode,
        final Map<Integer, Object> knownValues, final MethodNode methodNode) {
    final int opcode = currentNode.getOpcode();
    if (opcode >= ISTORE && opcode <= ASTORE) {
        handleStore(currentNode, knownValues);
    } else if (opcode >= ILOAD && opcode <= ALOAD) {
        return hanldeLoad(original, currentNode, knownValues).getNext();
    } else if (opcode == IINC) {
        handleIInc(currentNode, knownValues);
    } else if (NodeHelper.isIf(currentNode)) {
        return handleIf(currentNode, knownValues, original, methodNode);
    } else if (opcode == GOTO) {
        if (LoopMatcher.isGotoOfLoop(currentNode)) {
            final AbstractInsnNode skipVars = skipVars(currentNode, knownValues);
            final Pair<AbstractInsnNode, AbstractInsnNode> bodyBounds = LoopMatcher.getBodyBounds(currentNode);
            if (bodyBounds != null) {
                handleNodes(bodyBounds.getLeft(), bodyBounds.getRight(), original, new HashMap<>(knownValues),
                        methodNode);//from   w  w w. j  av a 2  s . c o  m
            }
            return skipVars;
        }
        return currentNode.getNext();
    }
    return currentNode.getNext();
}

From source file:com.codeveo.lago.bot.stomp.client.AbstractHttpLagoBot.java

protected void setupAndSignInClient(String lagoUrl, String botUsername, String botPassword,
        LagoRequestHelper requestHelper) throws Exception {
    try {/*from   ww w . j  av  a  2s.co m*/
        if (requestHelper == null) {
            throw new Exception("Request helper must not be null");
        }

        if (!(requestHelper instanceof HttpLagoRequestHelper)) {
            throw new Exception("Requires instance of '" + HttpLagoRequestHelper.class.getSimpleName()
                    + "' not '" + requestHelper.getClass().getSimpleName() + "'");
        }

        HttpLagoRequestHelper httpRequestHelper = (HttpLagoRequestHelper) requestHelper;

        lagoBot = new RLagoBot(null, null, botUsername, botPassword);

        Builder builder = new AsyncHttpClientConfig.Builder();
        Realm realm = new Realm.RealmBuilder().setPrincipal(botUsername).setPassword(botPassword)
                .setUsePreemptiveAuth(true).setScheme(AuthScheme.BASIC).build();
        builder.setRealm(realm).build();

        asyncHttpClient = new AsyncHttpClient(builder.build());

        Pair<Integer, String> statusWithCookieOrFaultJSON = HttpLagoRequestHelper.signIn(lagoUrl, botUsername,
                botPassword);

        int statusCode = statusWithCookieOrFaultJSON.getLeft();

        if (statusCode == HttpStatus.CREATED.value()) {
            cookie = statusWithCookieOrFaultJSON.getRight();

            /* websocket headers */
            wsHeaders.add("Cookie", cookie);
        } else {
            String faultJSON = statusWithCookieOrFaultJSON.getRight();

            if (faultJSON != null) {
                RFault fault = objectMapper.readValue(faultJSON, RFault.class);

                if (fault != null) {
                    throw new Exception("Error occured during authentication (HTTP status code: " + statusCode
                            + ", Error code: " + fault.getErrorCode() + ", Message: '" + fault.getMessage()
                            + "')");
                }
            }

            throw new Exception("Error occured during authentication (HTTP status code: " + statusCode);
        }

        if (cookie == null) {
            throw new Exception("Bot '" + botUsername + "' could not sign in");
        }

        /* setup request helper */
        httpRequestHelper.setAsyncHttpClient(asyncHttpClient).setCookie(cookie).setObjectMapper(objectMapper)
                .setServerUrl(lagoUrl);
        this.httpLagoRequestHelper = httpRequestHelper;

        String wsLagoUrl = toWsUrl(lagoUrl);
        URI uri = new URI(wsLagoUrl + WebServiceUserDesc.WS_PATH);

        LagoStompMessageHandler messageListener = new LagoStompMessageHandler(lagoBot, queue);

        List<Transport> transports = new ArrayList<>();
        transports.add(new WebSocketTransport(new StandardWebSocketClient()));
        RestTemplateXhrTransport xhrTransport = new RestTemplateXhrTransport(new RestTemplate());
        xhrTransport.setRequestHeaders(wsHeaders);
        transports.add(xhrTransport);

        sockJsClient = new SockJsClient(transports);
        stompClient = new WebSocketStompClient(uri, wsHeaders, sockJsClient);
        stompClient.setMessageConverter(converter);
        stompClient.connect(messageListener);

        taskExecutor.submit(new StompMessageListener());
    } catch (Exception e) {
        if (cookie != null) {
            httpLagoRequestHelper.signOut();
        }

        throw new Exception("Error occured while initializing lago bot", e);
    }
}

From source file:com.act.utils.parser.GenbankInterpreterTest.java

private void validateFeatureMap(Map<Pair<String, String>, Map<String, String>> feature_to_qualifiers,
        GenbankInterpreter gi) {//from   w  w w.j  av  a2  s .  c  om
    for (Pair<String, String> feature_type_and_source : feature_to_qualifiers.keySet()) {
        for (List<Qualifier> qual_list : gi
                .getQualifiers(0, feature_type_and_source.getLeft(), feature_type_and_source.getRight())
                .values()) {
            for (Qualifier qual : qual_list) {
                Map<String, String> qual_map = feature_to_qualifiers.get(feature_type_and_source);
                assertTrue("testing whether the qualifier name extracted is accurate",
                        qual_map.containsKey(qual.getName()));
                if (qual.getName().equals("dbxref")) {
                    assertEquals("testing whether the extracted value of the db_xref qualifier is accurate",
                            qual_map.get(qual.getName()),
                            ((DBReferenceInfo) qual).getDatabase() + ":" + ((DBReferenceInfo) qual).getId());
                } else {
                    assertEquals("testing whether the extracted value of the qualifier is accurate",
                            qual_map.get(qual.getName()), qual.getValue());
                }
            }
        }
    }
}

From source file:com.dgtlrepublic.anitomyj.Tokenizer.java

/** Tokenize by bracket. */
private void tokenizeByBrackets() {
    /** a ref to the closing brace of a found opening brace. (e.g "}" if we found an "}") */
    AtomicReference<String> matchingBracket = new AtomicReference<>();

    /** function to find an opening brace */
    BiFunction<Integer, Integer, Integer> findFirstBracket = (start, end) -> {
        for (int i = start; i < end; i++) {
            for (Pair<String, String> bracket : brackets) {
                if (String.valueOf(filename.charAt(i)).equals(bracket.getLeft())) {
                    matchingBracket.set(bracket.getRight());
                    return i;
                }/*from  w  w  w . ja v  a 2s  .  com*/
            }
        }

        return -1;
    };

    boolean isBracketOpen = false;
    for (int i = 0; i < filename.length();) {
        int foundIdx;
        if (!isBracketOpen) {
            /** look for opening brace */
            foundIdx = findFirstBracket.apply(i, filename.length());
        } else {
            /** look for closing brace */
            foundIdx = filename.indexOf(matchingBracket.get(), i);
        }

        TokenRange range = new TokenRange(i, foundIdx == -1 ? filename.length() : foundIdx - i);
        if (range.getSize() > 0) {
            /** check if our range contains any known anime identifies */
            tokenizeByPreidentified(isBracketOpen, range);
        }

        if (foundIdx != -1) {
            /** mark as bracket */
            addToken(TokenCategory.kBracket, true, new TokenRange(range.getOffset() + range.getSize(), 1));
            isBracketOpen = !isBracketOpen;
            i = foundIdx + 1;
        } else {
            break;
        }
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.agent.KubernetesV2OnDemandCachingAgent.java

@Override
public OnDemandAgent.OnDemandResult handle(ProviderCache providerCache, Map<String, ?> data) {
    String account = (String) data.get("account");
    String namespace = (String) data.get("location");
    String fullName = (String) data.get("name");
    String name;/*w ww.ja va 2s.  c  om*/
    KubernetesKind kind;

    try {
        Pair<KubernetesKind, String> parsedName = KubernetesManifest.fromFullResourceName(fullName);
        kind = parsedName.getLeft();
        if (!primaryKinds().contains(kind)) {
            return null;
        }

        name = parsedName.getRight();
    } catch (Exception e) {
        // This is OK - the cache controller tries (w/o much info) to get every cache agent to handle each request
        return null;
    }

    reloadNamespaces();
    if (StringUtils.isEmpty(account) || StringUtils.isEmpty(name)
            || (!StringUtils.isEmpty(namespace) && !namespaces.contains(namespace))) {
        return null;
    }

    log.info("Accepted on demand refresh of '{}'", data);
    OnDemandAgent.OnDemandResult result;
    KubernetesManifest manifest = loadPrimaryResource(kind, namespace, name);
    String resourceKey = Keys.infrastructure(kind, account, namespace, name);
    try {
        result = manifest == null ? evictEntry(providerCache, kind, resourceKey)
                : addEntry(providerCache, resourceKey, manifest);
    } catch (Exception e) {
        log.error("Failed to process update of '{}'", resourceKey, e);
        return null;
    }

    log.info("On demand cache refresh of (data: {}) succeeded", data);
    return result;
}

From source file:com.qq.tars.service.monitor.TARSStatMonitorService.java

private MultiKeyMap call(List<String> groupBy, List<String> conditions) throws IOException {
    String template = "{\"groupby\":%s,\"method\":\"query\",\"dataid\":\"tars_stat\","
            + "\"filter\":%s,\"indexs\":[\"succ_count\",\"timeout_count\",\"exce_count\",\"total_time\"]}";

    ObjectMapper mapper = new ObjectMapper();
    String request = String.format(template, mapper.writeValueAsString(groupBy),
            mapper.writeValueAsString(conditions));

    List<Pair<String, Integer>> addrs = adminService.getEndpoints("tars.tarsquerystat.NoTarsObj");
    if (addrs.isEmpty()) {
        throw new IOException("tars.tarsquerystat.NoTarsObj not found");
    }//ww w  .  ja v a2 s . com

    Pair<String, Integer> addr = addrs.get(0);
    log.info("tars.tarsquerystat.NoTarsObj, use {}:{}", addr.getLeft(), addr.getRight());

    TCPClient client = new TCPClient(addr.getLeft(), addr.getRight());
    List<String> response = client.sendAndReceive(request.getBytes(), 60000);

    log.debug("request={}", request);
    log.debug("reponse={}", StringUtils.join(response, "\n"));

    String line1 = response.get(0);
    if (!line1.startsWith("Ret:")) {
        throw new IOException(String.format("line #1, doesn't start with \"Ret:\", line=%s", line1));
    }
    int ret = Integer.parseInt(line1.substring(line1.lastIndexOf(':') + 1));
    if (ret == -1) {
        throw new IOException(String.format("line #1, Ret=%s", ret));
    }

    String line6 = response.get(5);
    if (!line6.startsWith("linecount:")) {
        throw new IOException(String.format("line #6, doesn't start with \"linecount:\", line=%s", line6));
    }
    int count = Integer.parseInt(line6.substring(line6.lastIndexOf(':') + 1));
    if (count + 7 != response.size()) {
        throw new IOException(String.format("line #6, size not match, %s vs %s", count + 7, response.size()));
    }

    String lastLine = response.get(response.size() - 1);
    if (!"endline".equals(lastLine)) {
        throw new IOException(
                String.format("line #%s, doesn't equal to \"endline\", line=%s", response.size(), lastLine));
    }

    MultiKeyMap result = new MultiKeyMap();
    for (int i = 6; i < response.size() - 1; i++) {
        String line = StringUtils.removeEnd(response.get(i), ",");
        String[] tokens = line.split(",");
        if (tokens.length != groupBy.size() + 4) {
            throw new IOException(String.format("line format error, line=%s", line));
        }

        String[] key = new String[groupBy.size()];
        int j = 0;
        for (; j < key.length; j++) {
            key[j] = tokens[j];
        }

        long[] value = new long[] { Long.parseLong(tokens[j++]), Long.parseLong(tokens[j++]),
                Long.parseLong(tokens[j++]), Long.parseLong(tokens[j]) };
        result.put(new MultiKey(key), value);
    }
    return result;
}

From source file:ca.on.oicr.pde.workflows.GATKHaplotypeCallerWorkflow.java

@Override
public void buildWorkflow() {

    final String binDir = this.getWorkflowBaseDir() + "/bin/";
    final Boolean manualOutput = BooleanUtils.toBoolean(getProperty("manual_output"), "true", "false");
    final String queue = getOptionalProperty("queue", "");
    final String java = getProperty("java");
    final String gatk = getOptionalProperty("gatk_jar", binDir);
    final String gatkKey = getProperty("gatk_key");
    final String identifier = getProperty("identifier");
    final String refFasta = getProperty("ref_fasta");
    final String dbsnpVcf = getProperty("gatk_dbsnp_vcf");
    final Integer intervalPadding = hasPropertyAndNotNull("interval_padding")
            ? Integer.parseInt(getProperty("interval_padding"))
            : null;/*  w  ww. j  a  v  a 2  s.c om*/
    final Integer downsamplingCoverage = hasPropertyAndNotNull("downsampling_coverage")
            ? Integer.parseInt(getProperty("downsampling_coverage"))
            : null;
    final String downsamplingType = getOptionalProperty("downsampling_type", null);
    final Integer gatkHaplotypeCallerThreads = Integer.parseInt(getProperty("gatk_haplotype_caller_threads"));
    final Integer gatkHaplotypeCallerXmx = Integer.parseInt(getProperty("gatk_haplotype_caller_xmx"));
    final Integer gatkCombineGVCFsXmx = Integer.parseInt(getProperty("gatk_combine_gvcfs_xmx"));
    final Integer gatkOverhead = Integer.parseInt(getProperty("gatk_sched_overhead_mem"));
    final String haplotypeCallerParams = getOptionalProperty("gatk_haplotype_caller_params", null);

    final List<String> intervalFilesList = Arrays
            .asList(StringUtils.split(getOptionalProperty("interval_files", ""), ","));
    final Set<String> intervalFiles = new HashSet<>(intervalFilesList);
    if (intervalFiles.size() != intervalFilesList.size()) {
        throw new RuntimeException("Duplicate interval_files detected");
    }

    final Set<String> chrSizes;
    if (hasProperty("chr_sizes")) {
        //chr_sizes has been set
        List<String> chrSizesList = Arrays.asList(StringUtils.split(getProperty("chr_sizes"), ","));
        chrSizes = new HashSet<>(chrSizesList);
        if (chrSizes.size() != chrSizesList.size()) {
            throw new RuntimeException("Duplicate chr_sizes detected.");
        }
    } else if (!intervalFiles.isEmpty()) {
        //chr_sizes not set, interval_files has been set - use interval files to calculate chrSizes
        try {
            chrSizes = BEDFileUtils.getChromosomes(intervalFiles);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    } else {
        //chr_sizes and interval_files not set - can not calculate chrSizes
        chrSizes = new HashSet<>();
    }

    // one chrSize record is required, null will result in no parallelization
    if (chrSizes.isEmpty()) {
        chrSizes.add(null);
    }

    Map<String, Pair<HaplotypeCaller, Job>> gvcfs = new HashMap<>();
    for (String chrSize : chrSizes) {
        //GATK Haplotype Caller ( https://www.broadinstitute.org/gatk/gatkdocs/org_broadinstitute_gatk_tools_walkers_haplotypecaller_HaplotypeCaller.php )
        HaplotypeCaller haplotypeCallerCommand = new HaplotypeCaller.Builder(java,
                Integer.toString(gatkHaplotypeCallerXmx) + "g", tmpDir, gatk, gatkKey, dataDir)
                        .setInputBamFiles(inputBamFiles).setReferenceSequence(refFasta)
                        .setDbsnpFilePath(dbsnpVcf).addInterval(chrSize).addIntervalFiles(intervalFiles)
                        .setIntervalPadding(intervalPadding)
                        .setDownsamplingCoverageThreshold(downsamplingCoverage)
                        .setDownsamplingType(downsamplingType)
                        .setOutputFileName(
                                identifier + (chrSize != null ? "." + chrSize.replace(":", "-") : ""))
                        .setNumCpuThreadsPerDataThread(gatkHaplotypeCallerThreads)
                        .setExtraParameters(haplotypeCallerParams).build();
        Job haplotypeCallerJob = this.getWorkflow().createBashJob("GATKHaplotypeCaller")
                .setMaxMemory(Integer.toString((gatkHaplotypeCallerXmx + gatkOverhead) * 1024)).setQueue(queue);
        haplotypeCallerJob.getCommand().setArguments(haplotypeCallerCommand.getCommand());

        if (gvcfs.put(chrSize, Pair.of(haplotypeCallerCommand, haplotypeCallerJob)) != null) {
            throw new RuntimeException("Unexpected state: Duplicate key.");
        }
    }

    if (gvcfs.size() > 1) {
        //GATK CatVariants ( https://www.broadinstitute.org/gatk/guide/tooldocs/org_broadinstitute_gatk_tools_CatVariants.php )
        CatVariants.Builder catVariantsBuilder = new CatVariants.Builder(java,
                Integer.toString(gatkCombineGVCFsXmx) + "g", tmpDir, gatk, gatkKey, dataDir)
                        .setReferenceSequence(refFasta).setOutputFileName(identifier);
        for (HaplotypeCaller hc : getLeftCollection(gvcfs.values())) {
            catVariantsBuilder.addInputFile(hc.getOutputFile());
        }
        CatVariants catvariantsCommand = catVariantsBuilder.build();
        Job combineGVCFsJob = getWorkflow().createBashJob("GATKCombineGVCFs")
                .setMaxMemory(Integer.toString((gatkCombineGVCFsXmx + gatkOverhead) * 1024)).setQueue(queue);
        combineGVCFsJob.getParents().addAll(getRightCollection(gvcfs.values()));
        combineGVCFsJob.getCommand().setArguments(catvariantsCommand.getCommand());
        combineGVCFsJob.addFile(
                createOutputFile(catvariantsCommand.getOutputFile(), "application/g-vcf-gz", manualOutput));
        combineGVCFsJob.addFile(
                createOutputFile(catvariantsCommand.getOutputIndex(), "application/tbi", manualOutput));
    } else if (gvcfs.size() == 1) {
        Pair<HaplotypeCaller, Job> p = Iterables.getOnlyElement(gvcfs.values());
        HaplotypeCaller hcCmd = p.getLeft();
        Job hcJob = p.getRight();
        hcJob.addFile(createOutputFile(hcCmd.getOutputFile(), "application/g-vcf-gz", manualOutput));
        hcJob.addFile(createOutputFile(hcCmd.getOutputIndex(), "application/tbi", manualOutput));
    } else {
        throw new RuntimeException("Unexpected state: No GVCFs");
    }
}

From source file:com.epam.catgenome.manager.externaldb.ncbi.NCBIGeneManager.java

/**
 * Retrieves XML gene info from NCBI's gene database
 *
 * @param id gene id//w w w.  ja v a 2 s . c  om
 * @return NCBIGeneVO
 * @throws ExternalDbUnavailableException
 */

public NCBIGeneVO fetchGeneById(final String id) throws ExternalDbUnavailableException {

    String realID = id;
    NCBIGeneVO ncbiGeneVO = null;

    if (StringUtils.isNotBlank(id)) {

        // if ID contains literals then we consider this external ID and perform search
        if (!id.matches("\\d+")) {
            String ncbiId = ncbiAuxiliaryManager.searchDbForId(NCBIDatabase.GENE.name(), realID);
            realID = StringUtils.isNotBlank(ncbiId) ? ncbiId : id;
        }

        String geneInfoXml = ncbiAuxiliaryManager.fetchXmlById(NCBIDatabase.GENE.name(), realID, null);
        ncbiGeneVO = geneInfoParser.parseGeneInfo(geneInfoXml);
        ncbiGeneVO.setLinkToCitations(String.format(NCBI_PUBMED_FULL_URL, ncbiGeneVO.getGeneId()));
        ncbiGeneVO.setGeneLink(String.format(NCBI_GENE_LINK, ncbiGeneVO.getGeneId()));
        String pubmedQueryXml = ncbiAuxiliaryManager.link(realID, NCBIDatabase.GENE.name(),
                NCBIDatabase.PUBMED.name(), "gene_pubmed");

        Pair<String, String> stringStringPair = geneInfoParser.parseHistoryResponse(pubmedQueryXml,
                NCBIUtility.NCBI_LINK);

        String pubmedHistoryQuery = stringStringPair.getLeft();
        String pubmedHistoryWebenv = stringStringPair.getRight();

        JsonNode pubmedEntries = ncbiAuxiliaryManager.summaryWithHistory(pubmedHistoryQuery,
                pubmedHistoryWebenv);
        JsonNode pubmedResultRoot = pubmedEntries.path(RESULT_PATH).path(UIDS);
        try {
            parseJsonFromPubmed(pubmedResultRoot, pubmedEntries, ncbiGeneVO);
        } catch (JsonProcessingException e) {
            throw new ExternalDbUnavailableException(
                    MessageHelper.getMessage(MessagesConstants.ERROR_NO_RESULT_BY_EXTERNAL_DB), e);
        }

        String biosystemsQueryXml = ncbiAuxiliaryManager.link(realID, NCBIDatabase.GENE.name(),
                NCBIDatabase.BIOSYSTEMS.name(), "gene_biosystems");
        Pair<String, String> biosystemsParams = geneInfoParser.parseHistoryResponse(biosystemsQueryXml,
                NCBIUtility.NCBI_LINK);

        String biosystemsHistoryQuery = biosystemsParams.getLeft();
        String biosystemsHistoryWebenv = biosystemsParams.getRight();

        JsonNode biosystemsEntries = ncbiAuxiliaryManager.summaryWithHistory(biosystemsHistoryQuery,
                biosystemsHistoryWebenv);
        JsonNode biosystemsResultRoot = biosystemsEntries.path(RESULT_PATH).path(UIDS);
        try {
            parseJsonFromBio(biosystemsResultRoot, biosystemsEntries, ncbiGeneVO);
        } catch (JsonProcessingException e) {
            throw new ExternalDbUnavailableException(
                    MessageHelper.getMessage(MessagesConstants.ERROR_NO_RESULT_BY_EXTERNAL_DB), e);
        }

        String homologsQueryXml = ncbiAuxiliaryManager.link(realID, NCBIDatabase.GENE.name(),
                NCBIDatabase.HOMOLOGENE.name(), "gene_homologene");
        Pair<String, String> homologsParams = geneInfoParser.parseHistoryResponse(homologsQueryXml,
                NCBIUtility.NCBI_LINK);
        String homologsQuery = homologsParams.getLeft();
        String homologsWebenv = homologsParams.getRight();

        JsonNode homologEntries = ncbiAuxiliaryManager.summaryWithHistory(homologsQuery, homologsWebenv);
        JsonNode homologsResultRoot = homologEntries.path(RESULT_PATH).path(UIDS);
        try {
            parseJsonFromHomolog(homologsResultRoot, homologEntries, ncbiGeneVO);
        } catch (JsonProcessingException e) {
            throw new ExternalDbUnavailableException(
                    MessageHelper.getMessage(MessagesConstants.ERROR_NO_RESULT_BY_EXTERNAL_DB), e);
        }
    }

    return ncbiGeneVO;
}

From source file:com.formkiq.core.service.ArchiveServiceImpl.java

@Override
public Pair<ArchiveDTO, String> get(final String folder, final String uuid, final boolean resetUUID)
        throws IOException {

    Pair<byte[], String> p = this.folderService.findFormData(folder, uuid);
    String sha1hash = p.getRight();

    ArchiveDTO archive = extractJSONFromZipFile(p.getLeft());

    // TODO remove..
    for (String formUUID : archive.getWorkflow().getSteps()) {
        if (!archive.getForms().containsKey(formUUID)) {

            byte[] d = this.folderService.findFormData(folder, formUUID).getLeft();

            ArchiveDTO fa = extractJSONFromZipFile(d);
            archive.getForms().putAll(fa.getForms());
        }/*from  w w w .j a  v a2  s.  c  o m*/
    }

    if (resetUUID) {
        resetUUID(archive);
    }

    return Pair.of(archive, sha1hash);
}

From source file:li.klass.fhem.domain.culhm.ThermostatTest.java

@SafeVarargs
private final void assertWeekProfileContainsExactly(
        WeekProfile<FilledTemperatureInterval, CULHMConfiguration, CULHMDevice> weekProfile, DayUtil.Day day,
        Pair<String, Double>... switchTimeTemperature) {
    DayProfile<FilledTemperatureInterval, CULHMDevice, CULHMConfiguration> dayProfile = weekProfile
            .getDayProfileFor(day);/*from   w ww .  j  av a2  s  .c  o m*/
    List<FilledTemperatureInterval> heatingIntervals = dayProfile.getHeatingIntervals();
    assertThat(heatingIntervals.size()).isEqualTo(switchTimeTemperature.length);

    for (Pair<String, Double> expected : switchTimeTemperature) {
        boolean found = false;
        for (FilledTemperatureInterval heatingInterval : heatingIntervals) {
            if (Math.abs(expected.getRight() - heatingInterval.getTemperature()) <= 0.01
                    && expected.getLeft().equals(heatingInterval.getSwitchTime())) {
                found = true;
                break;
            }
        }
        assertThat(found).as(day + " " + expected.toString()).isTrue();
    }
}